diff --git a/backend/src/index.ts b/backend/src/index.ts index be7db75c..4f4601c8 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -304,7 +304,7 @@ scheduleService.setWorktreeRemovedHandler(async (directory) => { const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthService, projectConfigService, terminalService, scheduleService) const scheduleRunnerInstance = new ScheduleRunner(scheduleService) -const chatService = new ChatService(openCodeClient) +const chatService = new ChatService(openCodeClient, terminalService) const notificationService = new NotificationService(db, opencodeServerRegistry, chatService) const sessionPermissionModeService = new SessionPermissionModeService(db, opencodeServerRegistry, sessionSettingsService, sessionAncestry) const goalOutcomes = new GoalOutcomeTracker() diff --git a/backend/src/services/chats.ts b/backend/src/services/chats.ts index 46c9ed92..ab8b0bec 100644 --- a/backend/src/services/chats.ts +++ b/backend/src/services/chats.ts @@ -13,8 +13,10 @@ import { type ListChatsResponse, } from '@opencode-manager/shared/schemas' import type { OpenCodeClient } from './opencode/client' +import type { TerminalService } from './terminal' import { ensureDirectoryExists } from './file-operations' import { canonicalPathSync } from '../utils/fs-safe' +import { logger } from '../utils/logger' const CHAT_ID_ATTEMPTS = 5 @@ -49,6 +51,7 @@ function formatChatTimestamp(now: Date): string { export class ChatService { constructor( private readonly openCodeClient: OpenCodeClient, + private readonly terminals: Pick, private readonly root: () => string = getChatsPath, private readonly now: () => Date = () => new Date(), ) {} @@ -77,12 +80,24 @@ export class ChatService { } async findByDirectory(directory: string): Promise { - const target = canonicalPathSync(path.resolve(directory)) - for (const id of await this.listChatIds()) { - const chat = this.toChat(id) - if (canonicalPathSync(chat.directory) === target) return chat + try { + const relative = path.relative( + canonicalPathSync(this.root()), + canonicalPathSync(path.resolve(directory)), + ) + if ( + !relative || + path.isAbsolute(relative) || + relative.includes(path.sep) || + relative.startsWith('..') + ) { + return null + } + if (!ChatIdSchema.safeParse(relative).success) return null + return await this.resolve(relative) + } catch { + return null } - return null } async create(input: CreateChatRequest): Promise<{ chat: Chat; sessionId: string }> { @@ -116,17 +131,28 @@ export class ChatService { } await this.openCodeClient.api.session.remove({ sessionID: sessionId }) - const remaining = await this.openCodeClient.api.session.list({ - directory: chat.directory, - limit: 1, - }) + try { + const remaining = await this.openCodeClient.api.session.list({ + directory: chat.directory, + limit: 1, + }) + + if (remaining.data.length > 0) { + return { deleted: true, folderRemoved: false } + } + + try { + await this.terminals.removeAll(chat.directory) + } catch (error) { + logger.warn(`Failed to remove terminals for chat ${chatId}:`, error) + } - const folderRemoved = remaining.data.length === 0 - if (folderRemoved) { await fs.rm(chat.directory, { recursive: true, force: true }) + return { deleted: true, folderRemoved: true } + } catch (error) { + logger.warn(`Failed to remove folder for chat ${chatId}:`, error) + return { deleted: true, folderRemoved: false } } - - return { deleted: true, folderRemoved } } private async listChatIds(): Promise { diff --git a/backend/src/services/notification.ts b/backend/src/services/notification.ts index b3e12a22..f9fd25a0 100644 --- a/backend/src/services/notification.ts +++ b/backend/src/services/notification.ts @@ -130,9 +130,7 @@ export function buildNotificationUrl( chat?: { id: string } | null ): string { if (chat) { - return sessionId - ? buildChatSessionPath(chat.id, sessionId) - : `/chats/${encodeURIComponent(chat.id)}`; + return sessionId ? buildChatSessionPath(chat.id, sessionId) : "/"; } if (!repo) return "/"; if (!sessionId) return `/repos/${repo.id}`; diff --git a/backend/test/routes/chats.test.ts b/backend/test/routes/chats.test.ts index 14dd3f20..9b8f4518 100644 --- a/backend/test/routes/chats.test.ts +++ b/backend/test/routes/chats.test.ts @@ -28,7 +28,7 @@ const roots: string[] = [] function createApp(root: string) { const fake = createFakeClient() const app = new Hono() - app.route('/chats', createChatRoutes(new ChatService(fake.client, () => root))) + app.route('/chats', createChatRoutes(new ChatService(fake.client, { removeAll: vi.fn(async () => undefined) }, () => root))) return { app, ...fake } } diff --git a/backend/test/services/chats.test.ts b/backend/test/services/chats.test.ts index fdba7a9c..91ec98e7 100644 --- a/backend/test/services/chats.test.ts +++ b/backend/test/services/chats.test.ts @@ -17,6 +17,10 @@ interface FakeClient { } } +interface FakeTerminals { + terminals: { removeAll: ReturnType } +} + function createFakeClient(): FakeClient { const session = { create: vi.fn(async () => ({ id: 'ses_new' })), @@ -30,6 +34,10 @@ function createFakeClient(): FakeClient { return { client: { api: { session } } as unknown as OpenCodeClient, session } } +function createFakeTerminals(): FakeTerminals { + return { terminals: { removeAll: vi.fn(async () => undefined) } } +} + function createChatFolder(root: string, id: string): string { const directory = path.join(root, id) mkdirSync(directory, { recursive: true }) @@ -54,7 +62,13 @@ describe('ChatService', () => { it('creates a chat folder matching the id format and leaves it empty', async () => { const root = createRoot() const fake = createFakeClient() - const service = new ChatService(fake.client, () => root, () => new Date('2026-01-02T03:04:05Z')) + const { terminals } = createFakeTerminals() + const service = new ChatService( + fake.client, + terminals, + () => root, + () => new Date('2026-01-02T03:04:05Z'), + ) const result = await service.create({ title: 'Hello' }) @@ -74,7 +88,7 @@ describe('ChatService', () => { const root = createRoot() const fake = createFakeClient() fake.session.create.mockRejectedValueOnce(new Error('session failed')) - const service = new ChatService(fake.client, () => root) + const service = new ChatService(fake.client, createFakeTerminals().terminals, () => root) await expect(service.create({})).rejects.toThrow('session failed') expect(readdirSync(root)).toEqual([]) @@ -86,7 +100,11 @@ describe('ChatService', () => { for (const id of ids) createChatFolder(root, id) createChatFolder(root, 'not-a-chat') mkdirSync(path.join(root, '.hidden')) - const service = new ChatService(createFakeClient().client, () => root) + const service = new ChatService( + createFakeClient().client, + createFakeTerminals().terminals, + () => root, + ) const first = await service.list({ limit: 2 }) expect(first.chats.map((chat) => chat.id)).toEqual([ids[2], ids[1]]) @@ -105,7 +123,11 @@ describe('ChatService', () => { const root = createRoot() const id = '20260203-040506-abcdef' createChatFolder(root, id) - const service = new ChatService(createFakeClient().client, () => root) + const service = new ChatService( + createFakeClient().client, + createFakeTerminals().terminals, + () => root, + ) expect((await service.resolve(id))?.id).toBe(id) expect(await service.resolve('20260203-040506-aaaaaa')).toBeNull() @@ -117,36 +139,84 @@ describe('ChatService', () => { const root = createRoot() const id = '20260203-040506-abcdef' const directory = createChatFolder(root, id) - const service = new ChatService(createFakeClient().client, () => root) + const service = new ChatService( + createFakeClient().client, + createFakeTerminals().terminals, + () => root, + ) expect((await service.findByDirectory(directory))?.id).toBe(id) expect(await service.findByDirectory(path.join(root, 'missing'))).toBeNull() }) + it('returns null for paths that are not an existing chat folder directly under the root', async () => { + const root = createRoot() + const id = '20260203-040506-abcdef' + const directory = createChatFolder(root, id) + createChatFolder(root, 'not-a-chat') + const service = new ChatService( + createFakeClient().client, + createFakeTerminals().terminals, + () => root, + ) + + expect(await service.findByDirectory(path.join(directory, 'nested'))).toBeNull() + expect((await service.findByDirectory(directory + path.sep))?.id).toBe(id) + expect(await service.findByDirectory(root)).toBeNull() + expect(await service.findByDirectory(path.join(root, 'not-a-chat'))).toBeNull() + expect(await service.findByDirectory(path.join(root, '..', 'elsewhere'))).toBeNull() + expect(await service.findByDirectory('/unrelated/path')).toBeNull() + }) + it('keeps the folder when another session remains after a delete', async () => { const root = createRoot() const id = '20260203-040506-abcdef' const directory = createChatFolder(root, id) const fake = createFakeClient() + const { terminals } = createFakeTerminals() fake.session.get.mockResolvedValueOnce({ id: 'ses_1', location: { directory } }) fake.session.list.mockResolvedValueOnce({ data: [{ id: 'ses_fork' }], cursor: {} }) - const service = new ChatService(fake.client, () => root) + const service = new ChatService(fake.client, terminals, () => root) const result = await service.deleteSession(id, 'ses_1') expect(result).toEqual({ deleted: true, folderRemoved: false }) expect(fake.session.remove).toHaveBeenCalledWith({ sessionID: 'ses_1' }) expect(fake.session.list).toHaveBeenCalledWith({ directory, limit: 1 }) + expect(terminals.removeAll).not.toHaveBeenCalled() expect(existsSync(directory)).toBe(true) }) - it('removes the folder when no session remains after a delete', async () => { + it('removes terminals before the folder when no session remains after a delete', async () => { const root = createRoot() const id = '20260203-040506-abcdef' const directory = createChatFolder(root, id) const fake = createFakeClient() + const { terminals } = createFakeTerminals() + let folderExistedDuringRemoval = false + terminals.removeAll.mockImplementationOnce(async (target: string) => { + folderExistedDuringRemoval = target === directory && existsSync(directory) + }) fake.session.get.mockResolvedValueOnce({ id: 'ses_1', location: { directory } }) - const service = new ChatService(fake.client, () => root) + const service = new ChatService(fake.client, terminals, () => root) + + const result = await service.deleteSession(id, 'ses_1') + + expect(result).toEqual({ deleted: true, folderRemoved: true }) + expect(terminals.removeAll).toHaveBeenCalledWith(directory) + expect(folderExistedDuringRemoval).toBe(true) + expect(existsSync(directory)).toBe(false) + }) + + it('removes the folder even when terminal cleanup fails', async () => { + const root = createRoot() + const id = '20260203-040506-abcdef' + const directory = createChatFolder(root, id) + const fake = createFakeClient() + const { terminals } = createFakeTerminals() + terminals.removeAll.mockRejectedValueOnce(new Error('terminal cleanup failed')) + fake.session.get.mockResolvedValueOnce({ id: 'ses_1', location: { directory } }) + const service = new ChatService(fake.client, terminals, () => root) const result = await service.deleteSession(id, 'ses_1') @@ -154,13 +224,31 @@ describe('ChatService', () => { expect(existsSync(directory)).toBe(false) }) + it('reports folderRemoved false without throwing when the remaining-session list fails', async () => { + const root = createRoot() + const id = '20260203-040506-abcdef' + const directory = createChatFolder(root, id) + const fake = createFakeClient() + const { terminals } = createFakeTerminals() + fake.session.get.mockResolvedValueOnce({ id: 'ses_1', location: { directory } }) + fake.session.list.mockRejectedValueOnce(new Error('list failed')) + const service = new ChatService(fake.client, terminals, () => root) + + const result = await service.deleteSession(id, 'ses_1') + + expect(result).toEqual({ deleted: true, folderRemoved: false }) + expect(fake.session.remove).toHaveBeenCalledWith({ sessionID: 'ses_1' }) + expect(terminals.removeAll).not.toHaveBeenCalled() + expect(existsSync(directory)).toBe(true) + }) + it('rejects a session that belongs to another folder', async () => { const root = createRoot() const id = '20260203-040506-abcdef' createChatFolder(root, id) const fake = createFakeClient() fake.session.get.mockResolvedValueOnce({ id: 'ses_1', location: { directory: '/tmp/other-chat' } }) - const service = new ChatService(fake.client, () => root) + const service = new ChatService(fake.client, createFakeTerminals().terminals, () => root) await expect(service.deleteSession(id, 'ses_1')).rejects.toBeInstanceOf(ChatSessionMismatchError) expect(fake.session.remove).not.toHaveBeenCalled() @@ -168,7 +256,7 @@ describe('ChatService', () => { it('rejects an unknown chat id before touching sessions', async () => { const fake = createFakeClient() - const service = new ChatService(fake.client, () => createRoot()) + const service = new ChatService(fake.client, createFakeTerminals().terminals, () => createRoot()) await expect(service.deleteSession('20260203-040506-abcdef', 'ses_1')).rejects.toBeInstanceOf(ChatNotFoundError) await expect(service.deleteSession('../escape', 'ses_1')).rejects.toBeInstanceOf(ChatNotFoundError) diff --git a/backend/test/services/notification-format.test.ts b/backend/test/services/notification-format.test.ts index a4ea5b98..a10ae4c6 100644 --- a/backend/test/services/notification-format.test.ts +++ b/backend/test/services/notification-format.test.ts @@ -243,4 +243,7 @@ describe('buildNotificationUrl', () => { it('returns the chat session page for a chat folder', () => { expect(buildNotificationUrl(null, 'ses_1', { id: CHAT_ID })).toBe(`/chats/${CHAT_ID}/sessions/ses_1`) }) + it('returns "/" for a chat folder without a session', () => { + expect(buildNotificationUrl(null, undefined, { id: CHAT_ID })).toBe('/') + }) }) diff --git a/backend/test/utils/repo-url.test.ts b/backend/test/utils/repo-url.test.ts index efe8b9eb..e520b968 100644 --- a/backend/test/utils/repo-url.test.ts +++ b/backend/test/utils/repo-url.test.ts @@ -5,6 +5,7 @@ import { normalizeSSHUrl, extractHostFromSSHUrl, getRepoNameFromUrl, + getChatIdFromDirectory, normalizeRepoUrlForCompare, } from '@opencode-manager/shared/utils' @@ -186,3 +187,29 @@ describe('normalizeRepoUrlForCompare', () => { expect(normalizeRepoUrlForCompare('file:///Users/me/repo')).toBe('file:///users/me/repo') }) }) + +describe('getChatIdFromDirectory', () => { + const chatId = '20260101-120000-abcdef' + + it('reads a chat id from a workspace chat root', () => { + expect(getChatIdFromDirectory(`/workspace/chats/${chatId}`)).toBe(chatId) + }) + + it('ignores trailing slashes and backslashes', () => { + expect(getChatIdFromDirectory(`/workspace/chats/${chatId}/`)).toBe(chatId) + expect(getChatIdFromDirectory(`C:\\workspace\\chats\\${chatId}\\`)).toBe(chatId) + }) + + it('returns null for a directory nested inside a chat', () => { + expect(getChatIdFromDirectory(`/workspace/chats/${chatId}/subagent`)).toBeNull() + }) + + it('returns null when the parent directory is not the chats directory', () => { + expect(getChatIdFromDirectory(`/workspace/repos/${chatId}`)).toBeNull() + }) + + it('returns null for a malformed chat id', () => { + expect(getChatIdFromDirectory('/workspace/chats/20260101-120000-xyzxyz')).toBeNull() + expect(getChatIdFromDirectory('/workspace/chats/not-a-chat')).toBeNull() + }) +}) diff --git a/frontend/src/App.permission-dialog.test.tsx b/frontend/src/App.permission-dialog.test.tsx index 86a7edfa..7ed8d0ec 100644 --- a/frontend/src/App.permission-dialog.test.tsx +++ b/frontend/src/App.permission-dialog.test.tsx @@ -5,7 +5,7 @@ import type { PermissionRequest } from '@opencode-manager/shared/opencode' const mocks = vi.hoisted(() => ({ usePermissions: vi.fn(), - getRepoIdForSession: vi.fn(), + getLocalSessionPath: vi.fn(), sessionQueryOptions: vi.fn(), navigateToCurrent: vi.fn(), PermissionRequestDialog: vi.fn(), @@ -13,7 +13,7 @@ const mocks = vi.hoisted(() => ({ vi.mock('@/contexts/EventContext', () => ({ usePermissions: mocks.usePermissions, - useEventContext: () => ({ getRepoIdForSession: mocks.getRepoIdForSession }), + useEventContext: () => ({ getLocalSessionPath: mocks.getLocalSessionPath }), })) vi.mock('@/hooks/useOpenCode', () => ({ sessionQueryOptions: mocks.sessionQueryOptions })) @@ -89,19 +89,19 @@ describe('PermissionDialogWrapper', () => { mocks.PermissionRequestDialog.mockReturnValue(
) }) - it('offers the session for a linked-server permission without a Manager repo lookup', () => { - mocks.getRepoIdForSession.mockReturnValue(null) + it('offers the session for a linked-server permission without a local path lookup', () => { + mocks.getLocalSessionPath.mockReturnValue(null) const props = renderWrapper(remotePermission) expect(props.permission).toEqual(remotePermission) expect(props.onOpenSession).toBe(mocks.navigateToCurrent) - expect(mocks.getRepoIdForSession).not.toHaveBeenCalled() + expect(mocks.getLocalSessionPath).not.toHaveBeenCalled() expect(mocks.sessionQueryOptions).toHaveBeenCalledWith('ses_remote', '/srv/app', 'srv_kitchen') }) it('resolves the remote session title from the permission server', async () => { - mocks.getRepoIdForSession.mockReturnValue(null) + mocks.getLocalSessionPath.mockReturnValue(null) renderWrapper(remotePermission) @@ -111,18 +111,28 @@ describe('PermissionDialogWrapper', () => { }) }) - it('offers the session for a local permission resolved through its Manager repo', () => { - mocks.getRepoIdForSession.mockReturnValue(12) + it('offers the session for a local permission resolved through its repo', () => { + mocks.getLocalSessionPath.mockReturnValue('/repos/12/sessions/ses_local') const props = renderWrapper(localPermission) expect(props.onOpenSession).toBe(mocks.navigateToCurrent) - expect(mocks.getRepoIdForSession).toHaveBeenCalledWith('ses_local') + expect(mocks.getLocalSessionPath).toHaveBeenCalledWith('ses_local') expect(mocks.sessionQueryOptions).toHaveBeenCalledWith('ses_local', '/srv/app', 'local') }) - it('hides the session action for a local permission without a Manager repo', () => { - mocks.getRepoIdForSession.mockReturnValue(null) + it('offers the session for a local permission resolved through its chat', () => { + const chatId = '20260101-120000-abcdef' + mocks.getLocalSessionPath.mockReturnValue(`/chats/${chatId}/sessions/ses_local`) + + const props = renderWrapper(localPermission) + + expect(props.onOpenSession).toBe(mocks.navigateToCurrent) + expect(mocks.getLocalSessionPath).toHaveBeenCalledWith('ses_local') + }) + + it('hides the session action for a local permission without a repo or chat', () => { + mocks.getLocalSessionPath.mockReturnValue(null) const props = renderWrapper(localPermission) diff --git a/frontend/src/App.push-subscription-sync.test.tsx b/frontend/src/App.push-subscription-sync.test.tsx index 69314526..4bd4eba6 100644 --- a/frontend/src/App.push-subscription-sync.test.tsx +++ b/frontend/src/App.push-subscription-sync.test.tsx @@ -46,7 +46,7 @@ vi.mock('@/contexts/EventContext', () => ({ currentIsFromDifferentSession: false, }), useEventContext: () => ({ - getRepoIdForSession: () => null, + getLocalSessionPath: () => null, sshHostKey: { request: null, respond: vi.fn() }, }), })) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 79557d9d..31d1d9d5 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -122,7 +122,7 @@ export function PermissionDialogWrapper() { currentDirectory, currentIsFromDifferentSession, } = usePermissions() - const { getRepoIdForSession } = useEventContext() + const { getLocalSessionPath } = useEventContext() const isRemotePermission = currentPermission !== null && !isLocalOpenCodeServer(currentPermission.serverId) const { data: session } = useQuery( sessionQueryOptions( @@ -133,7 +133,7 @@ export function PermissionDialogWrapper() { ) const canOpenCurrentSession = currentPermission !== null - && (isRemotePermission || getRepoIdForSession(currentPermission.sessionID) !== null) + && (isRemotePermission || getLocalSessionPath(currentPermission.sessionID) !== null) && (currentIsFromDifferentSession || viewedSessionId === null) return ( diff --git a/frontend/src/components/navigation/ChatsNavGroup.test.tsx b/frontend/src/components/navigation/ChatsNavGroup.test.tsx index 3b032e22..4b5e89f1 100644 --- a/frontend/src/components/navigation/ChatsNavGroup.test.tsx +++ b/frontend/src/components/navigation/ChatsNavGroup.test.tsx @@ -217,4 +217,13 @@ describe('ChatsNavGroup', () => { expect(await screen.findByText('No chats')).toBeTruthy() }) + + it('keeps Show more available when the loaded chats have no visible sessions', async () => { + mocks.sessionsData.splice(0, mocks.sessionsData.length) + + render(, { wrapper: createWrapper(['/']) }) + + expect(await screen.findByText('No chats')).toBeTruthy() + expect(screen.getByText('Show more')).toBeTruthy() + }) }) diff --git a/frontend/src/components/navigation/ChatsNavGroup.tsx b/frontend/src/components/navigation/ChatsNavGroup.tsx index cbb70d3f..2d67603d 100644 --- a/frontend/src/components/navigation/ChatsNavGroup.tsx +++ b/frontend/src/components/navigation/ChatsNavGroup.tsx @@ -61,21 +61,19 @@ export function ChatsNavGroup() { ) : rows.length === 0 ? ( No chats ) : ( - <> - {rows.map((row) => { - const item = toChatItem(row) - return ( - - ) - })} - {hasMore && Show more} - + rows.map((row) => { + const item = toChatItem(row) + return ( + + ) + }) )} + {hasMore && Show more} ) } diff --git a/frontend/src/components/navigation/moreDrawerItems.test.ts b/frontend/src/components/navigation/moreDrawerItems.test.ts index 2cd90aca..223b1ba9 100644 --- a/frontend/src/components/navigation/moreDrawerItems.test.ts +++ b/frontend/src/components/navigation/moreDrawerItems.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { buildMoreItems, buildNavModel, buildToolItems } from './moreDrawerItems' +import { buildMoreItems, buildNavModel, buildToolItems, isSessionDetailPath } from './moreDrawerItems' describe('buildMoreItems', () => { it('returns Home + All Schedules + Files + Settings + Logout for root path', () => { @@ -232,6 +232,14 @@ describe('buildToolItems', () => { }) }) +describe('isSessionDetailPath', () => { + it('recognizes repo and chat session routes but not linked-server routes', () => { + expect(isSessionDetailPath('/repos/42/sessions/abc')).toBe(true) + expect(isSessionDetailPath('/chats/20240102120000-aaaaaa/sessions/ses_1')).toBe(true) + expect(isSessionDetailPath('/servers/srv_kitchen/sessions/abc')).toBe(false) + }) +}) + describe('buildNavModel', () => { it.each([ '/', diff --git a/frontend/src/components/navigation/moreDrawerItems.ts b/frontend/src/components/navigation/moreDrawerItems.ts index 14e9479f..b2d6faf5 100644 --- a/frontend/src/components/navigation/moreDrawerItems.ts +++ b/frontend/src/components/navigation/moreDrawerItems.ts @@ -1,7 +1,7 @@ import type { LucideIcon } from 'lucide-react' import { BookOpen, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, List, Play, Globe, KeyRound } from 'lucide-react' import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' -import { getAssistantPath, isAssistantPath } from '@/lib/navigation' +import { getAssistantPath, isAssistantPath, parseChatSessionRoute } from '@/lib/navigation' export interface MoreDrawerItem { key: string @@ -50,10 +50,9 @@ function getBaseItems(): MoreDrawerItem[] { const SESSION_DETAIL_PATH = /^\/repos\/(\d+)\/sessions\/[^/]+$/ const SERVER_SESSION_DETAIL_PATH = /^\/servers\/[^/]+\/sessions\/[^/]+$/ const SERVER_PROJECT_PATH = /^\/servers\/[^/]+\/projects$/ -const CHAT_SESSION_DETAIL_PATH = /^\/chats\/[^/]+\/sessions\/[^/]+$/ export function isSessionDetailPath(pathname: string): boolean { - return SESSION_DETAIL_PATH.test(pathname) + return SESSION_DETAIL_PATH.test(pathname) || parseChatSessionRoute(pathname) !== null } const NON_TOOL_ITEM_KEYS = new Set(['home', 'settings', 'logout']) @@ -179,7 +178,7 @@ function buildRouteNavModel(pathname: string): NavModel { } } - if (CHAT_SESSION_DETAIL_PATH.test(pathname)) { + if (parseChatSessionRoute(pathname) !== null) { return { primary: [getAssistantNavItem()], items: [ diff --git a/frontend/src/components/session/ChatPickerContent.tsx b/frontend/src/components/session/ChatPickerContent.tsx index 82c1eca3..a817019e 100644 --- a/frontend/src/components/session/ChatPickerContent.tsx +++ b/frontend/src/components/session/ChatPickerContent.tsx @@ -182,21 +182,21 @@ export function ChatPickerContent({ onTogglePin={handleTogglePin} onRequestDelete={handleRequestDelete} registerRef={registerRef} - > - {hasMore && ( -
- -
- )} - + /> + + {hasMore && ( +
+ +
+ )}
↑↓ move · Enter open · Ctrl+D delete diff --git a/frontend/src/components/session/SessionPickerDialog.test.tsx b/frontend/src/components/session/SessionPickerDialog.test.tsx index 9b03fd9e..a921a053 100644 --- a/frontend/src/components/session/SessionPickerDialog.test.tsx +++ b/frontend/src/components/session/SessionPickerDialog.test.tsx @@ -1136,6 +1136,19 @@ describe('SessionPickerDialog', () => { expect(mocks.showMoreChats).toHaveBeenCalledTimes(1) }) + it('shows the show more action even when no chat sessions are visible', async () => { + mocks.chatRows = [] + mocks.chatHasMore = true + renderPicker() + + openChatsTab() + + expect(await screen.findByText('No chats yet')).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: 'Show more' })) + + expect(mocks.showMoreChats).toHaveBeenCalledTimes(1) + }) + it('creates a chat from the header action and navigates to its new session', async () => { const onNavigate = vi.fn() renderPicker({ onNavigate }) diff --git a/frontend/src/contexts/EventContext.test.tsx b/frontend/src/contexts/EventContext.test.tsx index 0616f539..61a9cb13 100644 --- a/frontend/src/contexts/EventContext.test.tsx +++ b/frontend/src/contexts/EventContext.test.tsx @@ -231,12 +231,12 @@ function createWrapper(queryClient = createTestQueryClient(), initialPath = '/') } function CacheResolutionHarness({ sessionID }: { sessionID: string }) { - const { getRepoIdForSession } = useEventContext() - const repoId = getRepoIdForSession(sessionID) + const { getLocalSessionPath } = useEventContext() + const sessionPath = getLocalSessionPath(sessionID) return (
-
{repoId ?? 'none'}
+
{sessionPath ?? 'none'}
) } @@ -1440,7 +1440,7 @@ describe('EventProvider permissions and forms', () => { render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => { - expect(screen.getByTestId('repo-id')).toHaveTextContent('123') + expect(screen.getByTestId('session-path')).toHaveTextContent('/repos/123/sessions/ses-infinite') }) }) @@ -1463,7 +1463,30 @@ describe('EventProvider permissions and forms', () => { render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => { - expect(screen.getByTestId('repo-id')).toHaveTextContent('123') + expect(screen.getByTestId('session-path')).toHaveTextContent('/repos/123/sessions/ses-detail') + }) + }) + + it('resolves a chat session to its chat route without a repo', async () => { + const chatId = '20260101-120000-abcdef' + const directory = `/workspace/chats/${chatId}` + const queryClient = createTestQueryClient() + + queryClient.setQueryData( + ['opencode', 'session', 'ses-chat', directory], + { + id: 'ses-chat', + projectID: 'proj-1', + title: 'Chat Session', + location: { directory }, + time: { created: 1000, updated: 1000 }, + }, + ) + + render(, { wrapper: createWrapper(queryClient) }) + + await waitFor(() => { + expect(screen.getByTestId('session-path')).toHaveTextContent(`/chats/${chatId}/sessions/ses-chat`) }) }) @@ -1499,7 +1522,7 @@ describe('EventProvider permissions and forms', () => { render(, { wrapper: createWrapper(queryClient) }) await waitFor(() => { - expect(screen.getByTestId('repo-id')).toHaveTextContent('456') + expect(screen.getByTestId('session-path')).toHaveTextContent('/repos/456/sessions/ses-second') }) }) diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index e3edb744..d4daccd7 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -14,6 +14,7 @@ import { } from '@/api/opencode' import { listRepos } from '@/api/repos' import { FetchError } from '@opencode-manager/shared' +import { getChatIdFromDirectory } from '@opencode-manager/shared/utils' import { buildServerDirectoryKey, LOCAL_OPENCODE_SERVER_ID, @@ -30,7 +31,7 @@ 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' -import { getServerSessionPath, getSessionPath, parseChatSessionRoute, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from '@/lib/navigation' +import { getChatSessionPath, getServerSessionPath, getSessionPath, parseChatSessionRoute, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from '@/lib/navigation' import { serverScopedKey } from '@/lib/serverScope' import { repoMatchesDirectory } from '@/components/navigation/sidebar-session-tree' import { changeWalkthroughQueryKey } from '@/hooks/useChangeWalkthrough' @@ -279,7 +280,8 @@ interface EventContextValue { forgetPendingActionsForSession: (sessionID: string) => void } sseHealth: SSEHealthState - getRepoIdForSession: (sessionID: string) => number | null + /** The in-app path of a local session: its repo or chat route, or null when neither resolves. */ + getLocalSessionPath: (sessionID: string) => string | null } /** @@ -527,15 +529,17 @@ export function EventProvider({ children }: { children: React.ReactNode }) { return key ? parseServerDirectoryKey(key).directory : null }, [findSessionDirectoryKey]) - const getRepoIdForSession = useCallback((sessionID: string): number | null => { - if (!repos) return null + const getLocalSessionPath = useCallback((sessionID: string): string | null => { if (useSessionStatus.getState().sessionServers.has(sessionID)) return null const key = findSessionDirectoryKey(sessionID) if (!key) return null const { serverId, directory } = parseServerDirectoryKey(key) if (!isLocalOpenCodeServer(serverId)) return null + const chatId = getChatIdFromDirectory(directory) + if (chatId) return getChatSessionPath(chatId, sessionID) + if (!repos) return null const repo = repos.find(r => repoMatchesDirectory(r, directory)) - return repo?.id ?? null + return repo ? getSessionPath(repo.id, sessionID) : null }, [repos, findSessionDirectoryKey]) const currentPermissionDirectory = useMemo( @@ -692,18 +696,14 @@ export function EventProvider({ children }: { children: React.ReactNode }) { }, [formsBySession]) const navigateToSession = useCallback((sessionID: string, serverId: string) => { - let targetPath: string - if (isLocalOpenCodeServer(serverId)) { - const repoId = getRepoIdForSession(sessionID) - if (repoId === null) return - targetPath = getSessionPath(repoId, sessionID) - } else { - targetPath = getServerSessionPath(serverId, sessionID) - } + const targetPath = isLocalOpenCodeServer(serverId) + ? getLocalSessionPath(sessionID) + : getServerSessionPath(serverId, sessionID) + if (!targetPath) return if (`${window.location.pathname}${window.location.search}` !== targetPath) { navigate(targetPath) } - }, [getRepoIdForSession, navigate]) + }, [getLocalSessionPath, navigate]) const navigateToCurrentForm = useCallback(() => { if (!currentForm) return @@ -1378,7 +1378,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { forgetPendingActionsForSession, }, sseHealth, - getRepoIdForSession, + getLocalSessionPath, }), [ sshHostKeyRequest, respondToSSHHostKey, @@ -1407,7 +1407,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { syncFormsForSession, forgetPendingActionsForSession, sseHealth, - getRepoIdForSession, + getLocalSessionPath, ]) return {children} diff --git a/frontend/src/hooks/useChats.test.tsx b/frontend/src/hooks/useChats.test.tsx index 366e4ac8..19b32c56 100644 --- a/frontend/src/hooks/useChats.test.tsx +++ b/frontend/src/hooks/useChats.test.tsx @@ -183,7 +183,16 @@ describe('useChatSessions', () => { expect(pinnedRow.path).toBe(`/chats/${olderChat.id}/sessions/ses_old_pinned`) expect(result.current.rows[1].isPinned).toBe(false) expect(result.current.rows[1].path).toBe(`/chats/${newestChat.id}/sessions/ses_new_newer`) - expect(result.current.chats.map((entry) => entry.id)).toEqual([newestChat.id, olderChat.id]) + + const folders = renderHook(() => useChatFolders(2), { + wrapper: createWrapper(queryClient), + }) + await waitFor(() => + expect(folders.result.current.chats.map((entry) => entry.id)).toEqual([ + newestChat.id, + olderChat.id, + ]), + ) expect(result.current.hasMore).toBe(false) }) }) diff --git a/frontend/src/hooks/useChats.ts b/frontend/src/hooks/useChats.ts index 48e98d40..4fb22598 100644 --- a/frontend/src/hooks/useChats.ts +++ b/frontend/src/hooks/useChats.ts @@ -107,7 +107,6 @@ export function useChatSessions(pageSize = 10) { return { rows, - chats, hasMore: Boolean(folders.hasNextPage), showMore: folders.fetchNextPage, isLoading: folders.isLoading || sessions.isLoading, diff --git a/frontend/src/hooks/useCommands.test.tsx b/frontend/src/hooks/useCommands.test.tsx index 84b88ef6..d4eea90c 100644 --- a/frontend/src/hooks/useCommands.test.tsx +++ b/frontend/src/hooks/useCommands.test.tsx @@ -1,6 +1,7 @@ import { renderHook, waitFor } from '@testing-library/react' import { describe, expect, it, vi, beforeEach } from 'vitest' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { MemoryRouter } from 'react-router-dom' import { useCommands } from './useCommands' import { listCommands } from '../api/opencode' import { BUILTIN_COMMANDS } from '@/lib/builtinCommands' @@ -11,7 +12,7 @@ vi.mock('../api/opencode', () => ({ listCommands: vi.fn(), })) -const createWrapper = (serverId?: string) => { +const createWrapper = (serverId?: string, initialPath = '/') => { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, @@ -19,7 +20,9 @@ const createWrapper = (serverId?: string) => { }) return ({ children }: { children: React.ReactNode }) => ( - {serverId ? {children} : children} + + {serverId ? {children} : children} + ) } @@ -139,7 +142,9 @@ describe('useCommands', () => { ]) const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: 60_000 } } }) const wrapper = ({ children }: { children: React.ReactNode }) => ( - {children} + + {children} + ) const { result, rerender } = renderHook(({ directory }) => useCommands({ directory }), { @@ -191,4 +196,19 @@ describe('useCommands', () => { expect(names).toContain('skills') expect(names).toContain('walkthrough') }) + + it('omits mcp, skills, and walkthrough on a chat session route', () => { + const { result } = renderHook(() => useCommands({ enabled: false }), { + wrapper: createWrapper(undefined, '/chats/20260101-120000-abcdef/sessions/ses_chat'), + }) + + const names = result.current.searchCommands('').map(({ item }) => item.name) + + expect(names).not.toContain('mcp') + expect(names).not.toContain('skills') + expect(names).not.toContain('walkthrough') + expect(names).toContain('sessions') + expect(names).toContain('models') + expect(names).toContain('compact') + }) }) diff --git a/frontend/src/hooks/useCommands.ts b/frontend/src/hooks/useCommands.ts index 1d0ff520..0987a8f0 100644 --- a/frontend/src/hooks/useCommands.ts +++ b/frontend/src/hooks/useCommands.ts @@ -1,7 +1,9 @@ import { useCallback, useMemo } from 'react' +import { useLocation } from 'react-router-dom' import { useQuery } from '@tanstack/react-query' import { listCommands } from '@/api/opencode' import { isLocalOpenCodeServer, useOpenCodeServerId } from '@/contexts/OpenCodeServerContext' +import { parseChatSessionRoute } from '@/lib/navigation' import { serverScopedKey } from '@/lib/serverScope' import type { CommandInfo } from '@opencode-manager/shared/opencode' import { getBuiltinCommands } from '@/lib/builtinCommands' @@ -20,11 +22,13 @@ interface UseCommandsOptions { export function useCommands(options: UseCommandsOptions = {}) { const { directory, enabled = true } = options const serverId = useOpenCodeServerId() + const location = useLocation() + const isChat = parseChatSessionRoute(location.pathname) !== null const recentNames = useRecentCommandsStore((state) => state.names) const builtinCommands = useMemo( - () => getBuiltinCommands(isLocalOpenCodeServer(serverId)), - [serverId], + () => getBuiltinCommands(isLocalOpenCodeServer(serverId), isChat), + [serverId, isChat], ) const sortedBuiltinCommands = useMemo(() => sortCommandsByName([...builtinCommands]), [builtinCommands]) diff --git a/frontend/src/hooks/useGlobalShortcutActions.test.tsx b/frontend/src/hooks/useGlobalShortcutActions.test.tsx index be60cc30..c18387ec 100644 --- a/frontend/src/hooks/useGlobalShortcutActions.test.tsx +++ b/frontend/src/hooks/useGlobalShortcutActions.test.tsx @@ -10,12 +10,13 @@ const mocks = vi.hoisted(() => ({ getSession: vi.fn(), createSession: vi.fn(), useMobile: vi.fn(), + preferences: undefined as + | { leaderKey?: string; keyboardShortcuts?: Record; directShortcuts?: string[] } + | undefined, })) vi.mock('@/hooks/useSettings', () => ({ - useSettings: () => ({ - preferences: { leaderKey: 'Ctrl+O', keyboardShortcuts: {}, directShortcuts: undefined }, - }), + useSettings: () => ({ preferences: mocks.preferences }), })) vi.mock('@/hooks/useMobile', () => ({ @@ -62,6 +63,11 @@ describe('useGlobalShortcutActions', () => { localStorage.clear() queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) mocks.useMobile.mockReturnValue(false) + mocks.preferences = { + leaderKey: 'Ctrl+O', + keyboardShortcuts: {}, + directShortcuts: undefined, + } mocks.getRepo.mockResolvedValue({ id: 5, fullPath: '/repo/five' }) mocks.getSession.mockResolvedValue({ id: 'ses_1', location: { directory: '/srv/kitchen' } }) mocks.createSession.mockResolvedValue({ id: 'session-new' }) @@ -144,6 +150,23 @@ describe('useGlobalShortcutActions', () => { expect(mocks.getRepo).not.toHaveBeenCalled() }) + it('does not fall back to a Manager host for a tool the chat session route lacks', async () => { + mocks.preferences = { + leaderKey: 'Ctrl+O', + keyboardShortcuts: { toggleSourceControl: 'G' }, + directShortcuts: [], + } + const { location } = renderHarness('/chats/20240102120000-aaaaaa/sessions/ses_1') + + pressLeaderFollowUp('g') + + await act(async () => { + await Promise.resolve() + }) + + expect(location()).toBe('/chats/20240102120000-aaaaaa/sessions/ses_1') + }) + it('toggles the navigation sidebar instead of the Files panel from the sidebar shortcut', async () => { const { location } = renderHarness('/repos/5') diff --git a/frontend/src/hooks/useGlobalShortcutActions.ts b/frontend/src/hooks/useGlobalShortcutActions.ts index 0c9b8ec4..32da7904 100644 --- a/frontend/src/hooks/useGlobalShortcutActions.ts +++ b/frontend/src/hooks/useGlobalShortcutActions.ts @@ -23,6 +23,7 @@ import { getServerSessionPath, getSessionPath, isAssistantPath, + parseChatSessionRoute, parseRepoRoute, parseServerSessionRoute, } from '@/lib/navigation' @@ -39,6 +40,7 @@ export function useGlobalShortcutActions(): void { const isMobile = useMobile() const serverId = useRouteOpenCodeServerId() const isRemoteRoute = !isLocalOpenCodeServer(serverId) + const isChatSessionRoute = parseChatSessionRoute(pathname) !== null const repoId = isAssistantPath(pathname) ? ASSISTANT_REPO_ID : parseRepoRoute(pathname).repoId @@ -75,10 +77,10 @@ export function useGlobalShortcutActions(): void { togglePanelTool(tool) return } - if (isRemoteRoute || tool === 'files') return + if (isRemoteRoute || isChatSessionRoute || tool === 'files') return const host = repoId !== null ? getRepoPath(repoId) : getAssistantPath() navigate(`${host}${dialogSearch(tool)}`) - }, [toolItems, isMobile, togglePanelTool, updateParams, navigate, repoId, isRemoteRoute]) + }, [toolItems, isMobile, togglePanelTool, updateParams, navigate, repoId, isRemoteRoute, isChatSessionRoute]) const newSession = sessionDirectory && !createSession.isPending ? () => createSession.mutate({}) diff --git a/frontend/src/hooks/useSessionPickerNavigation.test.tsx b/frontend/src/hooks/useSessionPickerNavigation.test.tsx index 29889932..bd9a3d79 100644 --- a/frontend/src/hooks/useSessionPickerNavigation.test.tsx +++ b/frontend/src/hooks/useSessionPickerNavigation.test.tsx @@ -221,6 +221,20 @@ describe('useSessionPickerNavigation', () => { expect(onClose).toHaveBeenCalledTimes(1) }) + it('returns to the home route when the open chat session is deleted', () => { + const { result, onClose, location } = renderPickerNavigation( + ['/chats/20240102120000-aaaaaa/sessions/a?mobileTab=sessions'], + { mode: 'push' }, + ) + + act(() => { + result.current.onDeleteActiveSession() + }) + + expect(location()).toBe('/ PUSH') + expect(onClose).toHaveBeenCalledTimes(1) + }) + it('closes the picker without navigating when the session is already open', () => { const { result, onClose, location } = renderPickerNavigation( ['/repos/1/sessions/a?mobileTab=sessions'], diff --git a/frontend/src/hooks/useSessionPickerNavigation.ts b/frontend/src/hooks/useSessionPickerNavigation.ts index 70fc1239..d755c0a9 100644 --- a/frontend/src/hooks/useSessionPickerNavigation.ts +++ b/frontend/src/hooks/useSessionPickerNavigation.ts @@ -8,6 +8,7 @@ import { getSessionListPath, getSessionPath, parseActivePickerSession, + parseChatSessionRoute, parseRepoRoute, withQueryParam, } from '@/lib/navigation' @@ -50,6 +51,7 @@ export function useSessionPickerNavigation({ const navigate = useNavigate() const { pathname, search } = useLocation() const currentRepoId = parseRepoRoute(pathname).repoId + const isChatSessionRoute = parseChatSessionRoute(pathname) !== null const { sessionId: activeSessionID, serverId: activeServerId } = parseActivePickerSession(pathname) const searchParams = new URLSearchParams(search) const isAssistantSession = searchParams.get('assistant') === '1' @@ -99,6 +101,10 @@ export function useSessionPickerNavigation({ open(deleteActiveSessionPath) return } + if (isChatSessionRoute) { + open('/') + return + } if (currentRepoId === null) { if (!isPanelMode) onClose() return @@ -108,6 +114,7 @@ export function useSessionPickerNavigation({ currentRepoId, deleteActiveSessionPath, isAssistantSession, + isChatSessionRoute, isPanelMode, onClose, open, diff --git a/frontend/src/lib/activeWork.test.ts b/frontend/src/lib/activeWork.test.ts index c3ca14d4..6d189f72 100644 --- a/frontend/src/lib/activeWork.test.ts +++ b/frontend/src/lib/activeWork.test.ts @@ -465,6 +465,10 @@ describe('hasUnmatchedActiveDirectory', () => { it('is false for an empty index', () => { expect(hasUnmatchedActiveDirectory(new Map(), [repoA])).toBe(false) }) + + it('is false when the only indexed directory is a chat root', () => { + expect(hasUnmatchedActiveDirectory(indexFor('/workspace/chats/20260101-120000-abcdef'), [repoA])).toBe(false) + }) }) describe('buildActiveWork', () => { @@ -515,6 +519,20 @@ describe('buildActiveWork', () => { expect(groups.recent).toEqual([]) }) + it('emits a chat root with its chat path and no repo or server', () => { + const chatId = '20260101-120000-abcdef' + const sessions = [createSession('chat-root', NOW - 1000, `/workspace/chats/${chatId}`)] + + const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents: new Map(), roots: emptyRoots, outcomes: new Map() }) + + expect(groups.recent.map((item) => item.session.id)).toEqual(['chat-root']) + expect(groups.recent[0].repo).toBeNull() + expect(groups.recent[0].serverId).toBeNull() + expect(groups.recent[0].serverName).toBeNull() + expect(groups.recent[0].worktreeBranch).toBeNull() + expect(groups.recent[0].path).toBe(`/chats/${chatId}/sessions/chat-root`) + }) + it('resolves a repo by local path and trims trailing slashes', () => { const repo = createRepo({ id: 5, fullPath: '/repos/full', localPath: '/local/path' }) const sessions = [createSession('local', NOW - 1000, '/local/path/')] @@ -779,6 +797,17 @@ describe('needsWorktreeLookup', () => { ).toBe(false) }) + it('returns false for a chat session updated inside the window', () => { + expect( + needsWorktreeLookup({ + ...base, + sessions: [createSession('chat-root', NOW - 1000, '/workspace/chats/20260101-120000-abcdef')], + parents: new Map(), + roots: emptyRoots, + }), + ).toBe(false) + }) + it('returns false for an archived unmatched session', () => { const archived = createSession('archived', NOW - 1000, '/repos/other') archived.time.archived = NOW - 500 diff --git a/frontend/src/lib/activeWork.ts b/frontend/src/lib/activeWork.ts index 92b7be70..9b31fb45 100644 --- a/frontend/src/lib/activeWork.ts +++ b/frontend/src/lib/activeWork.ts @@ -3,10 +3,10 @@ import { LOCAL_OPENCODE_SERVER_ID, parseServerDirectoryKey } from '@opencode-man import type { ChildOutcome } from '@/lib/backgroundWork' import type { SessionStatusType } from '@/stores/sessionStatusStore' import { getSessionKey } from '@/lib/sessionKey' -import { getServerSessionPath, getSessionPath } from '@/lib/navigation' +import { getChatSessionPath, getServerSessionPath, getSessionPath } from '@/lib/navigation' import { getRepoBranchLabel } from '@/lib/utils' import { findRepoForDirectory, normalizeDirectory } from '@/components/navigation/sidebar-session-tree' -import { isWorktreeSibling, type RepoSibling } from '@opencode-manager/shared/utils' +import { getChatIdFromDirectory, isWorktreeSibling, type RepoSibling } from '@opencode-manager/shared/utils' /** * The plain directory of a session-status directory value when it belongs to the local server, @@ -43,11 +43,11 @@ export type ActiveWorkState = 'needs-input' | 'running' | 'recent' export interface ActiveWorkItem { key: string session: Session - /** The local repo the session runs in; null for a session owned by a linked server. */ + /** The local repo the session runs in; null for a linked-server or chat session. */ repo: Repo | null - /** The linked server that owns the session; null for a local repo session. */ + /** The linked server that owns the session; null for a local repo or chat session. */ serverId: string | null - /** The owning linked server's display name; null for a local repo session. */ + /** The owning linked server's display name; null for a local repo or chat session. */ serverName: string | null state: ActiveWorkState updatedAt: number @@ -335,13 +335,15 @@ export function repoActivityFromIndex( /** * True when some indexed active directory matches no repo, so a session is active in a directory - * outside the repo list (such as a worktree) and the worktree lookup is worth running. + * outside the repo list (such as a worktree) and the worktree lookup is worth running. Chat + * directories are ignored because they never resolve to a repo worktree. */ export function hasUnmatchedActiveDirectory( index: ReadonlyMap, repos: Repo[], ): boolean { for (const directory of index.keys()) { + if (getChatIdFromDirectory(directory)) continue if (!findRepoForDirectory(repos, directory)) return true } return false @@ -410,7 +412,8 @@ export function resolveSessionBranch( /** * Whether the worktree lookup is worth running: true when some non-archived session that matches no - * repo is either updated inside the window or has its root active (needs-input or running). + * repo and is not a chat session is either updated inside the window or has its root active + * (needs-input or running). */ export function needsWorktreeLookup(input: { now: number @@ -427,6 +430,7 @@ export function needsWorktreeLookup(input: { return sessions.some((session) => { if (session.time.archived) return false if (sessionServers?.has(session.id)) return false + if (getChatIdFromDirectory(session.location.directory)) return false if (findRepoForDirectory(repos, session.location.directory)) return false if (session.time.updated >= windowStart) return true const rootID = rootSessionID(session.id, parents) @@ -437,11 +441,12 @@ export function needsWorktreeLookup(input: { /** * Groups the given sessions into needs-input, running, and recent roots. A session appears in * exactly one group (needs-input over running over recent) and only when it resolves to a local - * repo or to an owning linked server. A session owned by a linked server keeps its own row in any - * state, opening on that server instead of a local repo. A recent session in a schedule worktree is - * omitted so schedules only surface while they need attention. The input may mix roots and children; - * children never become items, but their latest update time rolls up into the root's `updatedAt` and - * decides the recent window and ordering. + * repo, a workspace chat, or an owning linked server. A session owned by a linked server keeps its + * own row in any state, opening on that server instead of a local repo. A chat session keeps its own + * row too, opening on its chat route. A recent session in a schedule worktree is omitted so + * schedules only surface while they need attention. The input may mix roots and children; children + * never become items, but their latest update time rolls up into the root's `updatedAt` and decides + * the recent window and ordering. */ export function buildActiveWork(input: { now: number @@ -517,7 +522,28 @@ export function buildActiveWork(input: { const directory = normalizeDirectory(session.location.directory) const worktree = directory ? worktreeByDirectory.get(directory) : undefined const repo = worktree?.ownerRepo ?? findRepoForDirectory(repos, session.location.directory) - if (!repo) continue + + if (!repo) { + const chatId = getChatIdFromDirectory(session.location.directory) + if (!chatId) continue + seen.add(session.id) + const item: ActiveWorkItem = { + key: getSessionKey(session), + session, + repo: null, + serverId: null, + serverName: null, + state, + updatedAt, + outcome: outcomes.get(session.id), + worktreeBranch: null, + path: getChatSessionPath(chatId, session.id), + } + if (state === 'needs-input') needsInput.push(item) + else if (state === 'running') running.push(item) + else recent.push(item) + continue + } if (worktree?.isSchedule && state === 'recent') continue seen.add(session.id) diff --git a/frontend/src/lib/builtinCommands.test.ts b/frontend/src/lib/builtinCommands.test.ts new file mode 100644 index 00000000..6b614d74 --- /dev/null +++ b/frontend/src/lib/builtinCommands.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import { getBuiltinCommands } from './builtinCommands' + +function commandNames(isLocalServer: boolean, isChat = false): string[] { + return getBuiltinCommands(isLocalServer, isChat).map((command) => command.name) +} + +describe('getBuiltinCommands', () => { + it('offers every built-in command for the local server outside chats', () => { + const names = commandNames(true) + + expect(names).toContain('mcp') + expect(names).toContain('skills') + expect(names).toContain('walkthrough') + expect(names).toContain('undo') + expect(names).toContain('sessions') + }) + + it('omits mcp, skills, and walkthrough for chat sessions and keeps the rest', () => { + const names = commandNames(true, true) + + expect(names).not.toContain('mcp') + expect(names).not.toContain('skills') + expect(names).not.toContain('walkthrough') + expect(names).toContain('sessions') + expect(names).toContain('models') + expect(names).toContain('compact') + expect(names).toContain('undo') + expect(names).toContain('settings') + }) + + it('keeps mcp and skills but omits walkthrough for a linked server outside chats', () => { + const names = commandNames(false) + + expect(names).toContain('mcp') + expect(names).toContain('skills') + expect(names).not.toContain('walkthrough') + }) + + it('omits mcp, skills, and walkthrough for a linked server in a chat session', () => { + const names = commandNames(false, true) + + expect(names).not.toContain('mcp') + expect(names).not.toContain('skills') + expect(names).not.toContain('walkthrough') + expect(names).toContain('models') + }) +}) diff --git a/frontend/src/lib/builtinCommands.ts b/frontend/src/lib/builtinCommands.ts index 4c25db67..7d7c7bb4 100644 --- a/frontend/src/lib/builtinCommands.ts +++ b/frontend/src/lib/builtinCommands.ts @@ -72,12 +72,26 @@ const MANAGER_ONLY_COMMAND_ACTIONS: ReadonlySet = new Set( 'showWalkthrough', ]) +const CHAT_UNAVAILABLE_COMMAND_ACTIONS: ReadonlySet = new Set([ + 'showMcp', + 'showSkills', + 'showWalkthrough', +]) + /** - * Built-in composer commands for a server scope. Commands backed by Manager-only features are omitted for - * linked OpenCode servers; MCP, skills, and the session picker stay because their views work against the - * linked server. + * Built-in composer commands for a server and page scope. Commands backed by Manager-only features are + * omitted for linked OpenCode servers; MCP, skills, and the session picker stay because their views work + * against the linked server. Chat sessions omit the MCP, skills, and walkthrough commands because their + * dialogs are not mounted there. + * + * @param isLocalServer Whether the composer targets the local Manager server. + * @param isChat Whether the composer is mounted on a chat session page. + * @returns The commands offered for that scope. */ -export function getBuiltinCommands(isLocalServer: boolean): readonly BuiltinCommand[] { - if (isLocalServer) return BUILTIN_COMMANDS - return BUILTIN_COMMANDS.filter((command) => !MANAGER_ONLY_COMMAND_ACTIONS.has(command.action)) +export function getBuiltinCommands(isLocalServer: boolean, isChat = false): readonly BuiltinCommand[] { + const available = isLocalServer + ? BUILTIN_COMMANDS + : BUILTIN_COMMANDS.filter((command) => !MANAGER_ONLY_COMMAND_ACTIONS.has(command.action)) + if (!isChat) return available + return available.filter((command) => !CHAT_UNAVAILABLE_COMMAND_ACTIONS.has(command.action)) } diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index 04b865c7..16e0e6bd 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -16,6 +16,7 @@ import type { TerminalTarget } from '@/lib/terminal-target' import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"; import { NotFoundState } from "@/components/ui/not-found-state"; +import { parseNetworkError } from '@/lib/opencode-errors'; import { useSession, useInterruptSession, useUpdateSession, useCreateSession } from "@/hooks/useOpenCode"; import { useSessionTranscript } from "@/hooks/useSessionTranscript"; import { useAutoOpenWalkthrough } from "@/hooks/useAutoOpenWalkthrough"; @@ -199,7 +200,7 @@ export function SessionDetail() { useRepoActivity(repoId, Boolean(repo) && !isRemoteServer && !isChatSession); - const { data: chat, isLoading: chatLoading } = useChat(chatId); + const { data: chat, isLoading: chatLoading, isError: chatFailed, error: chatError } = useChat(chatId); const { mutateAsync: deleteChatSessionAsync } = useDeleteChatSession(); const repoDirectory = repo?.fullPath; @@ -783,6 +784,16 @@ export function SessionDetail() { ); } + if (isChatSession && chatFailed && !chat) { + return ( + + ); + } + if (isChatSession && !chat) { return ; } diff --git a/frontend/src/pages/__tests__/SessionDetail.chat.test.tsx b/frontend/src/pages/__tests__/SessionDetail.chat.test.tsx index d9b8c8ca..5aa70fdd 100644 --- a/frontend/src/pages/__tests__/SessionDetail.chat.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.chat.test.tsx @@ -266,4 +266,19 @@ describe('SessionDetail chat session', () => { expect(await screen.findByText('Chat not found')).toBeInTheDocument() expect(screen.queryByTestId('message-thread')).not.toBeInTheDocument() }) + + it('shows the load error instead of not-found when the chat request fails', async () => { + mocks.useChat.mockReturnValue({ + data: undefined, + isLoading: false, + isError: true, + error: new Error('Chat request failed'), + }) + + renderChatSession() + + expect(await screen.findByText('Chat request failed')).toBeInTheDocument() + expect(screen.queryByText('Chat not found')).not.toBeInTheDocument() + expect(screen.queryByTestId('message-thread')).not.toBeInTheDocument() + }) }) diff --git a/shared/src/utils/repo.ts b/shared/src/utils/repo.ts index 23d6a9c2..56387903 100644 --- a/shared/src/utils/repo.ts +++ b/shared/src/utils/repo.ts @@ -1,3 +1,5 @@ +import { DEFAULTS } from '../config/defaults' +import { CHAT_ID_PATTERN } from '../schemas/chats' import type { Repo } from '../types' export const ASSISTANT_REPO_ID = 0 @@ -26,6 +28,27 @@ export function buildChatSessionPath(chatId: string, sessionId: string): string return `/chats/${encodeURIComponent(chatId)}/sessions/${encodeURIComponent(sessionId)}` } +/** + * Reads the chat id a workspace chat directory names. The directory must end in + * `//`; a path nested deeper inside a chat, a different parent + * directory, or a malformed id yields null. Works without Node's `path` module. + * + * @param directory Session directory to read. + * @returns The chat id, or null when the directory is not a chat root. + */ +export function getChatIdFromDirectory(directory: string): string | null { + const normalized = trimTrailingChar(trimTrailingChar(directory.trim(), '/'), '\\') + if (!normalized) return null + + const segments = normalized.split(/[\\/]/) + const chatId = segments[segments.length - 1] + const parent = segments[segments.length - 2] + if (!chatId || !parent) return null + if (parent !== DEFAULTS.WORKSPACE.CHATS_DIR) return null + + return CHAT_ID_PATTERN.test(chatId) ? chatId : null +} + export function buildServerSessionPath(serverId: string, sessionId: string): string { return `/servers/${encodeURIComponent(serverId)}/sessions/${encodeURIComponent(sessionId)}` }