mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Merge branch 'main' into feat/docker-self-upgrade
Resolve conflicts against the restart-coordinator rewrite and renumber the manager-upgrade-jobs migration from 16 to 19 to avoid colliding with main's 016-018 migrations. Includes review fixes: background the docker pull, add a staleness guard for stuck recreating jobs, move manager-upgrade types to @opencode-manager/shared, wire the active-session pre-check dialog into the Upgrade Manager button, and surface upgrade errors via FetchError-aware messaging.
This commit is contained in:
commit
9effe53bdc
125 files changed
+3899
-975
No files matched your search
@@ -0,0 +1,63 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { listSessionPins, toggleSessionPin } from './sessionPins'
|
||||
|
||||
describe('sessionPins', () => {
|
||||
const fetchMock = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('listSessionPins', () => {
|
||||
it('calls GET /api/session-pins and returns pins array', async () => {
|
||||
const expectedPins = [
|
||||
{ sessionId: 's1', directory: '/a', pinnedAt: 100 },
|
||||
{ sessionId: 's2', directory: '/b', pinnedAt: 200 },
|
||||
]
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ pins: expectedPins }), { status: 200 }),
|
||||
)
|
||||
|
||||
const result = await listSessionPins()
|
||||
|
||||
expect(result).toEqual(expectedPins)
|
||||
|
||||
const callUrl = fetchMock.mock.calls[0][0]
|
||||
expect(callUrl).toEqual(expect.stringContaining('/api/session-pins'))
|
||||
|
||||
const callOptions = fetchMock.mock.calls[0][1]
|
||||
expect(callOptions.method).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('toggleSessionPin', () => {
|
||||
it('calls PUT /api/session-pins with JSON body and returns pins', async () => {
|
||||
const input = { sessionId: 's1', directory: '/a', pinned: true }
|
||||
const expectedPins = [
|
||||
{ sessionId: 's1', directory: '/a', pinnedAt: 100 },
|
||||
]
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ pins: expectedPins }), { status: 200 }),
|
||||
)
|
||||
|
||||
const result = await toggleSessionPin(input)
|
||||
|
||||
expect(result).toEqual(expectedPins)
|
||||
|
||||
const callUrl = fetchMock.mock.calls[0][0]
|
||||
expect(callUrl).toEqual(expect.stringContaining('/api/session-pins'))
|
||||
|
||||
const callOptions = fetchMock.mock.calls[0][1]
|
||||
expect(callOptions.method).toBe('PUT')
|
||||
expect(callOptions.headers['Content-Type']).toBe('application/json')
|
||||
|
||||
const body = JSON.parse(callOptions.body)
|
||||
expect(body).toEqual(input)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type { SessionPin, ToggleSessionPinRequest } from '@opencode-manager/shared/schemas'
|
||||
|
||||
export async function listSessionPins(): Promise<SessionPin[]> {
|
||||
const res = await fetchWrapper<{ pins: SessionPin[] }>(`${API_BASE_URL}/api/session-pins`)
|
||||
return res.pins
|
||||
}
|
||||
|
||||
export async function toggleSessionPin(input: ToggleSessionPinRequest): Promise<SessionPin[]> {
|
||||
const res = await fetchWrapper<{ pins: SessionPin[] }>(`${API_BASE_URL}/api/session-pins`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
return res.pins
|
||||
}
|
||||
@@ -15,9 +15,12 @@ import type {
|
||||
InstallSkillResponse,
|
||||
OpenCodeDirectoryFileInfo,
|
||||
} from './types/settings'
|
||||
import type { ManagerUpgradeJob, ManagerUpgradeStatusResponse } from '@opencode-manager/shared/types'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper, FetchError } from './fetchWrapper'
|
||||
|
||||
export type { ManagerUpgradeJob, ManagerUpgradeStatusResponse }
|
||||
|
||||
const DEFAULT_USER_ID = 'default'
|
||||
|
||||
function appendFilesWithManifest(formData: FormData, files: File[]): void {
|
||||
@@ -152,6 +155,10 @@ export const settingsApi = {
|
||||
})
|
||||
},
|
||||
|
||||
getActiveOpenCodeSessions: async (): Promise<{ count: number; sessions: { sessionID: string; directory: string }[] }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-active-sessions`)
|
||||
},
|
||||
|
||||
reloadOpenCodeConfig: async (): Promise<{ success: boolean; message: string; details?: string }> => {
|
||||
try {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-reload`, {
|
||||
@@ -378,7 +385,7 @@ export const settingsApi = {
|
||||
})
|
||||
},
|
||||
|
||||
getManagerUpgradeStatus: async (): Promise<ManagerUpgradeStatus> => {
|
||||
getManagerUpgradeStatus: async (): Promise<ManagerUpgradeStatusResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/manager-upgrade/status`)
|
||||
},
|
||||
|
||||
@@ -430,24 +437,4 @@ export async function rotateManagerToken(): Promise<ManagerTokenResponse> {
|
||||
})
|
||||
}
|
||||
|
||||
export type ManagerUpgradeJobStatus = 'pending' | 'pulling' | 'recreating' | 'completed' | 'failed'
|
||||
|
||||
export interface ManagerUpgradeJob {
|
||||
id: number
|
||||
status: ManagerUpgradeJobStatus
|
||||
fromVersion: string | null
|
||||
toVersion: string | null
|
||||
targetImage: string | null
|
||||
error: string | null
|
||||
startedAt: number
|
||||
finishedAt: number | null
|
||||
}
|
||||
|
||||
export interface ManagerUpgradeStatus {
|
||||
supported: boolean
|
||||
inDocker: boolean
|
||||
socketAvailable: boolean
|
||||
enabled: boolean
|
||||
currentVersion: string | null
|
||||
job: ManagerUpgradeJob | null
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { Combobox, type ComboboxOption } from '@/components/ui/combobox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { TabsContent } from '@/components/ui/tabs'
|
||||
import { Info } from 'lucide-react'
|
||||
|
||||
@@ -27,6 +28,10 @@ type GeneralTabProps = {
|
||||
repoId?: number
|
||||
onRepoChange?: (repoId: number | undefined) => void
|
||||
repoOptions: ComboboxOption[]
|
||||
allowExternalDirectory: boolean
|
||||
onAllowExternalDirectoryChange: (value: boolean) => void
|
||||
bashDenyPatterns: string[]
|
||||
onBashDenyPatternsChange: (value: string[]) => void
|
||||
}
|
||||
|
||||
function InfoHint({ text }: { text: string }) {
|
||||
@@ -63,6 +68,10 @@ export function GeneralTab({
|
||||
repoId,
|
||||
onRepoChange,
|
||||
repoOptions,
|
||||
allowExternalDirectory,
|
||||
onAllowExternalDirectoryChange,
|
||||
bashDenyPatterns,
|
||||
onBashDenyPatternsChange,
|
||||
}: GeneralTabProps) {
|
||||
return (
|
||||
<TabsContent value="basics" className="mt-0 min-h-0 flex-1 overflow-y-auto pt-4 pb-5">
|
||||
@@ -157,6 +166,37 @@ export function GeneralTab({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-medium text-muted-foreground">Permissions</h3>
|
||||
<div className="rounded-lg border border-border bg-card p-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium">Allow access outside the working directory</p>
|
||||
<InfoHint text="When disabled, runs are confined to the worktree. Enable to allow the agent to read/write files elsewhere on the system." />
|
||||
</div>
|
||||
<Switch checked={allowExternalDirectory} onCheckedChange={onAllowExternalDirectoryChange} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg border border-border bg-card p-4">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="schedule-bash-deny">Blocked bash commands</Label>
|
||||
<InfoHint text="One glob per line. These bash commands are always blocked. The throwaway worktree (never auto-pushed) is the real safety boundary." />
|
||||
</div>
|
||||
<Textarea
|
||||
id="schedule-bash-deny"
|
||||
value={bashDenyPatterns.join('\n')}
|
||||
onChange={(event) => {
|
||||
const patterns = event.target.value.split('\n')
|
||||
onBashDenyPatternsChange(patterns)
|
||||
}}
|
||||
placeholder="rm -rf *"
|
||||
className="font-mono text-xs min-h-[100px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { ScheduleJobDialog } from './ScheduleJobDialog'
|
||||
import { DEFAULT_DESTRUCTIVE_BASH_PATTERNS } from '@opencode-manager/shared/schemas'
|
||||
import type { ScheduleJob } from '@opencode-manager/shared/types'
|
||||
|
||||
// jsdom does not implement scrollIntoView
|
||||
Element.prototype.scrollIntoView = vi.fn()
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
templates: [] as Array<{ id: number; title: string; description: string; category: string; cadenceHint: string; suggestedName: string; suggestedDescription: string; prompt: string }>,
|
||||
useDeletePromptTemplateMutate: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/usePromptTemplates', () => ({
|
||||
usePromptTemplates: () => ({ data: mocks.templates, isLoading: false }),
|
||||
useCreatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useUpdatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useDeletePromptTemplate: () => ({ mutate: mocks.useDeletePromptTemplateMutate, isPending: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/providers', () => ({
|
||||
getProvidersWithModels: () => Promise.resolve([]),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
createOpenCodeClient: () => ({
|
||||
listAgents: () => Promise.resolve([]),
|
||||
getConfig: () => Promise.resolve(null),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
listManagedSkills: () => Promise.resolve([]),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
listRepos: () => Promise.resolve([]),
|
||||
listBranches: () => Promise.resolve({ branches: [], status: { ahead: 0, behind: 0 } }),
|
||||
}))
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function getDefaultJob(overrides?: Partial<ScheduleJob>): ScheduleJob {
|
||||
return {
|
||||
id: 1,
|
||||
repoId: 1,
|
||||
name: 'Test Job',
|
||||
description: null,
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Test prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
nextRunAt: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
async function navigateToGeneralTab(user: ReturnType<typeof userEvent.setup>) {
|
||||
const generalTab = screen.getByRole('tab', { name: 'General' })
|
||||
await user.click(generalTab)
|
||||
}
|
||||
|
||||
async function fillRequiredFields(user: ReturnType<typeof userEvent.setup>) {
|
||||
const nameInput = screen.getByLabelText('Name')
|
||||
await user.type(nameInput, 'Test Job')
|
||||
const promptTab = screen.getByRole('tab', { name: 'Prompt' })
|
||||
await user.click(promptTab)
|
||||
const promptInput = screen.getByRole('textbox', { name: 'Prompt' })
|
||||
await user.type(promptInput, 'Run a test')
|
||||
}
|
||||
|
||||
/** The external-directory switch is the 2nd switch (index 1) after Enabled */
|
||||
function getExternalDirSwitch() {
|
||||
return screen.getAllByRole('switch')[1]
|
||||
}
|
||||
|
||||
describe('ScheduleJobDialog — permission config', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('shows default deny patterns and external-directory toggle off for a new job', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await navigateToGeneralTab(user)
|
||||
|
||||
const textarea = await screen.findByLabelText('Blocked bash commands')
|
||||
const defaultText = DEFAULT_DESTRUCTIVE_BASH_PATTERNS.join('\n')
|
||||
expect(textarea).toHaveValue(defaultText)
|
||||
|
||||
const switchInput = getExternalDirSwitch()
|
||||
expect(switchInput).not.toBeChecked()
|
||||
})
|
||||
|
||||
it('initializes permission config from an existing job', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
const customPatterns = ['rm -rf *', 'sudo *']
|
||||
const job = getDefaultJob({
|
||||
permissionConfig: {
|
||||
allowExternalDirectory: true,
|
||||
bashDenyPatterns: [...customPatterns],
|
||||
},
|
||||
})
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
job={job}
|
||||
onSubmit={onSubmit}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await navigateToGeneralTab(user)
|
||||
|
||||
const textarea = await screen.findByLabelText('Blocked bash commands')
|
||||
expect(textarea).toHaveValue(customPatterns.join('\n'))
|
||||
|
||||
const switchInput = getExternalDirSwitch()
|
||||
expect(switchInput).toBeChecked()
|
||||
})
|
||||
|
||||
it('submits permissionConfig in the create payload', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await navigateToGeneralTab(user)
|
||||
await fillRequiredFields(user)
|
||||
|
||||
// Navigate back to General tab
|
||||
await navigateToGeneralTab(user)
|
||||
|
||||
// Enable external directory access
|
||||
const switchInput = getExternalDirSwitch()
|
||||
await user.click(switchInput)
|
||||
|
||||
// Submit
|
||||
const submitButton = screen.getByRole('button', { name: /Create schedule/i })
|
||||
await user.click(submitButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
const payload = onSubmit.mock.calls[0][0]
|
||||
expect(payload.permissionConfig).toEqual({
|
||||
allowExternalDirectory: true,
|
||||
bashDenyPatterns: [...DEFAULT_DESTRUCTIVE_BASH_PATTERNS],
|
||||
})
|
||||
})
|
||||
|
||||
it('strips empty lines from bash deny patterns before submitting', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await navigateToGeneralTab(user)
|
||||
await fillRequiredFields(user)
|
||||
|
||||
// Navigate back to General tab
|
||||
await navigateToGeneralTab(user)
|
||||
|
||||
// Clear and set patterns with empty lines via paste to preserve newlines
|
||||
const textarea = await screen.findByLabelText('Blocked bash commands')
|
||||
await user.clear(textarea)
|
||||
await user.type(textarea, 'rm -rf *{Enter}{Enter}{Enter}sudo *{Enter}{Enter}')
|
||||
|
||||
// Submit
|
||||
const submitButton = screen.getByRole('button', { name: /Create schedule/i })
|
||||
await user.click(submitButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
const payload = onSubmit.mock.calls[0][0]
|
||||
expect(payload.permissionConfig).toEqual({
|
||||
allowExternalDirectory: false,
|
||||
bashDenyPatterns: ['rm -rf *', 'sudo *'],
|
||||
})
|
||||
})
|
||||
|
||||
it('submits updated permissionConfig when editing an existing job', async () => {
|
||||
const onSubmit = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
const job = getDefaultJob({
|
||||
permissionConfig: {
|
||||
allowExternalDirectory: false,
|
||||
bashDenyPatterns: ['rm -rf *', 'git push --force*'],
|
||||
},
|
||||
})
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
job={job}
|
||||
onSubmit={onSubmit}
|
||||
isSaving={false}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await navigateToGeneralTab(user)
|
||||
|
||||
// Toggle external directory on
|
||||
const switchInput = getExternalDirSwitch()
|
||||
await user.click(switchInput)
|
||||
|
||||
// Add a pattern via Enter key
|
||||
const textarea = await screen.findByLabelText('Blocked bash commands')
|
||||
const existingValue = textarea as HTMLTextAreaElement
|
||||
await user.type(existingValue, '{Enter}sudo *')
|
||||
|
||||
// Submit
|
||||
const submitButton = screen.getByRole('button', { name: /Save changes/i })
|
||||
await user.click(submitButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
const payload = onSubmit.mock.calls[0][0]
|
||||
expect(payload.permissionConfig).toEqual({
|
||||
allowExternalDirectory: true,
|
||||
bashDenyPatterns: ['rm -rf *', 'git push --force*', 'sudo *'],
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
} from '@/components/schedules/schedule-utils'
|
||||
import { getRepoDisplayName } from '@/lib/utils'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME } from '@opencode-manager/shared/utils'
|
||||
import { DEFAULT_DESTRUCTIVE_BASH_PATTERNS } from '@opencode-manager/shared/schemas'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { usePromptTemplates, useDeletePromptTemplate } from '@/hooks/usePromptTemplates'
|
||||
import { PromptTemplateDialog } from './PromptTemplateDialog'
|
||||
@@ -61,6 +62,8 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
const initialSkillSlugsRef = useRef<string[] | undefined>(undefined)
|
||||
const initialSkillNotesRef = useRef<string | undefined>(undefined)
|
||||
const [branch, setBranch] = useState('')
|
||||
const [allowExternalDirectory, setAllowExternalDirectory] = useState(false)
|
||||
const [bashDenyPatterns, setBashDenyPatterns] = useState<string[]>([...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
|
||||
const [templateDialogOpen, setTemplateDialogOpen] = useState(false)
|
||||
const [editingTemplate, setEditingTemplate] = useState<PromptTemplate | undefined>(undefined)
|
||||
const [deletingTemplateId, setDeletingTemplateId] = useState<number | null>(null)
|
||||
@@ -218,6 +221,8 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
initialSkillSlugsRef.current = initialSkillSlugs
|
||||
initialSkillNotesRef.current = initialSkillNotes
|
||||
setBranch(job?.branch ?? '')
|
||||
setAllowExternalDirectory(job?.permissionConfig?.allowExternalDirectory ?? false)
|
||||
setBashDenyPatterns(job?.permissionConfig?.bashDenyPatterns ?? [...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
|
||||
}, [job, open, templates])
|
||||
|
||||
const applyPromptTemplate = (template: PromptTemplate) => {
|
||||
@@ -250,6 +255,10 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
model: model.trim() || undefined,
|
||||
prompt: prompt.trim(),
|
||||
branch: branch.trim() || null,
|
||||
permissionConfig: {
|
||||
allowExternalDirectory,
|
||||
bashDenyPatterns: bashDenyPatterns.map((p) => p.trim()).filter(Boolean),
|
||||
},
|
||||
...(shouldIncludeSkillMetadata ? {
|
||||
skillMetadata: skillSlugs.length > 0 || skillNotes.trim()
|
||||
? {
|
||||
@@ -328,6 +337,10 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
repoId={selectedRepoId}
|
||||
onRepoChange={onRepoChange}
|
||||
repoOptions={repoOptions}
|
||||
allowExternalDirectory={allowExternalDirectory}
|
||||
onAllowExternalDirectoryChange={setAllowExternalDirectory}
|
||||
bashDenyPatterns={bashDenyPatterns}
|
||||
onBashDenyPatternsChange={setBashDenyPatterns}
|
||||
/>
|
||||
|
||||
<TimingTab
|
||||
|
||||
@@ -2,10 +2,12 @@ import { useRef, useEffect } from "react";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { SessionStatusIndicator } from "@/components/ui/session-status-indicator";
|
||||
import { Trash2, Clock } from "lucide-react";
|
||||
import { Trash2, Clock, MoreVertical, Pin, PinOff } from "lucide-react";
|
||||
import { formatDistanceToNow } from "date-fns";
|
||||
import type { Session } from "@/api/types";
|
||||
import { useSwipe } from "@/hooks/useSwipe";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface SessionCardProps {
|
||||
session: Session;
|
||||
@@ -13,6 +15,8 @@ interface SessionCardProps {
|
||||
isActive: boolean;
|
||||
manageMode: boolean;
|
||||
workspaceLabel?: string;
|
||||
isPinned?: boolean;
|
||||
onTogglePin?: () => void;
|
||||
onSelect: (sessionID: string) => void;
|
||||
onToggleSelection: (selected: boolean) => void;
|
||||
onDelete: (e: React.MouseEvent<HTMLButtonElement>) => void;
|
||||
@@ -24,6 +28,8 @@ export const SessionCard = ({
|
||||
isActive,
|
||||
manageMode,
|
||||
workspaceLabel,
|
||||
isPinned,
|
||||
onTogglePin,
|
||||
onSelect,
|
||||
onToggleSelection,
|
||||
onDelete,
|
||||
@@ -98,6 +104,7 @@ export const SessionCard = ({
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1">
|
||||
{isPinned && <Pin className="w-3 h-3 text-orange-500 shrink-0" />}
|
||||
<h3 className="text-base font-semibold text-orange-600 dark:text-orange-400 truncate">
|
||||
{session.title || "Untitled Session"}
|
||||
</h3>
|
||||
@@ -116,23 +123,54 @@ export const SessionCard = ({
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col flex-1 min-w-0">
|
||||
<h3 className="text-sm font-semibold text-orange-600 dark:text-orange-400 truncate">
|
||||
{session.title || "Untitled Session"}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground">
|
||||
<span className="flex items-center">
|
||||
<Clock className="w-3 h-3 mr-1" />
|
||||
{formatDistanceToNow(new Date(session.time.updated), {
|
||||
addSuffix: true,
|
||||
})}
|
||||
</span>
|
||||
{workspaceLabel ? (
|
||||
<span className="text-purple-400 truncate max-w-[120px]">{workspaceLabel}</span>
|
||||
) : null}
|
||||
<SessionStatusIndicator sessionID={session.id} size="sm" />
|
||||
<>
|
||||
<div className="flex flex-col flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1">
|
||||
{isPinned && <Pin className="w-3 h-3 text-orange-500 shrink-0" />}
|
||||
<h3 className="text-sm font-semibold text-orange-600 dark:text-orange-400 truncate">
|
||||
{session.title || "Untitled Session"}
|
||||
</h3>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground">
|
||||
<span className="flex items-center">
|
||||
<Clock className="w-3 h-3 mr-1" />
|
||||
{formatDistanceToNow(new Date(session.time.updated), {
|
||||
addSuffix: true,
|
||||
})}
|
||||
</span>
|
||||
{workspaceLabel ? (
|
||||
<span className="text-purple-400 truncate max-w-[120px]">{workspaceLabel}</span>
|
||||
) : null}
|
||||
<SessionStatusIndicator sessionID={session.id} size="sm" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{onTogglePin && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
aria-label="Session actions"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 w-7 p-0 shrink-0"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
align="end"
|
||||
className="z-[200]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<DropdownMenuItem onClick={() => onTogglePin()}>
|
||||
{isPinned ? <PinOff className="w-4 h-4 mr-2" /> : <Pin className="w-4 h-4 mr-2" />}
|
||||
{isPinned ? "Unpin" : "Pin to top"}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{manageMode && (
|
||||
<button
|
||||
|
||||
@@ -3,7 +3,7 @@ import { render, screen, waitFor, within, fireEvent } from '@testing-library/rea
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { SessionList } from './SessionList'
|
||||
|
||||
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, lastSessionsHookArgs } = vi.hoisted(() => ({
|
||||
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({
|
||||
createSessionMock: vi.fn(),
|
||||
deleteSessionMock: vi.fn(),
|
||||
sessionsData: [] as Array<{ id: string; title: string; directory: string; workspaceID?: string; parentID?: string; time: { updated: number } }>,
|
||||
@@ -12,6 +12,8 @@ const { createSessionMock, deleteSessionMock, sessionsData, createSessionState,
|
||||
hasNextPageRef: { current: false },
|
||||
isFetchingNextPageRef: { current: false },
|
||||
lastSessionsHookArgs: { current: undefined as { opcodeUrl: string; directories: string[]; options?: { search?: string; limit?: number } } | undefined },
|
||||
sessionPinsData: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
|
||||
togglePinMock: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
@@ -34,6 +36,11 @@ vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useDeleteSession: () => ({ mutateAsync: deleteSessionMock, isPending: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSessionPins', () => ({
|
||||
useSessionPins: () => ({ data: sessionPinsData }),
|
||||
useToggleSessionPin: () => ({ mutate: togglePinMock }),
|
||||
}))
|
||||
|
||||
describe('SessionList', () => {
|
||||
beforeEach(() => {
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
@@ -49,6 +56,8 @@ describe('SessionList', () => {
|
||||
hasNextPageRef.current = false
|
||||
isFetchingNextPageRef.current = false
|
||||
lastSessionsHookArgs.current = undefined
|
||||
sessionPinsData.splice(0, sessionPinsData.length)
|
||||
togglePinMock.mockReset()
|
||||
})
|
||||
|
||||
it('selects duplicate session IDs independently by workspace directory', async () => {
|
||||
@@ -267,4 +276,48 @@ describe('SessionList', () => {
|
||||
expect(fetchNextPageMock).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('renders pinned session under a Pinned heading and excludes it from Today', () => {
|
||||
const pinnedTime = Date.now()
|
||||
sessionPinsData.push({ sessionId: 'ses_a', directory: '/w/a', pinnedAt: pinnedTime })
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_a', title: 'pinned session', directory: '/w/a', time: { updated: pinnedTime } },
|
||||
)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Pinned')).toBeTruthy()
|
||||
expect(screen.getByText('pinned session')).toBeTruthy()
|
||||
// Pinned sessions are excluded from Today/Older, so Today heading should not appear
|
||||
expect(screen.queryByText('Today')).toBeNull()
|
||||
})
|
||||
|
||||
it('calls togglePinMock with correct args when Pin to top is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_x', title: 'test session', directory: '/w/a', time: { updated: Date.now() } },
|
||||
)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
const actionsButton = screen.getByRole('button', { name: 'Session actions' })
|
||||
await user.click(actionsButton)
|
||||
|
||||
const pinItem = screen.getByText('Pin to top')
|
||||
await user.click(pinItem)
|
||||
|
||||
expect(togglePinMock).toHaveBeenCalledWith({ sessionId: 'ses_x', directory: '/w/a', pinned: true })
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,9 @@
|
||||
import { useCallback, useState, useMemo, useEffect } from "react";
|
||||
import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
|
||||
import type { DeleteSessionTarget } from "@/hooks/useOpenCode";
|
||||
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins';
|
||||
import { buildSessionKey } from '@/lib/sessionKey';
|
||||
import { partitionSessions } from './session-partition';
|
||||
import { DeleteSessionDialog } from "./DeleteSessionDialog";
|
||||
import { SessionCard } from "./SessionCard";
|
||||
import { Card } from "@/components/ui/card";
|
||||
@@ -35,7 +38,7 @@ export const SessionList = ({
|
||||
const primaryDirectory = directoriesList[0];
|
||||
const sessionCreateDirectory = createDirectory ?? primaryDirectory;
|
||||
const getSessionSelectionKey = useCallback((session: { id: string; directory?: string }) =>
|
||||
`${session.directory ?? primaryDirectory ?? ''}:${session.id}`,
|
||||
buildSessionKey(session.directory ?? primaryDirectory, session.id),
|
||||
[primaryDirectory]);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { data: sessions, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } = useSessionsAcrossDirectories(opcodeUrl, directoriesList, { search: searchQuery, limit: 25 });
|
||||
@@ -43,6 +46,12 @@ export const SessionList = ({
|
||||
const createSession = useCreateSession(opcodeUrl, sessionCreateDirectory, (newSession) => {
|
||||
onSelectSession(newSession.id);
|
||||
});
|
||||
const { data: sessionPins } = useSessionPins();
|
||||
const togglePin = useToggleSessionPin();
|
||||
const pinnedKeys = useMemo(
|
||||
() => new Set((sessionPins ?? []).map((p) => buildSessionKey(p.directory, p.sessionId))),
|
||||
[sessionPins],
|
||||
);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [sessionToDelete, setSessionToDelete] = useState<DeleteSessionTarget | DeleteSessionTarget[] | null>(null);
|
||||
const [selectedSessions, setSelectedSessions] = useState<Set<string>>(new Set());
|
||||
@@ -68,17 +77,16 @@ export const SessionList = ({
|
||||
return Array.from(uniqueSessions.values()).sort((a, b) => b.time.updated - a.time.updated);
|
||||
}, [sessions, directorySet, getSessionSelectionKey]);
|
||||
|
||||
const todaySessions = useMemo(() => {
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
return filteredSessions.filter((session) => new Date(session.time.updated) >= today);
|
||||
}, [filteredSessions]);
|
||||
const { pinned: pinnedSessions, today: todaySessions, older: olderSessions } = useMemo(
|
||||
() => partitionSessions(filteredSessions, pinnedKeys, getSessionSelectionKey),
|
||||
[filteredSessions, pinnedKeys, getSessionSelectionKey],
|
||||
);
|
||||
|
||||
const olderSessions = useMemo(() => {
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
return filteredSessions.filter((session) => new Date(session.time.updated) < today);
|
||||
}, [filteredSessions]);
|
||||
const handleTogglePin = (session: { id: string; directory?: string }) => {
|
||||
const directory = session.directory ?? primaryDirectory ?? '';
|
||||
const key = getSessionSelectionKey(session);
|
||||
togglePin.mutate({ sessionId: session.id, directory, pinned: !pinnedKeys.has(key) });
|
||||
};
|
||||
|
||||
const handleSessionsScroll = useCallback((event: React.UIEvent<HTMLDivElement>) => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
|
||||
@@ -188,6 +196,25 @@ export const SessionList = ({
|
||||
}
|
||||
};
|
||||
|
||||
const renderSessionCard = (session: (typeof filteredSessions)[number], isPinned: boolean) => {
|
||||
const key = getSessionSelectionKey(session);
|
||||
return (
|
||||
<SessionCard
|
||||
key={key}
|
||||
session={session}
|
||||
isSelected={selectedSessions.has(key)}
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
workspaceLabel={session.directory ? directoryLabels?.[session.directory] : undefined}
|
||||
isPinned={isPinned}
|
||||
onSelect={onSelectSession}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}
|
||||
onTogglePin={() => handleTogglePin(session)}
|
||||
onDelete={(e) => handleDelete(session, e)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
<div className="px-4 pt-2 flex-shrink-0">
|
||||
@@ -260,43 +287,29 @@ export const SessionList = ({
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{pinnedSessions.length > 0 && (
|
||||
<>
|
||||
<div className="text-xs font-semibold text-muted-foreground px-1 py-2">Pinned</div>
|
||||
{pinnedSessions.map((session) => renderSessionCard(session, true))}
|
||||
{(todaySessions.length > 0 || olderSessions.length > 0) && (
|
||||
<div className="my-2 h-px bg-border/80" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{todaySessions.length > 0 && (
|
||||
<>
|
||||
<div className="text-xs font-semibold text-muted-foreground px-1 py-2">
|
||||
Today
|
||||
</div>
|
||||
{todaySessions.map((session) => (
|
||||
<SessionCard
|
||||
key={getSessionSelectionKey(session)}
|
||||
session={session}
|
||||
isSelected={selectedSessions.has(getSessionSelectionKey(session))}
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
workspaceLabel={session.directory ? directoryLabels?.[session.directory] : undefined}
|
||||
onSelect={onSelectSession}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}
|
||||
onDelete={(e) => handleDelete(session, e)}
|
||||
/>
|
||||
))}
|
||||
{todaySessions.map((session) => renderSessionCard(session, false))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{todaySessions.length > 0 && olderSessions.length > 0 && (
|
||||
<div className="my-2 h-px bg-border/80" />
|
||||
)}
|
||||
{olderSessions.map((session) => (
|
||||
<SessionCard
|
||||
key={getSessionSelectionKey(session)}
|
||||
session={session}
|
||||
isSelected={selectedSessions.has(getSessionSelectionKey(session))}
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
workspaceLabel={session.directory ? directoryLabels?.[session.directory] : undefined}
|
||||
onSelect={onSelectSession}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}
|
||||
onDelete={(e) => handleDelete(session, e)}
|
||||
/>
|
||||
))}
|
||||
{olderSessions.map((session) => renderSessionCard(session, false))}
|
||||
</>
|
||||
)}
|
||||
{isFetchingNextPage && (
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { partitionSessions } from './session-partition'
|
||||
import type { Session } from '@/api/types'
|
||||
|
||||
function createSession(id: string, updated: number, directory = '/test'): Session {
|
||||
return {
|
||||
id,
|
||||
projectID: 'proj-1',
|
||||
directory,
|
||||
title: `Session ${id}`,
|
||||
version: '1',
|
||||
time: { created: updated - 10000, updated },
|
||||
}
|
||||
}
|
||||
|
||||
const keyFn = (s: { id: string; directory?: string }) =>
|
||||
`${s.directory ?? ''}:${s.id}`
|
||||
|
||||
describe('partitionSessions', () => {
|
||||
it('places pinned sessions in pinned array sorted by updated desc', () => {
|
||||
const now = 1_000_000_000_000
|
||||
const sessions = [
|
||||
createSession('a', now - 2000),
|
||||
createSession('b', now - 1000),
|
||||
createSession('c', now - 3000),
|
||||
]
|
||||
const pinnedKeys = new Set(['/test:a', '/test:c'])
|
||||
|
||||
const result = partitionSessions(sessions, pinnedKeys, keyFn, now)
|
||||
|
||||
expect(result.pinned).toHaveLength(2)
|
||||
expect(result.pinned[0].id).toBe('a')
|
||||
expect(result.pinned[1].id).toBe('c')
|
||||
expect(result.today).toHaveLength(1)
|
||||
expect(result.today[0].id).toBe('b')
|
||||
expect(result.older).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('places unpinned sessions with updated >= start of today in today', () => {
|
||||
const now = 1_000_000_000_000
|
||||
const todayStart = new Date(now)
|
||||
todayStart.setHours(0, 0, 0, 0)
|
||||
const todayTs = todayStart.getTime() + 5000
|
||||
const yesterdayTs = todayStart.getTime() - 1000
|
||||
|
||||
const sessions = [
|
||||
createSession('today-session', todayTs),
|
||||
createSession('yesterday-session', yesterdayTs),
|
||||
]
|
||||
|
||||
const result = partitionSessions(sessions, new Set(), keyFn, now)
|
||||
|
||||
expect(result.pinned).toHaveLength(0)
|
||||
expect(result.today).toHaveLength(1)
|
||||
expect(result.today[0].id).toBe('today-session')
|
||||
expect(result.older).toHaveLength(1)
|
||||
expect(result.older[0].id).toBe('yesterday-session')
|
||||
})
|
||||
|
||||
it('sorts today and older arrays by updated desc', () => {
|
||||
const now = 1_000_000_000_000
|
||||
const todayStart = new Date(now)
|
||||
todayStart.setHours(0, 0, 0, 0)
|
||||
const todayTs = todayStart.getTime() + 5000
|
||||
|
||||
const sessions = [
|
||||
createSession('older-1', todayStart.getTime() - 3000),
|
||||
createSession('older-2', todayStart.getTime() - 1000),
|
||||
createSession('today-1', todayTs),
|
||||
createSession('today-2', todayTs - 2000),
|
||||
]
|
||||
|
||||
const result = partitionSessions(sessions, new Set(), keyFn, now)
|
||||
|
||||
expect(result.today[0].id).toBe('today-1')
|
||||
expect(result.today[1].id).toBe('today-2')
|
||||
expect(result.older[0].id).toBe('older-2')
|
||||
expect(result.older[1].id).toBe('older-1')
|
||||
})
|
||||
|
||||
it('keeps old pinned sessions in pinned (not older)', () => {
|
||||
const now = 1_000_000_000_000
|
||||
const todayStart = new Date(now)
|
||||
todayStart.setHours(0, 0, 0, 0)
|
||||
const oldTs = todayStart.getTime() - 86400_000
|
||||
|
||||
const sessions = [
|
||||
createSession('pinned-old', oldTs),
|
||||
createSession('normal-old', oldTs),
|
||||
]
|
||||
const pinnedKeys = new Set(['/test:pinned-old'])
|
||||
|
||||
const result = partitionSessions(sessions, pinnedKeys, keyFn, now)
|
||||
|
||||
expect(result.pinned).toHaveLength(1)
|
||||
expect(result.pinned[0].id).toBe('pinned-old')
|
||||
expect(result.today).toHaveLength(0)
|
||||
expect(result.older).toHaveLength(1)
|
||||
expect(result.older[0].id).toBe('normal-old')
|
||||
})
|
||||
|
||||
it('returns empty pinned when pinnedKeys is empty, matching today/older behavior', () => {
|
||||
const now = 1_000_000_000_000
|
||||
const todayStart = new Date(now)
|
||||
todayStart.setHours(0, 0, 0, 0)
|
||||
const todayTs = todayStart.getTime() + 5000
|
||||
const yesterdayTs = todayStart.getTime() - 1000
|
||||
|
||||
const sessions = [
|
||||
createSession('today-session', todayTs),
|
||||
createSession('yesterday-session', yesterdayTs),
|
||||
]
|
||||
|
||||
const result = partitionSessions(sessions, new Set(), keyFn, now)
|
||||
|
||||
expect(result.pinned).toHaveLength(0)
|
||||
expect(result.today).toHaveLength(1)
|
||||
expect(result.older).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('produces disjoint pinned/today/older arrays', () => {
|
||||
const now = 1_000_000_000_000
|
||||
const todayStart = new Date(now)
|
||||
todayStart.setHours(0, 0, 0, 0)
|
||||
const todayTs = todayStart.getTime() + 5000
|
||||
const yesterdayTs = todayStart.getTime() - 1000
|
||||
|
||||
const sessions = [
|
||||
createSession('pinned', todayTs),
|
||||
createSession('normal-today', todayTs - 2000),
|
||||
createSession('normal-old', yesterdayTs),
|
||||
]
|
||||
const pinnedKeys = new Set(['/test:pinned'])
|
||||
|
||||
const result = partitionSessions(sessions, pinnedKeys, keyFn, now)
|
||||
|
||||
const all = [...result.pinned, ...result.today, ...result.older]
|
||||
expect(all).toHaveLength(sessions.length)
|
||||
const allIds = all.map((s) => s.id).sort()
|
||||
expect(allIds).toEqual(['normal-old', 'normal-today', 'pinned'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { Session } from '@/api/types'
|
||||
|
||||
export interface PartitionedSessions {
|
||||
pinned: Session[]
|
||||
today: Session[]
|
||||
older: Session[]
|
||||
}
|
||||
|
||||
export function partitionSessions(
|
||||
sessions: Session[],
|
||||
pinnedKeys: Set<string>,
|
||||
keyFn: (session: { id: string; directory?: string }) => string,
|
||||
now: number = Date.now(),
|
||||
): PartitionedSessions {
|
||||
const startOfDay = new Date(now)
|
||||
startOfDay.setHours(0, 0, 0, 0)
|
||||
const startMs = startOfDay.getTime()
|
||||
const byUpdatedDesc = (a: Session, b: Session) => b.time.updated - a.time.updated
|
||||
|
||||
const pinned: Session[] = []
|
||||
const today: Session[] = []
|
||||
const older: Session[] = []
|
||||
for (const s of sessions) {
|
||||
if (pinnedKeys.has(keyFn(s))) {
|
||||
pinned.push(s)
|
||||
} else if (s.time.updated >= startMs) {
|
||||
today.push(s)
|
||||
} else {
|
||||
older.push(s)
|
||||
}
|
||||
}
|
||||
pinned.sort(byUpdatedDesc)
|
||||
today.sort(byUpdatedDesc)
|
||||
older.sort(byUpdatedDesc)
|
||||
return { pinned, today, older }
|
||||
}
|
||||
@@ -9,6 +9,7 @@ const {
|
||||
mockGetOpenCodeConfigs,
|
||||
mockUpdateOpenCodeConfig,
|
||||
mockRestartOpenCodeServer,
|
||||
mockGetActiveOpenCodeSessions,
|
||||
mockGetOpenCodeImportStatus,
|
||||
mockListManagedSkills,
|
||||
mockListOpenCodeDirectoryFiles,
|
||||
@@ -17,6 +18,7 @@ const {
|
||||
mockGetOpenCodeConfigs: vi.fn(),
|
||||
mockUpdateOpenCodeConfig: vi.fn(),
|
||||
mockRestartOpenCodeServer: vi.fn(),
|
||||
mockGetActiveOpenCodeSessions: vi.fn(),
|
||||
mockGetOpenCodeImportStatus: vi.fn(),
|
||||
mockListManagedSkills: vi.fn(),
|
||||
mockListOpenCodeDirectoryFiles: vi.fn(),
|
||||
@@ -36,6 +38,7 @@ vi.mock('@/api/settings', () => ({
|
||||
getOpenCodeConfigs: mockGetOpenCodeConfigs,
|
||||
updateOpenCodeConfig: mockUpdateOpenCodeConfig,
|
||||
restartOpenCodeServer: mockRestartOpenCodeServer,
|
||||
getActiveOpenCodeSessions: mockGetActiveOpenCodeSessions,
|
||||
getOpenCodeImportStatus: mockGetOpenCodeImportStatus,
|
||||
listManagedSkills: mockListManagedSkills,
|
||||
listOpenCodeDirectoryFiles: mockListOpenCodeDirectoryFiles,
|
||||
@@ -85,6 +88,7 @@ describe('OpenCodeConfigManager', () => {
|
||||
})
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue(defaultConfig)
|
||||
mockRestartOpenCodeServer.mockResolvedValue({ success: true, message: 'ok' })
|
||||
mockGetActiveOpenCodeSessions.mockResolvedValue({ count: 2, sessions: [] })
|
||||
})
|
||||
|
||||
it('shows uploaded command and agent directory files in settings', async () => {
|
||||
|
||||
@@ -21,9 +21,11 @@ import { VersionSelectDialog } from './VersionSelectDialog'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { parseJsonc, hasJsoncComments } from '@/lib/jsonc'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import type { OpenCodeConfig, OpenCodeImportStatus } from '@/api/types/settings'
|
||||
|
||||
@@ -81,7 +83,16 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
|
||||
const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false)
|
||||
const [deleteConfirmConfig, setDeleteConfirmConfig] = useState<OpenCodeConfig | null>(null)
|
||||
const [isRestartPromptOpen, setIsRestartPromptOpen] = useState(false)
|
||||
const {
|
||||
restartServerMutation,
|
||||
upgradeOpenCodeMutation,
|
||||
confirmOpen: isRestartPromptOpen,
|
||||
setConfirmOpen: setIsRestartPromptOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
performUpgrade,
|
||||
} = useOpenCodeServerActions()
|
||||
|
||||
const agentsMdRef = useRef<HTMLButtonElement>(null)
|
||||
const commandsRef = useRef<HTMLButtonElement>(null)
|
||||
@@ -124,56 +135,6 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
}
|
||||
}
|
||||
|
||||
const restartServerMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
return await settingsApi.restartOpenCodeServer()
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
|
||||
const upgradeOpenCodeMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
return await settingsApi.upgradeOpenCode()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
if (data.upgraded && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
if (data.upgraded) {
|
||||
showToast.success(`Upgraded to v${data.newVersion} and server restarted`, { id: 'upgrade-opencode' })
|
||||
} else {
|
||||
showToast.success('OpenCode is already up to date', { id: 'upgrade-opencode' })
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
const defaultMessage = 'Failed to upgrade OpenCode'
|
||||
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = (error as { response?: { data?: { recovered?: boolean; recoveryMessage?: string; newVersion?: string } } }).response
|
||||
const data = response?.data
|
||||
|
||||
if (data?.recovered && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
showToast.success(`Upgrade failed but server recovered at v${data.newVersion}`, { id: 'upgrade-opencode' })
|
||||
} else {
|
||||
showToast.error(data?.recoveryMessage || defaultMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
} else {
|
||||
showToast.error(defaultMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
|
||||
const syncOpenCodeImportMutation = useMutation({
|
||||
mutationFn: async () => settingsApi.syncOpenCodeImport(),
|
||||
onSuccess: async () => {
|
||||
@@ -183,50 +144,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
},
|
||||
})
|
||||
|
||||
const getApiErrorMessage = (error: unknown, fallback: string): string => {
|
||||
if (error instanceof FetchError) {
|
||||
let message = error.detail || error.message || fallback
|
||||
|
||||
if (error.validationIssues && error.validationIssues.length > 0) {
|
||||
const issues = error.validationIssues
|
||||
.map((issue) => `${issue.path}: ${issue.message}`)
|
||||
.join('; ')
|
||||
message = `Validation failed: ${issues}`
|
||||
}
|
||||
|
||||
if (error.removedFields && error.removedFields.length > 0) {
|
||||
message += ` (removed invalid fields: ${error.removedFields.join(', ')})`
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = (error as { response?: { data?: { details?: string; error?: string; validationIssues?: Array<{ path: string; message: string }>; removedFields?: string[] } } }).response
|
||||
const data = response?.data
|
||||
|
||||
let message = data?.details || data?.error || fallback
|
||||
|
||||
if (data?.validationIssues && data.validationIssues.length > 0) {
|
||||
const issues = data.validationIssues
|
||||
.map((issue) => `${issue.path}: ${issue.message}`)
|
||||
.join('; ')
|
||||
message = `Validation failed: ${issues}`
|
||||
}
|
||||
|
||||
if (data?.removedFields && data.removedFields.length > 0) {
|
||||
const removed = data.removedFields.join(', ')
|
||||
message += ` (removed invalid fields: ${removed})`
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
const getRestartErrorMessage = (error: unknown): string => {
|
||||
return getApiErrorMessage(error, 'Failed to restart OpenCode server')
|
||||
}
|
||||
const getApiErrorMessage = getOpenCodeApiErrorMessage
|
||||
|
||||
const getOpenCodeImportErrorMessage = (error: unknown): string => {
|
||||
if (error instanceof FetchError && error.code === 'OPENCODE_IMPORT_PROTECTED') {
|
||||
@@ -452,19 +370,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
showToast.loading('Upgrading OpenCode...', { id: 'upgrade-opencode' })
|
||||
try {
|
||||
await upgradeOpenCodeMutation.mutateAsync()
|
||||
} catch (error) {
|
||||
const errorMessage = error && typeof error === 'object' && 'response' in error
|
||||
? ((error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.details
|
||||
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|
||||
|| 'Failed to upgrade OpenCode')
|
||||
: 'Failed to upgrade OpenCode'
|
||||
showToast.error(errorMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
}}
|
||||
onClick={performUpgrade}
|
||||
disabled={upgradeOpenCodeMutation.isPending}
|
||||
>
|
||||
{upgradeOpenCodeMutation.isPending ? (
|
||||
@@ -477,15 +383,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
showToast.loading('Restarting OpenCode server...', { id: 'manual-restart' })
|
||||
try {
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Server restarted successfully', { id: 'manual-restart' })
|
||||
} catch (error) {
|
||||
showToast.error(getRestartErrorMessage(error), { id: 'manual-restart' })
|
||||
}
|
||||
}}
|
||||
onClick={requestRestart}
|
||||
disabled={restartServerMutation.isPending}
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
@@ -519,7 +417,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setIsRestartPromptOpen(true)}
|
||||
onClick={requestRestart}
|
||||
disabled={restartServerMutation.isPending}
|
||||
className="shrink-0"
|
||||
>
|
||||
@@ -1080,18 +978,10 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<RestartServerDialog
|
||||
open={isRestartPromptOpen}
|
||||
onOpenChange={setIsRestartPromptOpen}
|
||||
activeSessionCount={activeSessionCount}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setIsRestartPromptOpen(false)}
|
||||
onConfirm={async () => {
|
||||
showToast.loading('Restarting OpenCode server...', { id: 'config-restart' })
|
||||
try {
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Server restarted successfully', { id: 'config-restart' })
|
||||
setIsRestartPromptOpen(false)
|
||||
} catch (error) {
|
||||
showToast.error(getRestartErrorMessage(error), { id: 'config-restart' })
|
||||
}
|
||||
}}
|
||||
onConfirm={confirmRestart}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -58,4 +58,20 @@ describe('RestartServerDialog', () => {
|
||||
const laterButton = screen.getByRole('button', { name: /later/i })
|
||||
expect(laterButton).toBeDisabled()
|
||||
})
|
||||
|
||||
it('renders the active-session warning when activeSessionCount > 0', () => {
|
||||
render(<RestartServerDialog {...baseProps} activeSessionCount={2} />)
|
||||
|
||||
expect(screen.getByText(/2 sessions/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/continue/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render the active-session warning when activeSessionCount is omitted', () => {
|
||||
render(<RestartServerDialog {...baseProps} />)
|
||||
|
||||
expect(
|
||||
screen.getByText(/Restart the OpenCode server after your changes are saved to apply them to the running server\./)
|
||||
).toBeInTheDocument()
|
||||
expect(screen.queryByText(/sessions? currently working/)).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,11 @@ interface RestartServerDialogProps {
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
isRestarting?: boolean
|
||||
activeSessionCount?: number
|
||||
title?: string
|
||||
description?: string
|
||||
confirmLabel?: string
|
||||
pendingLabel?: string
|
||||
}
|
||||
|
||||
export function RestartServerDialog({
|
||||
@@ -16,30 +21,37 @@ export function RestartServerDialog({
|
||||
onConfirm,
|
||||
onCancel,
|
||||
isRestarting = false,
|
||||
activeSessionCount,
|
||||
title = 'Restart OpenCode Server?',
|
||||
description,
|
||||
confirmLabel = 'Restart now',
|
||||
pendingLabel = 'Restarting...',
|
||||
}: RestartServerDialogProps) {
|
||||
const isConfirmDisabled = isRestarting
|
||||
const defaultDescription = activeSessionCount && activeSessionCount > 0
|
||||
? `${activeSessionCount} session${activeSessionCount === 1 ? '' : 's'} ${activeSessionCount === 1 ? 'is' : 'are'} currently working. Restarting will interrupt ${activeSessionCount === 1 ? 'it' : 'them'} and send "continue" to resume after the server is healthy.`
|
||||
: 'Restart the OpenCode server after your changes are saved to apply them to the running server.'
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-[90%] sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Restart OpenCode Server?</DialogTitle>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Restart the OpenCode server after your changes are saved to apply them to the running server.
|
||||
{description ?? defaultDescription}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="outline" onClick={onCancel} disabled={isRestarting}>
|
||||
Later
|
||||
</Button>
|
||||
<Button onClick={onConfirm} disabled={isConfirmDisabled}>
|
||||
<Button onClick={onConfirm} disabled={isRestarting}>
|
||||
{isRestarting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
|
||||
Restarting...
|
||||
{pendingLabel}
|
||||
</>
|
||||
) : (
|
||||
'Restart now'
|
||||
confirmLabel
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -4,65 +4,34 @@ import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Loader2, ArrowUpCircle, RotateCcw, History } from 'lucide-react'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useManagerUpgrade } from '@/hooks/useManagerUpgrade'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { RestartServerDialog } from './RestartServerDialog'
|
||||
|
||||
interface ServerHealthStatusProps {
|
||||
onOpenVersionDialog?: () => void
|
||||
}
|
||||
|
||||
export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: health } = useServerHealth()
|
||||
const { isSupported, startUpgrade, isUpgrading, status } = useManagerUpgrade()
|
||||
|
||||
const restartServerMutation = useMutation({
|
||||
mutationFn: async () => settingsApi.restartOpenCodeServer(),
|
||||
onSuccess: () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
|
||||
const upgradeOpenCodeMutation = useMutation({
|
||||
mutationFn: async () => settingsApi.upgradeOpenCode(),
|
||||
onSuccess: (data) => {
|
||||
if (data.upgraded && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
if (data.upgraded) {
|
||||
showToast.success(`Upgraded to v${data.newVersion} and server restarted`, { id: 'upgrade-opencode' })
|
||||
} else {
|
||||
showToast.success('OpenCode is already up to date', { id: 'upgrade-opencode' })
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
const defaultMessage = 'Failed to upgrade OpenCode'
|
||||
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = (error as { response?: { data?: { recovered?: boolean; recoveryMessage?: string; newVersion?: string } } }).response
|
||||
const data = response?.data
|
||||
|
||||
if (data?.recovered && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
showToast.success(`Upgrade failed but server recovered at v${data.newVersion}`, { id: 'upgrade-opencode' })
|
||||
} else {
|
||||
showToast.error(data?.recoveryMessage || defaultMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
} else {
|
||||
showToast.error(defaultMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
const {
|
||||
isSupported,
|
||||
requestUpgrade,
|
||||
confirmUpgrade,
|
||||
confirmOpen: upgradeConfirmOpen,
|
||||
setConfirmOpen: setUpgradeConfirmOpen,
|
||||
activeSessionCount: upgradeActiveSessionCount,
|
||||
isUpgrading,
|
||||
} = useManagerUpgrade()
|
||||
const {
|
||||
restartServerMutation,
|
||||
upgradeOpenCodeMutation,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
performUpgrade,
|
||||
} = useOpenCodeServerActions()
|
||||
|
||||
if (!health) {
|
||||
return (
|
||||
@@ -108,19 +77,7 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
showToast.loading('Upgrading OpenCode...', { id: 'upgrade-opencode' })
|
||||
try {
|
||||
await upgradeOpenCodeMutation.mutateAsync()
|
||||
} catch (error) {
|
||||
const errorMessage = error && typeof error === 'object' && 'response' in error
|
||||
? ((error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.details
|
||||
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|
||||
|| 'Failed to upgrade OpenCode')
|
||||
: 'Failed to upgrade OpenCode'
|
||||
showToast.error(errorMessage, { id: 'upgrade-opencode' })
|
||||
}
|
||||
}}
|
||||
onClick={performUpgrade}
|
||||
disabled={upgradeOpenCodeMutation.isPending}
|
||||
>
|
||||
{upgradeOpenCodeMutation.isPending ? (
|
||||
@@ -133,20 +90,7 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
showToast.loading('Restarting OpenCode server...', { id: 'manual-restart' })
|
||||
try {
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Server restarted successfully', { id: 'manual-restart' })
|
||||
} catch (error) {
|
||||
const errorMessage = error && typeof error === 'object' && 'response' in error
|
||||
? ((error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.details
|
||||
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|
||||
|| 'Failed to restart OpenCode server')
|
||||
: 'Failed to restart OpenCode server'
|
||||
showToast.error(errorMessage, { id: 'manual-restart' })
|
||||
}
|
||||
}}
|
||||
onClick={requestRestart}
|
||||
disabled={restartServerMutation.isPending}
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
@@ -168,22 +112,10 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
showToast.loading('Upgrading Manager — the app will restart…', { id: 'upgrade-manager' })
|
||||
try {
|
||||
await startUpgrade()
|
||||
} catch (error) {
|
||||
const errorMessage = error && typeof error === 'object' && 'response' in error
|
||||
? ((error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.details
|
||||
|| (error as { response?: { data?: { details?: string; error?: string } } }).response?.data?.error
|
||||
|| 'Failed to upgrade Manager')
|
||||
: 'Failed to upgrade Manager'
|
||||
showToast.error(errorMessage, { id: 'upgrade-manager' })
|
||||
}
|
||||
}}
|
||||
disabled={isUpgrading || status?.job?.status === 'recreating'}
|
||||
onClick={requestUpgrade}
|
||||
disabled={isUpgrading}
|
||||
>
|
||||
{isUpgrading || status?.job?.status === 'recreating' ? (
|
||||
{isUpgrading ? (
|
||||
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
|
||||
) : (
|
||||
<ArrowUpCircle className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
@@ -194,6 +126,25 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
<RestartServerDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
activeSessionCount={activeSessionCount}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
onConfirm={confirmRestart}
|
||||
/>
|
||||
<RestartServerDialog
|
||||
open={upgradeConfirmOpen}
|
||||
onOpenChange={setUpgradeConfirmOpen}
|
||||
isRestarting={isUpgrading}
|
||||
onCancel={() => setUpgradeConfirmOpen(false)}
|
||||
onConfirm={confirmUpgrade}
|
||||
title="Upgrade Manager?"
|
||||
description={`${upgradeActiveSessionCount} session${upgradeActiveSessionCount === 1 ? ' is' : 's are'} currently working. Upgrading recreates the container and will interrupt ${upgradeActiveSessionCount === 1 ? 'it' : 'them'}.`}
|
||||
confirmLabel="Upgrade now"
|
||||
pendingLabel="Upgrading..."
|
||||
/>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -130,31 +130,6 @@ describe("DialogContent", () => {
|
||||
expect(screen.queryByRole("button", { name: /close/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("merges custom className with default classes", () => {
|
||||
render(
|
||||
<Dialog open>
|
||||
<DialogContent className="custom-class" data-testid="dialog-content">
|
||||
Content
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
const content = screen.getByTestId("dialog-content");
|
||||
expect(content).toHaveClass("custom-class");
|
||||
expect(content).toHaveClass("fixed");
|
||||
expect(content).toHaveClass("z-[70]");
|
||||
});
|
||||
|
||||
it("renders children correctly", () => {
|
||||
render(
|
||||
<Dialog open>
|
||||
<DialogContent>
|
||||
<span>Test Child Content</span>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
expect(screen.getByText("Test Child Content")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("accepts mobileSwipeToClose prop without breaking rendering", () => {
|
||||
const onOpenChange = vi.fn();
|
||||
render(
|
||||
|
||||
@@ -3,19 +3,6 @@ import { render, screen } from "@testing-library/react";
|
||||
import { PageHeader } from "./page-header";
|
||||
|
||||
describe("PageHeader", () => {
|
||||
it("applies pt-safe class for iOS safe area", () => {
|
||||
render(<PageHeader data-testid="header">Content</PageHeader>);
|
||||
const header = screen.getByTestId("header");
|
||||
expect(header).toHaveClass("pt-safe");
|
||||
});
|
||||
|
||||
it("applies sticky top-0 positioning", () => {
|
||||
render(<PageHeader data-testid="header">Content</PageHeader>);
|
||||
const header = screen.getByTestId("header");
|
||||
expect(header).toHaveClass("sticky");
|
||||
expect(header).toHaveClass("top-0");
|
||||
});
|
||||
|
||||
it("renders children correctly", () => {
|
||||
render(
|
||||
<PageHeader>
|
||||
@@ -24,37 +11,4 @@ describe("PageHeader", () => {
|
||||
);
|
||||
expect(screen.getByText("Test Child")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("merges custom className", () => {
|
||||
render(
|
||||
<PageHeader data-testid="header" className="custom-class">
|
||||
Content
|
||||
</PageHeader>
|
||||
);
|
||||
const header = screen.getByTestId("header");
|
||||
expect(header).toHaveClass("custom-class");
|
||||
expect(header).toHaveClass("pt-safe");
|
||||
});
|
||||
|
||||
it("forwards additional props", () => {
|
||||
render(
|
||||
<PageHeader data-testid="header" aria-label="Page header">
|
||||
Content
|
||||
</PageHeader>
|
||||
);
|
||||
const header = screen.getByTestId("header");
|
||||
expect(header).toHaveAttribute("aria-label", "Page header");
|
||||
});
|
||||
|
||||
it("applies z-10 for proper stacking", () => {
|
||||
render(<PageHeader data-testid="header">Content</PageHeader>);
|
||||
const header = screen.getByTestId("header");
|
||||
expect(header).toHaveClass("z-10");
|
||||
});
|
||||
|
||||
it("applies transparent background", () => {
|
||||
render(<PageHeader data-testid="header">Content</PageHeader>);
|
||||
const header = screen.getByTestId("header");
|
||||
expect(header).toHaveClass("bg-transparent");
|
||||
});
|
||||
});
|
||||
@@ -48,46 +48,6 @@ describe('SideDrawer', () => {
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('applies pt-safe and pb-safe classes', () => {
|
||||
render(
|
||||
<SideDrawer isOpen onClose={() => {}} ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog).toHaveClass('pt-safe')
|
||||
expect(dialog).toHaveClass('pb-safe')
|
||||
})
|
||||
|
||||
it('defaults to right side', () => {
|
||||
render(
|
||||
<SideDrawer isOpen onClose={() => {}} ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog).toHaveClass('right-0')
|
||||
})
|
||||
|
||||
it('applies left side when specified', () => {
|
||||
render(
|
||||
<SideDrawer isOpen onClose={() => {}} side="left" ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog).toHaveClass('left-0')
|
||||
})
|
||||
|
||||
it('applies custom widthClass', () => {
|
||||
render(
|
||||
<SideDrawer isOpen onClose={() => {}} widthClass="w-80" ariaLabel="Test drawer">
|
||||
<div>Test content</div>
|
||||
</SideDrawer>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
expect(dialog).toHaveClass('w-80')
|
||||
})
|
||||
})
|
||||
|
||||
describe('SideDrawerHeader', () => {
|
||||
@@ -119,14 +79,4 @@ describe('SideDrawerContent', () => {
|
||||
)
|
||||
expect(screen.getByText('Content')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('applies custom className', () => {
|
||||
render(
|
||||
<SideDrawerContent className="custom-class">
|
||||
<div>Content</div>
|
||||
</SideDrawerContent>,
|
||||
)
|
||||
const content = screen.getByText('Content').parentElement
|
||||
expect(content).toHaveClass('custom-class')
|
||||
})
|
||||
})
|
||||
@@ -2,17 +2,27 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { useManagerUpgrade } from '../useManagerUpgrade'
|
||||
import type { ManagerUpgradeStatus } from '@/api/settings'
|
||||
import type { ManagerUpgradeStatusResponse } from '@/api/settings'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getManagerUpgradeStatus: vi.fn(),
|
||||
startManagerUpgrade: vi.fn(),
|
||||
getActiveOpenCodeSessions: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
getManagerUpgradeStatus: mocks.getManagerUpgradeStatus,
|
||||
startManagerUpgrade: mocks.startManagerUpgrade,
|
||||
getActiveOpenCodeSessions: mocks.getActiveOpenCodeSessions,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: {
|
||||
loading: vi.fn(),
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -28,20 +38,26 @@ function createWrapper() {
|
||||
)
|
||||
}
|
||||
|
||||
function makeStatus(overrides: Partial<ManagerUpgradeStatusResponse> = {}): ManagerUpgradeStatusResponse {
|
||||
return {
|
||||
supported: true,
|
||||
inDocker: true,
|
||||
socketAvailable: true,
|
||||
enabled: true,
|
||||
currentVersion: '1.0.0',
|
||||
job: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('useManagerUpgrade', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.getActiveOpenCodeSessions.mockResolvedValue({ count: 0, sessions: [] })
|
||||
})
|
||||
|
||||
it('isSupported should be false when getManagerUpgradeStatus returns supported: false', async () => {
|
||||
const status: ManagerUpgradeStatus = {
|
||||
supported: false,
|
||||
inDocker: true,
|
||||
socketAvailable: true,
|
||||
enabled: false,
|
||||
currentVersion: null,
|
||||
job: null,
|
||||
}
|
||||
const status = makeStatus({ supported: false, enabled: false, currentVersion: null })
|
||||
mocks.getManagerUpgradeStatus.mockResolvedValue(status)
|
||||
|
||||
const { result } = renderHook(() => useManagerUpgrade(), {
|
||||
@@ -56,15 +72,7 @@ describe('useManagerUpgrade', () => {
|
||||
})
|
||||
|
||||
it('isSupported should be true when getManagerUpgradeStatus returns supported: true', async () => {
|
||||
const status: ManagerUpgradeStatus = {
|
||||
supported: true,
|
||||
inDocker: true,
|
||||
socketAvailable: true,
|
||||
enabled: true,
|
||||
currentVersion: '1.0.0',
|
||||
job: null,
|
||||
}
|
||||
mocks.getManagerUpgradeStatus.mockResolvedValue(status)
|
||||
mocks.getManagerUpgradeStatus.mockResolvedValue(makeStatus())
|
||||
|
||||
const { result } = renderHook(() => useManagerUpgrade(), {
|
||||
wrapper: createWrapper(),
|
||||
@@ -75,17 +83,9 @@ describe('useManagerUpgrade', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('startUpgrade should call settingsApi.startManagerUpgrade', async () => {
|
||||
const status: ManagerUpgradeStatus = {
|
||||
supported: true,
|
||||
inDocker: true,
|
||||
socketAvailable: true,
|
||||
enabled: true,
|
||||
currentVersion: '1.0.0',
|
||||
job: null,
|
||||
}
|
||||
mocks.getManagerUpgradeStatus.mockResolvedValue(status)
|
||||
mocks.startManagerUpgrade.mockResolvedValue({ job: { id: 1, status: 'pending', fromVersion: '1.0.0', toVersion: 'latest', targetImage: null, error: null, startedAt: Date.now(), finishedAt: null } })
|
||||
it('requestUpgrade starts the upgrade immediately when no sessions are active', async () => {
|
||||
mocks.getManagerUpgradeStatus.mockResolvedValue(makeStatus())
|
||||
mocks.startManagerUpgrade.mockResolvedValue({ job: { id: 1, status: 'pulling', fromVersion: '1.0.0', toVersion: 'latest', targetImage: null, error: null, startedAt: Date.now(), finishedAt: null } })
|
||||
|
||||
const { result } = renderHook(() => useManagerUpgrade(), {
|
||||
wrapper: createWrapper(),
|
||||
@@ -95,8 +95,50 @@ describe('useManagerUpgrade', () => {
|
||||
expect(result.current.isSupported).toBe(true)
|
||||
})
|
||||
|
||||
await result.current.startUpgrade()
|
||||
await result.current.requestUpgrade()
|
||||
|
||||
expect(mocks.startManagerUpgrade).toHaveBeenCalledTimes(1)
|
||||
expect(result.current.confirmOpen).toBe(false)
|
||||
})
|
||||
|
||||
it('requestUpgrade opens the confirmation dialog instead of upgrading when sessions are active', async () => {
|
||||
mocks.getManagerUpgradeStatus.mockResolvedValue(makeStatus())
|
||||
mocks.getActiveOpenCodeSessions.mockResolvedValue({ count: 2, sessions: [] })
|
||||
|
||||
const { result } = renderHook(() => useManagerUpgrade(), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSupported).toBe(true)
|
||||
})
|
||||
|
||||
await result.current.requestUpgrade()
|
||||
|
||||
expect(mocks.startManagerUpgrade).not.toHaveBeenCalled()
|
||||
await waitFor(() => {
|
||||
expect(result.current.confirmOpen).toBe(true)
|
||||
})
|
||||
expect(result.current.activeSessionCount).toBe(2)
|
||||
})
|
||||
|
||||
it('confirmUpgrade closes the dialog and starts the upgrade', async () => {
|
||||
mocks.getManagerUpgradeStatus.mockResolvedValue(makeStatus())
|
||||
mocks.startManagerUpgrade.mockResolvedValue({ job: { id: 1, status: 'pulling', fromVersion: '1.0.0', toVersion: 'latest', targetImage: null, error: null, startedAt: Date.now(), finishedAt: null } })
|
||||
|
||||
const { result } = renderHook(() => useManagerUpgrade(), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSupported).toBe(true)
|
||||
})
|
||||
|
||||
await result.current.confirmUpgrade()
|
||||
|
||||
expect(mocks.startManagerUpgrade).toHaveBeenCalledTimes(1)
|
||||
await waitFor(() => {
|
||||
expect(result.current.confirmOpen).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -52,9 +52,6 @@ describe('useScheduleTarget', () => {
|
||||
})
|
||||
|
||||
expect(result.current.scheduleTarget?.kind).toBe('assistant')
|
||||
expect(result.current.scheduleTarget?.fullPath).toBe('/abs/assistant')
|
||||
expect(result.current.scheduleTarget?.repoId).toBe(0)
|
||||
expect(result.current.scheduleTarget?.backHref).toBe('/assistant')
|
||||
expect(result.current.isLoading).toBe(false)
|
||||
expect(result.current.isError).toBe(false)
|
||||
})
|
||||
@@ -98,9 +95,6 @@ describe('useScheduleTarget', () => {
|
||||
})
|
||||
|
||||
expect(result.current.scheduleTarget?.kind).toBe('repo')
|
||||
expect(result.current.scheduleTarget?.repoId).toBe(5)
|
||||
expect(result.current.scheduleTarget?.fullPath).toBe('/abs/repos/my-repo')
|
||||
expect(result.current.scheduleTarget?.backHref).toBe('/repos/5')
|
||||
})
|
||||
|
||||
it('does not call getAssistantModeStatus for repo', async () => {
|
||||
|
||||
@@ -137,52 +137,6 @@ describe('useLSPStatus', () => {
|
||||
expect(result.current.error).toBeTruthy()
|
||||
})
|
||||
|
||||
it('should have 30s refetch interval', async () => {
|
||||
mockGetLSPStatus.mockResolvedValue([])
|
||||
vi.mocked(useOpenCodeClient).mockReturnValue(mockClient)
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } }
|
||||
})
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
const { result } = renderHook(() => useLSPStatus('http://localhost:5551', '/test'), {
|
||||
wrapper
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true)
|
||||
})
|
||||
|
||||
const observer = queryClient.getQueryCache().find({ queryKey: ['opencode', 'lsp', 'http://localhost:5551', '/test'] })
|
||||
expect((observer?.options as any).refetchInterval).toBe(30000)
|
||||
})
|
||||
|
||||
it('should have 10s stale time', async () => {
|
||||
mockGetLSPStatus.mockResolvedValue([])
|
||||
vi.mocked(useOpenCodeClient).mockReturnValue(mockClient)
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } }
|
||||
})
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
const { result } = renderHook(() => useLSPStatus('http://localhost:5551', '/test'), {
|
||||
wrapper
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true)
|
||||
})
|
||||
|
||||
const observer = queryClient.getQueryCache().find({ queryKey: ['opencode', 'lsp', 'http://localhost:5551', '/test'] })
|
||||
expect((observer?.options as any).staleTime).toBe(10000)
|
||||
})
|
||||
|
||||
it('should refetch on window focus', async () => {
|
||||
mockGetLSPStatus.mockResolvedValue([])
|
||||
vi.mocked(useOpenCodeClient).mockReturnValue(mockClient)
|
||||
|
||||
@@ -1,8 +1,22 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
|
||||
const UPGRADE_TOAST_ID = 'upgrade-manager'
|
||||
|
||||
/**
|
||||
* Manager self-upgrade state shared by the settings surfaces. `requestUpgrade`
|
||||
* first checks for active OpenCode sessions and opens a confirmation dialog
|
||||
* when any would be interrupted by the container recreate. The upgrade itself
|
||||
* runs in the background on the server; progress and terminal states are
|
||||
* surfaced through the polled job status.
|
||||
*/
|
||||
export function useManagerUpgrade() {
|
||||
const queryClient = useQueryClient()
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [activeSessionCount, setActiveSessionCount] = useState(0)
|
||||
|
||||
const { data: status } = useQuery({
|
||||
queryKey: ['manager-upgrade-status'],
|
||||
@@ -20,10 +34,55 @@ export function useManagerUpgrade() {
|
||||
},
|
||||
})
|
||||
|
||||
const job = status?.job
|
||||
const prevJobStatusRef = useRef(job?.status)
|
||||
useEffect(() => {
|
||||
const prev = prevJobStatusRef.current
|
||||
prevJobStatusRef.current = job?.status
|
||||
if (prev === undefined || prev === job?.status) return
|
||||
if (job?.status === 'failed') {
|
||||
showToast.error(job.error || 'Manager upgrade failed', { id: UPGRADE_TOAST_ID })
|
||||
} else if (job?.status === 'completed') {
|
||||
showToast.success('Manager upgraded successfully', { id: UPGRADE_TOAST_ID })
|
||||
}
|
||||
}, [job?.status, job?.error])
|
||||
|
||||
const performUpgrade = async () => {
|
||||
showToast.loading('Upgrading Manager — the app will restart…', { id: UPGRADE_TOAST_ID })
|
||||
try {
|
||||
await mutation.mutateAsync()
|
||||
} catch (error) {
|
||||
showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to upgrade Manager'), { id: UPGRADE_TOAST_ID })
|
||||
}
|
||||
}
|
||||
|
||||
const requestUpgrade = async () => {
|
||||
try {
|
||||
const { count } = await settingsApi.getActiveOpenCodeSessions()
|
||||
if (count > 0) {
|
||||
setActiveSessionCount(count)
|
||||
setConfirmOpen(true)
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Fall through to an immediate upgrade when the active-session probe fails.
|
||||
}
|
||||
await performUpgrade()
|
||||
}
|
||||
|
||||
const confirmUpgrade = async () => {
|
||||
setConfirmOpen(false)
|
||||
await performUpgrade()
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
isSupported: status?.supported ?? false,
|
||||
startUpgrade: mutation.mutateAsync,
|
||||
isUpgrading: mutation.isPending,
|
||||
requestUpgrade,
|
||||
confirmUpgrade,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
isUpgrading: mutation.isPending || job?.status === 'pulling' || job?.status === 'recreating',
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,10 @@ import { useSendErrorStore } from "../stores/sendErrorStore";
|
||||
import { useSessionStatus } from "../stores/sessionStatusStore";
|
||||
import { invalidateSessionListCaches, messagesQueryKey } from "../lib/queryInvalidation";
|
||||
import { reconcileConfirmedPrompt } from "../lib/sendErrorReconcile";
|
||||
import { buildSessionKey } from "../lib/sessionKey";
|
||||
import { toggleSessionPin } from "../api/sessionPins";
|
||||
import { SESSION_PINS_QUERY_KEY } from "./useSessionPins";
|
||||
import type { SessionPin } from "@opencode-manager/shared/schemas";
|
||||
|
||||
type AssistantMessage = components["schemas"]["AssistantMessage"];
|
||||
|
||||
@@ -200,7 +204,7 @@ const getDeleteSessionTargetWorkspaceID = (target: DeleteSessionTarget) =>
|
||||
typeof target === 'string' ? undefined : target.workspaceID;
|
||||
|
||||
const getDeleteSessionTargetKey = (target: DeleteSessionTarget, fallbackDirectory?: string) =>
|
||||
`${getDeleteSessionTargetDirectory(target, fallbackDirectory) ?? ''}:${getDeleteSessionTargetId(target)}`;
|
||||
buildSessionKey(getDeleteSessionTargetDirectory(target, fallbackDirectory), getDeleteSessionTargetId(target));
|
||||
|
||||
const isMissingWorkspaceError = (error: unknown) =>
|
||||
error instanceof Error && error.message.includes('Workspace not found:');
|
||||
@@ -279,12 +283,35 @@ export const useDeleteSession = (opcodeUrl: string | null | undefined, directory
|
||||
onError: () => {
|
||||
showToast.error('Failed to delete sessions');
|
||||
},
|
||||
onSettled: () => {
|
||||
onSettled: (_data, _error, variables) => {
|
||||
invalidateSessionListCaches(queryClient, opcodeUrl);
|
||||
cleanupSessionPins(queryClient, variables, primaryDirectory);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const cleanupSessionPins = (
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
variables: DeleteSessionTarget | DeleteSessionTarget[],
|
||||
primaryDirectory?: string,
|
||||
) => {
|
||||
const pins = queryClient.getQueryData<SessionPin[]>(SESSION_PINS_QUERY_KEY) ?? [];
|
||||
if (pins.length === 0) return;
|
||||
const pinnedKeys = new Set(pins.map((p) => buildSessionKey(p.directory, p.sessionId)));
|
||||
const targets = (Array.isArray(variables) ? variables : [variables])
|
||||
.map((target) => ({
|
||||
sessionId: getDeleteSessionTargetId(target),
|
||||
directory: getDeleteSessionTargetDirectory(target, primaryDirectory) ?? '',
|
||||
}))
|
||||
.filter((target) => pinnedKeys.has(buildSessionKey(target.directory, target.sessionId)));
|
||||
if (targets.length === 0) return;
|
||||
void Promise.allSettled(
|
||||
targets.map((target) => toggleSessionPin({ ...target, pinned: false })),
|
||||
).then(() => {
|
||||
void queryClient.invalidateQueries({ queryKey: SESSION_PINS_QUERY_KEY });
|
||||
});
|
||||
};
|
||||
|
||||
export const useUpdateSession = (opcodeUrl: string | null | undefined, directory?: string) => {
|
||||
const queryClient = useQueryClient();
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
|
||||
const RESTART_TOAST_ID = 'opencode-restart'
|
||||
const UPGRADE_TOAST_ID = 'upgrade-opencode'
|
||||
|
||||
/**
|
||||
* Centralizes OpenCode server restart/upgrade actions shared by the settings
|
||||
* surfaces. A restart always routes through `POST /opencode-restart`, which
|
||||
* aborts and resumes in-flight sessions; `requestRestart` first checks for
|
||||
* active sessions and opens a confirmation dialog when any would be interrupted.
|
||||
*/
|
||||
export function useOpenCodeServerActions() {
|
||||
const queryClient = useQueryClient()
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [activeSessionCount, setActiveSessionCount] = useState(0)
|
||||
|
||||
const restartServerMutation = useMutation({
|
||||
mutationFn: async () => settingsApi.restartOpenCodeServer(),
|
||||
onSuccess: () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
|
||||
const upgradeOpenCodeMutation = useMutation({
|
||||
mutationFn: async () => settingsApi.upgradeOpenCode(),
|
||||
onSuccess: (data) => {
|
||||
if (data.upgraded && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
if (data.upgraded) {
|
||||
showToast.success(`Upgraded to v${data.newVersion} and server restarted`, { id: UPGRADE_TOAST_ID })
|
||||
} else {
|
||||
showToast.success('OpenCode is already up to date', { id: UPGRADE_TOAST_ID })
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
const defaultMessage = 'Failed to upgrade OpenCode'
|
||||
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = (error as { response?: { data?: { recovered?: boolean; recoveryMessage?: string; newVersion?: string } } }).response
|
||||
const data = response?.data
|
||||
|
||||
if (data?.recovered && data.newVersion) {
|
||||
queryClient.setQueryData(['health'], (old: Record<string, unknown> | undefined) => {
|
||||
if (!old) return old
|
||||
return { ...old, opencodeVersion: data.newVersion }
|
||||
})
|
||||
showToast.success(`Upgrade failed but server recovered at v${data.newVersion}`, { id: UPGRADE_TOAST_ID })
|
||||
} else {
|
||||
showToast.error(data?.recoveryMessage || defaultMessage, { id: UPGRADE_TOAST_ID })
|
||||
}
|
||||
} else {
|
||||
showToast.error(defaultMessage, { id: UPGRADE_TOAST_ID })
|
||||
}
|
||||
invalidateConfigCaches(queryClient)
|
||||
},
|
||||
})
|
||||
|
||||
const performRestart = async () => {
|
||||
showToast.loading('Restarting OpenCode server...', { id: RESTART_TOAST_ID })
|
||||
try {
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Server restarted successfully', { id: RESTART_TOAST_ID })
|
||||
} catch (error) {
|
||||
showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to restart OpenCode server'), { id: RESTART_TOAST_ID })
|
||||
}
|
||||
}
|
||||
|
||||
const requestRestart = async () => {
|
||||
try {
|
||||
const { count } = await settingsApi.getActiveOpenCodeSessions()
|
||||
if (count > 0) {
|
||||
setActiveSessionCount(count)
|
||||
setConfirmOpen(true)
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Fall through to an immediate restart when the active-session probe fails.
|
||||
}
|
||||
await performRestart()
|
||||
}
|
||||
|
||||
const confirmRestart = async () => {
|
||||
await performRestart()
|
||||
setConfirmOpen(false)
|
||||
}
|
||||
|
||||
const performUpgrade = async () => {
|
||||
showToast.loading('Upgrading OpenCode...', { id: UPGRADE_TOAST_ID })
|
||||
try {
|
||||
await upgradeOpenCodeMutation.mutateAsync()
|
||||
} catch (error) {
|
||||
showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to upgrade OpenCode'), { id: UPGRADE_TOAST_ID })
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
restartServerMutation,
|
||||
upgradeOpenCodeMutation,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
performUpgrade,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { listSessionPins, toggleSessionPin } from '@/api/sessionPins'
|
||||
import type { SessionPin, ToggleSessionPinRequest } from '@opencode-manager/shared/schemas'
|
||||
|
||||
export const SESSION_PINS_QUERY_KEY = ['session-pins'] as const
|
||||
|
||||
export function useSessionPins() {
|
||||
return useQuery({
|
||||
queryKey: SESSION_PINS_QUERY_KEY,
|
||||
queryFn: listSessionPins,
|
||||
staleTime: 30000,
|
||||
})
|
||||
}
|
||||
|
||||
export function useToggleSessionPin() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (input: ToggleSessionPinRequest) => toggleSessionPin(input),
|
||||
onSuccess: (pins: SessionPin[]) => {
|
||||
queryClient.setQueryData(SESSION_PINS_QUERY_KEY, pins)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -137,3 +137,49 @@ export function getErrorMessage(error: OpenCodeError | undefined | null): string
|
||||
const parsed = parseOpenCodeError(error)
|
||||
return parsed ? `${parsed.title}: ${parsed.message}` : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a human-readable message from a Manager REST API error, handling
|
||||
* both {@link FetchError} and axios-style `{ response: { data } }` shapes,
|
||||
* including OpenCode config validation issues and removed fields.
|
||||
*/
|
||||
export function getOpenCodeApiErrorMessage(error: unknown, fallback: string): string {
|
||||
if (error instanceof FetchError) {
|
||||
let message = error.detail || error.message || fallback
|
||||
|
||||
if (error.validationIssues && error.validationIssues.length > 0) {
|
||||
const issues = error.validationIssues
|
||||
.map((issue) => `${issue.path}: ${issue.message}`)
|
||||
.join('; ')
|
||||
message = `Validation failed: ${issues}`
|
||||
}
|
||||
|
||||
if (error.removedFields && error.removedFields.length > 0) {
|
||||
message += ` (removed invalid fields: ${error.removedFields.join(', ')})`
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = (error as { response?: { data?: { details?: string; error?: string; validationIssues?: Array<{ path: string; message: string }>; removedFields?: string[] } } }).response
|
||||
const data = response?.data
|
||||
|
||||
let message = data?.details || data?.error || fallback
|
||||
|
||||
if (data?.validationIssues && data.validationIssues.length > 0) {
|
||||
const issues = data.validationIssues
|
||||
.map((issue) => `${issue.path}: ${issue.message}`)
|
||||
.join('; ')
|
||||
message = `Validation failed: ${issues}`
|
||||
}
|
||||
|
||||
if (data?.removedFields && data.removedFields.length > 0) {
|
||||
message += ` (removed invalid fields: ${data.removedFields.join(', ')})`
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function buildSessionKey(directory: string | undefined, id: string): string {
|
||||
return `${directory ?? ''}:${id}`
|
||||
}
|
||||
@@ -264,10 +264,10 @@ describe('SessionDetail assistant loading at repoId=0', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('renders "Assistant" as workspaceDisplayName for non-assistant sessions without repo', async () => {
|
||||
it('shows the loading state for a non-assistant session whose repo has not loaded', async () => {
|
||||
mocks.useSession.mockReturnValue({ data: undefined, isLoading: false })
|
||||
|
||||
return render(
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/repos/1/sessions/sess-1']}>
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
<Routes>
|
||||
@@ -276,5 +276,9 @@ describe('SessionDetail assistant loading at repoId=0', () => {
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Loading repository...')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,92 +1,248 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { render, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider, type Query } from '@tanstack/react-query'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import { SessionDetail } from '../SessionDetail'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
syncPendingActions: vi.fn(),
|
||||
useSession: vi.fn(),
|
||||
useMessages: vi.fn(),
|
||||
useSSE: vi.fn(),
|
||||
useRepoActivity: vi.fn(),
|
||||
usePermissions: vi.fn(),
|
||||
useQuestions: vi.fn(),
|
||||
useSSEHealth: vi.fn(),
|
||||
useConfig: vi.fn(),
|
||||
useOpenCodeClient: vi.fn(),
|
||||
useSettings: vi.fn(),
|
||||
useSettingsDialog: vi.fn(),
|
||||
useMobile: vi.fn(),
|
||||
useVisualViewport: vi.fn(),
|
||||
useKeyboardShortcuts: vi.fn(),
|
||||
useAutoScroll: vi.fn(),
|
||||
useDialogParam: vi.fn(),
|
||||
useSidebarAction: vi.fn(),
|
||||
useSessionStatusForSession: vi.fn(),
|
||||
syncPermissionsForSession: vi.fn(),
|
||||
syncQuestionsForSession: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('SessionDetail pending-actions polling', () => {
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useSession: mocks.useSession,
|
||||
useAbortSession: vi.fn(() => ({ mutate: vi.fn() })),
|
||||
useUpdateSession: vi.fn(() => ({ mutate: vi.fn() })),
|
||||
useCreateSession: vi.fn(() => ({ mutateAsync: vi.fn() })),
|
||||
useMessages: mocks.useMessages,
|
||||
useConfig: mocks.useConfig,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useModelSelection', () => ({
|
||||
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCodeClient', () => ({
|
||||
useOpenCodeClient: mocks.useOpenCodeClient,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useTTS', () => ({
|
||||
useTTS: vi.fn(() => ({ isEnabled: false })),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettings', () => ({
|
||||
useSettings: vi.fn(() => ({
|
||||
preferences: { expandToolCalls: false },
|
||||
updateSettings: vi.fn(),
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettingsDialog', () => ({
|
||||
useSettingsDialog: vi.fn(() => ({ open: vi.fn() })),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: vi.fn(() => false),
|
||||
useSwipeBack: vi.fn(() => ({ ref: vi.fn() })),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useVisualViewport', () => ({
|
||||
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
|
||||
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useAutoScroll', () => ({
|
||||
useAutoScroll: vi.fn(() => ({ scrollToBottom: vi.fn() })),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useDialogParam', () => ({
|
||||
useDialogParam: vi.fn(() => [false, vi.fn()]),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSidebarAction', () => ({
|
||||
useSidebarAction: vi.fn(() => {}),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
|
||||
getAssistantText: vi.fn(() => ''),
|
||||
getLatestPlayableAssistantMessage: vi.fn(() => null),
|
||||
useAutoPlayLastResponse: vi.fn(() => {}),
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/uiStateStore', () => ({
|
||||
useUIState: vi.fn(() => vi.fn()),
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/sessionStatusStore', () => ({
|
||||
useSessionStatus: vi.fn(() => ({ setStatus: vi.fn() })),
|
||||
useSessionStatusForSession: mocks.useSessionStatusForSession,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSSE', () => ({
|
||||
useSSE: mocks.useSSE,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useRepoActivity', () => ({
|
||||
useRepoActivity: mocks.useRepoActivity,
|
||||
}))
|
||||
|
||||
vi.mock('@/contexts/EventContext', async (importOriginal) => {
|
||||
const actual = await importOriginal()
|
||||
return {
|
||||
...(actual as object),
|
||||
usePermissions: mocks.usePermissions,
|
||||
useQuestions: mocks.useQuestions,
|
||||
useSSEHealth: mocks.useSSEHealth,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
getRepo: vi.fn(() => Promise.resolve({
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo',
|
||||
localPath: '/test/repo',
|
||||
sourcePath: null,
|
||||
fullPath: '/test/repo',
|
||||
branch: 'main',
|
||||
currentBranch: 'main',
|
||||
fullSlug: 'test/repo',
|
||||
repoType: 'github' as const,
|
||||
})),
|
||||
initializeAssistantMode: vi.fn(() => Promise.resolve({ directory: '/test/repo' })),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/model/ModelSelectDialog', () => ({ ModelSelectDialog: vi.fn(() => null) }))
|
||||
vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) }))
|
||||
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
|
||||
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
|
||||
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null) }))
|
||||
vi.mock('@/components/repo/RepoLspDialog', () => ({ RepoLspDialog: vi.fn(() => null) }))
|
||||
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: vi.fn(() => null) }))
|
||||
vi.mock('@/components/source-control', () => ({ SourceControlPanel: vi.fn(() => null) }))
|
||||
vi.mock('@/components/session/QuestionPrompt', () => ({ QuestionPrompt: vi.fn(() => null) }))
|
||||
vi.mock('@/components/session/MinimizedQuestionIndicator', () => ({ MinimizedQuestionIndicator: vi.fn(() => null) }))
|
||||
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: vi.fn(() => null) }))
|
||||
|
||||
const findPendingActionsQuery = (queryClient: QueryClient): Query | undefined =>
|
||||
queryClient
|
||||
.getQueryCache()
|
||||
.getAll()
|
||||
.find((query) => query.queryKey[1] === 'pending-actions')
|
||||
|
||||
describe('SessionDetail pending-actions polling gating', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mocks.useSession.mockReturnValue({ data: undefined, isLoading: false })
|
||||
mocks.useMessages.mockReturnValue({ data: [], isLoading: false })
|
||||
mocks.useRepoActivity.mockReturnValue(undefined)
|
||||
mocks.usePermissions.mockReturnValue({
|
||||
pendingCount: 0,
|
||||
hasPermissionsForSession: vi.fn(() => false),
|
||||
syncForSession: mocks.syncPermissionsForSession,
|
||||
})
|
||||
mocks.useQuestions.mockReturnValue({
|
||||
current: null,
|
||||
pendingCount: 0,
|
||||
hasQuestionsForSession: vi.fn(() => false),
|
||||
reply: vi.fn(),
|
||||
reject: vi.fn(),
|
||||
syncForSession: mocks.syncQuestionsForSession,
|
||||
})
|
||||
mocks.useSSEHealth.mockReturnValue({ isHealthy: true })
|
||||
mocks.useConfig.mockReturnValue({ data: undefined, isLoading: false })
|
||||
mocks.useOpenCodeClient.mockReturnValue({})
|
||||
mocks.useSettings.mockReturnValue({
|
||||
preferences: { expandToolCalls: false },
|
||||
updateSettings: vi.fn(),
|
||||
})
|
||||
mocks.useSettingsDialog.mockReturnValue({ open: vi.fn() })
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
|
||||
mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
|
||||
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn() })
|
||||
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
|
||||
mocks.useSidebarAction.mockReturnValue(undefined)
|
||||
mocks.useSessionStatusForSession.mockReturnValue({ type: 'idle' })
|
||||
})
|
||||
|
||||
const createQueryClient = () => new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
const createQueryClient = () =>
|
||||
new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
it('should poll pending-actions when refetchInterval is set', async () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
mocks.syncPendingActions.mockResolvedValue(null)
|
||||
|
||||
const testQueryOptions = {
|
||||
queryKey: ['opencode', 'pending-actions', 'http://localhost:5003', 'session-1', '/repo'] as const,
|
||||
queryFn: async () => {
|
||||
await mocks.syncPendingActions()
|
||||
return null
|
||||
},
|
||||
enabled: true,
|
||||
refetchOnMount: 'always' as const,
|
||||
refetchOnReconnect: true,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchInterval: 30000,
|
||||
retry: false,
|
||||
}
|
||||
|
||||
renderHook(
|
||||
() => useQuery(testQueryOptions),
|
||||
{ wrapper }
|
||||
const renderSessionDetail = (queryClient: QueryClient) =>
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/repos/1/sessions/session-1']}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Routes>
|
||||
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
|
||||
</Routes>
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(1)
|
||||
it('polls on the sync interval when disconnected and the session is active', async () => {
|
||||
mocks.useSSE.mockReturnValue({ isConnected: false, isReconnecting: false })
|
||||
mocks.useSessionStatusForSession.mockReturnValue({ type: 'busy' })
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30000)
|
||||
const queryClient = createQueryClient()
|
||||
renderSessionDetail(queryClient)
|
||||
|
||||
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(2)
|
||||
await waitFor(() => {
|
||||
expect(findPendingActionsQuery(queryClient)).toBeDefined()
|
||||
})
|
||||
|
||||
vi.useRealTimers()
|
||||
const query = findPendingActionsQuery(queryClient)
|
||||
expect((query?.options as { refetchInterval?: unknown }).refetchInterval).toBe(30000)
|
||||
})
|
||||
|
||||
it('should not poll pending-actions when refetchInterval is false', async () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
mocks.syncPendingActions.mockResolvedValue(null)
|
||||
it('does not poll while the SSE stream is connected', async () => {
|
||||
mocks.useSSE.mockReturnValue({ isConnected: true, isReconnecting: false })
|
||||
mocks.useSessionStatusForSession.mockReturnValue({ type: 'busy' })
|
||||
|
||||
const testQueryOptions = {
|
||||
queryKey: ['opencode', 'pending-actions', 'http://localhost:5003', 'session-1', '/repo'] as const,
|
||||
queryFn: async () => {
|
||||
await mocks.syncPendingActions()
|
||||
return null
|
||||
},
|
||||
enabled: true,
|
||||
refetchOnMount: 'always' as const,
|
||||
refetchOnReconnect: true,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchInterval: false as const,
|
||||
retry: false,
|
||||
}
|
||||
const queryClient = createQueryClient()
|
||||
renderSessionDetail(queryClient)
|
||||
|
||||
renderHook(
|
||||
() => useQuery(testQueryOptions),
|
||||
{ wrapper }
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(findPendingActionsQuery(queryClient)).toBeDefined()
|
||||
})
|
||||
|
||||
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(1)
|
||||
const query = findPendingActionsQuery(queryClient)
|
||||
expect((query?.options as { refetchInterval?: unknown }).refetchInterval).toBe(false)
|
||||
})
|
||||
|
||||
await vi.advanceTimersByTimeAsync(60000)
|
||||
|
||||
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(1)
|
||||
it('does not poll when disconnected but the session is idle with no incomplete messages', async () => {
|
||||
mocks.useSSE.mockReturnValue({ isConnected: false, isReconnecting: false })
|
||||
mocks.useSessionStatusForSession.mockReturnValue({ type: 'idle' })
|
||||
|
||||
vi.useRealTimers()
|
||||
const queryClient = createQueryClient()
|
||||
renderSessionDetail(queryClient)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(findPendingActionsQuery(queryClient)).toBeDefined()
|
||||
})
|
||||
|
||||
const query = findPendingActionsQuery(queryClient)
|
||||
expect((query?.options as { refetchInterval?: unknown }).refetchInterval).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,65 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { SessionSendErrorBanner } from '@/components/session/SessionSendErrorBanner'
|
||||
import { useSendErrorStore } from '@/stores/sendErrorStore'
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { error: vi.fn() },
|
||||
}))
|
||||
|
||||
describe('SessionDetail send error integration', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
useSendErrorStore.setState({ errors: {} })
|
||||
})
|
||||
|
||||
it('shows error banner with title, message, and detail when store is seeded', () => {
|
||||
useSendErrorStore.getState().setError({
|
||||
sessionID: 'sess-1',
|
||||
title: 'Model Unavailable',
|
||||
message: 'Selected model is no longer available.',
|
||||
detail: '409 Conflict',
|
||||
})
|
||||
|
||||
render(<SessionSendErrorBanner sessionId="sess-1" />)
|
||||
|
||||
expect(screen.getByText('Model Unavailable')).toBeInTheDocument()
|
||||
expect(screen.getByText('Selected model is no longer available.')).toBeInTheDocument()
|
||||
expect(screen.getByText('409 Conflict')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('dismisses banner and clears store entry on click', () => {
|
||||
useSendErrorStore.getState().setError({
|
||||
sessionID: 'sess-2',
|
||||
title: 'Error',
|
||||
message: 'Something failed',
|
||||
})
|
||||
|
||||
render(<SessionSendErrorBanner sessionId="sess-2" />)
|
||||
expect(screen.getByText('Something failed')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button'))
|
||||
|
||||
expect(screen.queryByText('Something failed')).not.toBeInTheDocument()
|
||||
expect(useSendErrorStore.getState().getError('sess-2')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not trigger a toast error when banner renders', async () => {
|
||||
const { showToast } = await import('@/lib/toast')
|
||||
|
||||
useSendErrorStore.getState().setError({
|
||||
sessionID: 'sess-3',
|
||||
title: 'Error',
|
||||
message: 'No toast please',
|
||||
})
|
||||
|
||||
render(<SessionSendErrorBanner sessionId="sess-3" />)
|
||||
expect(screen.getByText('No toast please')).toBeInTheDocument()
|
||||
expect(showToast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not render banner when no error exists for session', () => {
|
||||
render(<SessionSendErrorBanner sessionId="sess-empty" />)
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import { useSessionTodos } from '@/stores/sessionTodosStore'
|
||||
@@ -239,40 +238,6 @@ describe('SessionDetail todo-header integration', () => {
|
||||
)
|
||||
}
|
||||
|
||||
it('renders SessionTodoDisplay collapsed by default inside SessionDetail header', async () => {
|
||||
useSessionTodos.getState().setTodos('session-1', activeTodos)
|
||||
|
||||
renderSessionDetail('session-1', 1)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
expect(screen.queryByText('Implement mobile header fix')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('expands todo list when clicked inside SessionDetail header', async () => {
|
||||
const user = userEvent.setup()
|
||||
useSessionTodos.getState().setTodos('session-1', activeTodos)
|
||||
|
||||
renderSessionDetail('session-1', 1)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const collapsedRow = screen.getByText('Tasks: 1/3 complete')
|
||||
await user.click(collapsedRow)
|
||||
|
||||
expect(screen.getByText('Implement mobile header fix')).toBeInTheDocument()
|
||||
expect(screen.getByText('Add regression tests')).toBeInTheDocument()
|
||||
|
||||
const expandedContainer = screen.getByTestId('todo-expanded-list')
|
||||
expect(expandedContainer).toHaveClass('max-h-[80px]')
|
||||
expect(expandedContainer).toHaveClass('sm:max-h-[160px]')
|
||||
expect(expandedContainer).toHaveClass('overflow-y-auto')
|
||||
})
|
||||
|
||||
it('header wrapper uses max-h-72 sm:max-h-80 and overflow-hidden for proper containment', async () => {
|
||||
useSessionTodos.getState().setTodos('session-1', activeTodos)
|
||||
|
||||
@@ -283,48 +248,10 @@ describe('SessionDetail todo-header integration', () => {
|
||||
})
|
||||
|
||||
const headerRegion = screen.getByTestId('session-header-region')
|
||||
|
||||
|
||||
expect(headerRegion.className).toContain('max-h-72')
|
||||
expect(headerRegion.className).toContain('sm:max-h-80')
|
||||
expect(headerRegion.className).toContain('overflow-hidden')
|
||||
expect(headerRegion.className).not.toContain('max-h-40')
|
||||
})
|
||||
|
||||
it('collapses todo list when expanded header is clicked again', async () => {
|
||||
const user = userEvent.setup()
|
||||
useSessionTodos.getState().setTodos('session-1', activeTodos)
|
||||
|
||||
renderSessionDetail('session-1', 1)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const collapsedRow = screen.getByText('Tasks: 1/3 complete')
|
||||
await user.click(collapsedRow)
|
||||
|
||||
expect(screen.getByTestId('todo-expanded-list')).toBeInTheDocument()
|
||||
|
||||
const expandedHeader = screen.getByText('Tasks: 1/3 complete')
|
||||
await user.click(expandedHeader)
|
||||
|
||||
expect(screen.queryByTestId('todo-expanded-list')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render SessionTodoDisplay when all tasks are completed', async () => {
|
||||
const allCompletedTodos: Todo[] = [
|
||||
{ id: '1', content: 'Task one', status: 'completed', priority: 'high' },
|
||||
{ id: '2', content: 'Task two', status: 'completed', priority: 'medium' },
|
||||
]
|
||||
useSessionTodos.getState().setTodos('session-1', allCompletedTodos)
|
||||
|
||||
renderSessionDetail('session-1', 1)
|
||||
|
||||
await waitFor(() => {
|
||||
const headerRegion = screen.getByTestId('session-header-region')
|
||||
expect(headerRegion).toBeInTheDocument()
|
||||
})
|
||||
|
||||
expect(screen.queryByText(/Tasks:/)).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user