mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
chore(lint): replace ESLint with Oxlint and clear anti-slop findings
This commit is contained in:
1 parent
c6c13335e5
commit
b625acfc0c
1083 files changed
+67089
-80136
No files matched your search
@@ -1,29 +1,16 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { act, render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { ReactNode } from 'react'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { act, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import type { SessionMessageAssistant, SessionMessageInfo } from '@opencode-manager/shared/opencode'
|
||||
import type { JsonObject } from '@opencode-manager/shared/utils'
|
||||
import type { ShellInfo } from '@/api/opencode'
|
||||
import { clearShellExitRecord, recordShellExit } from '@/lib/backgroundWork'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { BackgroundWorkBar } from './BackgroundWorkBar'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
import { makeSession } from '@/test/fixtures/api'
|
||||
import type { FetchRouteResult, RecordedFetchRequest } from '@/test/fetchFake'
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
backgroundSession: vi.fn(),
|
||||
getSession: vi.fn(),
|
||||
listShells: vi.fn(),
|
||||
readShellOutput: vi.fn(),
|
||||
removeShell: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/api/opencode')>()),
|
||||
...api,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), loading: vi.fn() },
|
||||
}))
|
||||
const SHELLS_PATH = '/api/opencode/api/shell'
|
||||
|
||||
const shell = (id: string, sessionID = 'session-1', status: ShellInfo['status'] = 'running'): ShellInfo => ({
|
||||
id,
|
||||
@@ -79,13 +66,17 @@ const shellNotice = (
|
||||
shellID: string,
|
||||
state: 'completed' | 'error',
|
||||
exit?: number,
|
||||
): SessionMessageInfo => ({
|
||||
id: `notice-${shellID}`,
|
||||
type: 'synthetic',
|
||||
text: '',
|
||||
metadata: { source: 'shell', shellID, state, ...(exit === undefined ? {} : { exit }) },
|
||||
time: { created: 3 },
|
||||
})
|
||||
): SessionMessageInfo => {
|
||||
const metadata: JsonObject = { source: 'shell', shellID, state }
|
||||
if (exit !== undefined) metadata.exit = exit
|
||||
return {
|
||||
id: `notice-${shellID}`,
|
||||
type: 'synthetic',
|
||||
text: '',
|
||||
metadata,
|
||||
time: { created: 3 },
|
||||
}
|
||||
}
|
||||
|
||||
const backgroundSubagentTool = (childSessionID: string, description = 'Explore'): SessionMessageAssistant => ({
|
||||
id: 'msg-sub',
|
||||
@@ -109,68 +100,92 @@ const backgroundSubagentTool = (childSessionID: string, description = 'Explore')
|
||||
time: { created: 1 },
|
||||
})
|
||||
|
||||
function renderBar(messages: SessionMessageInfo[], isSessionActive: boolean, onChildSessionClick = vi.fn()) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
interface BackgroundWorkBarFixture {
|
||||
shells?: ShellInfo[]
|
||||
listLoader?: () => Promise<FetchRouteResult> | FetchRouteResult
|
||||
outputLoader?: (request: RecordedFetchRequest) => Promise<FetchRouteResult> | FetchRouteResult
|
||||
sessionLoader?: () => Promise<FetchRouteResult> | FetchRouteResult
|
||||
}
|
||||
|
||||
function renderBar(
|
||||
messages: SessionMessageInfo[],
|
||||
isSessionActive: boolean,
|
||||
fixture: BackgroundWorkBarFixture = {},
|
||||
) {
|
||||
const onChildSessionClick = () => {}
|
||||
const shellList = fixture.listLoader ?? (() => ({ json: { data: fixture.shells ?? [] } }))
|
||||
const sessionLoader = fixture.sessionLoader ?? (() => new Promise<FetchRouteResult>(() => {}))
|
||||
const outputLoader = fixture.outputLoader ?? (() => ({ json: { data: { output: '', cursor: 0, size: 0, truncated: false } } }))
|
||||
|
||||
return renderWithProviders(
|
||||
<BackgroundWorkBar
|
||||
sessionID="session-1"
|
||||
directory="/repo"
|
||||
messages={messages}
|
||||
isSessionActive={isSessionActive}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
/>,
|
||||
{
|
||||
auth: false,
|
||||
theme: false,
|
||||
toaster: false,
|
||||
fetchRoutes: [
|
||||
{ method: 'GET', path: SHELLS_PATH, respond: () => shellList() },
|
||||
{ method: 'GET', path: `${SHELLS_PATH}/:id/output`, respond: (request) => outputLoader(request) },
|
||||
{ method: 'DELETE', path: `${SHELLS_PATH}/:id`, respond: () => ({ status: 204 }) },
|
||||
{ method: 'POST', path: '/api/opencode/api/session/:sessionID/background', respond: () => ({ status: 204 }) },
|
||||
{ method: 'GET', path: '/api/opencode/api/session/:sessionID', respond: () => sessionLoader() },
|
||||
],
|
||||
},
|
||||
)
|
||||
return {
|
||||
...render(
|
||||
<BackgroundWorkBar
|
||||
sessionID="session-1"
|
||||
directory="/repo"
|
||||
messages={messages}
|
||||
isSessionActive={isSessionActive}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
/>,
|
||||
{ wrapper },
|
||||
),
|
||||
queryClient,
|
||||
onChildSessionClick,
|
||||
}
|
||||
}
|
||||
|
||||
function resetSessionStatus() {
|
||||
useSessionStatus.setState({
|
||||
statuses: new Map(),
|
||||
statusCache: new Map(),
|
||||
statusRevisions: new Map(),
|
||||
knownSessions: new Set(),
|
||||
outcomes: new Map(),
|
||||
revision: 0,
|
||||
})
|
||||
}
|
||||
|
||||
describe('BackgroundWorkBar', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
api.listShells.mockResolvedValue([])
|
||||
api.getSession.mockImplementation(() => new Promise(() => {}))
|
||||
api.backgroundSession.mockResolvedValue(undefined)
|
||||
api.removeShell.mockResolvedValue(undefined)
|
||||
api.readShellOutput.mockResolvedValue({ output: '', cursor: 0, size: 0, truncated: false })
|
||||
useSessionStatus.setState({
|
||||
statuses: new Map(),
|
||||
statusCache: new Map(),
|
||||
statusRevisions: new Map(),
|
||||
knownSessions: new Set(),
|
||||
outcomes: new Map(),
|
||||
revision: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('renders nothing when there is no running or background work', async () => {
|
||||
const { container } = renderBar([], false)
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalledWith('/repo', 'local'))
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
resetSessionStatus()
|
||||
const result = renderBar([], false)
|
||||
|
||||
await waitFor(() => expect(result.fetchFake.lastRequest('GET', SHELLS_PATH)).toBeDefined())
|
||||
expect(result.container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('moves running shell work to the background', async () => {
|
||||
renderBar([runningShellTool()], true)
|
||||
resetSessionStatus()
|
||||
const result = renderBar([runningShellTool()], true)
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /Move to background/ }))
|
||||
|
||||
await waitFor(() => expect(api.backgroundSession).toHaveBeenCalledWith('session-1', 'local'))
|
||||
await waitFor(() =>
|
||||
expect(result.fetchFake.lastRequest('POST', '/api/opencode/api/session/:sessionID/background')?.path).toBe(
|
||||
'/api/opencode/api/session/session-1/background',
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
it('hides the background action once the session is idle', async () => {
|
||||
renderBar([runningShellTool()], false)
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
|
||||
resetSessionStatus()
|
||||
const result = renderBar([runningShellTool()], false)
|
||||
|
||||
await waitFor(() => expect(result.fetchFake.lastRequest('GET', SHELLS_PATH)).toBeDefined())
|
||||
expect(screen.queryByRole('button', { name: /Move to background/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides completed shells and removes a killed shell', async () => {
|
||||
api.listShells.mockResolvedValue([shell('dev'), shell('other', 'session-2'), shell('done', 'session-1', 'exited')])
|
||||
const { container } = renderBar([], false)
|
||||
resetSessionStatus()
|
||||
const result = renderBar([], false, {
|
||||
shells: [shell('dev'), shell('other', 'session-2'), shell('done', 'session-1', 'exited')],
|
||||
})
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
|
||||
@@ -180,20 +195,20 @@ describe('BackgroundWorkBar', () => {
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Kill npm run dev' }))
|
||||
|
||||
await waitFor(() => expect(api.removeShell).toHaveBeenCalledWith('dev', '/repo', 'local'))
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
await waitFor(() => expect(result.fetchFake.lastRequest('DELETE', `${SHELLS_PATH}/:id`)?.path).toBe(`${SHELLS_PATH}/dev`))
|
||||
await waitFor(() => expect(result.container).toBeEmptyDOMElement())
|
||||
clearShellExitRecord('/repo', 'dev')
|
||||
})
|
||||
|
||||
it('removes a shell row once it completes', async () => {
|
||||
api.listShells.mockResolvedValue([shell('dev')])
|
||||
const { queryClient } = renderBar([], false)
|
||||
resetSessionStatus()
|
||||
const result = renderBar([], false, { shells: [shell('dev')] })
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
expect(screen.getByText('running')).toBeInTheDocument()
|
||||
|
||||
await act(async () => {
|
||||
queryClient.setQueryData(['opencode', 'shells', '/repo'], [
|
||||
act(() => {
|
||||
result.queryClient.setQueryData(['opencode', 'shells', '/repo'], [
|
||||
{ ...shell('dev', 'session-1', 'exited'), exit: 0, time: { started: 1, completed: 2 } },
|
||||
])
|
||||
})
|
||||
@@ -203,19 +218,21 @@ describe('BackgroundWorkBar', () => {
|
||||
})
|
||||
|
||||
it('preserves a shell created while a stale list fetch was in flight', async () => {
|
||||
let resolveList: ((value: ShellInfo[]) => void) | undefined
|
||||
api.listShells.mockImplementation(() => new Promise<ShellInfo[]>((resolve) => { resolveList = resolve }))
|
||||
const { queryClient } = renderBar([], false)
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
|
||||
resetSessionStatus()
|
||||
let resolveList: ((value: FetchRouteResult) => void) | undefined
|
||||
const result = renderBar([], false, {
|
||||
listLoader: () => new Promise<FetchRouteResult>((resolve) => { resolveList = resolve }),
|
||||
})
|
||||
await waitFor(() => expect(result.fetchFake.lastRequest('GET', SHELLS_PATH)).toBeDefined())
|
||||
|
||||
await act(async () => {
|
||||
queryClient.setQueryData(['opencode', 'shells', '/repo'], [
|
||||
act(() => {
|
||||
result.queryClient.setQueryData(['opencode', 'shells', '/repo'], [
|
||||
{ ...shell('dev'), time: { started: Date.now() + 60_000 } },
|
||||
])
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
resolveList?.([])
|
||||
resolveList?.({ json: { data: [] } })
|
||||
})
|
||||
|
||||
expect(await screen.findByRole('button', { name: /1 background task$/ })).toBeInTheDocument()
|
||||
@@ -223,31 +240,31 @@ describe('BackgroundWorkBar', () => {
|
||||
})
|
||||
|
||||
it('hides a running shell omitted from a fresh list once it becomes unavailable', async () => {
|
||||
api.listShells.mockResolvedValue([])
|
||||
const { queryClient, container } = renderBar([], false)
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
|
||||
resetSessionStatus()
|
||||
const result = renderBar([], false)
|
||||
await waitFor(() => expect(result.fetchFake.lastRequest('GET', SHELLS_PATH)).toBeDefined())
|
||||
|
||||
await act(async () => {
|
||||
queryClient.setQueryData(['opencode', 'shells', '/repo'], [shell('dev')])
|
||||
await queryClient.invalidateQueries({ queryKey: ['opencode', 'shells', '/repo'] })
|
||||
result.queryClient.setQueryData(['opencode', 'shells', '/repo'], [shell('dev')])
|
||||
await result.queryClient.invalidateQueries({ queryKey: ['opencode', 'shells', '/repo'] })
|
||||
})
|
||||
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
await waitFor(() => expect(result.container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('does not resurrect a completed shell from a stale list fetch', async () => {
|
||||
api.listShells.mockResolvedValue([shell('dev')])
|
||||
const { queryClient } = renderBar([], false)
|
||||
resetSessionStatus()
|
||||
const result = renderBar([], false, { shells: [shell('dev')] })
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
expect(screen.getByText('running')).toBeInTheDocument()
|
||||
|
||||
queryClient.setQueryData(['opencode', 'shells', '/repo'], [
|
||||
result.queryClient.setQueryData(['opencode', 'shells', '/repo'], [
|
||||
{ ...shell('dev', 'session-1', 'exited'), exit: 0, time: { started: 1, completed: 2 } },
|
||||
])
|
||||
|
||||
await act(async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['opencode', 'shells', '/repo'] })
|
||||
await result.queryClient.invalidateQueries({ queryKey: ['opencode', 'shells', '/repo'] })
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.queryByText('npm run dev')).not.toBeInTheDocument())
|
||||
@@ -255,6 +272,7 @@ describe('BackgroundWorkBar', () => {
|
||||
})
|
||||
|
||||
it('shows a backgrounded subagent and removes it when the child goes idle', async () => {
|
||||
resetSessionStatus()
|
||||
renderBar([backgroundSubagentTool('child-1')], false)
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
@@ -274,6 +292,7 @@ describe('BackgroundWorkBar', () => {
|
||||
})
|
||||
|
||||
it('treats an unknown child session as still running', async () => {
|
||||
resetSessionStatus()
|
||||
renderBar([backgroundSubagentTool('child-unknown')], false)
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
@@ -283,89 +302,89 @@ describe('BackgroundWorkBar', () => {
|
||||
})
|
||||
|
||||
it('reconciles a child session that finished before it was observed', async () => {
|
||||
api.getSession.mockResolvedValue({
|
||||
id: 'child-1',
|
||||
projectID: 'project-1',
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
outcome: 'succeeded',
|
||||
time: { created: 1, updated: 2, idle: 2 },
|
||||
location: { directory: '/repo' },
|
||||
resetSessionStatus()
|
||||
const result = renderBar([backgroundSubagentTool('child-1')], false, {
|
||||
sessionLoader: () => ({
|
||||
json: { data: makeSession({ id: 'child-1', outcome: 'succeeded', time: { created: 1, updated: 2, idle: 2 } }) },
|
||||
}),
|
||||
})
|
||||
const { container } = renderBar([backgroundSubagentTool('child-1')], false)
|
||||
|
||||
await waitFor(() => expect(api.getSession).toHaveBeenCalled())
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
await waitFor(() => expect(result.fetchFake.lastRequest('GET', '/api/opencode/api/session/:sessionID')).toBeDefined())
|
||||
await waitFor(() => expect(result.container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides a failed child session outcome', async () => {
|
||||
resetSessionStatus()
|
||||
act(() => {
|
||||
useSessionStatus.getState().setOutcome('child-1', 'failed')
|
||||
useSessionStatus.getState().setStatus('child-1', { type: 'idle' })
|
||||
})
|
||||
const { container } = renderBar([backgroundSubagentTool('child-1')], false)
|
||||
const result = renderBar([backgroundSubagentTool('child-1')], false)
|
||||
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
await waitFor(() => expect(result.container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides an interrupted child session outcome', async () => {
|
||||
resetSessionStatus()
|
||||
act(() => {
|
||||
useSessionStatus.getState().setOutcome('child-1', 'interrupted')
|
||||
useSessionStatus.getState().setStatus('child-1', { type: 'idle' })
|
||||
})
|
||||
const { container } = renderBar([backgroundSubagentTool('child-1')], false)
|
||||
const result = renderBar([backgroundSubagentTool('child-1')], false)
|
||||
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
await waitFor(() => expect(result.container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides a deleted shell once it becomes unavailable', async () => {
|
||||
api.listShells.mockResolvedValue([shell('dev')])
|
||||
const { queryClient, container } = renderBar([], false)
|
||||
resetSessionStatus()
|
||||
const result = renderBar([], false, { shells: [shell('dev')] })
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
|
||||
await act(async () => {
|
||||
queryClient.setQueryData(['opencode', 'shells', '/repo'], [
|
||||
act(() => {
|
||||
result.queryClient.setQueryData(['opencode', 'shells', '/repo'], [
|
||||
{ ...shell('dev'), status: 'unavailable', time: { started: 1, completed: 2 } },
|
||||
])
|
||||
})
|
||||
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
await waitFor(() => expect(result.container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides a historical shell absent from the fetched list', async () => {
|
||||
api.listShells.mockResolvedValue([])
|
||||
const { container } = renderBar([backgroundShellTool('sh-history', 'npm run history')], false)
|
||||
resetSessionStatus()
|
||||
const result = renderBar([backgroundShellTool('sh-history', 'npm run history')], false)
|
||||
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
await waitFor(() => expect(result.fetchFake.lastRequest('GET', SHELLS_PATH)).toBeDefined())
|
||||
await waitFor(() => expect(result.container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides a historical shell absent from the list once its notice reports completion', async () => {
|
||||
api.listShells.mockResolvedValue([])
|
||||
const { container } = renderBar(
|
||||
resetSessionStatus()
|
||||
const result = renderBar(
|
||||
[backgroundShellTool('sh-notice', 'npm run notice'), shellNotice('sh-notice', 'completed', 0)],
|
||||
false,
|
||||
)
|
||||
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
await waitFor(() => expect(result.fetchFake.lastRequest('GET', SHELLS_PATH)).toBeDefined())
|
||||
await waitFor(() => expect(result.container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('hides a historical shell absent from the list once its error notice reports failure', async () => {
|
||||
api.listShells.mockResolvedValue([])
|
||||
const { container } = renderBar(
|
||||
resetSessionStatus()
|
||||
const result = renderBar(
|
||||
[backgroundShellTool('sh-notice', 'npm run notice'), shellNotice('sh-notice', 'error')],
|
||||
false,
|
||||
)
|
||||
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
await waitFor(() => expect(result.fetchFake.lastRequest('GET', SHELLS_PATH)).toBeDefined())
|
||||
await waitFor(() => expect(result.container).toBeEmptyDOMElement())
|
||||
})
|
||||
|
||||
it('keeps a historical shell unknown while its list is still loading', async () => {
|
||||
api.listShells.mockImplementation(() => new Promise(() => {}))
|
||||
renderBar([backgroundShellTool('sh-history', 'npm run history')], false)
|
||||
resetSessionStatus()
|
||||
renderBar([backgroundShellTool('sh-history', 'npm run history')], false, {
|
||||
listLoader: () => new Promise<FetchRouteResult>(() => {}),
|
||||
})
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
|
||||
@@ -374,24 +393,26 @@ describe('BackgroundWorkBar', () => {
|
||||
})
|
||||
|
||||
it('uses an already cached shell list when the bar remounts', async () => {
|
||||
resetSessionStatus()
|
||||
const messages = [backgroundShellTool('sh-history', 'npm run history')]
|
||||
const { queryClient, unmount, container } = renderBar(messages, false)
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
unmount()
|
||||
const result = renderBar(messages, false)
|
||||
await waitFor(() => expect(result.container).toBeEmptyDOMElement())
|
||||
result.unmount()
|
||||
|
||||
const remount = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BackgroundWorkBar sessionID="session-1" directory="/repo" messages={messages} isSessionActive={false} />
|
||||
</QueryClientProvider>,
|
||||
const remount = renderWithProviders(
|
||||
<BackgroundWorkBar sessionID="session-1" directory="/repo" messages={messages} isSessionActive={false} />,
|
||||
{ auth: false, theme: false, toaster: false, queryClient: result.queryClient },
|
||||
)
|
||||
await waitFor(() => expect(remount.container).toBeEmptyDOMElement())
|
||||
expect(api.listShells).toHaveBeenCalledTimes(1)
|
||||
expect(result.fetchFake.findRequests('GET', SHELLS_PATH)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('does not overwrite a newer live child status with a stale child query', async () => {
|
||||
let resolveSession: ((value: unknown) => void) | undefined
|
||||
api.getSession.mockImplementation(() => new Promise((resolve) => { resolveSession = resolve }))
|
||||
renderBar([backgroundSubagentTool('child-1')], false)
|
||||
resetSessionStatus()
|
||||
let resolveSession: ((value: FetchRouteResult) => void) | undefined
|
||||
const result = renderBar([backgroundSubagentTool('child-1')], false, {
|
||||
sessionLoader: () => new Promise<FetchRouteResult>((resolve) => { resolveSession = resolve }),
|
||||
})
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
|
||||
@@ -401,75 +422,100 @@ describe('BackgroundWorkBar', () => {
|
||||
expect(screen.queryByText('Explore')).not.toBeInTheDocument()
|
||||
|
||||
await act(async () => {
|
||||
resolveSession?.({
|
||||
id: 'child-1',
|
||||
projectID: 'project-1',
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: 1, updated: 2 },
|
||||
location: { directory: '/repo' },
|
||||
})
|
||||
resolveSession?.({ json: { data: makeSession({ id: 'child-1', time: { created: 1, updated: 2 } }) } })
|
||||
})
|
||||
|
||||
expect(screen.queryByText('Explore')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('running')).not.toBeInTheDocument()
|
||||
expect(result.fetchFake.lastRequest('GET', '/api/opencode/api/session/:sessionID')).toBeDefined()
|
||||
})
|
||||
|
||||
it('applies a shell exit recorded before the list was seeded', async () => {
|
||||
resetSessionStatus()
|
||||
recordShellExit('/repo', { id: 'sh-seeded', status: 'exited', exit: 0 })
|
||||
api.listShells.mockResolvedValue([shell('sh-seeded')])
|
||||
const { container } = renderBar([], false)
|
||||
const result = renderBar([], false, { shells: [shell('sh-seeded')] })
|
||||
|
||||
await waitFor(() => expect(api.listShells).toHaveBeenCalled())
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement())
|
||||
await waitFor(() => expect(result.fetchFake.lastRequest('GET', SHELLS_PATH)).toBeDefined())
|
||||
await waitFor(() => expect(result.container).toBeEmptyDOMElement())
|
||||
clearShellExitRecord('/repo', 'sh-seeded')
|
||||
})
|
||||
|
||||
it('navigates to a backgrounded subagent session', async () => {
|
||||
const { onChildSessionClick } = renderBar([backgroundSubagentTool('child-1')], false)
|
||||
resetSessionStatus()
|
||||
let clickedSession: string | undefined
|
||||
renderWithProviders(
|
||||
<BackgroundWorkBar
|
||||
sessionID="session-1"
|
||||
directory="/repo"
|
||||
messages={[backgroundSubagentTool('child-1')]}
|
||||
isSessionActive={false}
|
||||
onChildSessionClick={(sessionId) => { clickedSession = sessionId }}
|
||||
/>,
|
||||
{
|
||||
auth: false,
|
||||
theme: false,
|
||||
toaster: false,
|
||||
fetchRoutes: [
|
||||
{ method: 'GET', path: SHELLS_PATH, respond: () => ({ json: { data: [] } }) },
|
||||
{ method: 'GET', path: '/api/opencode/api/session/:sessionID', respond: () => new Promise<FetchRouteResult>(() => {}) },
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'View Explore' }))
|
||||
|
||||
expect(onChildSessionClick).toHaveBeenCalledWith('child-1')
|
||||
expect(clickedSession).toBe('child-1')
|
||||
})
|
||||
|
||||
it('shows the tail of a background shell output', async () => {
|
||||
api.listShells.mockResolvedValue([shell('dev')])
|
||||
api.readShellOutput.mockResolvedValue({ output: 'server listening on 3000', cursor: 24, size: 24, truncated: false })
|
||||
renderBar([], false)
|
||||
resetSessionStatus()
|
||||
const result = renderBar([], false, {
|
||||
shells: [shell('dev')],
|
||||
outputLoader: () => ({ json: { data: { output: 'server listening on 3000', cursor: 24, size: 24, truncated: false } } }),
|
||||
})
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Output' }))
|
||||
|
||||
expect(await screen.findByText('server listening on 3000')).toBeInTheDocument()
|
||||
expect(api.readShellOutput).toHaveBeenCalledWith('dev', '/repo', 0, 50_000, 'local')
|
||||
const outputRequest = result.fetchFake.lastRequest('GET', `${SHELLS_PATH}/:id/output`)
|
||||
expect(outputRequest?.path).toBe(`${SHELLS_PATH}/dev/output`)
|
||||
expect(outputRequest?.searchParams.get('cursor')).toBe('0')
|
||||
expect(outputRequest?.searchParams.get('limit')).toBe('50000')
|
||||
expect(outputRequest?.searchParams.get('location[directory]')).toBe('/repo')
|
||||
})
|
||||
|
||||
it('reads the final output when the shell exits during an in-flight poll', async () => {
|
||||
let resolveFirst: ((value: { output: string; cursor: number; size: number; truncated: boolean }) => void) | undefined
|
||||
resetSessionStatus()
|
||||
let resolveFirst: ((value: FetchRouteResult) => void) | undefined
|
||||
let calls = 0
|
||||
api.listShells.mockResolvedValue([shell('dev')])
|
||||
api.readShellOutput.mockImplementation(() => {
|
||||
calls += 1
|
||||
if (calls === 1) {
|
||||
return new Promise<{ output: string; cursor: number; size: number; truncated: boolean }>((resolve) => {
|
||||
resolveFirst = resolve
|
||||
})
|
||||
}
|
||||
return Promise.resolve({ output: 'final tail', cursor: 10, size: 10, truncated: false })
|
||||
let shellList: ShellInfo[] = [shell('dev')]
|
||||
const result = renderBar([], false, {
|
||||
listLoader: () => ({ json: { data: shellList } }),
|
||||
outputLoader: () => {
|
||||
calls += 1
|
||||
if (calls === 1) {
|
||||
return new Promise<FetchRouteResult>((resolve) => { resolveFirst = resolve })
|
||||
}
|
||||
return { json: { data: { output: 'final tail', cursor: 10, size: 10, truncated: false } } }
|
||||
},
|
||||
})
|
||||
const { queryClient } = renderBar([], false)
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /1 background task$/ }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Output' }))
|
||||
await waitFor(() => expect(calls).toBe(1))
|
||||
|
||||
api.listShells.mockResolvedValue([])
|
||||
await queryClient.invalidateQueries({ queryKey: ['opencode', 'shells', '/repo'] })
|
||||
shellList = []
|
||||
result.queryClient.setQueryData(['opencode', 'shells', '/repo'], [])
|
||||
await act(async () => {
|
||||
await result.queryClient.invalidateQueries({ queryKey: ['opencode', 'shells', '/repo'] })
|
||||
})
|
||||
|
||||
expect(await screen.findByText('final tail')).toBeInTheDocument()
|
||||
|
||||
resolveFirst?.({ output: '', cursor: 0, size: 0, truncated: false })
|
||||
await act(async () => {
|
||||
resolveFirst?.({ json: { data: { output: '', cursor: 0, size: 0, truncated: false } } })
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -3,7 +3,7 @@ import { Bot, Check, ChevronDown, ChevronUp, ExternalLink, Loader2, MoveDownRigh
|
||||
import { useShallow } from 'zustand/react/shallow'
|
||||
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
|
||||
import { readShellOutput } from '@/api/opencode'
|
||||
import { useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
import { useOpenCodeServerId } from '@/contexts/opencode-server-context'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useBackgroundSession, useChildSessionReconciliation } from '@/hooks/useOpenCode'
|
||||
|
||||
@@ -1,25 +1,12 @@
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { useReducer } from 'react'
|
||||
import { describe, it, expect, beforeAll } from 'vitest'
|
||||
import { act, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { ReactNode } from 'react'
|
||||
import { ChangesWalkthroughSheet } from './ChangesWalkthroughSheet'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { ChangeWalkthrough, ChangeWalkthroughState } from '@opencode-manager/shared/schemas'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getChangeWalkthrough: vi.fn(),
|
||||
generateChangeWalkthrough: vi.fn(),
|
||||
refineChangeWalkthrough: vi.fn(),
|
||||
cancelChangeWalkthrough: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/changeWalkthroughs', () => ({
|
||||
getChangeWalkthrough: mocks.getChangeWalkthrough,
|
||||
generateChangeWalkthrough: mocks.generateChangeWalkthrough,
|
||||
refineChangeWalkthrough: mocks.refineChangeWalkthrough,
|
||||
cancelChangeWalkthrough: mocks.cancelChangeWalkthrough,
|
||||
}))
|
||||
import { ChangesWalkthroughSheet } from './ChangesWalkthroughSheet'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
import type { FetchRoute, FetchRouteResult } from '@/test/fetchFake'
|
||||
|
||||
const artifactPath = '/workspace/walkthroughs/ses_1/gen/index.html'
|
||||
|
||||
@@ -45,24 +32,90 @@ const generatingWalkthrough: ChangeWalkthrough = {
|
||||
publishedAt: null,
|
||||
}
|
||||
|
||||
function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
|
||||
return { walkthrough, currentDiffHash: 'hash-1', hasChanges: true, stale: false, generating: false, running: false, error: null, ...overrides }
|
||||
function makeState(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
|
||||
return {
|
||||
walkthrough,
|
||||
currentDiffHash: 'hash-1',
|
||||
hasChanges: true,
|
||||
stale: false,
|
||||
generating: false,
|
||||
running: false,
|
||||
error: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
function stateOf(overrides: Partial<ChangeWalkthroughState> = {}) {
|
||||
return () => ({ json: makeState(overrides) })
|
||||
}
|
||||
|
||||
function renderSheet(overrides: Partial<React.ComponentProps<typeof ChangesWalkthroughSheet>> = {}) {
|
||||
const onOpenChange = vi.fn()
|
||||
const view = render(
|
||||
<ChangesWalkthroughSheet sessionId="ses_1" open onOpenChange={onOpenChange} {...overrides} />,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
return { ...view, onOpenChange }
|
||||
interface WalkthroughFixture {
|
||||
state?: () => FetchRouteResult | Promise<FetchRouteResult>
|
||||
generate?: () => FetchRouteResult | Promise<FetchRouteResult>
|
||||
refine?: () => FetchRouteResult | Promise<FetchRouteResult>
|
||||
cancel?: () => FetchRouteResult | Promise<FetchRouteResult>
|
||||
}
|
||||
|
||||
type SheetProps = ComponentProps<typeof ChangesWalkthroughSheet>
|
||||
|
||||
function walkthroughRoutes(fixture: WalkthroughFixture): FetchRoute[] {
|
||||
return [
|
||||
{ method: 'GET', path: '/api/change-walkthroughs/helper-sessions', respond: () => ({ json: { sessionIds: [] } }) },
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/change-walkthroughs/:sessionId',
|
||||
respond: () => (fixture.state ?? stateOf())(),
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/change-walkthroughs/:sessionId',
|
||||
respond: () => fixture.generate?.() ?? { json: makeState() },
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/change-walkthroughs/:sessionId/refine',
|
||||
respond: () => fixture.refine?.() ?? { json: makeState() },
|
||||
},
|
||||
{
|
||||
method: 'DELETE',
|
||||
path: '/api/change-walkthroughs/:sessionId',
|
||||
respond: () => fixture.cancel?.() ?? { status: 204 },
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function renderSheet(fixture: WalkthroughFixture = {}, overrides: Partial<SheetProps> = {}) {
|
||||
const active: SheetProps = { sessionId: 'ses_1', open: true, onOpenChange: () => {}, ...overrides }
|
||||
const harness = { rerender: () => {} }
|
||||
|
||||
function Harness() {
|
||||
const [, force] = useReducer((count: number) => count + 1, 0)
|
||||
harness.rerender = force
|
||||
return <ChangesWalkthroughSheet {...active} />
|
||||
}
|
||||
|
||||
const result = renderWithProviders(<Harness />, {
|
||||
auth: false,
|
||||
theme: false,
|
||||
toaster: false,
|
||||
fetchRoutes: walkthroughRoutes(fixture),
|
||||
})
|
||||
|
||||
return {
|
||||
...result,
|
||||
rerenderWith: async (update: Partial<SheetProps>) => {
|
||||
Object.assign(active, update)
|
||||
await act(async () => {
|
||||
harness.rerender()
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function requestedSources(fixture: ReturnType<typeof renderSheet>): string[] {
|
||||
return fixture.fetchFake
|
||||
.findRequests('GET', '/api/change-walkthroughs/:sessionId')
|
||||
.map((request) => request.searchParams.get('source') ?? '')
|
||||
}
|
||||
|
||||
describe('ChangesWalkthroughSheet', () => {
|
||||
@@ -74,66 +127,64 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
Element.prototype.scrollTo ??= () => {}
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('offers to generate a walkthrough and starts a walkthrough session', async () => {
|
||||
const user = userEvent.setup()
|
||||
let generated = false
|
||||
mocks.getChangeWalkthrough.mockImplementation(async () =>
|
||||
generated ? state() : state({ walkthrough: null }),
|
||||
)
|
||||
mocks.generateChangeWalkthrough.mockImplementation(async () => {
|
||||
generated = true
|
||||
return state()
|
||||
const result = renderSheet({
|
||||
state: () => ({ json: makeState({ walkthrough: generated ? walkthrough : null }) }),
|
||||
generate: () => {
|
||||
generated = true
|
||||
return { json: makeState() }
|
||||
},
|
||||
})
|
||||
renderSheet()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { source: { kind: 'session' } })
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(result.fetchFake.lastRequest('POST', '/api/change-walkthroughs/:sessionId')?.body).toEqual({
|
||||
source: { kind: 'session' },
|
||||
}),
|
||||
)
|
||||
expect(await screen.findByTitle('Change walkthrough')).toHaveAttribute('sandbox', 'allow-scripts')
|
||||
})
|
||||
|
||||
it('generates with the selected model', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
mocks.generateChangeWalkthrough.mockResolvedValue(state())
|
||||
renderSheet({ model: { providerID: 'anthropic', id: 'claude', variant: 'high' } })
|
||||
const result = renderSheet({ state: stateOf({ walkthrough: null }) }, {
|
||||
model: { providerID: 'anthropic', id: 'claude', variant: 'high' },
|
||||
})
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', {
|
||||
await waitFor(() =>
|
||||
expect(result.fetchFake.lastRequest('POST', '/api/change-walkthroughs/:sessionId')?.body).toEqual({
|
||||
source: { kind: 'session' },
|
||||
model: 'anthropic/claude#high',
|
||||
})
|
||||
})
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the building status and opens the walkthrough session while generating', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onOpenSession = vi.fn()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ generating: true, walkthrough: generatingWalkthrough }))
|
||||
mocks.cancelChangeWalkthrough.mockResolvedValue(undefined)
|
||||
renderSheet({ onOpenSession })
|
||||
let openedSession: string | undefined
|
||||
const result = renderSheet({ state: stateOf({ generating: true, walkthrough: generatingWalkthrough }) }, {
|
||||
onOpenSession: (sessionId: string) => { openedSession = sessionId },
|
||||
})
|
||||
|
||||
expect(await screen.findByText('Building the walkthrough in a separate session…')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Open walkthrough session' }))
|
||||
expect(onOpenSession).toHaveBeenCalledWith('ses_walk')
|
||||
expect(openedSession).toBe('ses_walk')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Stop generating walkthrough' }))
|
||||
await waitFor(() => {
|
||||
expect(mocks.cancelChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'session' })
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(result.fetchFake.lastRequest('DELETE', '/api/change-walkthroughs/:sessionId')?.searchParams.get('source')).toBe(
|
||||
'session',
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
it('does not show a stop button when idle', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state())
|
||||
renderSheet()
|
||||
|
||||
await screen.findByRole('button', { name: 'Regenerate walkthrough' })
|
||||
@@ -142,22 +193,21 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
|
||||
it('keeps the stop control and hides the refine form while a published walkthrough is still running', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ running: true }))
|
||||
mocks.cancelChangeWalkthrough.mockResolvedValue(undefined)
|
||||
renderSheet()
|
||||
const result = renderSheet({ state: stateOf({ running: true }) })
|
||||
|
||||
expect(await screen.findByTitle('Change walkthrough')).toBeInTheDocument()
|
||||
expect(screen.getByText('Refining…')).toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Refine walkthrough')).not.toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Stop generating walkthrough' }))
|
||||
await waitFor(() => {
|
||||
expect(mocks.cancelChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'session' })
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(result.fetchFake.lastRequest('DELETE', '/api/change-walkthroughs/:sessionId')?.searchParams.get('source')).toBe(
|
||||
'session',
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the refine form and no stop control once the execution ends', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state())
|
||||
renderSheet()
|
||||
|
||||
expect(await screen.findByLabelText('Refine walkthrough')).toBeInTheDocument()
|
||||
@@ -166,7 +216,6 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
})
|
||||
|
||||
it('renders the published artifact in a sandboxed iframe with the raw file source', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state())
|
||||
renderSheet()
|
||||
|
||||
const frame = await screen.findByTitle('Change walkthrough')
|
||||
@@ -181,7 +230,6 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
})
|
||||
|
||||
it('renders no stop list or page navigation', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state())
|
||||
renderSheet()
|
||||
|
||||
await screen.findByTitle('Change walkthrough')
|
||||
@@ -193,92 +241,82 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
|
||||
it('refines a published walkthrough through the walkthrough session', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state())
|
||||
mocks.refineChangeWalkthrough.mockResolvedValue(state({ generating: true }))
|
||||
renderSheet()
|
||||
const result = renderSheet({ refine: () => ({ json: makeState({ generating: true }) }) })
|
||||
|
||||
const textarea = await screen.findByLabelText('Refine walkthrough')
|
||||
await user.type(textarea, 'tighten the introduction')
|
||||
await user.click(screen.getByRole('button', { name: 'Send' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.refineChangeWalkthrough).toHaveBeenCalledWith('ses_1', {
|
||||
await waitFor(() =>
|
||||
expect(result.fetchFake.lastRequest('POST', '/api/change-walkthroughs/:sessionId/refine')?.body).toEqual({
|
||||
source: { kind: 'session' },
|
||||
text: 'tighten the introduction',
|
||||
})
|
||||
})
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('updates a stale walkthrough', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ stale: true, currentDiffHash: 'hash-2' }))
|
||||
mocks.generateChangeWalkthrough.mockResolvedValue(state({ generating: true }))
|
||||
renderSheet()
|
||||
const result = renderSheet({
|
||||
state: stateOf({ stale: true, currentDiffHash: 'hash-2' }),
|
||||
generate: () => ({ json: makeState({ generating: true }) }),
|
||||
})
|
||||
|
||||
expect(
|
||||
await screen.findByText('Changes have been updated since this walkthrough was generated'),
|
||||
).toBeInTheDocument()
|
||||
expect(await screen.findByText('Changes have been updated since this walkthrough was generated')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Update walkthrough' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { source: { kind: 'session' } })
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(result.fetchFake.lastRequest('POST', '/api/change-walkthroughs/:sessionId')?.body).toEqual({
|
||||
source: { kind: 'session' },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('regenerates from the header without a stale walkthrough', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state())
|
||||
mocks.generateChangeWalkthrough.mockResolvedValue(state())
|
||||
renderSheet()
|
||||
const result = renderSheet()
|
||||
|
||||
await screen.findByTitle('Change walkthrough')
|
||||
await user.click(screen.getByRole('button', { name: 'Regenerate walkthrough' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', {
|
||||
await waitFor(() =>
|
||||
expect(result.fetchFake.lastRequest('POST', '/api/change-walkthroughs/:sessionId')?.body).toEqual({
|
||||
regenerate: true,
|
||||
source: { kind: 'session' },
|
||||
})
|
||||
})
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('switches to staged changes', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
mocks.generateChangeWalkthrough.mockResolvedValue(state())
|
||||
renderSheet()
|
||||
const result = renderSheet({ state: stateOf({ walkthrough: null }) })
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Staged' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
|
||||
})
|
||||
await waitFor(() => expect(requestedSources(result)).toContain('staged'))
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { source: { kind: 'staged' } })
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(result.fetchFake.lastRequest('POST', '/api/change-walkthroughs/:sessionId')?.body).toEqual({
|
||||
source: { kind: 'staged' },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('renders the source picker in the drawer header before any walkthrough exists', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
renderSheet()
|
||||
renderSheet({ state: stateOf({ walkthrough: null }) })
|
||||
|
||||
const header = screen.getByRole('button', { name: 'Close' }).parentElement
|
||||
expect(header).not.toBeNull()
|
||||
expect(
|
||||
within(header as HTMLElement).getByRole('combobox', { name: 'Changes to walk through' }),
|
||||
).toBeInTheDocument()
|
||||
if (!(header instanceof HTMLElement)) throw new Error('drawer header is not rendered')
|
||||
expect(within(header).getByRole('combobox', { name: 'Changes to walk through' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('sends the branch base', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
mocks.generateChangeWalkthrough.mockResolvedValue(state())
|
||||
renderSheet()
|
||||
const result = renderSheet({ state: stateOf({ walkthrough: null }) })
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Branch vs base' }))
|
||||
@@ -287,24 +325,20 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
await user.type(base, 'develop')
|
||||
await user.tab()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'branch', base: 'develop' })
|
||||
})
|
||||
await waitFor(() => expect(requestedSources(result)).toContain('branch:develop'))
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Generate walkthrough' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', {
|
||||
await waitFor(() =>
|
||||
expect(result.fetchFake.lastRequest('POST', '/api/change-walkthroughs/:sessionId')?.body).toEqual({
|
||||
source: { kind: 'branch', base: 'develop' },
|
||||
})
|
||||
})
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('prompts for a pull request number and withholds the actions until it is valid', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
mocks.generateChangeWalkthrough.mockResolvedValue(state())
|
||||
renderSheet()
|
||||
const result = renderSheet({ state: stateOf({ walkthrough: null }) })
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Pull request' }))
|
||||
@@ -315,18 +349,13 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
|
||||
expect(await screen.findByText('Enter a pull request number')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Generate walkthrough' })).not.toBeInTheDocument()
|
||||
expect(mocks.generateChangeWalkthrough).not.toHaveBeenCalled()
|
||||
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith(
|
||||
'ses_1',
|
||||
expect.objectContaining({ kind: 'pullRequest' }),
|
||||
)
|
||||
expect(result.fetchFake.findRequests('POST', '/api/change-walkthroughs/:sessionId')).toHaveLength(0)
|
||||
expect(requestedSources(result).some((source) => source.startsWith('pr:'))).toBe(false)
|
||||
})
|
||||
|
||||
it('commits a valid pull request number and restores the generate action', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
mocks.generateChangeWalkthrough.mockResolvedValue(state())
|
||||
renderSheet()
|
||||
const result = renderSheet({ state: stateOf({ walkthrough: null }) })
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Pull request' }))
|
||||
@@ -335,123 +364,88 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
await user.type(number, '12')
|
||||
await user.tab()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'pullRequest', number: 12 })
|
||||
})
|
||||
await waitFor(() => expect(requestedSources(result)).toContain('pr:12:'))
|
||||
expect(screen.queryByText('Enter a pull request number')).not.toBeInTheDocument()
|
||||
expect(await screen.findByRole('button', { name: 'Generate walkthrough' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('resets the source before querying a new session', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
const { rerender, onOpenChange } = renderSheet()
|
||||
const result = renderSheet({ state: stateOf({ walkthrough: null }) })
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Staged' }))
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
|
||||
})
|
||||
await waitFor(() => expect(requestedSources(result)).toContain('staged'))
|
||||
|
||||
rerender(<ChangesWalkthroughSheet sessionId="ses_2" open onOpenChange={onOpenChange} />)
|
||||
await result.rerenderWith({ sessionId: 'ses_2' })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_2', { kind: 'session' })
|
||||
})
|
||||
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith('ses_2', { kind: 'staged' })
|
||||
await waitFor(() =>
|
||||
expect(result.fetchFake.lastRequest('GET', '/api/change-walkthroughs/:sessionId')?.path).toBe(
|
||||
'/api/change-walkthroughs/ses_2',
|
||||
),
|
||||
)
|
||||
expect(result.fetchFake.lastRequest('GET', '/api/change-walkthroughs/:sessionId')?.searchParams.get('source')).toBe('session')
|
||||
})
|
||||
|
||||
it('applies an external source request to the walkthrough source', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
renderSheet({ sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' } } })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
|
||||
const result = renderSheet({ state: stateOf({ walkthrough: null }) }, {
|
||||
sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' } },
|
||||
})
|
||||
|
||||
await waitFor(() => expect(requestedSources(result)).toContain('staged'))
|
||||
expect(screen.getByRole('combobox', { name: 'Changes to walk through' })).toHaveTextContent('Staged')
|
||||
})
|
||||
|
||||
it('applies a pull request request with its number and base', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
renderSheet({
|
||||
const result = renderSheet({ state: stateOf({ walkthrough: null }) }, {
|
||||
sourceRequest: { sessionId: 'ses_1', source: { kind: 'pullRequest', number: 12 } },
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'pullRequest', number: 12 })
|
||||
})
|
||||
await waitFor(() => expect(requestedSources(result)).toContain('pr:12:'))
|
||||
expect(screen.getByLabelText('Pull request number')).toHaveValue(12)
|
||||
})
|
||||
|
||||
it('re-applies a repeated request for the same source', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
const { rerender, onOpenChange } = renderSheet({
|
||||
const result = renderSheet({ state: stateOf({ walkthrough: null }) }, {
|
||||
sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' } },
|
||||
})
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
|
||||
})
|
||||
await waitFor(() => expect(requestedSources(result)).toContain('staged'))
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Unstaged' }))
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'unstaged' })
|
||||
})
|
||||
await waitFor(() => expect(requestedSources(result)).toContain('unstaged'))
|
||||
|
||||
rerender(
|
||||
<ChangesWalkthroughSheet
|
||||
sessionId="ses_1"
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
sourceRequest={{ sessionId: 'ses_1', source: { kind: 'staged' } }}
|
||||
/>,
|
||||
)
|
||||
await result.rerenderWith({ sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' } } })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
|
||||
})
|
||||
await waitFor(() => expect(requestedSources(result)).toContain('staged'))
|
||||
expect(screen.getByRole('combobox', { name: 'Changes to walk through' })).toHaveTextContent('Staged')
|
||||
})
|
||||
|
||||
it('leaves the current selection when a request carries no source', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
const { rerender, onOpenChange } = renderSheet({
|
||||
const result = renderSheet({ state: stateOf({ walkthrough: null }) }, {
|
||||
sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' } },
|
||||
})
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
|
||||
})
|
||||
await waitFor(() => expect(requestedSources(result)).toContain('staged'))
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Unstaged' }))
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'unstaged' })
|
||||
})
|
||||
mocks.getChangeWalkthrough.mockClear()
|
||||
await waitFor(() => expect(requestedSources(result)).toContain('unstaged'))
|
||||
const requestsBefore = requestedSources(result).length
|
||||
|
||||
rerender(
|
||||
<ChangesWalkthroughSheet
|
||||
sessionId="ses_1"
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
sourceRequest={{ sessionId: 'ses_1', source: undefined }}
|
||||
/>,
|
||||
)
|
||||
await result.rerenderWith({ sourceRequest: { sessionId: 'ses_1', source: undefined } })
|
||||
|
||||
expect(screen.getByRole('combobox', { name: 'Changes to walk through' })).toHaveTextContent('Unstaged')
|
||||
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith('ses_1', { kind: 'session' })
|
||||
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith('ses_1', { kind: 'staged' })
|
||||
expect(requestedSources(result)).toHaveLength(requestsBefore)
|
||||
})
|
||||
|
||||
it('clears a generation error when the source changes', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
mocks.generateChangeWalkthrough.mockRejectedValue(
|
||||
new FetchError('Not a git repository', 409, 'WALKTHROUGH_NOT_A_REPO'),
|
||||
)
|
||||
renderSheet()
|
||||
renderSheet({
|
||||
state: stateOf({ walkthrough: null }),
|
||||
generate: () => ({ status: 409, json: { error: 'Not a git repository', code: 'WALKTHROUGH_NOT_A_REPO' } }),
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Branch vs base' }))
|
||||
@@ -462,47 +456,40 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Staged' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Not a git repository')).not.toBeInTheDocument()
|
||||
})
|
||||
await waitFor(() => expect(screen.queryByText('Not a git repository')).not.toBeInTheDocument())
|
||||
expect(await screen.findByRole('button', { name: 'Generate walkthrough' })).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows a loading status while the walkthrough state is loading', async () => {
|
||||
mocks.getChangeWalkthrough.mockImplementation(() => new Promise(() => {}))
|
||||
renderSheet()
|
||||
renderSheet({ state: () => new Promise<FetchRouteResult>(() => {}) })
|
||||
|
||||
expect(await screen.findByText('Loading the walkthrough…')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders a generation failure recorded by the server', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(
|
||||
state({
|
||||
renderSheet({
|
||||
state: stateOf({
|
||||
walkthrough: null,
|
||||
error: { message: 'The walkthrough session did not publish within 15 minutes', code: 'WALKTHROUGH_TIMEOUT' },
|
||||
}),
|
||||
)
|
||||
renderSheet()
|
||||
})
|
||||
|
||||
expect(
|
||||
await screen.findByText('The walkthrough session did not publish within 15 minutes'),
|
||||
).toBeInTheDocument()
|
||||
expect(await screen.findByText('The walkthrough session did not publish within 15 minutes')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Generate walkthrough' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('shows an upfront empty state when the session has no changes', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(
|
||||
state({ walkthrough: null, currentDiffHash: 'e3b0c44298fc1c149afbf4c8996fb924', hasChanges: false }),
|
||||
)
|
||||
renderSheet()
|
||||
renderSheet({
|
||||
state: stateOf({ walkthrough: null, currentDiffHash: 'e3b0c44298fc1c149afbf4c8996fb924', hasChanges: false }),
|
||||
})
|
||||
|
||||
expect(await screen.findByText('No changes in this session')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Generate walkthrough' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides the refine form until a walkthrough is published', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(
|
||||
state({
|
||||
renderSheet({
|
||||
state: stateOf({
|
||||
walkthrough: {
|
||||
...walkthrough,
|
||||
status: 'failed',
|
||||
@@ -512,35 +499,47 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
},
|
||||
error: { message: 'The walkthrough session did not publish within 15 minutes', code: 'WALKTHROUGH_TIMEOUT' },
|
||||
}),
|
||||
)
|
||||
renderSheet()
|
||||
})
|
||||
|
||||
expect(
|
||||
await screen.findByText('The walkthrough session did not publish within 15 minutes'),
|
||||
).toBeInTheDocument()
|
||||
expect(await screen.findByText('The walkthrough session did not publish within 15 minutes')).toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Refine walkthrough')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['WALKTHROUGH_NO_CHANGES', 'This session has no changes to walk through', 'This session has no changes to walk through'],
|
||||
['WALKTHROUGH_NO_CHANGES', 'The staged changes contain no changes to walk through', 'The staged changes contain no changes to walk through'],
|
||||
['WALKTHROUGH_NO_TEXT_CHANGES', '', 'This session has no text changes to walk through'],
|
||||
])('renders the %s message for the selected source inline', async (code, serverMessage, shown) => {
|
||||
['WALKTHROUGH_NO_CHANGES', 'This session has no changes to walk through'],
|
||||
['WALKTHROUGH_NO_CHANGES', 'The staged changes contain no changes to walk through'],
|
||||
])('renders the %s message for the selected source inline', async (code, serverMessage) => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null, currentDiffHash: null }))
|
||||
mocks.generateChangeWalkthrough.mockRejectedValue(new FetchError(serverMessage, 409, code))
|
||||
renderSheet()
|
||||
renderSheet({
|
||||
state: stateOf({ walkthrough: null, currentDiffHash: null }),
|
||||
generate: () => ({ status: 409, json: { error: serverMessage, code } }),
|
||||
})
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
|
||||
|
||||
expect(await screen.findByText(shown)).toBeInTheDocument()
|
||||
expect(await screen.findByText(serverMessage)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('falls back to a no-text-changes message when the server records none', async () => {
|
||||
renderSheet({
|
||||
state: stateOf({
|
||||
walkthrough: null,
|
||||
currentDiffHash: null,
|
||||
error: { message: '', code: 'WALKTHROUGH_NO_TEXT_CHANGES' },
|
||||
}),
|
||||
})
|
||||
|
||||
expect(await screen.findByText('This session has no text changes to walk through')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders other generation errors inline', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null, currentDiffHash: null }))
|
||||
mocks.generateChangeWalkthrough.mockRejectedValue(new Error('model exploded'))
|
||||
renderSheet()
|
||||
renderSheet({
|
||||
state: stateOf({ walkthrough: null, currentDiffHash: null }),
|
||||
generate: () => {
|
||||
throw new Error('model exploded')
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
|
||||
|
||||
@@ -553,23 +552,22 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
])('recovers from a prior %s error once changes appear and the dialog is reopened', async (code, serverMessage) => {
|
||||
const user = userEvent.setup()
|
||||
let generated = false
|
||||
mocks.getChangeWalkthrough.mockImplementation(async () =>
|
||||
generated ? state() : state({ walkthrough: null, currentDiffHash: null }),
|
||||
)
|
||||
mocks.generateChangeWalkthrough
|
||||
.mockRejectedValueOnce(new FetchError(serverMessage, 409, code))
|
||||
.mockImplementationOnce(async () => {
|
||||
let generateCalls = 0
|
||||
const result = renderSheet({
|
||||
state: () => ({ json: makeState(generated ? {} : { walkthrough: null, currentDiffHash: null }) }),
|
||||
generate: () => {
|
||||
generateCalls += 1
|
||||
if (generateCalls === 1) return { status: 409, json: { error: serverMessage, code } }
|
||||
generated = true
|
||||
return state()
|
||||
})
|
||||
|
||||
const { rerender, onOpenChange } = renderSheet()
|
||||
return { json: makeState() }
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
|
||||
expect(await screen.findByText(serverMessage)).toBeInTheDocument()
|
||||
|
||||
rerender(<ChangesWalkthroughSheet sessionId="ses_1" open={false} onOpenChange={onOpenChange} />)
|
||||
rerender(<ChangesWalkthroughSheet sessionId="ses_1" open onOpenChange={onOpenChange} />)
|
||||
await result.rerenderWith({ open: false })
|
||||
await result.rerenderWith({ open: true })
|
||||
|
||||
const generate = await screen.findByRole('button', { name: 'Generate walkthrough' })
|
||||
expect(generate).toBeEnabled()
|
||||
|
||||
@@ -23,24 +23,36 @@ import {
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { ChangeWalkthrough, WalkthroughSource } from '@opencode-manager/shared/schemas'
|
||||
import { formatOpenCodeModelRef, type ModelRef } from '@opencode-manager/shared/opencode'
|
||||
import { z } from 'zod'
|
||||
|
||||
interface WalkthroughErrorLike {
|
||||
message?: string
|
||||
code?: string
|
||||
const walkthroughErrorSchema = z.object({
|
||||
message: z.string().optional(),
|
||||
code: z.string().optional(),
|
||||
})
|
||||
|
||||
const walkthroughSourceKindSchema = z.enum([
|
||||
'session',
|
||||
'uncommitted',
|
||||
'staged',
|
||||
'unstaged',
|
||||
'branch',
|
||||
'pullRequest',
|
||||
])
|
||||
|
||||
type WalkthroughSourceKind = z.infer<typeof walkthroughSourceKindSchema>
|
||||
|
||||
function errorCode(cause: unknown): string | undefined {
|
||||
return walkthroughErrorSchema.safeParse(cause).data?.code
|
||||
}
|
||||
|
||||
function errorCode(error: unknown): string | undefined {
|
||||
return (error as WalkthroughErrorLike | null)?.code
|
||||
}
|
||||
|
||||
function isNoChangesError(error: unknown): boolean {
|
||||
const code = errorCode(error)
|
||||
function isNoChangesError(cause: unknown): boolean {
|
||||
const code = errorCode(cause)
|
||||
return code === 'WALKTHROUGH_NO_CHANGES' || code === 'WALKTHROUGH_NO_TEXT_CHANGES'
|
||||
}
|
||||
|
||||
function walkthroughErrorMessage(error: unknown): string {
|
||||
const message = (error as WalkthroughErrorLike | null)?.message
|
||||
if (isNoChangesError(error)) {
|
||||
function walkthroughErrorMessage(cause: unknown): string {
|
||||
const message = walkthroughErrorSchema.safeParse(cause).data?.message
|
||||
if (isNoChangesError(cause)) {
|
||||
return message || 'This session has no text changes to walk through'
|
||||
}
|
||||
return message || 'Failed to load the walkthrough'
|
||||
@@ -80,7 +92,7 @@ function useChangesWalkthrough(): ChangesWalkthroughContextValue {
|
||||
return value
|
||||
}
|
||||
|
||||
const WALKTHROUGH_SOURCE_OPTIONS: { value: WalkthroughSource['kind']; label: string }[] = [
|
||||
const WALKTHROUGH_SOURCE_OPTIONS: Array<{ value: WalkthroughSourceKind; label: string }> = [
|
||||
{ value: 'session', label: 'This session' },
|
||||
{ value: 'uncommitted', label: 'Uncommitted' },
|
||||
{ value: 'staged', label: 'Staged' },
|
||||
@@ -89,12 +101,11 @@ const WALKTHROUGH_SOURCE_OPTIONS: { value: WalkthroughSource['kind']; label: str
|
||||
{ value: 'pullRequest', label: 'Pull request' },
|
||||
]
|
||||
|
||||
/** Chooses which set of changes the walkthrough covers from the surrounding chrome; git sources commit as soon as they are valid. */
|
||||
export const ChangesWalkthroughSourcePicker = memo(function ChangesWalkthroughSourcePicker() {
|
||||
const { sourceKind, setSourceKind, baseInput, setSource } = useChangesWalkthrough()
|
||||
|
||||
const handleKindChange = useCallback(
|
||||
(next: WalkthroughSource['kind']) => {
|
||||
(next: WalkthroughSourceKind) => {
|
||||
setSourceKind(next)
|
||||
if (next === 'pullRequest') return
|
||||
const nextSource = toWalkthroughSource({ kind: next, base: baseInput })
|
||||
@@ -104,7 +115,10 @@ export const ChangesWalkthroughSourcePicker = memo(function ChangesWalkthroughSo
|
||||
)
|
||||
|
||||
return (
|
||||
<Select value={sourceKind} onValueChange={(value) => handleKindChange(value as WalkthroughSource['kind'])}>
|
||||
<Select value={sourceKind} onValueChange={(value) => {
|
||||
const parsedKind = walkthroughSourceKindSchema.safeParse(value)
|
||||
if (parsedKind.success) handleKindChange(parsedKind.data)
|
||||
}}>
|
||||
<SelectTrigger
|
||||
aria-label="Changes to walk through"
|
||||
className="h-7 w-auto gap-1 px-2 text-xs md:text-xs"
|
||||
@@ -122,7 +136,6 @@ export const ChangesWalkthroughSourcePicker = memo(function ChangesWalkthroughSo
|
||||
)
|
||||
})
|
||||
|
||||
/** Collects the base branch or pull request number for git-backed walkthrough sources. */
|
||||
const WalkthroughSourceInputs = memo(function WalkthroughSourceInputs() {
|
||||
const { sourceKind, baseInput, setBaseInput, numberInput, setNumberInput, setSource } =
|
||||
useChangesWalkthrough()
|
||||
@@ -163,10 +176,6 @@ const WalkthroughSourceInputs = memo(function WalkthroughSourceInputs() {
|
||||
)
|
||||
})
|
||||
|
||||
/**
|
||||
* A one-shot request to open the walkthrough on a given source. A new request object re-applies, so a
|
||||
* repeated request for the same source takes effect; `source` undefined leaves the selection alone.
|
||||
*/
|
||||
export interface WalkthroughSourceRequest {
|
||||
sessionId: string
|
||||
source?: WalkthroughSource
|
||||
@@ -181,7 +190,6 @@ interface ChangesWalkthroughProviderProps {
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/** Loads a session's change walkthrough and shares its state with the surrounding chrome and body. */
|
||||
export function ChangesWalkthroughProvider({
|
||||
sessionId,
|
||||
active,
|
||||
@@ -266,7 +274,6 @@ export function ChangesWalkthroughProvider({
|
||||
return <ChangesWalkthroughContext.Provider value={value}>{children}</ChangesWalkthroughContext.Provider>
|
||||
}
|
||||
|
||||
/** Stops the in-flight walkthrough session from the chrome; renders nothing when the walkthrough is neither generating nor running. */
|
||||
export const ChangesWalkthroughCancel = memo(function ChangesWalkthroughCancel() {
|
||||
const { generating, running, stopping, stop } = useChangesWalkthrough()
|
||||
|
||||
@@ -287,7 +294,6 @@ export const ChangesWalkthroughCancel = memo(function ChangesWalkthroughCancel()
|
||||
)
|
||||
})
|
||||
|
||||
/** Regenerates the current walkthrough from the chrome; renders nothing until one exists. */
|
||||
export const ChangesWalkthroughRegenerate = memo(function ChangesWalkthroughRegenerate() {
|
||||
const { walkthrough, generating, regenerate, sourcePending } = useChangesWalkthrough()
|
||||
|
||||
@@ -306,7 +312,6 @@ export const ChangesWalkthroughRegenerate = memo(function ChangesWalkthroughRege
|
||||
)
|
||||
})
|
||||
|
||||
/** Renders the walkthrough body; the provider and its chrome supply the surrounding panel. */
|
||||
export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
|
||||
const {
|
||||
isLoading,
|
||||
@@ -479,7 +484,6 @@ interface ChangesWalkthroughSheetProps {
|
||||
onOpenSession?: (walkthroughSessionId: string) => void
|
||||
}
|
||||
|
||||
/** The walkthrough as a right-side sheet: full screen on mobile, a drawer over the page on desktop. */
|
||||
export function ChangesWalkthroughSheet({
|
||||
sessionId,
|
||||
open,
|
||||
|
||||
@@ -7,10 +7,6 @@ interface ContextUsageMeterProps {
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Thin context-window fill bar. Its accessible label lives on the model pill, so the bar itself is hidden
|
||||
* from assistive technology.
|
||||
*/
|
||||
export function ContextUsageMeter({ percentage, className }: ContextUsageMeterProps) {
|
||||
return (
|
||||
<Progress
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
import { fireEvent, render as renderRaw, screen, waitFor, within } from '@testing-library/react'
|
||||
import { fireEvent, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ReactElement } from 'react'
|
||||
import type { FormInfo } from '@opencode-manager/shared/opencode'
|
||||
import { KeyboardShortcutsProvider, useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
|
||||
import { KeyboardShortcutsProvider } from '@/contexts/KeyboardShortcutsContext'
|
||||
import { useShortcutActions } from '@/contexts/keyboard-shortcuts-context'
|
||||
import { makeSettingsResponse } from '@/test/fixtures/api'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
import { FormPrompt } from './FormPrompt'
|
||||
|
||||
vi.mock('@/hooks/useSettings', () => ({
|
||||
useSettings: () => ({ preferences: undefined }),
|
||||
}))
|
||||
|
||||
function render(ui: ReactElement) {
|
||||
return renderRaw(ui, { wrapper: KeyboardShortcutsProvider })
|
||||
return renderWithProviders(<KeyboardShortcutsProvider>{ui}</KeyboardShortcutsProvider>, {
|
||||
auth: false,
|
||||
theme: false,
|
||||
tts: false,
|
||||
toaster: false,
|
||||
fetchRoutes: [{ method: 'GET', path: '/api/settings', respond: () => ({ json: makeSettingsResponse() }) }],
|
||||
})
|
||||
}
|
||||
|
||||
function AbortLayer({ onAbort }: { onAbort: () => void }) {
|
||||
@@ -112,8 +117,8 @@ describe('FormPrompt', () => {
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
const input = screen.getByLabelText(/Count/) as HTMLInputElement
|
||||
expect(input.value).toBe('3')
|
||||
const input = screen.getByLabelText(/Count/)
|
||||
expect(input).toHaveValue(3)
|
||||
const submit = screen.getByRole('button', { name: 'Submit' })
|
||||
expect(submit).toBeEnabled()
|
||||
|
||||
@@ -131,11 +136,11 @@ describe('FormPrompt', () => {
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
const input = screen.getByLabelText(/Count/) as HTMLInputElement
|
||||
const input = screen.getByLabelText(/Count/)
|
||||
const submit = screen.getByRole('button', { name: 'Submit' })
|
||||
|
||||
await userEvent.clear(input)
|
||||
expect(input.value).toBe('')
|
||||
expect(input).toHaveValue(null)
|
||||
expect(submit).toBeDisabled()
|
||||
|
||||
await userEvent.type(input, '5')
|
||||
@@ -168,7 +173,7 @@ describe('FormPrompt', () => {
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
expect((screen.getByLabelText(/Name/) as HTMLTextAreaElement).value).toBe('Ada')
|
||||
expect(screen.getByLabelText(/Name/)).toHaveValue('Ada')
|
||||
expect(screen.getByRole('button', { name: 'No' })).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(screen.getByRole('button', { name: 'Alpha' })).toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
@@ -235,8 +240,8 @@ describe('FormPrompt', () => {
|
||||
expect(screen.getByRole('button', { name: 'Submit' })).toBeEnabled()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Other...' }))
|
||||
const customInput = screen.getByLabelText('Other answer for Answer') as HTMLTextAreaElement
|
||||
expect(customInput.value).toBe('Yesterday')
|
||||
const customInput = screen.getByLabelText('Other answer for Answer')
|
||||
expect(customInput).toHaveValue('Yesterday')
|
||||
|
||||
await userEvent.clear(customInput)
|
||||
await userEvent.type(customInput, 'Tomorrow')
|
||||
@@ -407,7 +412,7 @@ describe('FormPrompt', () => {
|
||||
const customInput = screen.getByLabelText('Other answer for Answer')
|
||||
await userEvent.type(customInput, 'Yesterday')
|
||||
|
||||
expect((customInput as HTMLTextAreaElement).value).toBe('Yesterday')
|
||||
expect(customInput).toHaveValue('Yesterday')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
|
||||
await waitFor(() =>
|
||||
@@ -442,7 +447,7 @@ describe('FormPrompt', () => {
|
||||
const customInput = screen.getByLabelText('Other answer for Features')
|
||||
await userEvent.type(customInput, 'Yesterday')
|
||||
|
||||
expect((customInput as HTMLTextAreaElement).value).toBe('Yesterday')
|
||||
expect(customInput).toHaveValue('Yesterday')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
|
||||
await waitFor(() =>
|
||||
@@ -478,8 +483,8 @@ describe('FormPrompt', () => {
|
||||
expect(screen.getByText('Yesterday')).toBeInTheDocument()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Other...' }))
|
||||
const reopened = screen.getByLabelText('Other answer for Answer') as HTMLTextAreaElement
|
||||
expect(reopened.value).toBe('Yesterday')
|
||||
const reopened = screen.getByLabelText('Other answer for Answer')
|
||||
expect(reopened).toHaveValue('Yesterday')
|
||||
|
||||
await userEvent.clear(reopened)
|
||||
await userEvent.type(reopened, 'Tomorrow')
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from 'react'
|
||||
import { z } from 'zod'
|
||||
import { X, ChevronDown, ChevronUp, Check, Loader2, MessageCircleQuestion } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { ExternalFieldCard } from '@/components/ui/external-field-card'
|
||||
import { readJsonNumber, readJsonString } from '@/components/jsonValue'
|
||||
import type { FormAnswer, FormField, FormInfo } from '@opencode-manager/shared/opencode'
|
||||
import { buildAnswer, hasMissingAnswers, visibleFields } from '@/lib/formFields'
|
||||
import { clearFormDraft, loadFormDraft, saveFormDraft, type FormDraft } from '@/lib/formDrafts'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
|
||||
import { useShortcutActions } from '@/contexts/keyboard-shortcuts-context'
|
||||
import { useMobile, useSwipeDismiss } from '@/hooks/useMobile'
|
||||
|
||||
type AnswerableFormField = Exclude<FormField, { type: 'external' }>
|
||||
@@ -48,8 +50,9 @@ function buildInitialState(fields: AnswerableFormField[]): FormDraft {
|
||||
if (custom.length > 0) customValues[field.key] = [...new Set(custom)]
|
||||
continue
|
||||
}
|
||||
if (typeof value === 'string' && usesCustomInput(field) && !isPredefinedValue(field, value)) {
|
||||
customDrafts[field.key] = value
|
||||
const textValue = z.string().safeParse(value)
|
||||
if (textValue.success && usesCustomInput(field) && !isPredefinedValue(field, textValue.data)) {
|
||||
customDrafts[field.key] = textValue.data
|
||||
continue
|
||||
}
|
||||
answer[field.key] = value
|
||||
@@ -202,7 +205,7 @@ export function FormPrompt({ form, onReply, onCancel, onMinimize, onAskSideQuest
|
||||
const descriptionId = field.description ? `${inputId}-description` : undefined
|
||||
|
||||
if (field.type === 'boolean') {
|
||||
const selected = typeof value === 'boolean' ? value : undefined
|
||||
const selected = z.boolean().safeParse(value).data
|
||||
return (
|
||||
<FieldGroup key={field.key} label={label} description={field.description} required={required}>
|
||||
<div className="flex gap-3 md:gap-2">
|
||||
@@ -214,7 +217,7 @@ export function FormPrompt({ form, onReply, onCancel, onMinimize, onAskSideQuest
|
||||
}
|
||||
|
||||
if (field.type === 'number' || field.type === 'integer') {
|
||||
const numberValue = typeof value === 'number' || typeof value === 'string' ? value : ''
|
||||
const numberValue = z.union([z.number(), z.string()]).safeParse(value).data ?? ''
|
||||
return (
|
||||
<div key={field.key} className="space-y-2">
|
||||
<FieldLabel id={inputId} label={label} description={field.description} required={required} />
|
||||
@@ -223,8 +226,8 @@ export function FormPrompt({ form, onReply, onCancel, onMinimize, onAskSideQuest
|
||||
type="number"
|
||||
aria-describedby={descriptionId}
|
||||
value={numberValue}
|
||||
min={typeof field.minimum === 'number' ? field.minimum : undefined}
|
||||
max={typeof field.maximum === 'number' ? field.maximum : undefined}
|
||||
min={readJsonNumber(field.minimum)}
|
||||
max={readJsonNumber(field.maximum)}
|
||||
step={field.type === 'integer' ? 1 : 'any'}
|
||||
onChange={(e) => setFieldAnswer(field.key, e.target.value === '' ? '' : Number(e.target.value))}
|
||||
className="w-full rounded-lg border border-border bg-muted/60 dark:bg-muted/5 px-3.5 py-3 text-base focus:border-primary focus:outline-none md:px-3 md:py-2 md:text-sm"
|
||||
@@ -274,7 +277,7 @@ export function FormPrompt({ form, onReply, onCancel, onMinimize, onAskSideQuest
|
||||
}
|
||||
|
||||
if (field.options && field.options.length > 0) {
|
||||
const selected = typeof value === 'string' ? value : ''
|
||||
const selected = readJsonString(value) ?? ''
|
||||
const customValue = customDrafts[field.key] ?? ''
|
||||
return (
|
||||
<FieldGroup key={field.key} label={label} description={field.description} required={required}>
|
||||
@@ -317,7 +320,7 @@ export function FormPrompt({ form, onReply, onCancel, onMinimize, onAskSideQuest
|
||||
<Textarea
|
||||
id={inputId}
|
||||
aria-describedby={descriptionId}
|
||||
value={typeof value === 'string' ? value : ''}
|
||||
value={readJsonString(value) ?? ''}
|
||||
onChange={(e) => setFieldAnswer(field.key, e.target.value)}
|
||||
placeholder={field.placeholder ?? 'Type your answer...'}
|
||||
className="min-h-[60px] md:min-h-[80px] text-[16px] md:text-sm resize-none border-primary/30 focus:border-primary"
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { PermissionRequestDialog } from '@/components/session/PermissionRequestDialog'
|
||||
import { isLocalOpenCodeServer } from '@/contexts/opencode-server-context'
|
||||
import { useEventContext, usePermissions } from '@/contexts/event-context'
|
||||
import { sessionQueryOptions } from '@/hooks/useOpenCode'
|
||||
|
||||
export function PermissionDialogWrapper() {
|
||||
const {
|
||||
current: currentPermission,
|
||||
pendingCount,
|
||||
respond: replyToPermission,
|
||||
showDialog,
|
||||
setShowDialog,
|
||||
navigateToCurrent,
|
||||
viewedSessionId,
|
||||
currentDirectory,
|
||||
currentIsFromDifferentSession,
|
||||
} = usePermissions()
|
||||
const { getRepoIdForSession } = useEventContext()
|
||||
const isRemotePermission = currentPermission !== null && !isLocalOpenCodeServer(currentPermission.serverId)
|
||||
const { data: session } = useQuery(
|
||||
sessionQueryOptions(
|
||||
currentPermission?.sessionID,
|
||||
currentDirectory ?? undefined,
|
||||
currentPermission?.serverId ?? LOCAL_OPENCODE_SERVER_ID,
|
||||
),
|
||||
)
|
||||
|
||||
const canOpenCurrentSession = currentPermission !== null
|
||||
&& (isRemotePermission || getRepoIdForSession(currentPermission.sessionID) !== null)
|
||||
&& (currentIsFromDifferentSession || viewedSessionId === null)
|
||||
|
||||
return (
|
||||
<PermissionRequestDialog
|
||||
permission={currentPermission}
|
||||
pendingCount={pendingCount}
|
||||
isFromDifferentSession={currentIsFromDifferentSession}
|
||||
sessionTitle={session?.title ?? undefined}
|
||||
repoDirectory={currentDirectory}
|
||||
onOpenSession={canOpenCurrentSession ? navigateToCurrent : undefined}
|
||||
onRespond={replyToPermission}
|
||||
open={showDialog}
|
||||
onOpenChange={setShowDialog}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import {
|
||||
SetSessionPermissionModeRequestSchema,
|
||||
type SessionPermissionModeState,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { FetchRoute, FetchRouteResult } from '@/test/fetchFake'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
import { PermissionModeToggle } from './PermissionModeToggle'
|
||||
import { useSessionPermissionMode, useSetSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
|
||||
import type { SessionPermissionModeState } from '@opencode-manager/shared/schemas'
|
||||
|
||||
vi.mock('@/hooks/useSessionPermissionMode')
|
||||
|
||||
const baseState: SessionPermissionModeState = {
|
||||
sessionId: 'ses_1',
|
||||
@@ -14,108 +16,87 @@ const baseState: SessionPermissionModeState = {
|
||||
lockedReason: null,
|
||||
}
|
||||
|
||||
function mockHooks(overrides: {
|
||||
data?: SessionPermissionModeState | undefined
|
||||
state?: Partial<SessionPermissionModeState>
|
||||
mutate?: ReturnType<typeof vi.fn>
|
||||
isPending?: boolean
|
||||
isError?: boolean
|
||||
} = {}) {
|
||||
const data = 'data' in overrides ? overrides.data : { ...baseState, ...overrides.state }
|
||||
vi.mocked(useSessionPermissionMode).mockReturnValue({
|
||||
data,
|
||||
isError: overrides.isError ?? false,
|
||||
} as ReturnType<typeof useSessionPermissionMode>)
|
||||
vi.mocked(useSetSessionPermissionMode).mockReturnValue({
|
||||
mutate: overrides.mutate ?? vi.fn(),
|
||||
isPending: overrides.isPending ?? false,
|
||||
} as unknown as ReturnType<typeof useSetSessionPermissionMode>)
|
||||
function renderToggle(initial: SessionPermissionModeState, getRespond?: FetchRoute['respond']) {
|
||||
let state = initial
|
||||
const modeUrl = `/api/session-permission-modes/${initial.sessionId}`
|
||||
|
||||
const routes: FetchRoute[] = [
|
||||
{
|
||||
method: 'GET',
|
||||
path: modeUrl,
|
||||
respond: getRespond ?? (() => ({ json: state })),
|
||||
},
|
||||
{
|
||||
method: 'PUT',
|
||||
path: modeUrl,
|
||||
respond: (request) => {
|
||||
const parsed = SetSessionPermissionModeRequestSchema.safeParse(request.body)
|
||||
if (parsed.success) state = { ...state, mode: parsed.data.mode }
|
||||
return { json: state }
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
return renderWithProviders(<PermissionModeToggle sessionID={initial.sessionId} directory="/repo" />, {
|
||||
auth: false,
|
||||
theme: false,
|
||||
tts: false,
|
||||
toaster: false,
|
||||
serverId: 'srv_remote',
|
||||
fetchRoutes: routes,
|
||||
})
|
||||
}
|
||||
|
||||
describe('PermissionModeToggle', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders the ask state', () => {
|
||||
mockHooks()
|
||||
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Permissions: follow configured rules' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('switches to accept-everything with the directory when clicked', async () => {
|
||||
it.each([
|
||||
['ask', 'Permissions: follow configured rules', 'auto'],
|
||||
['auto', 'Permissions: auto-accept all', 'ask'],
|
||||
] as const)('switches a loaded %s mode to %s through the current server', async (mode, label, nextMode) => {
|
||||
const user = userEvent.setup()
|
||||
const mutate = vi.fn()
|
||||
mockHooks({ mutate })
|
||||
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
|
||||
const { fetchFake } = renderToggle({ ...baseState, mode })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Permissions: follow configured rules' }))
|
||||
await user.click(await screen.findByRole('button', { name: label }))
|
||||
|
||||
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'auto' })
|
||||
await waitFor(() =>
|
||||
expect(fetchFake.lastRequest('PUT', '/api/session-permission-modes/ses_1')?.body).toEqual({
|
||||
directory: '/repo',
|
||||
mode: nextMode,
|
||||
serverId: 'srv_remote',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('switches back to ask when already accepting everything', async () => {
|
||||
it.each([
|
||||
['child', 'Inherited from parent session'],
|
||||
['schedule', "Scheduled runs use the schedule's permission configuration"],
|
||||
] as const)('is disabled and labelled for %s-locked sessions', async (lockedReason, label) => {
|
||||
renderToggle({ ...baseState, mode: 'auto', lockedReason })
|
||||
|
||||
expect(await screen.findByRole('button', { name: label })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('stays disabled and skips the write while the mode read is pending', async () => {
|
||||
const user = userEvent.setup()
|
||||
const mutate = vi.fn()
|
||||
mockHooks({ state: { mode: 'auto' }, mutate })
|
||||
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Permissions: auto-accept all' }))
|
||||
|
||||
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'ask' })
|
||||
})
|
||||
|
||||
it('is disabled and labelled as locked for child sessions', () => {
|
||||
mockHooks({ state: { lockedReason: 'child', mode: 'auto' } })
|
||||
render(<PermissionModeToggle sessionID="ses_child" directory="/repo" />)
|
||||
|
||||
const button = screen.getByRole('button', { name: 'Inherited from parent session' })
|
||||
expect(button).toBeDisabled()
|
||||
})
|
||||
|
||||
it('is disabled and labelled for schedule-run sessions', () => {
|
||||
mockHooks({ state: { lockedReason: 'schedule', mode: 'ask' } })
|
||||
render(<PermissionModeToggle sessionID="ses_sched" directory="/repo" />)
|
||||
|
||||
const button = screen.getByRole('button', { name: "Scheduled runs use the schedule's permission configuration" })
|
||||
expect(button).toBeDisabled()
|
||||
})
|
||||
|
||||
it('cannot mutate while the mode read is still loading', async () => {
|
||||
const user = userEvent.setup()
|
||||
const mutate = vi.fn()
|
||||
mockHooks({ data: undefined, mutate })
|
||||
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
|
||||
const { fetchFake } = renderToggle(
|
||||
baseState,
|
||||
() => new Promise<FetchRouteResult>(() => undefined),
|
||||
)
|
||||
|
||||
const button = screen.getByRole('button', { name: 'Permissions: loading' })
|
||||
expect(button).toBeDisabled()
|
||||
|
||||
await user.click(button)
|
||||
expect(mutate).not.toHaveBeenCalled()
|
||||
expect(fetchFake.findRequests('PUT', '/api/session-permission-modes/ses_1')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('cannot mutate and reports unavailable when the mode read failed', async () => {
|
||||
it('stays disabled and reports unavailable when the mode read fails', async () => {
|
||||
const user = userEvent.setup()
|
||||
const mutate = vi.fn()
|
||||
mockHooks({ data: undefined, isError: true, mutate })
|
||||
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
|
||||
const { fetchFake } = renderToggle(baseState, () => ({ status: 500, json: { error: 'boom' } }))
|
||||
|
||||
const button = screen.getByRole('button', { name: 'Permissions: unavailable' })
|
||||
const button = await screen.findByRole('button', { name: 'Permissions: unavailable' })
|
||||
expect(button).toBeDisabled()
|
||||
|
||||
await user.click(button)
|
||||
expect(mutate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('switches a loaded auto mode back to ask when clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const mutate = vi.fn()
|
||||
mockHooks({ data: { ...baseState, mode: 'auto' }, mutate })
|
||||
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Permissions: auto-accept all' }))
|
||||
|
||||
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'ask' })
|
||||
expect(fetchFake.findRequests('PUT', '/api/session-permission-modes/ses_1')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -1,15 +1,11 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import type { PermissionReply, PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
import { PermissionRequestDialog } from './PermissionRequestDialog'
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: {
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const permission: PermissionRequest = {
|
||||
id: 'perm-1',
|
||||
sessionID: 'session-1',
|
||||
@@ -25,40 +21,36 @@ const secondPermission: PermissionRequest = {
|
||||
resources: ['git push origin main'],
|
||||
}
|
||||
|
||||
function renderDialog(overrides: Partial<Parameters<typeof PermissionRequestDialog>[0]> = {}) {
|
||||
const onRespond = overrides.onRespond ?? vi.fn<
|
||||
(permissionID: string, sessionID: string, response: PermissionReply, message?: string) => Promise<void>
|
||||
>(() => Promise.resolve())
|
||||
const result = renderWithProviders(
|
||||
<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} {...overrides} />,
|
||||
)
|
||||
return { ...result, onRespond }
|
||||
}
|
||||
|
||||
describe('PermissionRequestDialog', () => {
|
||||
it('renders the action label and command detail', () => {
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={vi.fn()} />)
|
||||
renderDialog()
|
||||
|
||||
expect(screen.getByText('Run Command')).toBeInTheDocument()
|
||||
expect(screen.getByText('Command')).toBeInTheDocument()
|
||||
expect(screen.getByText('rm -rf node_modules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('phrases the allow question in lowercase while preserving acronyms', () => {
|
||||
const { unmount } = render(
|
||||
<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={vi.fn()} />,
|
||||
)
|
||||
expect(screen.getByText('Allow run command?')).toBeInTheDocument()
|
||||
unmount()
|
||||
it.each([
|
||||
['shell', 'Allow run command?'],
|
||||
['webfetch', 'Allow fetch URL?'],
|
||||
] as const)('phrases the allow question in lowercase for %s', (action, question) => {
|
||||
renderDialog({ permission: { ...permission, action, resources: [], metadata: { url: 'https://example.com' } } })
|
||||
|
||||
render(
|
||||
<PermissionRequestDialog
|
||||
permission={{ ...permission, action: 'webfetch', resources: [], metadata: { url: 'https://example.com' } }}
|
||||
pendingCount={1}
|
||||
onRespond={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('Allow fetch URL?')).toBeInTheDocument()
|
||||
expect(screen.getByText(question)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('labels multiple shell resources as commands', () => {
|
||||
render(
|
||||
<PermissionRequestDialog
|
||||
permission={{ ...permission, resources: ['git status', 'git push origin main'] }}
|
||||
pendingCount={1}
|
||||
onRespond={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
renderDialog({ permission: { ...permission, resources: ['git status', 'git push origin main'] } })
|
||||
|
||||
expect(screen.getByText('Commands')).toBeInTheDocument()
|
||||
expect(screen.getByText(/git status/)).toBeInTheDocument()
|
||||
@@ -66,37 +58,19 @@ describe('PermissionRequestDialog', () => {
|
||||
})
|
||||
|
||||
it('shows the request message when present', () => {
|
||||
render(
|
||||
<PermissionRequestDialog
|
||||
permission={{ ...permission, message: 'This command modifies tracked files.' }}
|
||||
pendingCount={1}
|
||||
onRespond={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
renderDialog({ permission: { ...permission, message: 'This command modifies tracked files.' } })
|
||||
|
||||
expect(screen.getByText('This command modifies tracked files.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('describes a wildcard always scope', () => {
|
||||
render(
|
||||
<PermissionRequestDialog
|
||||
permission={{ ...permission, save: ['*'] }}
|
||||
pendingCount={1}
|
||||
onRespond={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
renderDialog({ permission: { ...permission, save: ['*'] } })
|
||||
|
||||
expect(screen.getByText('This will always allow run command for this project.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('lists the patterns an always decision approves', () => {
|
||||
render(
|
||||
<PermissionRequestDialog
|
||||
permission={{ ...permission, save: ['printf *', 'echo *'] }}
|
||||
pendingCount={1}
|
||||
onRespond={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
renderDialog({ permission: { ...permission, save: ['printf *', 'echo *'] } })
|
||||
|
||||
expect(
|
||||
screen.getByText('This will always allow the following patterns for this project.'),
|
||||
@@ -106,114 +80,96 @@ describe('PermissionRequestDialog', () => {
|
||||
})
|
||||
|
||||
it('omits the always option when no save patterns are provided', () => {
|
||||
render(
|
||||
<PermissionRequestDialog
|
||||
permission={{ ...permission, save: undefined }}
|
||||
pendingCount={1}
|
||||
onRespond={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
renderDialog({ permission: { ...permission, save: undefined } })
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Allow Always' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText(/This will always allow/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders an open session control that triggers the handler', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onOpenSession = vi.fn()
|
||||
render(
|
||||
<PermissionRequestDialog
|
||||
permission={permission}
|
||||
pendingCount={1}
|
||||
onRespond={vi.fn()}
|
||||
onOpenSession={onOpenSession}
|
||||
/>,
|
||||
)
|
||||
renderDialog({ onOpenSession })
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Open session' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Open session' }))
|
||||
|
||||
expect(onOpenSession).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('omits the open session control without a handler', () => {
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={vi.fn()} />)
|
||||
renderDialog()
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Open session' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('focuses the allow action instead of the optional reason field', async () => {
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={vi.fn()} />)
|
||||
renderDialog()
|
||||
|
||||
const allowOnce = screen.getByRole('button', { name: 'Allow Once' })
|
||||
await waitFor(() => expect(allowOnce).toHaveFocus())
|
||||
expect(screen.getByLabelText('Reason (optional)')).not.toHaveFocus()
|
||||
})
|
||||
|
||||
it('replies with the selected decision for the permission request', async () => {
|
||||
const onRespond = vi.fn().mockResolvedValue(undefined)
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
|
||||
it.each([
|
||||
['Allow Once', undefined, 'once', undefined],
|
||||
['Allow Always', 'not allowed', 'always', undefined],
|
||||
['Deny', 'not allowed', 'reject', 'not allowed'],
|
||||
['Deny', undefined, 'reject', undefined],
|
||||
] as const)(
|
||||
'replies with %s and the expected reason',
|
||||
async (button, typedReason, response, reason) => {
|
||||
const user = userEvent.setup()
|
||||
const { onRespond } = renderDialog()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Allow Once' }))
|
||||
if (typedReason) await user.type(screen.getByLabelText('Reason (optional)'), typedReason)
|
||||
await user.click(screen.getByRole('button', { name: button }))
|
||||
|
||||
expect(onRespond).toHaveBeenCalledWith('perm-1', 'session-1', 'once', undefined)
|
||||
})
|
||||
|
||||
it('forwards an optional rejection reason when denying', async () => {
|
||||
const onRespond = vi.fn().mockResolvedValue(undefined)
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Reason (optional)'), 'not allowed')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Deny' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onRespond).toHaveBeenCalledWith('perm-1', 'session-1', 'reject', 'not allowed'),
|
||||
)
|
||||
})
|
||||
|
||||
it('denies without a reason when none is supplied', async () => {
|
||||
const onRespond = vi.fn().mockResolvedValue(undefined)
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Deny' }))
|
||||
|
||||
await waitFor(() => expect(onRespond).toHaveBeenCalledWith('perm-1', 'session-1', 'reject', undefined))
|
||||
})
|
||||
|
||||
it('omits the reason for allow decisions', async () => {
|
||||
const onRespond = vi.fn().mockResolvedValue(undefined)
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Reason (optional)'), 'not allowed')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Allow Always' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onRespond).toHaveBeenCalledWith('perm-1', 'session-1', 'always', undefined),
|
||||
)
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(onRespond).toHaveBeenCalledWith('perm-1', 'session-1', response, reason),
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
it('resets the rejection reason when the permission identity changes', async () => {
|
||||
const onRespond = vi.fn().mockResolvedValue(undefined)
|
||||
const { rerender } = render(
|
||||
<PermissionRequestDialog permission={permission} pendingCount={2} onRespond={onRespond} />,
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Reason (optional)'), 'not allowed')
|
||||
expect((screen.getByLabelText('Reason (optional)') as HTMLTextAreaElement).value).toBe('not allowed')
|
||||
function Host() {
|
||||
const [current, setCurrent] = useState(permission)
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setCurrent(secondPermission)}>
|
||||
next permission
|
||||
</button>
|
||||
<PermissionRequestDialog
|
||||
permission={current}
|
||||
pendingCount={current.id === 'perm-1' ? 2 : 1}
|
||||
onRespond={vi.fn(() => Promise.resolve())}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
rerender(<PermissionRequestDialog permission={secondPermission} pendingCount={1} onRespond={onRespond} />)
|
||||
renderWithProviders(<Host />)
|
||||
|
||||
await waitFor(() =>
|
||||
expect((screen.getByLabelText('Reason (optional)') as HTMLTextAreaElement).value).toBe(''),
|
||||
)
|
||||
await user.type(screen.getByLabelText('Reason (optional)'), 'not allowed')
|
||||
expect(screen.getByLabelText('Reason (optional)')).toHaveValue('not allowed')
|
||||
|
||||
fireEvent.click(screen.getByText('next permission'))
|
||||
|
||||
await waitFor(() => expect(screen.getByLabelText('Reason (optional)')).toHaveValue(''))
|
||||
})
|
||||
|
||||
it('retains the rejection reason when the request fails', async () => {
|
||||
const onRespond = vi.fn().mockRejectedValueOnce(new Error('network'))
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
|
||||
it('retains the rejection reason and reports the failure', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onRespond } = renderDialog({ onRespond: vi.fn(() => Promise.reject(new Error('network'))) })
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Reason (optional)'), 'not allowed')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Deny' }))
|
||||
await user.type(screen.getByLabelText('Reason (optional)'), 'not allowed')
|
||||
await user.click(screen.getByRole('button', { name: 'Deny' }))
|
||||
|
||||
await waitFor(() => expect(onRespond).toHaveBeenCalledTimes(1))
|
||||
expect((screen.getByLabelText('Reason (optional)') as HTMLTextAreaElement).value).toBe('not allowed')
|
||||
expect(screen.getByLabelText('Reason (optional)')).toHaveValue('not allowed')
|
||||
expect(
|
||||
await screen.findByText('Failed to respond to permission. Please try again.'),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -36,12 +36,6 @@ interface PermissionRequestDialogProps {
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a modal prompt for the current pending permission request with
|
||||
* allow-once, always-allow, and reject actions plus a count of further queued
|
||||
* requests. Focus starts on allow-once, and the rejection reason resets
|
||||
* whenever the request changes.
|
||||
*/
|
||||
export function PermissionRequestDialog({
|
||||
permission,
|
||||
pendingCount,
|
||||
@@ -66,10 +60,6 @@ export function PermissionRequestDialog({
|
||||
if (!permission) return null
|
||||
if (parentOpen === false) return null
|
||||
|
||||
/**
|
||||
* Sends the user's reply for the current permission request, passing the trimmed rejection reason
|
||||
* only for rejections, and reports failures as a toast while clearing the pending action state.
|
||||
*/
|
||||
const handleResponse = async (response: PermissionReply) => {
|
||||
setIsLoading(true)
|
||||
setLoadingAction(response)
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Search } from 'lucide-react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
|
||||
export interface PickerSearchBarProps {
|
||||
inputRef: React.RefObject<HTMLInputElement | null>
|
||||
listId: string
|
||||
open: boolean
|
||||
activeDescendantId: string | undefined
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void
|
||||
placeholder: string
|
||||
name: string
|
||||
trailing?: React.ReactNode
|
||||
}
|
||||
|
||||
export function PickerSearchBar({
|
||||
inputRef,
|
||||
listId,
|
||||
open,
|
||||
activeDescendantId,
|
||||
value,
|
||||
onChange,
|
||||
onKeyDown,
|
||||
placeholder,
|
||||
name,
|
||||
trailing,
|
||||
}: PickerSearchBarProps) {
|
||||
return (
|
||||
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
ref={inputRef}
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
aria-controls={listId}
|
||||
aria-autocomplete="list"
|
||||
aria-activedescendant={activeDescendantId}
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder={placeholder}
|
||||
className="h-9 pl-9"
|
||||
autoComplete="off"
|
||||
name={name}
|
||||
/>
|
||||
</div>
|
||||
{trailing}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -4,12 +4,8 @@ import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
|
||||
import { LocalRepoNewSessionButton } from '@/components/navigation/RepoSessionNav'
|
||||
import { isRepoReady } from '@/components/navigation/sidebar-session-tree'
|
||||
import { cn, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
|
||||
import {
|
||||
PickerSearchBar,
|
||||
optionId,
|
||||
usePickerCursor,
|
||||
usePickerKeyNav,
|
||||
} from '@/components/session/usePickerKeyboardNav'
|
||||
import { PickerSearchBar } from '@/components/session/PickerSearchBar'
|
||||
import { optionId, usePickerCursor, usePickerKeyNav } from '@/components/session/picker-cursor'
|
||||
|
||||
interface ProjectPickerContentProps {
|
||||
open: boolean
|
||||
|
||||
@@ -4,19 +4,10 @@ import type { SessionPickerNavigation } from '@/hooks/useSessionPickerNavigation
|
||||
import { useSessionPickerRouteScope } from '@/hooks/useSessionPickerRouteScope'
|
||||
|
||||
export interface RouteSessionPickerProps {
|
||||
/** Session and repo handlers built by the host, so choosing a row navigates the same way it hosts. */
|
||||
navigation: SessionPickerNavigation
|
||||
/**
|
||||
* Replaces the panel's internal add-repo dialog with the host's own, letting the host close itself
|
||||
* first. When omitted the panel opens its own dialog.
|
||||
*/
|
||||
onAddRepo?: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Session picker scoped to the route in view, including the linked-server selector. Hosts mount it
|
||||
* only while visible, so the route scope resolves repos and the remote server only then.
|
||||
*/
|
||||
export function RouteSessionPicker({ navigation, onAddRepo }: RouteSessionPickerProps) {
|
||||
const { currentRepo, activeSessionID, remote } = useSessionPickerRouteScope(true)
|
||||
|
||||
|
||||
@@ -1,19 +1,10 @@
|
||||
import { useState } from 'react'
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { installWindowSize } from '@/test/browserFakes'
|
||||
import { SessionDetailsSheet, type SessionDetailsSheetProps } from './SessionDetailsSheet'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useMobile: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: mocks.useMobile,
|
||||
useSwipeBack: vi.fn(() => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} })),
|
||||
useSwipeDismiss: vi.fn(() => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} })),
|
||||
}))
|
||||
|
||||
const baseProps: SessionDetailsSheetProps = {
|
||||
open: true,
|
||||
onOpenChange: vi.fn(),
|
||||
@@ -38,15 +29,11 @@ function failingRename(error = new Error('nope')) {
|
||||
}
|
||||
|
||||
function renderSheet(overrides: Partial<SessionDetailsSheetProps> = {}) {
|
||||
installWindowSize(1024)
|
||||
return render(<SessionDetailsSheet {...baseProps} {...overrides} />)
|
||||
}
|
||||
|
||||
describe('SessionDetailsSheet', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
})
|
||||
|
||||
it('lists the local session details', () => {
|
||||
renderSheet({ branch: 'feat/header', directory: '/abs/repos/oc-manager' })
|
||||
|
||||
@@ -244,8 +231,8 @@ describe('SessionDetailsSheet', () => {
|
||||
})
|
||||
|
||||
it('renders as a bottom sheet on mobile', () => {
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
renderSheet({ branch: 'feat/header' })
|
||||
installWindowSize(500, 800)
|
||||
render(<SessionDetailsSheet {...baseProps} branch="feat/header" />)
|
||||
|
||||
expect(screen.getByRole('dialog')).toHaveAccessibleName('Session details')
|
||||
expect(screen.getByText('feat/header')).toBeInTheDocument()
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { SessionGoalRead } from '@opencode-manager/shared/opencode'
|
||||
import type { FetchRoute, FetchRouteResult } from '@/test/fetchFake'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
import { SessionGoalBar } from './SessionGoalBar'
|
||||
import { useSessionGoal, useSessionGoalCommand } from '@/hooks/useSessionGoals'
|
||||
import type { GoalState, SessionGoalRead } from '@opencode-manager/shared/opencode'
|
||||
|
||||
vi.mock('@/hooks/useSessionGoals')
|
||||
|
||||
const baseGoal: GoalState = {
|
||||
const goal = {
|
||||
id: 'goal_1',
|
||||
objective: 'Ship the feature',
|
||||
status: 'active',
|
||||
@@ -15,88 +14,111 @@ const baseGoal: GoalState = {
|
||||
maxRounds: 50,
|
||||
boot: 'boot_1',
|
||||
updatedAt: 1,
|
||||
}
|
||||
} as const
|
||||
|
||||
function mockGoal(
|
||||
read: SessionGoalRead,
|
||||
overrides: { mutate?: ReturnType<typeof vi.fn>; isPending?: boolean } = {},
|
||||
) {
|
||||
vi.mocked(useSessionGoal).mockReturnValue({ data: read } as ReturnType<typeof useSessionGoal>)
|
||||
vi.mocked(useSessionGoalCommand).mockReturnValue({
|
||||
mutate: overrides.mutate ?? vi.fn(),
|
||||
isPending: overrides.isPending ?? false,
|
||||
} as unknown as ReturnType<typeof useSessionGoalCommand>)
|
||||
}
|
||||
const goalRoute = (read: SessionGoalRead): FetchRoute => ({
|
||||
method: 'POST',
|
||||
path: '/api/opencode/api/rpc/opencode.goal/get',
|
||||
respond: () => ({ json: { output: read.goal } }),
|
||||
})
|
||||
|
||||
function renderBar() {
|
||||
return render(<SessionGoalBar sessionID="ses_1" directory="/repo" />)
|
||||
const commandRoute = (respond?: FetchRoute['respond']): FetchRoute => ({
|
||||
method: 'POST',
|
||||
path: '/api/opencode/api/session/ses_1/command',
|
||||
respond: respond ?? (() => ({ status: 204 })),
|
||||
})
|
||||
|
||||
function renderBar(read: SessionGoalRead, commandRespond?: FetchRoute['respond']) {
|
||||
return renderWithProviders(<SessionGoalBar sessionID="ses_1" directory="/repo" />, {
|
||||
auth: false,
|
||||
theme: false,
|
||||
tts: false,
|
||||
toaster: false,
|
||||
fetchRoutes: [goalRoute(read), commandRoute(commandRespond)],
|
||||
})
|
||||
}
|
||||
|
||||
describe('SessionGoalBar', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
it.each([
|
||||
['an empty goal', { supported: true, goal: null }],
|
||||
['an unsupported server', { supported: false }],
|
||||
] as const)('renders nothing for %s', (_label, read) => {
|
||||
const { container } = renderBar(read)
|
||||
|
||||
it('renders nothing when the active goal is empty', () => {
|
||||
mockGoal({ supported: true, goal: null })
|
||||
const { container } = renderBar()
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('renders nothing when the server does not support goals', () => {
|
||||
mockGoal({ supported: false })
|
||||
const { container } = renderBar()
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('shows the active goal and pauses it', async () => {
|
||||
it('shows the active goal and pauses or clears it through the goal command', async () => {
|
||||
const user = userEvent.setup()
|
||||
const mutate = vi.fn()
|
||||
mockGoal({ supported: true, goal: { ...baseGoal } }, { mutate })
|
||||
renderBar()
|
||||
const { fetchFake } = renderBar({ supported: true, goal })
|
||||
|
||||
expect(screen.getByText('Goal active')).toBeInTheDocument()
|
||||
expect(await screen.findByText('Goal active')).toBeInTheDocument()
|
||||
expect(screen.getByText('Round 3/50')).toBeInTheDocument()
|
||||
expect(screen.getByText('Ship the feature')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Pause' }))
|
||||
expect(mutate).toHaveBeenCalledWith({ sessionID: 'ses_1', text: 'pause' })
|
||||
await waitFor(() =>
|
||||
expect(fetchFake.lastRequest('POST', '/api/opencode/api/session/ses_1/command')?.body).toMatchObject({
|
||||
name: 'goal',
|
||||
text: 'pause',
|
||||
}),
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Clear' }))
|
||||
expect(mutate).toHaveBeenCalledWith({ sessionID: 'ses_1', text: 'clear' })
|
||||
await waitFor(() =>
|
||||
expect(fetchFake.lastRequest('POST', '/api/opencode/api/session/ses_1/command')?.body).toMatchObject({
|
||||
name: 'goal',
|
||||
text: 'clear',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('resumes a paused goal and shows the pause reason', async () => {
|
||||
const user = userEvent.setup()
|
||||
const mutate = vi.fn()
|
||||
mockGoal({ supported: true, goal: { ...baseGoal, status: 'paused', reason: 'Paused by the user' } }, { mutate })
|
||||
renderBar()
|
||||
const { fetchFake } = renderBar({
|
||||
supported: true,
|
||||
goal: { ...goal, status: 'paused', reason: 'Paused by the user' },
|
||||
})
|
||||
|
||||
expect(screen.getByText('Goal paused')).toBeInTheDocument()
|
||||
expect(await screen.findByText('Goal paused')).toBeInTheDocument()
|
||||
expect(screen.getByText('Paused by the user')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Resume' }))
|
||||
expect(mutate).toHaveBeenCalledWith({ sessionID: 'ses_1', text: 'resume' })
|
||||
await waitFor(() =>
|
||||
expect(fetchFake.lastRequest('POST', '/api/opencode/api/session/ses_1/command')?.body).toMatchObject({
|
||||
name: 'goal',
|
||||
text: 'resume',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('shows a completed goal with its reason and clears it', async () => {
|
||||
const user = userEvent.setup()
|
||||
const mutate = vi.fn()
|
||||
mockGoal({ supported: true, goal: { ...baseGoal, status: 'complete', reason: 'Objective met' } }, { mutate })
|
||||
renderBar()
|
||||
const { fetchFake } = renderBar({
|
||||
supported: true,
|
||||
goal: { ...goal, status: 'complete', reason: 'Objective met' },
|
||||
})
|
||||
|
||||
expect(screen.getByText('Goal completed')).toBeInTheDocument()
|
||||
expect(await screen.findByText('Goal completed')).toBeInTheDocument()
|
||||
expect(screen.getByText('Objective met')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Pause' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Resume' })).not.toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Clear' }))
|
||||
expect(mutate).toHaveBeenCalledWith({ sessionID: 'ses_1', text: 'clear' })
|
||||
await waitFor(() =>
|
||||
expect(fetchFake.lastRequest('POST', '/api/opencode/api/session/ses_1/command')?.body).toMatchObject({
|
||||
name: 'goal',
|
||||
text: 'clear',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('disables the goal buttons while the command is pending', () => {
|
||||
mockGoal({ supported: true, goal: { ...baseGoal } }, { isPending: true })
|
||||
renderBar()
|
||||
it('disables the goal buttons while the command is pending', async () => {
|
||||
const user = userEvent.setup()
|
||||
const command = new Promise<FetchRouteResult>(() => undefined)
|
||||
renderBar({ supported: true, goal }, () => command)
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Pause' }))
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Pause' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Clear' })).toBeDisabled()
|
||||
|
||||
@@ -6,15 +6,14 @@ import { useSessionGoal, useSessionGoalCommand } from '@/hooks/useSessionGoals'
|
||||
import { getGoalRoundsLabel, getGoalStatusTitle } from '@opencode-manager/shared/notifications'
|
||||
import type { GoalStatus } from '@opencode-manager/shared/opencode'
|
||||
|
||||
const STATUS_CHIP_CLASSES: Record<GoalStatus, string> = {
|
||||
const STATUS_CHIP_CLASSES = {
|
||||
active: 'bg-highlight text-highlight-foreground border-highlight',
|
||||
paused: 'bg-warning/15 text-warning border-warning/40',
|
||||
complete: 'bg-success/15 text-success border-success/40',
|
||||
}
|
||||
} satisfies Record<GoalStatus, string>
|
||||
|
||||
const GOAL_BUTTON_CLASSES = 'h-6 px-2 text-xs'
|
||||
|
||||
/** Renders the session's OpenCode goal with pause, resume and clear controls. */
|
||||
export function SessionGoalBar({ sessionID, directory }: { sessionID: string; directory: string | undefined }) {
|
||||
const { data } = useSessionGoal(sessionID, directory)
|
||||
const goalCommand = useSessionGoalCommand(directory)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -21,10 +21,6 @@ interface SessionListProps {
|
||||
renderSessions?: (args: SessionListRenderArgs) => ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets a caller lay out the loaded root sessions itself, for example grouped by worktree.
|
||||
* Search, paging, pinning, selection and delete stay owned by SessionList.
|
||||
*/
|
||||
export interface SessionListRenderArgs {
|
||||
sessions: Session[];
|
||||
searchQuery: string;
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { useState } from 'react'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
|
||||
import { installMatchMedia } from '@/test/browserFakes'
|
||||
import { makeUserMessage } from '@/test/fixtures/api'
|
||||
import { SessionMessagePickerDialog } from './SessionMessagePickerDialog'
|
||||
|
||||
function userMessage(id: string, text: string, created = 1000): SessionMessageInfo {
|
||||
return { id, type: 'user', text, time: { created } } as SessionMessageInfo
|
||||
return makeUserMessage({ id, text, time: { created } })
|
||||
}
|
||||
|
||||
function assistantMessage(id: string, text: string): SessionMessageInfo {
|
||||
return { id, type: 'assistant', text, time: { created: 1000 } } as unknown as SessionMessageInfo
|
||||
return {
|
||||
id,
|
||||
type: 'assistant',
|
||||
agent: 'build',
|
||||
model: { providerID: 'anthropic', id: 'claude-sonnet-4-5' },
|
||||
content: [{ type: 'text', text }],
|
||||
time: { created: 1000 },
|
||||
}
|
||||
}
|
||||
|
||||
const renderPicker = (
|
||||
@@ -49,12 +57,8 @@ function FocusHost() {
|
||||
}
|
||||
|
||||
describe('SessionMessagePickerDialog', () => {
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'matchMedia')
|
||||
})
|
||||
|
||||
it('focuses its search on open and returns focus to the previous element on Escape', async () => {
|
||||
stubMatchMedia(true)
|
||||
installMatchMedia(true)
|
||||
render(<FocusHost />)
|
||||
const prompt = screen.getByLabelText('prompt')
|
||||
prompt.focus()
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,9 +1,11 @@
|
||||
import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
|
||||
import { z } from 'zod'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { format, startOfDay } from 'date-fns'
|
||||
import { ChevronsUpDown, MoreHorizontal, Pin, PinOff, Plus } from 'lucide-react'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { OpenCodeServerProvider, useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
|
||||
import { useOpenCodeServerId } from '@/contexts/opencode-server-context'
|
||||
import { openCodeLocationQueryOptions } from '@/lib/openCodeLocation'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import { ACTIVE_WORK_GROUPS, MS_PER_MINUTE, formatActivityEmptyMessage } from '@/lib/activeWork'
|
||||
@@ -22,12 +24,8 @@ import { ProjectPickerContent } from '@/components/session/ProjectPickerContent'
|
||||
import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
|
||||
import { LocalRepoNewSessionButton } from '@/components/navigation/RepoSessionNav'
|
||||
import { RemoteProjectNavList } from '@/components/navigation/RemoteProjectNav'
|
||||
import {
|
||||
PickerSearchBar,
|
||||
optionId,
|
||||
usePickerCursor,
|
||||
usePickerKeyNav,
|
||||
} from '@/components/session/usePickerKeyboardNav'
|
||||
import { PickerSearchBar } from '@/components/session/PickerSearchBar'
|
||||
import { optionId, usePickerCursor, usePickerKeyNav } from '@/components/session/picker-cursor'
|
||||
import { partitionSessions } from '@/components/session/session-partition'
|
||||
import { buildRepoByDirectory, isRepoReady } from '@/components/navigation/sidebar-session-tree'
|
||||
import { useDeleteSession } from '@/hooks/useOpenCode'
|
||||
@@ -37,7 +35,7 @@ import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
|
||||
import { usePersistentBoolean } from '@/hooks/usePersistentBoolean'
|
||||
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
|
||||
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
|
||||
import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
|
||||
import { useShortcutActions } from '@/contexts/keyboard-shortcuts-context'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { buildPinnedSessionKeys, getSessionKey } from '@/lib/sessionKey'
|
||||
import { formatShortcutLabel, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
|
||||
@@ -48,15 +46,17 @@ const ALL_PROJECTS_STORAGE_KEY = 'oc:session-picker:all-projects'
|
||||
const UNTITLED_SESSION_TITLE = 'Untitled Session'
|
||||
const NEAR_BOTTOM_PX = 240
|
||||
|
||||
type SessionPickerTab = 'active' | 'sessions' | 'projects'
|
||||
const sessionPickerTabSchema = z.enum(['active', 'sessions', 'projects'])
|
||||
|
||||
type SessionPickerTab = z.infer<typeof sessionPickerTabSchema>
|
||||
|
||||
const SESSION_PICKER_TABS: SessionPickerTab[] = ['active', 'sessions', 'projects']
|
||||
|
||||
const SESSION_PICKER_TAB_LABELS: Record<SessionPickerTab, string> = {
|
||||
const SESSION_PICKER_TAB_LABELS = {
|
||||
active: 'Activity',
|
||||
sessions: 'Sessions',
|
||||
projects: 'Projects',
|
||||
}
|
||||
} satisfies Record<SessionPickerTab, string>
|
||||
|
||||
function nextSessionPickerTab(tab: SessionPickerTab, tabs: SessionPickerTab[]): SessionPickerTab {
|
||||
const index = tabs.indexOf(tab)
|
||||
@@ -71,9 +71,7 @@ function sessionsTabLabel(scopeEnabled: boolean, allProjects: boolean): string {
|
||||
export interface RemotePickerScope {
|
||||
serverId: string
|
||||
serverName?: string
|
||||
/** Canonical project directory in view; omitted when the route scopes to the whole server. */
|
||||
projectDirectory?: string
|
||||
/** Whether the route's project directory is still resolving, which holds the all-sessions search. */
|
||||
isPending?: boolean
|
||||
}
|
||||
|
||||
@@ -1204,17 +1202,12 @@ export interface SessionPickerPanelProps {
|
||||
onDeleteActiveSession: () => void
|
||||
onSelectRepo: (repo: Repo) => void
|
||||
onNavigate: (path: string) => void
|
||||
/** Set on a linked-server route to list that server's sessions instead of Manager repos. */
|
||||
remote?: RemotePickerScope
|
||||
searchTrailing?: React.ReactNode
|
||||
onAddRepo?: () => void
|
||||
renderTitle?: (label: string) => React.ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Picker content shared by the desktop dialog and the mobile sheet. A remote scope supplies its own
|
||||
* server, so every host reads the linked server's sessions without wrapping the panel itself.
|
||||
*/
|
||||
export function SessionPickerPanel(props: SessionPickerPanelProps) {
|
||||
if (!props.remote) return <SessionPickerPanelBody {...props} />
|
||||
return (
|
||||
@@ -1330,12 +1323,6 @@ function SessionPickerPanelBody({
|
||||
|
||||
const canToggleScope = scopeEnabled && activeTab === 'sessions'
|
||||
|
||||
/**
|
||||
* The sessions tab re-activates itself to toggle the scope. Pointer activation records whether the
|
||||
* tab was already selected before Radix activates it, so the click that follows only toggles a
|
||||
* tab that was already current. Keyboard activation toggles on Enter/Space directly and suppresses
|
||||
* the click Radix would otherwise synthesize for the same key press.
|
||||
*/
|
||||
const handleSessionsPointerDown = () => {
|
||||
scopePressRef.current = canToggleScope
|
||||
}
|
||||
@@ -1357,7 +1344,10 @@ function SessionPickerPanelBody({
|
||||
<>
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={(value) => setActiveTab(value as SessionPickerTab)}
|
||||
onValueChange={(value) => {
|
||||
const parsedTab = sessionPickerTabSchema.safeParse(value)
|
||||
if (parsedTab.success) setActiveTab(parsedTab.data)
|
||||
}}
|
||||
className="flex min-h-0 w-full min-w-0 flex-1 flex-col gap-0"
|
||||
>
|
||||
<div className="shrink-0 px-4 pt-4 sm:px-0 sm:pt-6">
|
||||
@@ -1481,8 +1471,8 @@ export function SessionPickerDialog({
|
||||
onEscapeKeyDown={() => onOpenChange(false)}
|
||||
onOpenAutoFocus={(event) => {
|
||||
event.preventDefault()
|
||||
if (!hasFinePointer) {
|
||||
;(event.currentTarget as HTMLElement).focus()
|
||||
if (!hasFinePointer && event.currentTarget instanceof HTMLElement) {
|
||||
event.currentTarget.focus()
|
||||
}
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,252 +1,116 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import type { ActiveWorkGroups, ActiveWorkItem } from '@/lib/activeWork'
|
||||
import { DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@/api/types/settings'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import type { OpenCodeProject } from '@/api/opencode'
|
||||
import type { Repo } from '@/api/types'
|
||||
import { makeOpenCodeServer, makeRepo, makeSession } from '@/test/fixtures/api'
|
||||
import { installMatchMedia } from '@/test/browserFakes'
|
||||
import { createSessionServer, type SessionServer } from '@/test/fixtures/sessionServer'
|
||||
import type { FetchRouteResult } from '@/test/fetchFake'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
import { LocationCatcher } from '@/test/test-components'
|
||||
import { KeyboardShortcutsProvider } from '@/contexts/KeyboardShortcutsContext'
|
||||
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
|
||||
import { LocationCatcher, stubMatchMedia } from '@/test/test-utils'
|
||||
import { makeRepo, makeSession } from '@/test/fixtures/session-picker'
|
||||
import { SessionPickerSheet } from './SessionPickerSheet'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
sessionsData: [] as Session[],
|
||||
lastDirectories: [] as string[],
|
||||
lastAllDirectories: false,
|
||||
createSessionDirectories: [] as string[],
|
||||
deleteSessionMock: vi.fn(),
|
||||
locationData: undefined as
|
||||
| { directory: string; project: { id: string; directory: string; canonical: string } }
|
||||
| undefined,
|
||||
getOpenCodeLocation: vi.fn(),
|
||||
listProjects: vi.fn(),
|
||||
getSession: vi.fn(),
|
||||
repos: [] as Repo[],
|
||||
activeWorkGroups: { needsInput: [], running: [], recent: [] } as ActiveWorkGroups,
|
||||
}))
|
||||
const repos: Repo[] = [
|
||||
makeRepo({ id: 1, name: 'alpha', fullPath: '/w/a', localPath: '/w/a' }),
|
||||
makeRepo({ id: 2, name: 'beta', fullPath: '/w/b', localPath: '/w/b' }),
|
||||
]
|
||||
|
||||
vi.mock('@/hooks/useSettings', () => ({
|
||||
useSettings: () => ({ preferences: undefined }),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/api/opencode')>()
|
||||
return {
|
||||
...actual,
|
||||
getOpenCodeLocation: mocks.getOpenCodeLocation,
|
||||
listProjects: mocks.listProjects,
|
||||
getSession: mocks.getSession,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
listRepos: vi.fn().mockResolvedValue([]),
|
||||
createRepo: vi.fn(),
|
||||
discoverRepos: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
|
||||
return {
|
||||
...actual,
|
||||
useSessionsAcrossDirectories: (
|
||||
directories: string[],
|
||||
options?: { search?: string; allDirectories?: boolean },
|
||||
) => {
|
||||
mocks.lastDirectories = directories
|
||||
mocks.lastAllDirectories = options?.allDirectories ?? false
|
||||
const search = options?.search?.toLowerCase() ?? ''
|
||||
const base = directories.length === 0 && !options?.allDirectories ? [] : mocks.sessionsData
|
||||
const data = search
|
||||
? base.filter((session) => (session.title ?? '').toLowerCase().includes(search))
|
||||
: base
|
||||
return {
|
||||
data,
|
||||
isLoading: false,
|
||||
isPlaceholderData: false,
|
||||
fetchNextPage: vi.fn(),
|
||||
hasNextPage: false,
|
||||
isFetchingNextPage: false,
|
||||
isFetchNextPageError: false,
|
||||
}
|
||||
},
|
||||
useDeleteSession: () => ({
|
||||
mutateAsync: mocks.deleteSessionMock,
|
||||
isPending: false,
|
||||
}),
|
||||
useCreateSession: (directory: string, onSuccess?: (session: { id: string }) => void) => ({
|
||||
mutate: () => {
|
||||
mocks.createSessionDirectories.push(directory)
|
||||
onSuccess?.({ id: 'ses_new' })
|
||||
},
|
||||
isPending: false,
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/hooks/useSessionPins', () => ({
|
||||
SESSION_PINS_QUERY_KEY: ['session-pins'],
|
||||
useSessionPins: () => ({ data: [] }),
|
||||
useToggleSessionPin: () => ({ mutate: vi.fn() }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSidebarRepoGroups', () => ({
|
||||
useNavigableRepos: () => ({ repos: mocks.repos, isLoading: false, refetch: vi.fn() }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useActiveWork', () => ({
|
||||
useActiveWork: () => ({ groups: mocks.activeWorkGroups, isLoading: false, isError: false }),
|
||||
useActivityWindowMinutes: () => DEFAULT_ACTIVITY_WINDOW_MINUTES,
|
||||
useProjectActivityState: () => null,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCodeServers', () => ({
|
||||
useOpenCodeServers: () => ({
|
||||
servers: [{ id: 'srv_kitchen', name: 'Kitchen', enabled: true }],
|
||||
isLoading: false,
|
||||
}),
|
||||
useOpenCodeServerStatuses: () => ({ statuses: [], statusById: {}, isLoading: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/navigation/LinkedServersNav', () => ({
|
||||
LinkedServersNav: () => <div data-testid="linked-servers-nav" />,
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/stores/sessionStatusStore')>()
|
||||
return { ...actual, useSessionStatusForSession: () => ({ type: 'idle' }) }
|
||||
})
|
||||
|
||||
function activeWorkItem(
|
||||
id: string,
|
||||
directory: string,
|
||||
server?: { id: string; name: string },
|
||||
): ActiveWorkItem {
|
||||
const now = Date.now()
|
||||
return {
|
||||
key: `${server?.id ?? LOCAL_OPENCODE_SERVER_ID}:${id}`,
|
||||
state: 'recent',
|
||||
session: makeSession(id, `Active ${id}`, directory, now),
|
||||
repo: server ? null : makeRepo(1, 'alpha', directory),
|
||||
serverId: server?.id ?? null,
|
||||
serverName: server?.name ?? null,
|
||||
updatedAt: now,
|
||||
path: `/repos/1/sessions/${id}`,
|
||||
}
|
||||
function deferred() {
|
||||
let resolve: (result: FetchRouteResult) => void = () => undefined
|
||||
const promise = new Promise<FetchRouteResult>((settle) => {
|
||||
resolve = settle
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
function renderSheet(
|
||||
server: SessionServer,
|
||||
initialEntries: string[] = ['/repos/1?mobileTab=sessions'],
|
||||
options: { isOpen?: boolean; cachedRepos?: Repo[] } = {},
|
||||
options: { isOpen?: boolean } = {},
|
||||
) {
|
||||
installMatchMedia(true)
|
||||
const onClose = vi.fn()
|
||||
const capturedPathname: { current: string } = { current: '' }
|
||||
const capturedSearch: { current: string } = { current: '' }
|
||||
const capturedNavigationType: { current: string } = { current: '' }
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
if (options.cachedRepos) queryClient.setQueryData(['repos'], options.cachedRepos)
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<KeyboardShortcutsProvider>
|
||||
<MemoryRouter initialEntries={initialEntries}>
|
||||
<Routes>
|
||||
<Route
|
||||
path="*"
|
||||
element={
|
||||
<>
|
||||
<SessionPickerSheet isOpen={options.isOpen ?? true} onClose={onClose} />
|
||||
<LocationCatcher
|
||||
capturedPathname={capturedPathname}
|
||||
capturedSearch={capturedSearch}
|
||||
capturedNavigationType={capturedNavigationType}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</KeyboardShortcutsProvider>
|
||||
</QueryClientProvider>,
|
||||
const capturedPathname = { current: '' }
|
||||
const capturedSearch = { current: '' }
|
||||
const capturedNavigationType = { current: '' }
|
||||
const result = renderWithProviders(
|
||||
<KeyboardShortcutsProvider>
|
||||
<SessionPickerSheet isOpen={options.isOpen ?? true} onClose={onClose} />
|
||||
<LocationCatcher
|
||||
capturedPathname={capturedPathname}
|
||||
capturedSearch={capturedSearch}
|
||||
capturedNavigationType={capturedNavigationType}
|
||||
/>
|
||||
</KeyboardShortcutsProvider>,
|
||||
{ initialEntries, events: true, fetchRoutes: server.routes },
|
||||
)
|
||||
return {
|
||||
...result,
|
||||
onClose,
|
||||
location: () =>
|
||||
`${capturedPathname.current}${capturedSearch.current} ${capturedNavigationType.current}`,
|
||||
location: () => `${capturedPathname.current}${capturedSearch.current} ${capturedNavigationType.current}`,
|
||||
}
|
||||
}
|
||||
|
||||
function session(id: string, title: string, directory: string, updated = Date.now()) {
|
||||
return makeSession({ id, title, location: { directory }, time: { created: updated, updated } })
|
||||
}
|
||||
|
||||
const kitchen = makeOpenCodeServer({ id: 'srv_kitchen', name: 'Kitchen' })
|
||||
|
||||
describe('SessionPickerSheet', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
stubMatchMedia(true)
|
||||
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
mocks.sessionsData = []
|
||||
mocks.lastDirectories = []
|
||||
mocks.lastAllDirectories = false
|
||||
mocks.createSessionDirectories = []
|
||||
mocks.activeWorkGroups = { needsInput: [], running: [], recent: [] }
|
||||
mocks.listProjects.mockResolvedValue([])
|
||||
mocks.locationData = {
|
||||
directory: '/w/a',
|
||||
project: { id: 'global', directory: '/w/a', canonical: '/w/a' },
|
||||
}
|
||||
mocks.getOpenCodeLocation.mockResolvedValue(mocks.locationData)
|
||||
mocks.getSession.mockResolvedValue(null)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'matchMedia')
|
||||
})
|
||||
|
||||
it('renders the picker in a bottom sheet with Activity, Sessions and Projects tabs', () => {
|
||||
renderSheet(['/'])
|
||||
it('renders the picker in a bottom sheet with Activity, Sessions and Projects tabs', async () => {
|
||||
renderSheet(createSessionServer({ repos, remoteServers: [kitchen] }), ['/'])
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Sessions' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('tab', { name: 'Activity' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('tab', { name: 'Sessions', selected: true })).toBeInTheDocument()
|
||||
expect(screen.getByRole('tab', { name: 'Projects' })).toBeInTheDocument()
|
||||
expect(screen.getByTestId('linked-servers-nav')).toBeInTheDocument()
|
||||
expect(
|
||||
await screen.findByRole('button', { name: /Switch server, current:/ }),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('navigates to the chosen session, replacing the sheet history entry', async () => {
|
||||
mocks.sessionsData = [makeSession('ses_one', 'Solo session', '/w/a')]
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
sessions: [session('ses_one', 'Solo session', '/w/a')],
|
||||
})
|
||||
|
||||
const { location } = renderSheet()
|
||||
const { location } = renderSheet(server)
|
||||
|
||||
const row = await screen.findByRole('option', { name: /Solo session/ })
|
||||
fireEvent.click(row)
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Solo session/ }))
|
||||
|
||||
expect(location()).toBe('/repos/1/sessions/ses_one REPLACE')
|
||||
await waitFor(() => expect(location()).toBe('/repos/1/sessions/ses_one REPLACE'))
|
||||
})
|
||||
|
||||
it('closes instead of navigating when the chosen session is already open', async () => {
|
||||
mocks.sessionsData = [makeSession('ses_one', 'Solo session', '/w/a')]
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
sessions: [session('ses_one', 'Solo session', '/w/a')],
|
||||
})
|
||||
|
||||
const { onClose, location } = renderSheet(['/repos/1/sessions/ses_one?mobileTab=sessions'])
|
||||
const { onClose, location } = renderSheet(server, ['/repos/1/sessions/ses_one?mobileTab=sessions'])
|
||||
|
||||
const row = await screen.findByRole('option', { name: /Solo session/ })
|
||||
fireEvent.click(row)
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Solo session/ }))
|
||||
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalled())
|
||||
expect(location()).toBe('/repos/1/sessions/ses_one?mobileTab=sessions POP')
|
||||
})
|
||||
|
||||
it('creates a session in the current repo from the header action and opens it', async () => {
|
||||
const { location } = renderSheet()
|
||||
const server = createSessionServer({ repos })
|
||||
const { location } = renderSheet(server)
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'New session in alpha' }))
|
||||
|
||||
expect(mocks.createSessionDirectories).toEqual(['/w/a'])
|
||||
expect(location()).toBe('/repos/1/sessions/ses_new REPLACE')
|
||||
await waitFor(() => expect(server.createdDirectories()).toEqual(['/w/a']))
|
||||
await waitFor(() => expect(location()).toBe('/repos/1/sessions/ses_new REPLACE'))
|
||||
})
|
||||
|
||||
it('opens the add repository dialog from the projects tab header action', async () => {
|
||||
const { onClose } = renderSheet()
|
||||
const { onClose } = renderSheet(createSessionServer({ repos }))
|
||||
|
||||
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Projects' }))
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Add repository' }))
|
||||
@@ -257,15 +121,16 @@ describe('SessionPickerSheet', () => {
|
||||
|
||||
it('lists and opens the linked server sessions when a linked server is selected', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
mocks.sessionsData = [makeSession('ses_remote', 'Remote session', '/home/me/app')]
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
remoteServers: [kitchen],
|
||||
remoteSessions: [session('ses_remote', 'Remote session', '/home/me/app')],
|
||||
})
|
||||
|
||||
const { location } = renderSheet()
|
||||
const { location } = renderSheet(server)
|
||||
|
||||
const row = await screen.findByRole('option', { name: /Remote session/ })
|
||||
expect(row).toHaveTextContent('Kitchen')
|
||||
expect(mocks.lastDirectories).toEqual([])
|
||||
expect(mocks.lastAllDirectories).toBe(true)
|
||||
expect(screen.getByTestId('linked-servers-nav')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('tab', { name: 'This project' })).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(row)
|
||||
@@ -275,17 +140,20 @@ describe('SessionPickerSheet', () => {
|
||||
|
||||
it('lists the linked server projects on the projects tab and opens one', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
mocks.listProjects.mockResolvedValue([
|
||||
{
|
||||
id: 'p1',
|
||||
name: 'Alpha',
|
||||
canonical: '/projects/alpha',
|
||||
time: { created: 1, updated: 2 },
|
||||
sandboxes: [],
|
||||
},
|
||||
])
|
||||
const project: OpenCodeProject = {
|
||||
id: 'p1',
|
||||
name: 'Alpha',
|
||||
canonical: '/projects/alpha',
|
||||
time: { created: 1, updated: 2 },
|
||||
sandboxes: [],
|
||||
}
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
remoteServers: [kitchen],
|
||||
projects: [project],
|
||||
})
|
||||
|
||||
const { location } = renderSheet()
|
||||
const { location } = renderSheet(server)
|
||||
|
||||
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Projects' }))
|
||||
fireEvent.click(await screen.findByText('Alpha'))
|
||||
@@ -294,9 +162,13 @@ describe('SessionPickerSheet', () => {
|
||||
})
|
||||
|
||||
it('follows the sidebar server selection to list that server', async () => {
|
||||
mocks.sessionsData = [makeSession('ses_remote', 'Remote session', '/home/me/app')]
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
remoteServers: [kitchen],
|
||||
remoteSessions: [session('ses_remote', 'Remote session', '/home/me/app')],
|
||||
})
|
||||
|
||||
renderSheet()
|
||||
renderSheet(server)
|
||||
|
||||
act(() => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
@@ -308,13 +180,12 @@ describe('SessionPickerSheet', () => {
|
||||
})
|
||||
|
||||
it('lists activity sessions and opens one', async () => {
|
||||
mocks.activeWorkGroups = {
|
||||
needsInput: [],
|
||||
running: [],
|
||||
recent: [activeWorkItem('ses_active', '/w/a')],
|
||||
}
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
sessions: [session('ses_active', 'Active ses_active', '/w/a')],
|
||||
})
|
||||
|
||||
const { location } = renderSheet()
|
||||
const { location } = renderSheet(server)
|
||||
|
||||
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Activity' }))
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Active ses_active/ }))
|
||||
@@ -323,13 +194,13 @@ describe('SessionPickerSheet', () => {
|
||||
})
|
||||
|
||||
it('opens a remote activity row on its own server while the local server is selected', async () => {
|
||||
mocks.activeWorkGroups = {
|
||||
needsInput: [],
|
||||
running: [],
|
||||
recent: [activeWorkItem('ses_kitchen', '/home/me/app', { id: 'srv_kitchen', name: 'Kitchen' })],
|
||||
}
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
remoteServers: [kitchen],
|
||||
remoteSessions: [session('ses_kitchen', 'Active ses_kitchen', '/home/me/app')],
|
||||
})
|
||||
|
||||
const { location } = renderSheet()
|
||||
const { location } = renderSheet(server)
|
||||
|
||||
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Activity' }))
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Active ses_kitchen/ }))
|
||||
@@ -339,13 +210,14 @@ describe('SessionPickerSheet', () => {
|
||||
|
||||
it('opens a remote activity row of the same session id that is open on another server', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
mocks.activeWorkGroups = {
|
||||
needsInput: [],
|
||||
running: [],
|
||||
recent: [activeWorkItem('ses_shared', '/home/me/hall', { id: 'srv_hall', name: 'Hall' })],
|
||||
}
|
||||
const hall = makeOpenCodeServer({ id: 'srv_hall', name: 'Hall' })
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
remoteServers: [kitchen, hall],
|
||||
remoteSessions: [session('ses_shared', 'Active ses_shared', '/home/me/hall')],
|
||||
})
|
||||
|
||||
const { onClose, location } = renderSheet([
|
||||
const { onClose, location } = renderSheet(server, [
|
||||
'/servers/srv_kitchen/sessions/ses_shared?mobileTab=sessions',
|
||||
])
|
||||
|
||||
@@ -357,9 +229,13 @@ describe('SessionPickerSheet', () => {
|
||||
})
|
||||
|
||||
it('opens a local session row that shares the id of the open remote session', async () => {
|
||||
mocks.sessionsData = [makeSession('ses_shared', 'Shared session', '/w/a')]
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
sessions: [session('ses_shared', 'Shared session', '/w/a')],
|
||||
remoteServers: [kitchen],
|
||||
})
|
||||
|
||||
const { onClose, location } = renderSheet([
|
||||
const { onClose, location } = renderSheet(server, [
|
||||
'/servers/srv_kitchen/sessions/ses_shared?mobileTab=sessions',
|
||||
])
|
||||
|
||||
@@ -371,13 +247,14 @@ describe('SessionPickerSheet', () => {
|
||||
|
||||
it('opens a session row of another linked server than the selected one', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
mocks.activeWorkGroups = {
|
||||
needsInput: [],
|
||||
running: [],
|
||||
recent: [activeWorkItem('ses_hall', '/home/me/hall', { id: 'srv_hall', name: 'Hall' })],
|
||||
}
|
||||
const hall = makeOpenCodeServer({ id: 'srv_hall', name: 'Hall' })
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
remoteServers: [kitchen, hall],
|
||||
remoteSessions: [session('ses_hall', 'Active ses_hall', '/home/me/hall')],
|
||||
})
|
||||
|
||||
const { location } = renderSheet()
|
||||
const { location } = renderSheet(server)
|
||||
|
||||
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Activity' }))
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Active ses_hall/ }))
|
||||
@@ -386,9 +263,12 @@ describe('SessionPickerSheet', () => {
|
||||
})
|
||||
|
||||
it('keeps the assistant session flag when choosing another session of the same repo', async () => {
|
||||
mocks.sessionsData = [makeSession('ses_b', 'Second assistant session', '/w/a')]
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
sessions: [session('ses_b', 'Second assistant session', '/w/a')],
|
||||
})
|
||||
|
||||
const { location } = renderSheet(['/repos/1/sessions/ses_a?assistant=1&mobileTab=sessions'])
|
||||
const { location } = renderSheet(server, ['/repos/1/sessions/ses_a?assistant=1&mobileTab=sessions'])
|
||||
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Second assistant session/ }))
|
||||
|
||||
@@ -397,12 +277,15 @@ describe('SessionPickerSheet', () => {
|
||||
|
||||
it('drops the assistant session flag when choosing a session of another repo', async () => {
|
||||
localStorage.setItem('oc:session-picker:all-projects', 'true')
|
||||
mocks.sessionsData = [
|
||||
makeSession('ses_a', 'Assistant session', '/w/a'),
|
||||
makeSession('ses_b', 'Beta session', '/w/b'),
|
||||
]
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
sessions: [
|
||||
session('ses_a', 'Assistant session', '/w/a'),
|
||||
session('ses_b', 'Beta session', '/w/b'),
|
||||
],
|
||||
})
|
||||
|
||||
const { location } = renderSheet(['/repos/1/sessions/ses_a?assistant=1&mobileTab=sessions'])
|
||||
const { location } = renderSheet(server, ['/repos/1/sessions/ses_a?assistant=1&mobileTab=sessions'])
|
||||
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Beta session/ }))
|
||||
|
||||
@@ -411,79 +294,132 @@ describe('SessionPickerSheet', () => {
|
||||
|
||||
it('scopes the sheet to the open remote session directory on a linked server session route', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
mocks.getSession.mockResolvedValue(makeSession('ses_remote', 'Remote session', '/home/me/app'))
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
remoteServers: [kitchen],
|
||||
remoteSessions: [session('ses_remote', 'Remote session', '/home/me/app')],
|
||||
})
|
||||
|
||||
renderSheet(['/servers/srv_kitchen/sessions/ses_remote?mobileTab=sessions'])
|
||||
renderSheet(server, ['/servers/srv_kitchen/sessions/ses_remote?mobileTab=sessions'])
|
||||
|
||||
await waitFor(() => expect(mocks.lastDirectories).toEqual(['/home/me/app']))
|
||||
expect(mocks.lastAllDirectories).toBe(false)
|
||||
await waitFor(() => {
|
||||
const remoteList = server.sessionRequests().filter((request) =>
|
||||
request.path.startsWith('/api/opencode/servers/srv_kitchen/api/session'),
|
||||
)
|
||||
expect(
|
||||
remoteList.some((request) => request.searchParams.get('directory') === '/home/me/app'),
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('scopes the sheet to the canonical project directory of a remote session subdirectory', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
mocks.getSession.mockResolvedValue(makeSession('ses_remote', 'Remote session', '/home/me/app/packages/web'))
|
||||
mocks.listProjects.mockResolvedValue([
|
||||
{
|
||||
id: 'p1',
|
||||
name: 'App',
|
||||
canonical: '/home/me/app',
|
||||
time: { created: 1, updated: 2 },
|
||||
sandboxes: [],
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
remoteServers: [kitchen],
|
||||
remoteSessions: [session('ses_remote', 'Remote session', '/home/me/app/packages/web')],
|
||||
projects: [
|
||||
{
|
||||
id: 'p1',
|
||||
name: 'App',
|
||||
canonical: '/home/me/app',
|
||||
time: { created: 1, updated: 2 },
|
||||
sandboxes: [],
|
||||
},
|
||||
],
|
||||
sessionRespond: (_request, params) => {
|
||||
const found = [session('ses_remote', 'Remote session', '/home/me/app/packages/web')].find(
|
||||
(candidate) => candidate.id === params.sessionID,
|
||||
)
|
||||
return found ? { json: { data: found } } : { status: 404, json: { error: 'missing' } }
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
renderSheet(['/servers/srv_kitchen/sessions/ses_remote?mobileTab=sessions'])
|
||||
renderSheet(server, ['/servers/srv_kitchen/sessions/ses_remote?mobileTab=sessions'])
|
||||
|
||||
await waitFor(() => expect(mocks.lastDirectories).toEqual(['/home/me/app']))
|
||||
expect(mocks.lastAllDirectories).toBe(false)
|
||||
await waitFor(() => {
|
||||
const remoteList = server.sessionRequests().filter((request) =>
|
||||
request.path.startsWith('/api/opencode/servers/srv_kitchen/api/session'),
|
||||
)
|
||||
expect(remoteList.some((request) => request.searchParams.get('directory') === '/home/me/app')).toBe(
|
||||
true,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('holds the all-directories search while the remote session directory resolves', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
mocks.getSession.mockReturnValue(new Promise(() => undefined))
|
||||
const sessionDetail = deferred()
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
remoteServers: [kitchen],
|
||||
sessionRespond: () => sessionDetail.promise,
|
||||
})
|
||||
|
||||
renderSheet(['/servers/srv_kitchen/sessions/ses_remote?mobileTab=sessions'])
|
||||
const { fetchFake } = renderSheet(server, ['/servers/srv_kitchen/sessions/ses_remote?mobileTab=sessions'])
|
||||
|
||||
await waitFor(() => expect(mocks.getSession).toHaveBeenCalled())
|
||||
expect(mocks.lastDirectories).toEqual([])
|
||||
expect(mocks.lastAllDirectories).toBe(false)
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
fetchFake.findRequests('GET', '/api/opencode/servers/srv_kitchen/api/session/ses_remote'),
|
||||
).toHaveLength(1),
|
||||
)
|
||||
expect(
|
||||
fetchFake.findRequests('GET', '/api/opencode/servers/srv_kitchen/api/session'),
|
||||
).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('returns to the repo session list keeping its tab when the open session is deleted', async () => {
|
||||
mocks.sessionsData = [makeSession('ses_active', 'Active session', '/w/a')]
|
||||
mocks.deleteSessionMock.mockResolvedValue(undefined)
|
||||
const server = createSessionServer({
|
||||
repos,
|
||||
sessions: [session('ses_active', 'Active session', '/w/a')],
|
||||
})
|
||||
|
||||
const { location } = renderSheet(['/repos/1/sessions/ses_active?mobileTab=sessions&repoTab=changes'])
|
||||
const { location } = renderSheet(server, [
|
||||
'/repos/1/sessions/ses_active?mobileTab=sessions&repoTab=changes',
|
||||
])
|
||||
|
||||
const combobox = await screen.findByRole('combobox')
|
||||
await screen.findByRole('option', { name: /Active session/ })
|
||||
fireEvent.keyDown(combobox, { key: 'd', ctrlKey: true })
|
||||
expect(screen.getByText('Press Ctrl+D again to confirm')).toBeInTheDocument()
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('option', { name: /Press Ctrl\+D again to confirm/ })).toBeInTheDocument(),
|
||||
)
|
||||
fireEvent.keyDown(combobox, { key: 'd', ctrlKey: true })
|
||||
|
||||
await waitFor(() => expect(mocks.deleteSessionMock).toHaveBeenCalled())
|
||||
await waitFor(() => expect(server.deletedSessionIDs()).toEqual(['ses_active']))
|
||||
expect(location()).toBe('/repos/1?repoTab=changes REPLACE')
|
||||
})
|
||||
|
||||
it('does not resolve the remote session directory while the sheet is closed', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
const server = createSessionServer({ repos, remoteServers: [kitchen] })
|
||||
|
||||
renderSheet(['/servers/srv_kitchen/sessions/ses_remote'], { isOpen: false })
|
||||
renderSheet(server, ['/servers/srv_kitchen/sessions/ses_remote'], { isOpen: false })
|
||||
|
||||
await waitFor(() => expect(mocks.getSession).not.toHaveBeenCalled())
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(
|
||||
server
|
||||
.sessionRequests()
|
||||
.some((request) => request.path === '/api/opencode/servers/srv_kitchen/api/session/ses_remote'),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('prefetches the project location on a repo route while the sheet is closed', async () => {
|
||||
renderSheet(['/repos/1'], { isOpen: false, cachedRepos: mocks.repos })
|
||||
const server = createSessionServer({ repos })
|
||||
|
||||
const { fetchFake } = renderSheet(server, ['/repos/1'], { isOpen: false })
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.getOpenCodeLocation).toHaveBeenCalledWith('/w/a', LOCAL_OPENCODE_SERVER_ID),
|
||||
expect(fetchFake.findRequests('GET', '/api/opencode/api/location')).toHaveLength(1),
|
||||
)
|
||||
})
|
||||
|
||||
it('does not prefetch the project location outside a repo route', async () => {
|
||||
renderSheet(['/'], { isOpen: false, cachedRepos: mocks.repos })
|
||||
const server = createSessionServer({ repos })
|
||||
|
||||
await waitFor(() => expect(mocks.getOpenCodeLocation).not.toHaveBeenCalled())
|
||||
const { fetchFake } = renderSheet(server, ['/'], { isOpen: false })
|
||||
|
||||
await waitFor(() => expect(fetchFake.lastRequest('GET', '/api/repos')).toBeDefined())
|
||||
expect(fetchFake.findRequests('GET', '/api/opencode/api/location')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -1,11 +1,13 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import {
|
||||
SetSessionSandboxRequestSchema,
|
||||
type SessionSandboxState,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { FetchRoute, FetchRouteResult } from '@/test/fetchFake'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
import { SessionSandboxMenu } from './SessionSandboxMenu'
|
||||
import { useSessionSandbox, useSetSessionSandbox } from '@/hooks/useSessionSandbox'
|
||||
import type { SessionSandboxState } from '@opencode-manager/shared/schemas'
|
||||
|
||||
vi.mock('@/hooks/useSessionSandbox')
|
||||
|
||||
const baseSandboxState: SessionSandboxState = {
|
||||
sessionId: 'ses_1',
|
||||
@@ -18,87 +20,79 @@ const baseSandboxState: SessionSandboxState = {
|
||||
available: true,
|
||||
}
|
||||
|
||||
function mockSandbox(
|
||||
state: Partial<SessionSandboxState> = {},
|
||||
mutateAsync = vi.fn().mockResolvedValue(undefined),
|
||||
) {
|
||||
const mutate = vi.fn()
|
||||
vi.mocked(useSessionSandbox).mockReturnValue({
|
||||
data: { ...baseSandboxState, ...state },
|
||||
isError: false,
|
||||
} as ReturnType<typeof useSessionSandbox>)
|
||||
vi.mocked(useSetSessionSandbox).mockReturnValue({
|
||||
mutate,
|
||||
mutateAsync,
|
||||
isPending: false,
|
||||
} as unknown as ReturnType<typeof useSetSessionSandbox>)
|
||||
return { mutate, mutateAsync }
|
||||
}
|
||||
function renderMenu(overrides: Partial<SessionSandboxState> = {}, putRespond?: FetchRoute['respond']) {
|
||||
let state: SessionSandboxState = { ...baseSandboxState, ...overrides }
|
||||
const sandboxUrl = '/api/session-sandbox/ses_1'
|
||||
|
||||
function renderMenu() {
|
||||
render(<SessionSandboxMenu sessionID="ses_1" />)
|
||||
const routes: FetchRoute[] = [
|
||||
{ method: 'GET', path: sandboxUrl, respond: () => ({ json: state }) },
|
||||
{
|
||||
method: 'PUT',
|
||||
path: sandboxUrl,
|
||||
respond: (request) => {
|
||||
if (putRespond) return putRespond(request)
|
||||
const parsed = SetSessionSandboxRequestSchema.safeParse(request.body)
|
||||
if (parsed.success) state = { ...state, ...parsed.data }
|
||||
return { json: state }
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
return renderWithProviders(<SessionSandboxMenu sessionID="ses_1" />, {
|
||||
auth: false,
|
||||
theme: false,
|
||||
tts: false,
|
||||
toaster: false,
|
||||
fetchRoutes: routes,
|
||||
})
|
||||
}
|
||||
|
||||
describe('SessionSandboxMenu', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockSandbox()
|
||||
it('renders nothing when sandboxing is unavailable', async () => {
|
||||
renderMenu({ available: false })
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('button', { name: /Sandbox:/ })).not.toBeInTheDocument(),
|
||||
)
|
||||
})
|
||||
|
||||
it('renders nothing when sandboxing is unavailable', () => {
|
||||
mockSandbox({ available: false })
|
||||
renderMenu()
|
||||
it.each([
|
||||
[false, 'Sandbox: off'],
|
||||
[true, 'Sandbox: on'],
|
||||
] as const)('reflects the sandboxed=%s state in the trigger', async (sandboxed, label) => {
|
||||
renderMenu({ sandboxed })
|
||||
|
||||
expect(screen.queryByRole('button', { name: /Sandbox:/ })).not.toBeInTheDocument()
|
||||
const trigger = await screen.findByRole('button', { name: label })
|
||||
if (sandboxed) expect(trigger).toHaveClass('bg-highlight')
|
||||
else expect(trigger).not.toHaveClass('bg-highlight')
|
||||
})
|
||||
|
||||
it('reflects the off state in the trigger label', () => {
|
||||
mockSandbox({ sandboxed: false })
|
||||
renderMenu()
|
||||
it.each([
|
||||
[false, 'Sandbox: off', 'false', { sandboxed: true }, 'Sandbox: on'],
|
||||
[true, 'Sandbox: on', 'true', { sandboxed: false }, 'Sandbox: off'],
|
||||
] as const)(
|
||||
'toggles sandboxing from the %s state through the checkbox item',
|
||||
async (sandboxed, label, checked, expectedBody, nextLabel) => {
|
||||
const user = userEvent.setup()
|
||||
const { fetchFake } = renderMenu({ sandboxed })
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'Sandbox: off' })
|
||||
expect(trigger).not.toHaveClass('bg-highlight')
|
||||
})
|
||||
await user.click(await screen.findByRole('button', { name: label }))
|
||||
const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
|
||||
expect(item).toHaveAttribute('aria-checked', checked)
|
||||
await user.click(item)
|
||||
|
||||
it('reflects the on state in the trigger label', () => {
|
||||
mockSandbox({ sandboxed: true })
|
||||
renderMenu()
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Sandbox: on' })).toHaveClass('bg-highlight')
|
||||
})
|
||||
|
||||
it('enables sandboxing through the checkbox item', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { mutate } = mockSandbox({ sandboxed: false })
|
||||
renderMenu()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Sandbox: off' }))
|
||||
const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
|
||||
expect(item).toHaveAttribute('aria-checked', 'false')
|
||||
await user.click(item)
|
||||
|
||||
expect(mutate).toHaveBeenCalledWith({ sandboxed: true })
|
||||
})
|
||||
|
||||
it('disables sandboxing through the checkbox item', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { mutate } = mockSandbox({ sandboxed: true })
|
||||
renderMenu()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Sandbox: on' }))
|
||||
const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
|
||||
expect(item).toHaveAttribute('aria-checked', 'true')
|
||||
await user.click(item)
|
||||
|
||||
expect(mutate).toHaveBeenCalledWith({ sandboxed: false })
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(fetchFake.lastRequest('PUT', '/api/session-sandbox/ses_1')?.body).toEqual(expectedBody),
|
||||
)
|
||||
expect(await screen.findByRole('button', { name: nextLabel })).toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
|
||||
it('hides the resources item when the session is not sandboxed', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockSandbox({ sandboxed: false })
|
||||
renderMenu()
|
||||
renderMenu({ sandboxed: false })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Sandbox: off' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Sandbox: off' }))
|
||||
await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
|
||||
|
||||
expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument()
|
||||
@@ -106,10 +100,9 @@ describe('SessionSandboxMenu', () => {
|
||||
|
||||
it('opens the resources dialog from the menu item', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockSandbox({ sandboxed: true, effectiveResources: { cpus: 2, memoryMib: 4096 } })
|
||||
renderMenu()
|
||||
renderMenu({ sandboxed: true, effectiveResources: { cpus: 2, memoryMib: 4096 } })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Sandbox: on' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Sandbox: on' }))
|
||||
const item = await screen.findByRole('menuitem', { name: /Sandbox resources/ })
|
||||
await user.click(item)
|
||||
|
||||
@@ -119,14 +112,24 @@ describe('SessionSandboxMenu', () => {
|
||||
|
||||
it('disables the checkbox and explains inheritance for a child session', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockSandbox({ sandboxed: true, lockedReason: 'child' })
|
||||
renderMenu()
|
||||
const { fetchFake } = renderMenu({ sandboxed: true, lockedReason: 'child' })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Inherited from parent session/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /Inherited from parent session/ }))
|
||||
const item = await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ })
|
||||
|
||||
expect(item).toHaveAttribute('aria-disabled', 'true')
|
||||
expect(item).toHaveTextContent('Inherited from parent session')
|
||||
expect(screen.queryByRole('menuitem', { name: /Sandbox resources/ })).not.toBeInTheDocument()
|
||||
expect(fetchFake.findRequests('PUT', '/api/session-sandbox/ses_1')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('keeps the trigger label when the toggle write fails', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderMenu({ sandboxed: false }, () => new Promise<FetchRouteResult>(() => undefined))
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Sandbox: off' }))
|
||||
await user.click(await screen.findByRole('menuitemcheckbox', { name: /Sandbox commands/ }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Sandbox: off' })).toBeInTheDocument())
|
||||
})
|
||||
})
|
||||
@@ -1,12 +1,8 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { SessionSendErrorBanner } from './SessionSendErrorBanner'
|
||||
import { useSendErrorStore } from '@/stores/sendErrorStore'
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { error: vi.fn() },
|
||||
}))
|
||||
|
||||
const defaultProps = {
|
||||
sessionId: 'test-session',
|
||||
isConnected: true,
|
||||
@@ -63,18 +59,6 @@ describe('SessionSendErrorBanner', () => {
|
||||
expect(useSendErrorStore.getState().getError('test-session')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not call showToast.error', async () => {
|
||||
const { showToast } = await import('@/lib/toast')
|
||||
useSendErrorStore.getState().setError({
|
||||
sessionID: 'test-session',
|
||||
title: 'Error',
|
||||
message: 'Something failed',
|
||||
})
|
||||
|
||||
render(<SessionSendErrorBanner {...defaultProps} />)
|
||||
expect(showToast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not render a network-kind error while disconnected', () => {
|
||||
useSendErrorStore.getState().setError({
|
||||
sessionID: 'test-session',
|
||||
|
||||
@@ -1,28 +1,66 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { useState } from 'react'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { SIDE_QUESTION_INSTRUCTIONS } from '@/api/opencode'
|
||||
import { installMatchMedia } from '@/test/browserFakes'
|
||||
import type { FetchRoute, FetchRouteResult, RecordedFetchRequest } from '@/test/fetchFake'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
import { SideQuestionDialog } from './SideQuestionDialog'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
askSideQuestion: vi.fn(),
|
||||
}))
|
||||
interface GenerationServer {
|
||||
route: FetchRoute
|
||||
requests: RecordedFetchRequest[]
|
||||
signals: Array<AbortSignal | null | undefined>
|
||||
resolve: (index: number, result: FetchRouteResult) => void
|
||||
}
|
||||
|
||||
vi.mock('@/api/opencode', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/api/opencode')>()),
|
||||
askSideQuestion: mocks.askSideQuestion,
|
||||
}))
|
||||
function createGenerationServer(plan: Array<FetchRouteResult | 'pending'>): GenerationServer {
|
||||
const requests: RecordedFetchRequest[] = []
|
||||
const signals: Array<AbortSignal | null | undefined> = []
|
||||
const resolvers: Array<(result: FetchRouteResult) => void> = []
|
||||
|
||||
const renderDialog = (props: Partial<React.ComponentProps<typeof SideQuestionDialog>> = {}) =>
|
||||
render(
|
||||
<SideQuestionDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
sessionID="ses_1"
|
||||
initialQuestion=""
|
||||
{...props}
|
||||
/>,
|
||||
const route: FetchRoute = {
|
||||
method: 'POST',
|
||||
path: '/api/opencode/api/session/ses_1/generate',
|
||||
respond: (request, _params, init) => {
|
||||
const index = requests.length
|
||||
requests.push(request)
|
||||
signals.push(init?.signal)
|
||||
const outcome = plan[index] ?? { status: 500, json: { error: 'unexpected request' } }
|
||||
if (outcome !== 'pending') return outcome
|
||||
return new Promise<FetchRouteResult>((resolve) => {
|
||||
resolvers[index] = resolve
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
route,
|
||||
requests,
|
||||
signals,
|
||||
resolve: (index, result) => resolvers[index]?.(result),
|
||||
}
|
||||
}
|
||||
|
||||
function renderDialog(
|
||||
server: GenerationServer,
|
||||
props: Partial<React.ComponentProps<typeof SideQuestionDialog>> = {},
|
||||
) {
|
||||
return renderWithProviders(
|
||||
<SideQuestionDialog open onOpenChange={vi.fn()} sessionID="ses_1" {...props} />,
|
||||
{
|
||||
auth: false,
|
||||
theme: false,
|
||||
tts: false,
|
||||
toaster: false,
|
||||
fetchRoutes: [server.route],
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
function expectedPrompt(question: string): string {
|
||||
return `${SIDE_QUESTION_INSTRUCTIONS}\n\n${question}`
|
||||
}
|
||||
|
||||
function FocusHost() {
|
||||
const [open, setOpen] = useState(false)
|
||||
@@ -44,16 +82,8 @@ function FocusHost() {
|
||||
}
|
||||
|
||||
describe('SideQuestionDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'matchMedia')
|
||||
})
|
||||
|
||||
it('focuses its input on open and returns focus to the previous element on Escape', async () => {
|
||||
stubMatchMedia(true)
|
||||
installMatchMedia(true)
|
||||
render(<FocusHost />)
|
||||
const prompt = screen.getByLabelText('prompt')
|
||||
prompt.focus()
|
||||
@@ -69,158 +99,103 @@ describe('SideQuestionDialog', () => {
|
||||
})
|
||||
|
||||
it('asks a non-empty initial question once on mount and renders the answer', async () => {
|
||||
mocks.askSideQuestion.mockResolvedValue('**42**')
|
||||
const server = createGenerationServer([{ json: { data: { text: '**42**' } } }])
|
||||
|
||||
renderDialog({ initialQuestion: 'what is the answer?' })
|
||||
renderDialog(server, { initialQuestion: 'what is the answer?' })
|
||||
|
||||
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(1))
|
||||
expect(mocks.askSideQuestion).toHaveBeenCalledWith(
|
||||
'ses_1',
|
||||
'what is the answer?',
|
||||
expect.any(AbortSignal),
|
||||
'local',
|
||||
)
|
||||
await waitFor(() => expect(server.requests).toHaveLength(1))
|
||||
expect(server.requests[0].body).toEqual({ prompt: expectedPrompt('what is the answer?') })
|
||||
expect(await screen.findByText('42')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('asks nothing until the user types and submits when the initial question is empty', async () => {
|
||||
mocks.askSideQuestion.mockResolvedValue('because')
|
||||
const server = createGenerationServer([{ json: { data: { text: 'because' } } }])
|
||||
|
||||
renderDialog()
|
||||
renderDialog(server)
|
||||
|
||||
expect(mocks.askSideQuestion).not.toHaveBeenCalled()
|
||||
expect(server.requests).toHaveLength(0)
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
|
||||
target: { value: 'why?' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Ask' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.askSideQuestion).toHaveBeenCalledWith('ses_1', 'why?', expect.any(AbortSignal), 'local'),
|
||||
)
|
||||
await waitFor(() => expect(server.requests).toHaveLength(1))
|
||||
expect(server.requests[0].body).toEqual({ prompt: expectedPrompt('why?') })
|
||||
expect(await screen.findByText('because')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows Retry on failure and asks again when clicked', async () => {
|
||||
mocks.askSideQuestion.mockRejectedValueOnce(new Error('nope'))
|
||||
it('shows Retry on failure and asks the same question again when clicked', async () => {
|
||||
const server = createGenerationServer([
|
||||
{ status: 500, json: { error: 'nope' } },
|
||||
{ json: { data: { text: 'retried answer' } } },
|
||||
])
|
||||
|
||||
renderDialog({ initialQuestion: 'why?' })
|
||||
renderDialog(server, { initialQuestion: 'why?' })
|
||||
|
||||
await screen.findByText('Failed to get an answer')
|
||||
|
||||
mocks.askSideQuestion.mockResolvedValueOnce('retried answer')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
|
||||
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
|
||||
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith('ses_1', 'why?', expect.any(AbortSignal), 'local')
|
||||
await waitFor(() => expect(server.requests).toHaveLength(2))
|
||||
expect(server.requests[1].body).toEqual({ prompt: expectedPrompt('why?') })
|
||||
expect(await screen.findByText('retried answer')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('retries the failed question even when the draft was edited to another value', async () => {
|
||||
mocks.askSideQuestion.mockRejectedValueOnce(new Error('nope'))
|
||||
it.each([
|
||||
['another value', 'question B'],
|
||||
['cleared', ''],
|
||||
] as const)('retries the failed question even when the draft was %s', async (_label, draft) => {
|
||||
const server = createGenerationServer([
|
||||
{ status: 500, json: { error: 'nope' } },
|
||||
{ json: { data: { text: 'retried answer' } } },
|
||||
])
|
||||
|
||||
renderDialog({ initialQuestion: 'question A' })
|
||||
renderDialog(server, { initialQuestion: 'question A' })
|
||||
|
||||
await screen.findByText('Failed to get an answer')
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
|
||||
target: { value: 'question B' },
|
||||
target: { value: draft },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
|
||||
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
|
||||
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith(
|
||||
'ses_1',
|
||||
'question A',
|
||||
expect.any(AbortSignal),
|
||||
'local',
|
||||
)
|
||||
})
|
||||
|
||||
it('retries the failed question even when the draft was cleared', async () => {
|
||||
mocks.askSideQuestion.mockRejectedValueOnce(new Error('nope'))
|
||||
|
||||
renderDialog({ initialQuestion: 'question A' })
|
||||
|
||||
await screen.findByText('Failed to get an answer')
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
|
||||
target: { value: '' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
|
||||
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
|
||||
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith(
|
||||
'ses_1',
|
||||
'question A',
|
||||
expect.any(AbortSignal),
|
||||
'local',
|
||||
)
|
||||
await waitFor(() => expect(server.requests).toHaveLength(2))
|
||||
expect(server.requests[1].body).toEqual({ prompt: expectedPrompt('question A') })
|
||||
})
|
||||
|
||||
it('cancels the pending request when a replacement question is submitted', async () => {
|
||||
let resolveA: (value: string) => void = () => {}
|
||||
let resolveB: (value: string) => void = () => {}
|
||||
let signalA: AbortSignal | undefined
|
||||
let signalB: AbortSignal | undefined
|
||||
const server = createGenerationServer(['pending', 'pending'])
|
||||
renderDialog(server, { initialQuestion: 'question A' })
|
||||
|
||||
mocks.askSideQuestion
|
||||
.mockImplementationOnce((_sessionID: string, _question: string, signal?: AbortSignal) => {
|
||||
signalA = signal
|
||||
return new Promise<string>((resolve) => {
|
||||
resolveA = resolve
|
||||
})
|
||||
})
|
||||
.mockImplementationOnce((_sessionID: string, _question: string, signal?: AbortSignal) => {
|
||||
signalB = signal
|
||||
return new Promise<string>((resolve) => {
|
||||
resolveB = resolve
|
||||
})
|
||||
})
|
||||
|
||||
renderDialog({ initialQuestion: 'question A' })
|
||||
|
||||
await waitFor(() => expect(signalA).toBeDefined())
|
||||
await waitFor(() => expect(server.requests).toHaveLength(1))
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
|
||||
target: { value: 'question B' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Ask' }))
|
||||
|
||||
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
|
||||
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith(
|
||||
'ses_1',
|
||||
'question B',
|
||||
expect.any(AbortSignal),
|
||||
'local',
|
||||
)
|
||||
expect(signalB).toBeDefined()
|
||||
expect(signalA?.aborted).toBe(true)
|
||||
await waitFor(() => expect(server.requests).toHaveLength(2))
|
||||
expect(server.requests[1].body).toEqual({ prompt: expectedPrompt('question B') })
|
||||
expect(server.signals[0]?.aborted).toBe(true)
|
||||
expect(server.signals[1]?.aborted).toBe(false)
|
||||
|
||||
resolveB('answer B')
|
||||
server.resolve(1, { json: { data: { text: 'answer B' } } })
|
||||
expect(await screen.findByText('answer B')).toBeInTheDocument()
|
||||
|
||||
resolveA('answer A')
|
||||
server.resolve(0, { json: { data: { text: 'answer A' } } })
|
||||
await waitFor(() => expect(screen.queryByText('answer A')).not.toBeInTheDocument())
|
||||
expect(screen.getByText('answer B')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('aborts the in-flight request when unmounted', async () => {
|
||||
let capturedSignal: AbortSignal | undefined
|
||||
mocks.askSideQuestion.mockImplementation(
|
||||
(_sessionID: string, _question: string, signal?: AbortSignal) => {
|
||||
capturedSignal = signal
|
||||
return new Promise<string>(() => {})
|
||||
},
|
||||
)
|
||||
const server = createGenerationServer(['pending'])
|
||||
const { unmount } = renderDialog(server, { initialQuestion: 'why?' })
|
||||
|
||||
const { unmount } = renderDialog({ initialQuestion: 'why?' })
|
||||
|
||||
await waitFor(() => expect(capturedSignal).toBeDefined())
|
||||
expect(capturedSignal?.aborted).toBe(false)
|
||||
await waitFor(() => expect(server.signals).toHaveLength(1))
|
||||
expect(server.signals[0]?.aborted).toBe(false)
|
||||
|
||||
unmount()
|
||||
|
||||
expect(capturedSignal?.aborted).toBe(true)
|
||||
expect(server.signals[0]?.aborted).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -6,7 +6,7 @@ import { Input } from '@/components/ui/input'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { TextPart } from '@/components/message/TextPart'
|
||||
import { askSideQuestion } from '@/api/opencode'
|
||||
import { useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
import { useOpenCodeServerId } from '@/contexts/opencode-server-context'
|
||||
|
||||
interface SideQuestionDialogProps {
|
||||
open: boolean
|
||||
|
||||
+1
-54
@@ -1,7 +1,4 @@
|
||||
/* eslint-disable react-refresh/only-export-components */
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Search } from 'lucide-react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
|
||||
const PAGE_STEP = 10
|
||||
|
||||
@@ -52,7 +49,7 @@ export function usePickerCursor<Row extends PickerRow>(
|
||||
useEffect(() => {
|
||||
if (!cursorRow) return
|
||||
const node = rowRefs.current.get(cursorRow.key)
|
||||
if (node && typeof node.scrollIntoView === 'function') {
|
||||
if (node) {
|
||||
node.scrollIntoView({ block: 'nearest' })
|
||||
}
|
||||
}, [cursorRow])
|
||||
@@ -157,53 +154,3 @@ export function usePickerKeyNav<Row extends PickerRow>({
|
||||
[rows, cursorIndex, cursorRow, moveCursor, onOpenRow, onDeleteRow, onToggleAllProjects],
|
||||
)
|
||||
}
|
||||
|
||||
export interface PickerSearchBarProps {
|
||||
inputRef: React.RefObject<HTMLInputElement | null>
|
||||
listId: string
|
||||
open: boolean
|
||||
activeDescendantId: string | undefined
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void
|
||||
placeholder: string
|
||||
name: string
|
||||
trailing?: React.ReactNode
|
||||
}
|
||||
|
||||
export function PickerSearchBar({
|
||||
inputRef,
|
||||
listId,
|
||||
open,
|
||||
activeDescendantId,
|
||||
value,
|
||||
onChange,
|
||||
onKeyDown,
|
||||
placeholder,
|
||||
name,
|
||||
trailing,
|
||||
}: PickerSearchBarProps) {
|
||||
return (
|
||||
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
ref={inputRef}
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
aria-controls={listId}
|
||||
aria-autocomplete="list"
|
||||
aria-activedescendant={activeDescendantId}
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder={placeholder}
|
||||
className="h-9 pl-9"
|
||||
autoComplete="off"
|
||||
name={name}
|
||||
/>
|
||||
</div>
|
||||
{trailing}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -33,7 +33,7 @@ describe('selectRootSessions', () => {
|
||||
const sessions = [
|
||||
createSession('inside', 3000, '/a'),
|
||||
createSession('outside', 2000, '/b'),
|
||||
{ ...createSession('no-directory', 1000), location: {} as Session['location'] },
|
||||
createSession('no-directory', 1000, ''),
|
||||
]
|
||||
|
||||
const result = selectRootSessions(sessions, { directories: new Set(['/a']), keyFn })
|
||||
|
||||
Reference in new issue
Block a user