mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
section 13: Phase 13: Session status from the client type, compaction-dr
This commit is contained in:
1 parent
717536c5a6
commit
2d4abe79e1
21 files changed
+194
-100
No files matched your search
@@ -80,6 +80,7 @@ describe('OpenCode facade', () => {
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: 'deploy',
|
||||
parentID: null,
|
||||
})
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
@@ -93,7 +94,7 @@ describe('OpenCode facade', () => {
|
||||
it('passes the directory and cursor for continuation pages', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: [], cursor: {} }))
|
||||
|
||||
const page = await listSessionPage({ directory: '/repo', cursor: 'cursor_1' })
|
||||
const page = await listSessionPage({ directory: '/repo', cursor: 'cursor_1', parentID: null })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session?parentID=null&directory=%2Frepo&cursor=cursor_1',
|
||||
@@ -108,7 +109,7 @@ describe('OpenCode facade', () => {
|
||||
jsonResponse({ data: [sessionInfo('ses_1', '/repo')], cursor: { next: 'cursor_next' } }),
|
||||
)
|
||||
|
||||
const page = await listSessionPage({ limit: 25, order: 'desc' })
|
||||
const page = await listSessionPage({ limit: 25, order: 'desc', parentID: null })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session?limit=25&order=desc&parentID=null',
|
||||
@@ -121,7 +122,7 @@ describe('OpenCode facade', () => {
|
||||
it('omits the directory on an all-directories continuation page', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ data: [], cursor: {} }))
|
||||
|
||||
await listSessionPage({ cursor: 'cursor_1' })
|
||||
await listSessionPage({ cursor: 'cursor_1', parentID: null })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session?parentID=null&cursor=cursor_1',
|
||||
@@ -134,7 +135,7 @@ describe('OpenCode facade', () => {
|
||||
jsonResponse({ data: [sessionInfo('ses_child', '/repo')], cursor: {} }),
|
||||
)
|
||||
|
||||
await listSessionPage({ directory: '/repo', limit: 25, order: 'desc', includeChildren: true })
|
||||
await listSessionPage({ directory: '/repo', limit: 25, order: 'desc' })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/session?limit=25&order=desc&directory=%2Frepo',
|
||||
@@ -313,7 +314,7 @@ describe('OpenCode facade', () => {
|
||||
}),
|
||||
)
|
||||
|
||||
const files = await findFiles({ directory: '/repo', query: 'index', limit: 20 })
|
||||
const files = await findFiles({ location: { directory: '/repo' }, query: 'index', limit: 20 })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/fs/find?location%5Bdirectory%5D=%2Frepo&query=index&type=file&limit=20',
|
||||
@@ -325,7 +326,7 @@ describe('OpenCode facade', () => {
|
||||
it('finds files without a limit when none is given', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ location: { directory: '/repo' }, data: [] }))
|
||||
|
||||
await findFiles({ directory: '/repo', query: 'index' })
|
||||
await findFiles({ location: { directory: '/repo' }, query: 'index' })
|
||||
|
||||
expect(lastRequest().url).toBe(
|
||||
'http://localhost/api/opencode/api/fs/find?location%5Bdirectory%5D=%2Frepo&query=index&type=file',
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
FormInfo,
|
||||
ModelRef,
|
||||
OpenCodeApi,
|
||||
PermissionReply,
|
||||
PermissionRequest,
|
||||
SessionGoalRead,
|
||||
SessionInboxCompaction,
|
||||
@@ -146,16 +147,7 @@ export interface SessionPage {
|
||||
nextCursor?: string
|
||||
}
|
||||
|
||||
export interface SessionPageInput {
|
||||
directory?: string
|
||||
project?: string
|
||||
subpath?: string
|
||||
limit?: number
|
||||
order?: 'asc' | 'desc'
|
||||
search?: string
|
||||
cursor?: string
|
||||
includeChildren?: boolean
|
||||
}
|
||||
export type SessionPageInput = NonNullable<Parameters<OpenCodeApi['session']['list']>[0]>
|
||||
|
||||
export interface CreateSessionInput {
|
||||
directory: string
|
||||
@@ -164,11 +156,7 @@ export interface CreateSessionInput {
|
||||
model?: string
|
||||
}
|
||||
|
||||
export interface FindFilesInput {
|
||||
directory?: string
|
||||
query: string
|
||||
limit?: number
|
||||
}
|
||||
export type FindFilesInput = Parameters<OpenCodeApi['file']['find']>[0]
|
||||
|
||||
export interface SessionMessagesPage {
|
||||
messages: SessionMessageInfo[]
|
||||
@@ -204,19 +192,7 @@ function buildPromptFields(input: PromptFields) {
|
||||
}
|
||||
|
||||
export async function listSessionPage(input: SessionPageInput, serverId?: string): Promise<SessionPage> {
|
||||
const { data, cursor } = await callOpenCode((api) =>
|
||||
api.session.list({
|
||||
...(input.directory === undefined ? {} : { directory: input.directory }),
|
||||
...(input.project === undefined ? {} : { project: input.project }),
|
||||
...(input.subpath === undefined ? {} : { subpath: input.subpath }),
|
||||
...(input.includeChildren ? {} : { parentID: 'null' }),
|
||||
limit: input.limit,
|
||||
order: input.order,
|
||||
search: input.search,
|
||||
cursor: input.cursor,
|
||||
}),
|
||||
serverId,
|
||||
)
|
||||
const { data, cursor } = await callOpenCode((api) => api.session.list(input), serverId)
|
||||
return { items: data, nextCursor: cursor.next ?? undefined }
|
||||
}
|
||||
|
||||
@@ -546,7 +522,7 @@ export async function listPendingPermissions(
|
||||
export async function replyPermission(
|
||||
sessionID: string,
|
||||
requestID: string,
|
||||
decision: 'once' | 'always' | 'reject',
|
||||
decision: PermissionReply,
|
||||
message?: string,
|
||||
serverId?: string,
|
||||
): Promise<void> {
|
||||
@@ -581,16 +557,7 @@ export async function cancelForm(sessionID: string, formID: string, serverId?: s
|
||||
}
|
||||
|
||||
export async function findFiles(input: FindFilesInput, serverId?: string): Promise<string[]> {
|
||||
const { data } = await callOpenCode(
|
||||
(api) =>
|
||||
api.file.find({
|
||||
...openCodeLocation(input.directory),
|
||||
query: input.query,
|
||||
type: 'file',
|
||||
limit: input.limit,
|
||||
}),
|
||||
serverId,
|
||||
)
|
||||
const { data } = await callOpenCode((api) => api.file.find({ ...input, type: 'file' }), serverId)
|
||||
return data.map((entry) => entry.path)
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ export interface Repo {
|
||||
}
|
||||
|
||||
export type Session = SessionInfo
|
||||
export type PermissionResponse = 'once' | 'always' | 'reject'
|
||||
|
||||
export interface FileAttachmentInfo {
|
||||
path: string
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import type { AgentInfo } from '@opencode-manager/shared/opencode'
|
||||
import { useAgents } from '@/hooks/useOpenCode'
|
||||
import { getAgentStyleVars } from '@/lib/agent-colors'
|
||||
import { getPrimaryAgents } from '@/lib/primaryAgents'
|
||||
@@ -19,16 +20,9 @@ interface AgentQuickSelectProps {
|
||||
isBashMode?: boolean
|
||||
}
|
||||
|
||||
interface AgentInfo {
|
||||
id: string
|
||||
name: string
|
||||
color?: string
|
||||
description?: string
|
||||
mode?: string
|
||||
hidden?: boolean
|
||||
}
|
||||
type SelectableAgent = Pick<AgentInfo, 'id' | 'name' | 'color' | 'description' | 'mode' | 'hidden'>
|
||||
|
||||
const findAgent = (agents: AgentInfo[], agentId: string): AgentInfo | undefined => {
|
||||
const findAgent = (agents: SelectableAgent[], agentId: string): SelectableAgent | undefined => {
|
||||
return agents.find(a => a.id.toLowerCase() === agentId.toLowerCase())
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,7 @@ import {
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import type { PermissionResponse } from '@/api/types'
|
||||
import type { PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import type { PermissionReply, PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
getPermissionLabel,
|
||||
getPermissionPhrase,
|
||||
@@ -30,7 +29,7 @@ interface PermissionRequestDialogProps {
|
||||
onRespond: (
|
||||
permissionID: string,
|
||||
sessionID: string,
|
||||
response: PermissionResponse,
|
||||
response: PermissionReply,
|
||||
message?: string,
|
||||
) => Promise<void>
|
||||
open?: boolean
|
||||
@@ -49,7 +48,7 @@ export function PermissionRequestDialog({
|
||||
onOpenChange,
|
||||
}: PermissionRequestDialogProps) {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [loadingAction, setLoadingAction] = useState<PermissionResponse | null>(null)
|
||||
const [loadingAction, setLoadingAction] = useState<PermissionReply | null>(null)
|
||||
const [rejectReason, setRejectReason] = useState('')
|
||||
const reasonInputId = useId()
|
||||
const allowOnceRef = useRef<HTMLButtonElement>(null)
|
||||
@@ -61,7 +60,7 @@ export function PermissionRequestDialog({
|
||||
if (!permission) return null
|
||||
if (parentOpen === false) return null
|
||||
|
||||
const handleResponse = async (response: PermissionResponse) => {
|
||||
const handleResponse = async (response: PermissionReply) => {
|
||||
setIsLoading(true)
|
||||
setLoadingAction(response)
|
||||
const message = response === 'reject' ? rejectReason.trim() : ''
|
||||
|
||||
@@ -37,6 +37,14 @@ describe('SessionStatusIndicator background activity', () => {
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('labels a compacting session', () => {
|
||||
useSessionStatus.getState().setStatus('session-a', { type: 'compact' })
|
||||
|
||||
render(<SessionStatusIndicator sessionID="session-a" />)
|
||||
|
||||
expect(screen.getByLabelText('Compacting')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the braille spinner with a running label for a busy session', () => {
|
||||
useSessionStatus.getState().setStatus('session-a', { type: 'busy' })
|
||||
|
||||
|
||||
@@ -1929,6 +1929,58 @@ describe('EventProvider permissions and forms', () => {
|
||||
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'busy' })
|
||||
})
|
||||
|
||||
it('shows compaction from compaction events and restores the previous status', async () => {
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.execution.started', data: { sessionID: 'session-compact' }, directory: '/repo' })
|
||||
onEvent({
|
||||
type: 'session.compaction.started',
|
||||
data: { sessionID: 'session-compact', reason: 'manual' },
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
expect(useSessionStatus.getState().getStatus('session-compact')).toEqual({ type: 'compact' })
|
||||
|
||||
act(() => {
|
||||
onEvent({
|
||||
type: 'session.compaction.ended',
|
||||
data: { sessionID: 'session-compact', reason: 'manual', text: 'summary' },
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
expect(useSessionStatus.getState().getStatus('session-compact')).toEqual({ type: 'busy' })
|
||||
|
||||
act(() => {
|
||||
onEvent({
|
||||
type: 'session.compaction.started',
|
||||
data: { sessionID: 'session-compact', reason: 'auto' },
|
||||
directory: '/repo',
|
||||
})
|
||||
onEvent({
|
||||
type: 'session.status',
|
||||
data: { sessionID: 'session-compact', status: { type: 'retry', attempt: 1, message: 'rate limited', next: 5 } },
|
||||
directory: '/repo',
|
||||
})
|
||||
onEvent({
|
||||
type: 'session.compaction.failed',
|
||||
data: { sessionID: 'session-compact', reason: 'auto', error: { message: 'boom' } },
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
expect(useSessionStatus.getState().getStatus('session-compact')).toEqual({
|
||||
type: 'retry',
|
||||
attempt: 1,
|
||||
message: 'rate limited',
|
||||
next: 5,
|
||||
})
|
||||
})
|
||||
|
||||
it('applies execution lifecycle and idle events from the global monitor to the status store', async () => {
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
|
||||
@@ -25,8 +25,8 @@ import { isLocalOpenCodeServer } from '@/contexts/OpenCodeServerContext'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
|
||||
import { remoteProjectsQueryOptions } from '@/hooks/useRemoteProjects'
|
||||
import type { FormAnswer, FormInfo, PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import type { PermissionResponse, Repo } from '@/api/types'
|
||||
import type { FormAnswer, FormInfo, PermissionReply, PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import type { Repo } from '@/api/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
|
||||
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
|
||||
@@ -238,7 +238,7 @@ interface EventContextValue {
|
||||
respond: (
|
||||
permissionID: string,
|
||||
sessionID: string,
|
||||
response: PermissionResponse,
|
||||
response: PermissionReply,
|
||||
message?: string,
|
||||
) => Promise<void>
|
||||
dismiss: (permissionID: string, sessionID?: string) => void
|
||||
@@ -626,7 +626,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const replyToPermission = useCallback(async (
|
||||
permissionID: string,
|
||||
sessionID: string,
|
||||
response: PermissionResponse,
|
||||
response: PermissionReply,
|
||||
message?: string,
|
||||
) => {
|
||||
const permission = allPermissions.find(candidate => candidate.id === permissionID)
|
||||
@@ -1098,6 +1098,15 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' })
|
||||
break
|
||||
}
|
||||
case 'session.compaction.started': {
|
||||
useSessionStatus.getState().beginCompaction(event.data.sessionID)
|
||||
break
|
||||
}
|
||||
case 'session.compaction.ended':
|
||||
case 'session.compaction.failed': {
|
||||
useSessionStatus.getState().endCompaction(event.data.sessionID)
|
||||
break
|
||||
}
|
||||
case 'session.execution.started': {
|
||||
useSessionStatus.getState().setSessionServer(event.data.sessionID, serverId)
|
||||
rememberSessionDirectory(event.data.sessionID, event.directory, serverId)
|
||||
|
||||
@@ -153,7 +153,7 @@ describe('useActiveWork', () => {
|
||||
|
||||
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('root2'))
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledWith({ cursor: 'page2', includeChildren: true }, 'local')
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledWith({ cursor: 'page2' }, 'local')
|
||||
})
|
||||
|
||||
it('does not request another page when the oldest loaded session is outside the window', async () => {
|
||||
@@ -333,7 +333,7 @@ describe('useActiveWork', () => {
|
||||
expect(row.repo).toBeNull()
|
||||
expect(row.path).toBe('/servers/srv_kitchen/sessions/ses_remote_recent')
|
||||
expect(mocks.listRemoteSessionPage).toHaveBeenCalledWith(
|
||||
{ limit: 50, order: 'desc', includeChildren: true },
|
||||
{ limit: 50, order: 'desc' },
|
||||
'srv_kitchen',
|
||||
)
|
||||
expect(result.current.isError).toBe(false)
|
||||
|
||||
@@ -303,7 +303,7 @@ export function useActiveWork(windowMs: number): {
|
||||
queryKey: activeWorkSessionsQueryKey(serverId),
|
||||
queryFn: async (): Promise<SessionInfo[]> => {
|
||||
const page = await listSessionPage(
|
||||
{ limit: ACTIVE_WORK_SESSION_LIMIT, order: 'desc', includeChildren: true },
|
||||
{ limit: ACTIVE_WORK_SESSION_LIMIT, order: 'desc' },
|
||||
serverId,
|
||||
)
|
||||
return page.items
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { openCodeLocation } from '@opencode-manager/shared/opencode'
|
||||
import { useDebouncedValue } from '@/hooks/useDebouncedValue'
|
||||
import { findFiles } from '@/api/opencode'
|
||||
import { useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
@@ -20,7 +21,7 @@ export function useFileSearch(
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: serverScopedKey(['file-search', debouncedQuery, directory], serverId),
|
||||
queryFn: () => findFiles({ directory, query: debouncedQuery }, serverId),
|
||||
queryFn: () => findFiles({ ...openCodeLocation(directory), query: debouncedQuery }, serverId),
|
||||
enabled: enabled && !!debouncedQuery,
|
||||
staleTime: 60000,
|
||||
})
|
||||
|
||||
@@ -95,12 +95,14 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: undefined,
|
||||
parentID: null,
|
||||
}, 'local')
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledWith({
|
||||
directory: '/w/b',
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: undefined,
|
||||
parentID: null,
|
||||
}, 'local')
|
||||
|
||||
await act(async () => {
|
||||
@@ -111,7 +113,7 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
expect(result.current.data).toHaveLength(3)
|
||||
})
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledWith({ directory: '/w/a', cursor: 'cursor_a' }, 'local')
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledWith({ directory: '/w/a', cursor: 'cursor_a', parentID: null }, 'local')
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_a1', 'ses_b1', 'ses_a2'])
|
||||
})
|
||||
|
||||
@@ -130,6 +132,7 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: 'deploy',
|
||||
parentID: null,
|
||||
}, 'local')
|
||||
})
|
||||
})
|
||||
@@ -157,6 +160,7 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: undefined,
|
||||
parentID: null,
|
||||
}, 'local')
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1'])
|
||||
expect(result.current.hasNextPage).toBe(true)
|
||||
@@ -170,7 +174,7 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
})
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledTimes(2)
|
||||
expect(mocks.listSessionPage).toHaveBeenLastCalledWith({ cursor: 'cursor_all' }, 'local')
|
||||
expect(mocks.listSessionPage).toHaveBeenLastCalledWith({ cursor: 'cursor_all', parentID: null }, 'local')
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1', 'ses_all2'])
|
||||
})
|
||||
|
||||
@@ -194,6 +198,7 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: undefined,
|
||||
parentID: null,
|
||||
}, 'local')
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_all'])
|
||||
})
|
||||
@@ -216,7 +221,6 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: undefined,
|
||||
includeChildren: true,
|
||||
}, 'local')
|
||||
expect(queryClient.getQueryCache().getAll()[0]?.queryKey).toEqual([
|
||||
'opencode',
|
||||
@@ -278,6 +282,7 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
search: undefined,
|
||||
project: 'proj_x',
|
||||
subpath: '',
|
||||
parentID: null,
|
||||
}, 'local')
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_root'])
|
||||
expect(result.current.hasNextPage).toBe(true)
|
||||
@@ -291,7 +296,7 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
})
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledTimes(2)
|
||||
expect(mocks.listSessionPage).toHaveBeenLastCalledWith({ cursor: 'cursor_project' }, 'local')
|
||||
expect(mocks.listSessionPage).toHaveBeenLastCalledWith({ cursor: 'cursor_project', parentID: null }, 'local')
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_root', 'ses_wt'])
|
||||
})
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ export const useSessionsAcrossDirectories = (
|
||||
*/
|
||||
const persistedGcTime = normalizedSearch === undefined ? PERSISTED_CACHE_MAX_AGE_MS : undefined;
|
||||
const directoryKey = uniqueDirectories.join('|');
|
||||
const childSessionsParam = includeChildren ? { includeChildren: true } : {};
|
||||
const childSessionsParam = includeChildren ? {} : { parentID: null };
|
||||
const isQueryEnabled = uniqueDirectories.length > 0 || allDirectories;
|
||||
|
||||
const query = useInfiniteQuery<
|
||||
|
||||
@@ -217,7 +217,7 @@ describe('useRemoteProjectsByActivity', () => {
|
||||
await waitFor(() => expect(mocks.listSessionPage).toHaveBeenCalledTimes(1))
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledWith(
|
||||
{ limit: 100, order: 'desc' },
|
||||
{ limit: 100, order: 'desc', search: undefined, parentID: null },
|
||||
'srv_kitchen',
|
||||
)
|
||||
})
|
||||
|
||||
@@ -59,7 +59,7 @@ describe('resolveDefaultSessionAgent', () => {
|
||||
|
||||
it('ignores agents that are not primary or all mode', () => {
|
||||
const agents = [
|
||||
{ id: 'sub-agent', name: 'sub-agent', mode: 'secondary' },
|
||||
{ id: 'sub-agent', name: 'sub-agent', mode: 'subagent' },
|
||||
{ id: 'build', name: 'build', mode: 'primary' },
|
||||
]
|
||||
expect(resolveDefaultSessionAgent(agents, true)).toBe('build')
|
||||
|
||||
@@ -2,18 +2,13 @@ import { useMemo, useEffect } from 'react'
|
||||
import { useSession, useAgents } from './useOpenCode'
|
||||
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
|
||||
import { getPrimaryAgents } from '@/lib/primaryAgents'
|
||||
import type { ModelRef } from '@opencode-manager/shared/opencode'
|
||||
import type { AgentInfo, ModelRef } from '@opencode-manager/shared/opencode'
|
||||
|
||||
interface AgentInfo {
|
||||
id: string
|
||||
name?: string
|
||||
mode?: string
|
||||
hidden?: boolean
|
||||
}
|
||||
type SessionAgentInfo = Pick<AgentInfo, 'id' | 'mode' | 'hidden'>
|
||||
|
||||
const resolveAvailableAgentId = (
|
||||
agentId: string | undefined,
|
||||
agents: AgentInfo[] | undefined,
|
||||
agents: SessionAgentInfo[] | undefined,
|
||||
agentsLoaded: boolean
|
||||
): string | undefined => {
|
||||
if (!agentId) return undefined
|
||||
@@ -26,7 +21,7 @@ const resolveAvailableAgentId = (
|
||||
}
|
||||
|
||||
export function resolveDefaultSessionAgent(
|
||||
agents: AgentInfo[] | undefined,
|
||||
agents: SessionAgentInfo[] | undefined,
|
||||
agentsLoaded: boolean
|
||||
): string {
|
||||
const primaryAgents = getPrimaryAgents(agents)
|
||||
|
||||
@@ -9,7 +9,7 @@ import type {
|
||||
export interface SessionTranscript {
|
||||
messages: SessionMessageInfo[]
|
||||
pending: SessionInboxInfo[]
|
||||
status: 'idle' | 'busy' | 'retry'
|
||||
status: SessionStatus['type']
|
||||
retry?: SessionStatus
|
||||
}
|
||||
|
||||
|
||||
@@ -331,7 +331,8 @@ export function SessionDetail() {
|
||||
[sessionId, session?.agent, session?.model],
|
||||
);
|
||||
const { modelRef } = useModelSelection(sessionDirectory, modelSelectionSession);
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
const beginCompaction = useSessionStatus((state) => state.beginCompaction);
|
||||
const endCompaction = useSessionStatus((state) => state.endCompaction);
|
||||
const isEditingMessage = useUIState((state) => state.isEditingMessage);
|
||||
const { isEnabled: ttsEnabled } = useTTS();
|
||||
const { syncForSession: syncPermissionsForSession } = usePermissions();
|
||||
@@ -466,16 +467,16 @@ export function SessionDetail() {
|
||||
|
||||
const toastId = `compact-${sessionId}`;
|
||||
showToast.loading('Compacting session...', { id: toastId });
|
||||
setSessionStatus(sessionId, { type: 'compact' });
|
||||
beginCompaction(sessionId);
|
||||
|
||||
try {
|
||||
await compactSession(sessionId, serverId);
|
||||
showToast.success('Compaction requested', { id: toastId });
|
||||
} catch (error) {
|
||||
showToast.error(`Compact failed: ${error instanceof Error ? error.message : 'Unknown error'}`, { id: toastId });
|
||||
setSessionStatus(sessionId, { type: 'idle' });
|
||||
endCompaction(sessionId);
|
||||
}
|
||||
}, [sessionId, serverId, setSessionStatus]);
|
||||
}, [sessionId, serverId, beginCompaction, endCompaction]);
|
||||
|
||||
const handleUndo = useCallback(async () => {
|
||||
if (!sessionId) return;
|
||||
|
||||
@@ -31,6 +31,8 @@ const mocks = vi.hoisted(() => ({
|
||||
copyTextToClipboard: vi.fn(),
|
||||
downloadMarkdown: vi.fn(),
|
||||
setStatus: vi.fn(),
|
||||
beginCompaction: vi.fn(),
|
||||
endCompaction: vi.fn(),
|
||||
setPromptValue: vi.fn(),
|
||||
openModelPicker: vi.fn(),
|
||||
promptInputProps: null as Record<string, unknown> | null,
|
||||
@@ -158,8 +160,16 @@ vi.mock('@/stores/uiStateStore', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/sessionStatusStore', () => ({
|
||||
useSessionStatus: vi.fn((selector: (state: { setStatus: typeof mocks.setStatus }) => unknown) =>
|
||||
selector({ setStatus: mocks.setStatus })
|
||||
useSessionStatus: vi.fn((selector: (state: {
|
||||
setStatus: typeof mocks.setStatus
|
||||
beginCompaction: typeof mocks.beginCompaction
|
||||
endCompaction: typeof mocks.endCompaction
|
||||
}) => unknown) =>
|
||||
selector({
|
||||
setStatus: mocks.setStatus,
|
||||
beginCompaction: mocks.beginCompaction,
|
||||
endCompaction: mocks.endCompaction,
|
||||
})
|
||||
),
|
||||
useSessionStatusForSession: mocks.useSessionStatusForSession,
|
||||
}))
|
||||
@@ -354,7 +364,7 @@ describe('SessionDetail command actions', () => {
|
||||
await compact()
|
||||
})
|
||||
|
||||
expect(mocks.setStatus).toHaveBeenCalledWith(SESSION_ID, { type: 'compact' })
|
||||
expect(mocks.beginCompaction).toHaveBeenCalledWith(SESSION_ID)
|
||||
expect(mocks.compactSession).toHaveBeenCalledWith(SESSION_ID, 'local')
|
||||
expect(mocks.showToast.loading).toHaveBeenCalledWith('Compacting session...', { id: `compact-${SESSION_ID}` })
|
||||
expect(mocks.showToast.success).toHaveBeenCalledWith('Compaction requested', { id: `compact-${SESSION_ID}` })
|
||||
@@ -369,7 +379,7 @@ describe('SessionDetail command actions', () => {
|
||||
await compact()
|
||||
})
|
||||
|
||||
expect(mocks.setStatus).toHaveBeenCalledWith(SESSION_ID, { type: 'idle' })
|
||||
expect(mocks.endCompaction).toHaveBeenCalledWith(SESSION_ID)
|
||||
expect(mocks.showToast.error).toHaveBeenCalledWith('Compact failed: nope', { id: `compact-${SESSION_ID}` })
|
||||
})
|
||||
|
||||
|
||||
@@ -154,6 +154,43 @@ describe('sessionStatusStore', () => {
|
||||
expect(useSessionStatus.getState().getStatus('session-compact')).toEqual({ type: 'compact' })
|
||||
})
|
||||
|
||||
it('restores the pre-compaction status when compaction ends', () => {
|
||||
const store = useSessionStatus.getState()
|
||||
store.setStatus('session-a', { type: 'busy' })
|
||||
|
||||
store.beginCompaction('session-a')
|
||||
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'compact' })
|
||||
|
||||
store.endCompaction('session-a')
|
||||
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'busy' })
|
||||
})
|
||||
|
||||
it('keeps a status event that arrives during compaction', () => {
|
||||
const store = useSessionStatus.getState()
|
||||
store.setStatus('session-a', { type: 'busy' })
|
||||
store.beginCompaction('session-a')
|
||||
|
||||
const retry = { type: 'retry' as const, attempt: 1, message: 'rate limited', next: 9 }
|
||||
store.setStatus('session-a', retry)
|
||||
store.endCompaction('session-a')
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-a')).toEqual(retry)
|
||||
})
|
||||
|
||||
it('keeps the retry action of a retry status', () => {
|
||||
const retry = {
|
||||
type: 'retry' as const,
|
||||
attempt: 2,
|
||||
message: 'rate limited',
|
||||
next: 1234,
|
||||
action: { reason: 'usage', provider: 'provider', title: 'Usage limit', message: 'Try later', label: 'Upgrade' },
|
||||
}
|
||||
|
||||
useSessionStatus.getState().setStatus('session-retry', retry)
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-retry')).toEqual(retry)
|
||||
})
|
||||
|
||||
it('maps active session ids to busy statuses', () => {
|
||||
expect(busyStatusesFromActiveSessions({ 'session-a': { type: 'running' } })).toEqual({
|
||||
'session-a': { type: 'busy' },
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import { create } from 'zustand'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { SessionInfo } from '@opencode-manager/shared/opencode'
|
||||
import type { SessionInfo, SessionStatus } from '@opencode-manager/shared/opencode'
|
||||
import { childLifecycle, type BackgroundTaskLifecycle, type ChildOutcome } from '@/lib/backgroundWork'
|
||||
|
||||
export type SessionStatusType =
|
||||
| { type: 'idle' }
|
||||
| { type: 'busy' }
|
||||
| { type: 'compact' }
|
||||
| { type: 'retry'; attempt: number; message: string; next: number }
|
||||
export type SessionStatusType = SessionStatus | { type: 'compact' }
|
||||
|
||||
interface StatusSnapshotToken {
|
||||
revision: number
|
||||
@@ -41,6 +37,8 @@ interface SessionStatusStore {
|
||||
setOutcome: (sessionID: string, outcome: ChildOutcome) => void
|
||||
clearOutcome: (sessionID: string) => void
|
||||
setOptimisticActive: (sessionID: string, timeoutMs?: number) => void
|
||||
beginCompaction: (sessionID: string) => void
|
||||
endCompaction: (sessionID: string) => void
|
||||
replaceStatuses: (statuses: Record<string, SessionStatusType>, token: StatusSnapshotToken) => void
|
||||
replaceServerStatuses: (serverId: string, statuses: Record<string, SessionStatusType>, token: StatusSnapshotToken) => void
|
||||
applySessionSnapshot: (sessionID: string, session: SessionInfo, token: StatusSnapshotToken) => void
|
||||
@@ -62,6 +60,7 @@ interface SessionStatusStore {
|
||||
const DEFAULT_STATUS: SessionStatusType = { type: 'idle' }
|
||||
const OPTIMISTIC_ACTIVE_TIMEOUT_MS = 120_000
|
||||
const optimisticActiveTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
const preCompactionStatuses = new Map<string, SessionStatusType>()
|
||||
const inFlightSnapshots = new Map<number, number>()
|
||||
let snapshotOrderCounter = 0
|
||||
let lastAppliedSnapshotOrder = 0
|
||||
@@ -78,7 +77,7 @@ const clearOptimisticActiveTimer = (sessionID: string): void => {
|
||||
|
||||
const getStatusHash = (status: SessionStatusType): string => {
|
||||
if (status.type === 'retry') {
|
||||
return `${status.type}:${status.attempt}:${status.message}:${status.next}`
|
||||
return JSON.stringify(status)
|
||||
}
|
||||
return status.type
|
||||
}
|
||||
@@ -429,6 +428,22 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
|
||||
set((state) => applyStatusPatch(state, sessionID, { type: 'busy' }))
|
||||
},
|
||||
|
||||
beginCompaction: (sessionID: string) => {
|
||||
const currentStatus = get().getStatus(sessionID)
|
||||
if (currentStatus.type !== 'compact') {
|
||||
preCompactionStatuses.set(sessionID, currentStatus)
|
||||
}
|
||||
get().setStatus(sessionID, { type: 'compact' })
|
||||
},
|
||||
|
||||
endCompaction: (sessionID: string) => {
|
||||
const previousStatus = preCompactionStatuses.get(sessionID)
|
||||
if (previousStatus === undefined) return
|
||||
preCompactionStatuses.delete(sessionID)
|
||||
if (get().getStatus(sessionID).type !== 'compact') return
|
||||
get().setStatus(sessionID, previousStatus)
|
||||
},
|
||||
|
||||
replaceStatuses: (statuses: Record<string, SessionStatusType>, token: StatusSnapshotToken) => {
|
||||
releaseSnapshot(token)
|
||||
|
||||
@@ -624,6 +639,7 @@ export const useSessionStatus = create<SessionStatusStore>((set, get) => {
|
||||
|
||||
forgetSession: (sessionID: string) => {
|
||||
clearOptimisticActiveTimer(sessionID)
|
||||
preCompactionStatuses.delete(sessionID)
|
||||
const current = get()
|
||||
const ownsShell = Array.from(current.runningShells.values()).some((shell) => shell.sessionID === sessionID)
|
||||
const hasSession =
|
||||
|
||||
Reference in new issue
Block a user