From ccb150d5e65b0bd2662412478e1e469f8d6f8558 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:59:28 -0500 Subject: [PATCH] Desktop sidebar Chats group --- .../navigation/ChatsNavGroup.test.tsx | 220 ++++++++++++++++++ .../components/navigation/ChatsNavGroup.tsx | 81 +++++++ .../navigation/DesktopSessionTree.test.tsx | 72 +++++- .../navigation/DesktopSessionTree.tsx | 24 +- .../components/navigation/RepoSessionNav.tsx | 76 ++++-- .../navigation/sidebar-session-tree.test.ts | 21 ++ .../navigation/sidebar-session-tree.ts | 20 +- 7 files changed, 477 insertions(+), 37 deletions(-) create mode 100644 frontend/src/components/navigation/ChatsNavGroup.test.tsx create mode 100644 frontend/src/components/navigation/ChatsNavGroup.tsx diff --git a/frontend/src/components/navigation/ChatsNavGroup.test.tsx b/frontend/src/components/navigation/ChatsNavGroup.test.tsx new file mode 100644 index 00000000..3b032e22 --- /dev/null +++ b/frontend/src/components/navigation/ChatsNavGroup.test.tsx @@ -0,0 +1,220 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { MemoryRouter, useLocation } from 'react-router-dom' +import type { ReactNode } from 'react' +import type { Chat } from '@opencode-manager/shared/schemas' +import { ChatsNavGroup } from './ChatsNavGroup' + +type SessionFixture = { + id: string + projectID: string + title: string + time: { created: number; updated: number; archived?: number } + location: { directory: string } + cost: number + tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } +} + +const mocks = vi.hoisted(() => ({ + listChats: vi.fn(), + createChat: vi.fn(), + sessionsData: [] as SessionFixture[], + useSessionsAcrossDirectories: vi.fn(), + useSessionPins: vi.fn(), + showToast: { success: vi.fn(), error: vi.fn() }, +})) + +vi.mock('@/api/chats', () => ({ + listChats: mocks.listChats, + createChat: mocks.createChat, +})) + +vi.mock('@/hooks/useOpenCode', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useSessionsAcrossDirectories: mocks.useSessionsAcrossDirectories, + removeDeletedSessionsFromListCaches: vi.fn(), + cleanupSessionPins: vi.fn(), + } +}) + +vi.mock('@/hooks/useSessionPins', () => ({ + SESSION_PINS_QUERY_KEY: ['session-pins'], + useSessionPins: mocks.useSessionPins, +})) + +vi.mock('@/lib/toast', () => ({ showToast: mocks.showToast })) + +vi.mock('@/contexts/EventContext', () => ({ + usePermissions: () => ({ hasForSession: () => false }), + useForms: () => ({ hasForSession: () => false }), +})) + +function chat(id: string, directory: string): Chat { + return { id, directory, filesPath: `${directory}/files`, createdAt: 1000 } +} + +function createSession(id: string, directory: string, updated = Date.now()): SessionFixture { + return { + id, + projectID: 'proj-1', + title: `Session ${id}`, + time: { created: updated - 10000, updated }, + location: { directory }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + } +} + +const chatA = chat('20240103120000-aaaaaa', '/chats/a') +const chatB = chat('20240102120000-bbbbbb', '/chats/b') +const chatC = chat('20240101120000-cccccc', '/chats/c') +const chatD = chat('20231231120000-dddddd', '/chats/d') +const chatE = chat('20231230120000-eeeeee', '/chats/e') +const chatF = chat('20231229120000-ffffff', '/chats/f') + +function LocationDisplay() { + const location = useLocation() + return
{location.pathname}
+} + +function createWrapper(initialEntries: string[]) { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + }) + return ({ children }: { children: ReactNode }) => ( + + + {children} + + + + ) +} + +const chatRows = () => screen.getAllByText(/^Session /).map((row) => row.textContent) + +describe('ChatsNavGroup', () => { + beforeEach(() => { + localStorage.clear() + mocks.listChats.mockReset() + mocks.createChat.mockReset() + mocks.sessionsData.splice( + 0, + mocks.sessionsData.length, + createSession('a1', '/chats/a'), + createSession('b1', '/chats/b'), + createSession('c1', '/chats/c'), + createSession('d1', '/chats/d'), + createSession('e1', '/chats/e'), + createSession('f1', '/chats/f'), + ) + mocks.listChats.mockImplementation(async ({ cursor }: { cursor?: string }) => { + if (cursor === 'cursor_2') return { chats: [chatD, chatE, chatF] } + return { chats: [chatA, chatB, chatC], nextCursor: 'cursor_2' } + }) + mocks.createChat.mockResolvedValue({ + chat: chat('20240104120000-111111', '/chats/new'), + sessionId: 'ses_new', + }) + mocks.useSessionsAcrossDirectories.mockImplementation((directories: string[]) => ({ + data: mocks.sessionsData.filter((session) => directories.includes(session.location.directory)), + isLoading: false, + isError: false, + error: null, + })) + mocks.useSessionPins.mockReturnValue({ data: [] }) + mocks.showToast.success.mockReset() + mocks.showToast.error.mockReset() + }) + + it('lists the newest chats and loads the next page with Show more', async () => { + const user = userEvent.setup() + render(, { wrapper: createWrapper(['/']) }) + + await screen.findByRole('button', { name: /^Session a1/ }) + expect(chatRows()).toEqual(['Session a1', 'Session b1', 'Session c1']) + expect(mocks.listChats).toHaveBeenCalledWith({ limit: 3, cursor: undefined }) + + await user.click(screen.getByText('Show more')) + + await waitFor(() => expect(chatRows()).toHaveLength(6)) + expect(chatRows()).toEqual([ + 'Session a1', + 'Session b1', + 'Session c1', + 'Session d1', + 'Session e1', + 'Session f1', + ]) + expect(mocks.listChats).toHaveBeenLastCalledWith({ limit: 3, cursor: 'cursor_2' }) + expect(screen.queryByText('Show more')).toBeNull() + }) + + it('creates a chat and opens its session from the + button', async () => { + const user = userEvent.setup() + render(, { wrapper: createWrapper(['/']) }) + + await screen.findByRole('button', { name: /^Session a1/ }) + await user.click(screen.getByRole('button', { name: 'New chat' })) + + await waitFor(() => expect(mocks.createChat).toHaveBeenCalledWith({})) + await waitFor(() => + expect(screen.getByTestId('location').textContent).toBe( + '/chats/20240104120000-111111/sessions/ses_new', + ), + ) + }) + + it('folds the group and keeps that choice for the next mount', async () => { + const user = userEvent.setup() + const firstRender = render(, { wrapper: createWrapper(['/']) }) + + await screen.findByRole('button', { name: /^Session a1/ }) + expect(screen.getByRole('button', { name: 'Show sessions in Chats' })).toHaveAttribute( + 'aria-expanded', + 'true', + ) + + await user.click(screen.getByRole('button', { name: 'Show sessions in Chats' })) + + expect(screen.getByRole('button', { name: 'Show sessions in Chats' })).toHaveAttribute( + 'aria-expanded', + 'false', + ) + expect(screen.queryByRole('button', { name: /^Session a1/ })).toBeNull() + + firstRender.unmount() + render(, { wrapper: createWrapper(['/']) }) + + expect(screen.getByRole('button', { name: 'Show sessions in Chats' })).toHaveAttribute( + 'aria-expanded', + 'false', + ) + expect(screen.queryByRole('button', { name: /^Session a1/ })).toBeNull() + }) + + it('marks the open chat session and group as current', async () => { + render(, { + wrapper: createWrapper([`/chats/${chatA.id}/sessions/a1`]), + }) + + expect(await screen.findByRole('button', { name: /^Session a1/ })).toHaveAttribute( + 'aria-current', + 'page', + ) + expect(screen.getByRole('button', { name: /^Session b1/ })).not.toHaveAttribute('aria-current') + expect(screen.getByRole('button', { name: 'Chats' })).toHaveAttribute('aria-current', 'page') + }) + + it('shows an empty state when there are no chats', async () => { + mocks.listChats.mockResolvedValue({ chats: [] }) + + render(, { wrapper: createWrapper(['/']) }) + + expect(await screen.findByText('No chats')).toBeTruthy() + }) +}) diff --git a/frontend/src/components/navigation/ChatsNavGroup.tsx b/frontend/src/components/navigation/ChatsNavGroup.tsx new file mode 100644 index 00000000..cbb70d3f --- /dev/null +++ b/frontend/src/components/navigation/ChatsNavGroup.tsx @@ -0,0 +1,81 @@ +import { useLocation, useNavigate } from 'react-router-dom' +import { parseChatSessionRoute } from '@/lib/navigation' +import { usePersistentBoolean } from '@/hooks/usePersistentBoolean' +import { useChatSessions, type ChatSessionRow } from '@/hooks/useChats' +import { + NewChatButton, + RepoNavGroup, + SessionNavLink, + SessionNavRow, + SessionNavStatus, +} from '@/components/navigation/RepoSessionNav' +import { + SIDEBAR_CHATS_PER_PAGE, + isCurrentSessionItem, + type SidebarSessionItem, +} from '@/components/navigation/sidebar-session-tree' + +const CHATS_GROUP_OPEN_STORAGE_KEY = 'oc:sidebar:chats-open' + +function toChatItem(row: ChatSessionRow): SidebarSessionItem { + return { + key: row.key, + session: row.session, + chatId: row.chat.id, + repoLabel: 'Chat', + branchLabel: null, + isWorktree: false, + isPinned: row.isPinned, + path: row.path, + } +} + +/** + * The sidebar's chat group: the newest chat sessions above the repositories, expandable to more + * pages and persisted independently of the repository accordion. + */ +export function ChatsNavGroup() { + const navigate = useNavigate() + const location = useLocation() + const [isOpen, toggleOpen] = usePersistentBoolean(CHATS_GROUP_OPEN_STORAGE_KEY, true) + const { rows, hasMore, showMore, isLoading, isError } = useChatSessions(SIDEBAR_CHATS_PER_PAGE) + const firstRow = rows[0] + + const openGroup = () => { + if (firstRow) navigate(firstRow.path) + } + + return ( + } + > + {isLoading ? ( + Loading chats... + ) : isError ? ( + Failed to load chats + ) : rows.length === 0 ? ( + No chats + ) : ( + <> + {rows.map((row) => { + const item = toChatItem(row) + return ( + + ) + })} + {hasMore && Show more} + + )} + + ) +} diff --git a/frontend/src/components/navigation/DesktopSessionTree.test.tsx b/frontend/src/components/navigation/DesktopSessionTree.test.tsx index 864c4a8a..e08d55f4 100644 --- a/frontend/src/components/navigation/DesktopSessionTree.test.tsx +++ b/frontend/src/components/navigation/DesktopSessionTree.test.tsx @@ -38,6 +38,8 @@ const { sessionPinsData, sessionsHasNextPage, searchError, + listChatsMock, + createChatMock, } = vi.hoisted(() => ({ listReposMock: vi.fn(), getRepoSiblingsMock: vi.fn(), @@ -51,6 +53,8 @@ const { sessionPinsData: { current: [] as SessionPinFixture[] }, sessionsHasNextPage: { current: false }, searchError: { current: false }, + listChatsMock: vi.fn(), + createChatMock: vi.fn(), })) vi.mock('@/api/repos', async (importOriginal) => { @@ -63,6 +67,11 @@ vi.mock('@/api/opencode', async (importOriginal) => { return { ...actual, getSession: getSessionMock } }) +vi.mock('@/api/chats', () => ({ + listChats: listChatsMock, + createChat: createChatMock, +})) + vi.mock('@/hooks/useOpenCode', async (importOriginal) => { const actual = await importOriginal() return { @@ -187,6 +196,9 @@ describe('DesktopSessionTree', () => { sessionPinsData.current = [] sessionsHasNextPage.current = false searchError.current = false + listChatsMock.mockReset() + listChatsMock.mockResolvedValue({ chats: [] }) + createChatMock.mockReset() }) it('lists every repo by last access, even inside a repo, with no Recent section', async () => { @@ -197,10 +209,68 @@ describe('DesktopSessionTree', () => { .getAllByRole('button', { name: /^Show sessions in / }) .map((button) => button.getAttribute('aria-label')) - expect(names).toEqual(['Show sessions in Gamma', 'Show sessions in Alpha', 'Show sessions in Beta']) + expect(names).toEqual([ + 'Show sessions in Chats', + 'Show sessions in Gamma', + 'Show sessions in Alpha', + 'Show sessions in Beta', + ]) expect(screen.queryByText('Recent')).toBeNull() }) + it('puts the Chats group above the Assistant and every repository', async () => { + listReposMock.mockResolvedValue([ + repoA, + createRepo({ id: 0, fullPath: '/assistant', name: 'Assistant' }), + ]) + + render(, { wrapper: createWrapper(['/']) }) + + await screen.findByText('Assistant') + const names = screen + .getAllByRole('button', { name: /^Show sessions in / }) + .map((button) => button.getAttribute('aria-label')) + + expect(names).toEqual([ + 'Show sessions in Chats', + 'Show sessions in Assistant', + 'Show sessions in Alpha', + ]) + }) + + it('opens the newest chat from the Chats group header', async () => { + const user = userEvent.setup() + listChatsMock.mockResolvedValue({ + chats: [ + { + id: '20240103120000-aaaaaa', + directory: '/chats/a', + filesPath: '/chats/a', + createdAt: 1000, + }, + ], + }) + sessionsData.push(createSession('chat1', '/chats/a')) + + render(, { wrapper: createWrapper(['/']) }) + + await screen.findByRole('button', { name: /^Session chat1/ }) + await user.click(screen.getByRole('button', { name: 'Chats' })) + + expect(screen.getByTestId('location').textContent).toBe( + '/chats/20240103120000-aaaaaa/sessions/chat1', + ) + }) + + it('shows no Chats group for a linked server', async () => { + useSidebarServerStore.setState({ serverId: 'srv_remote' }) + + render(, { wrapper: createWrapper(['/']) }) + + expect(await screen.findByText('Server not found')).toBeTruthy() + expect(screen.queryByRole('button', { name: 'Show sessions in Chats' })).toBeNull() + }) + it('opens the active repo by default and lazily fetches only its sessions', async () => { render(, { wrapper: createWrapper(['/repos/1']) }) diff --git a/frontend/src/components/navigation/DesktopSessionTree.tsx b/frontend/src/components/navigation/DesktopSessionTree.tsx index 05ca0cf6..c119f7c5 100644 --- a/frontend/src/components/navigation/DesktopSessionTree.tsx +++ b/frontend/src/components/navigation/DesktopSessionTree.tsx @@ -10,6 +10,7 @@ import { useSessionSearch } from '@/hooks/useSessionSearch' import { useSessionPins } from '@/hooks/useSessionPins' import { useSidebarServerSelection } from '@/hooks/useSidebarServerSelection' import { RemoteProjectNavList } from '@/components/navigation/RemoteProjectNav' +import { ChatsNavGroup } from '@/components/navigation/ChatsNavGroup' import { LocalRepoNewSessionButton, RepoNavGroup, @@ -187,16 +188,19 @@ function LocalSessionTree() { isSearchError={isSearchError} /> ) : ( - navigate(getRepoPath(repoId))} - onSelectSession={navigate} - renderActions={(repo) => ( - - )} - /> + <> + + navigate(getRepoPath(repoId))} + onSelectSession={navigate} + renderActions={(repo) => ( + + )} + /> + )} ) diff --git a/frontend/src/components/navigation/RepoSessionNav.tsx b/frontend/src/components/navigation/RepoSessionNav.tsx index e3c2edd6..ce139e03 100644 --- a/frontend/src/components/navigation/RepoSessionNav.tsx +++ b/frontend/src/components/navigation/RepoSessionNav.tsx @@ -5,6 +5,7 @@ import { SessionStatusIndicator } from '@/components/ui/session-status-indicator import { RepoActivityIndicator } from '@/components/activity/RepoActivityIndicator' import { useForms, usePermissions } from '@/contexts/EventContext' import { useCreateSession } from '@/hooks/useOpenCode' +import { useCreateChat } from '@/hooks/useChats' import { useRepoSiblings } from '@/hooks/useRepoSiblings' import { useSidebarRepoGroups } from '@/hooks/useSidebarRepoGroups' import { buildWorktreeActivity, type ActiveWorktree } from '@/lib/activeWork' @@ -298,6 +299,40 @@ export function RepoSessionNavList({ ) } +interface GroupActionButtonProps { + title: string + ariaLabel: string + isPending: boolean + onClick: () => void +} + +function GroupActionButton({ title, ariaLabel, isPending, onClick }: GroupActionButtonProps) { + return ( + + ) +} + interface NewSessionButtonProps { directory: string label: string @@ -321,31 +356,26 @@ export function NewSessionButton({ serverId, ) - const isCreating = createSession.isPending + return ( + createSession.mutate({ agent: undefined })} + /> + ) +} + +export function NewChatButton({ onOpenSession }: { onOpenSession: (path: string) => void }) { + const createChat = useCreateChat(onOpenSession) return ( - + createChat.mutate({})} + /> ) } diff --git a/frontend/src/components/navigation/sidebar-session-tree.test.ts b/frontend/src/components/navigation/sidebar-session-tree.test.ts index cf95e9e0..9d9c31c5 100644 --- a/frontend/src/components/navigation/sidebar-session-tree.test.ts +++ b/frontend/src/components/navigation/sidebar-session-tree.test.ts @@ -72,6 +72,27 @@ describe('isCurrentSessionItem', () => { }) }) +describe('isCurrentSessionItem for chat rows', () => { + const chatId = '20240103120000-aaaaaa' + const item = { + key: `/chats/${chatId}:c1`, + session: createSession('c1', NOW, `/chats/${chatId}`), + chatId, + repoLabel: 'Chat', + branchLabel: null, + isWorktree: false, + isPinned: false, + path: `/chats/${chatId}/sessions/c1`, + } + + it('matches only the exact chat and session route', () => { + expect(isCurrentSessionItem(item, `/chats/${chatId}/sessions/c1`)).toBe(true) + expect(isCurrentSessionItem(item, `/chats/${chatId}/sessions/c2`)).toBe(false) + expect(isCurrentSessionItem(item, '/chats/20240102120000-bbbbbb/sessions/c1')).toBe(false) + expect(isCurrentSessionItem(item, `/repos/1/sessions/c1`)).toBe(false) + }) +}) + describe('isRepoReady', () => { it('is true only for ready repos', () => { expect(isRepoReady(createRepo({ id: 1, fullPath: '/repos/a' }))).toBe(true) diff --git a/frontend/src/components/navigation/sidebar-session-tree.ts b/frontend/src/components/navigation/sidebar-session-tree.ts index ffb0b28a..a617a370 100644 --- a/frontend/src/components/navigation/sidebar-session-tree.ts +++ b/frontend/src/components/navigation/sidebar-session-tree.ts @@ -2,11 +2,18 @@ import type { Repo, Session } from '@/api/types' import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' import { getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils' import { getSessionKey } from '@/lib/sessionKey' -import { getSessionPath, isAssistantPath, parseRepoRoute, parseServerSessionRoute } from '@/lib/navigation' +import { + getSessionPath, + isAssistantPath, + parseChatSessionRoute, + parseRepoRoute, + parseServerSessionRoute, +} from '@/lib/navigation' import { partitionSessions, selectRootSessions } from '@/components/session/session-partition' import type { ActiveWorktree } from '@/lib/activeWork' export const SIDEBAR_SESSIONS_PER_REPO = 10 +export const SIDEBAR_CHATS_PER_PAGE = 3 /** Collects the loaded session from each query result, dropping unresolved queries. */ export const combineQuerySessions = (results: Array<{ data?: Session }>): Session[] => @@ -28,8 +35,11 @@ export function mergeExtraSessions(sessions: Session[], extraSessions: Session[] export interface SidebarSessionItem { key: string session: Session - repoId: number - /** The linked server owning the session; absent for local repo sessions. */ + /** The repository owning the session; absent for chat and linked-server sessions. */ + repoId?: number + /** The chat folder owning the session; absent for repo and linked-server sessions. */ + chatId?: string + /** The linked server owning the session; absent for local repo and chat sessions. */ serverId?: string repoLabel: string branchLabel: string | null @@ -48,6 +58,10 @@ export interface SidebarRepoGroup { } export function isCurrentSessionItem(item: SidebarSessionItem, pathname: string): boolean { + if (item.chatId) { + const selection = parseChatSessionRoute(pathname) + return selection?.chatId === item.chatId && item.session.id === selection.sessionId + } if (item.serverId) { const selection = parseServerSessionRoute(pathname) return selection?.serverId === item.serverId && item.session.id === selection.sessionId