From bcabd901ddb935eff968d30fbbe2140c9984f12a Mon Sep 17 00:00:00 2001 From: Diao Shengjia <104132148+GoDiao@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:57:35 +0800 Subject: [PATCH] feat(sessions): add side chats in the session's side panel A side chat is a full session forked from the parent's latest message, in the same working folder. It opens as a tab in the parent's workspace panel, is named `btw: `, and can be renamed, detached into a regular forked session, or closed (which deletes it). Deleting a session deletes its side chats. Server: - parent kind `side`; the branch route takes `kind: 'side'` without a target message, adds a side chat note and answers open tool calls. - `forkSession`, `removeSessions` and `setSessionParent` hold the fork, delete and relation-rewrite logic. Deletes report side chats that could not be removed separately (`sideChatFailures`). - `GET /api/sessions/:id/side-chats` and `PATCH {detach: true}`. Detach refuses a running side chat and blocks CLI starts while the relation is rewritten (`SESSION_DETACHING`). - side chats stay out of the session list, search and `ListSessions`, except a session's own side chats in `ListSessions`. - discarding a fork no longer removes the parent's worktree: only the session that created a worktree (`worktreeOwnerSessionId`) removes it. - repository sessions that already have messages are prewarmed again. Desktop: - `SessionConversation` is the conversation view shared by the main session and side chat tabs; chat components take an explicit `sessionId` instead of the active tab. - CLI tasks are kept per session. - side chat tabs: all connect, only the visible one prewarms; pages, browser and file tabs a side chat opens go to the parent panel without taking the active tab; Cmd+. stops the focused conversation. - `RenameSessionDialog` is shared by the session header menu and the side chat tab menu. --- CHANGELOG.md | 3 + desktop/src/api/sessions.ts | 32 +- .../components/chat/AskUserQuestion.test.tsx | 12 +- .../src/components/chat/AskUserQuestion.tsx | 11 +- .../src/components/chat/ChatInput.test.tsx | 126 ++++-- desktop/src/components/chat/ChatInput.tsx | 142 +++--- .../src/components/chat/MessageList.test.tsx | 131 +++--- desktop/src/components/chat/MessageList.tsx | 147 +++---- .../src/components/chat/PermissionDialog.tsx | 15 +- .../chat/SessionConversation.test.tsx | 95 ++++ .../components/chat/SessionConversation.tsx | 194 +++++++++ .../components/chat/SessionTaskBar.test.tsx | 40 +- .../src/components/chat/SessionTaskBar.tsx | 12 +- .../chat/StreamingIndicator.test.tsx | 10 +- .../components/chat/StreamingIndicator.tsx | 14 +- .../src/components/chat/chatBlocks.test.tsx | 1 + .../components/chat/cuaToolBlocks.test.tsx | 3 +- .../chat/streamingRenderCounts.test.tsx | 10 +- .../controls/PermissionModeSelector.test.tsx | 8 +- .../controls/PermissionModeSelector.tsx | 9 +- .../components/layout/RenameSessionDialog.tsx | 57 +++ .../components/layout/SessionHeaderMenu.tsx | 39 +- .../src/components/layout/Sidebar.test.tsx | 5 +- desktop/src/components/layout/Sidebar.tsx | 12 +- .../WorkspacePanel.sideChatPrewarm.test.tsx | 119 +++++ .../workspace/WorkspacePanel.test.tsx | 144 +++++- .../components/workspace/WorkspacePanel.tsx | 97 ++++- .../src/hooks/useKeyboardShortcuts.test.tsx | 57 +++ desktop/src/hooks/useKeyboardShortcuts.ts | 10 +- .../src/hooks/useReleaseIdleSessions.test.ts | 19 + desktop/src/hooks/useReleaseIdleSessions.ts | 5 +- desktop/src/i18n/locales/en.ts | 9 + desktop/src/i18n/locales/zh.ts | 9 + .../src/lib/browserControlRequests.test.ts | 13 + desktop/src/lib/browserControlRequests.ts | 3 +- desktop/src/lib/browserViewReporter.test.ts | 15 + desktop/src/lib/browserViewReporter.ts | 9 +- .../lib/desktopNotificationNavigation.test.ts | 34 ++ desktop/src/lib/sessionNavigation.ts | 12 +- desktop/src/lib/sessionView.ts | 8 + desktop/src/lib/sideChats.test.ts | 45 ++ desktop/src/lib/sideChats.ts | 14 + desktop/src/pages/ActiveSession.test.tsx | 6 +- desktop/src/pages/ActiveSession.tsx | 171 +------- desktop/src/stores/chatStore.test.ts | 24 +- desktop/src/stores/chatStore.ts | 19 +- desktop/src/stores/cliTaskStore.test.ts | 161 +++---- desktop/src/stores/cliTaskStore.ts | 220 +++++----- desktop/src/stores/sessionStore.test.ts | 74 +++- desktop/src/stores/sessionStore.ts | 22 +- .../src/stores/workspacePanelStore.test.ts | 196 +++++++++ desktop/src/stores/workspacePanelStore.ts | 141 +++++- desktop/src/types/session.ts | 2 +- docs/README.md | 1 + docs/features/session-links/tech-design.md | 8 +- docs/features/side-chat/tech-design.md | 226 ++++++++++ src/server/__tests__/conversations.test.ts | 2 +- .../__tests__/session-links-delivery.test.ts | 107 +++++ src/server/__tests__/session-links.test.ts | 409 +++++++++++++++++- src/server/__tests__/session-pipeline.test.ts | 2 +- src/server/__tests__/sessions.test.ts | 12 +- .../__tests__/websocket-handler.test.ts | 2 +- src/server/api/sessions.ts | 110 ++--- src/server/services/conversationService.ts | 50 +-- .../services/repositoryLaunchService.ts | 3 + src/server/services/sessionLinksService.ts | 205 ++++++--- src/server/services/sessionService.ts | 239 ++++++---- src/server/session/state/types.ts | 1 + src/server/ws/handler.ts | 37 +- src/utils/sessionBranching.ts | 36 +- 70 files changed, 3135 insertions(+), 1101 deletions(-) create mode 100644 desktop/src/components/chat/SessionConversation.test.tsx create mode 100644 desktop/src/components/chat/SessionConversation.tsx create mode 100644 desktop/src/components/layout/RenameSessionDialog.tsx create mode 100644 desktop/src/components/workspace/WorkspacePanel.sideChatPrewarm.test.tsx create mode 100644 desktop/src/lib/sessionView.ts create mode 100644 desktop/src/lib/sideChats.test.ts create mode 100644 desktop/src/lib/sideChats.ts create mode 100644 docs/features/side-chat/tech-design.md diff --git a/CHANGELOG.md b/CHANGELOG.md index b389ee99..24e5a188 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to DreamCoder will be documented in this file. - **Sessions can start other sessions and message each other.** The agent can start a new session with `StartSession`, either fresh with a brief or as a fork of its own conversation, optionally in a new git worktree; you approve every new session, whatever the permission mode. Any session can message any other with `SendMessage`, across projects: a message wakes the receiver, and a progress report from a child to its parent waits for the parent's next turn instead of interrupting it (a parent that is already working sees it right away). Reports waiting for the parent are listed above its message box. The server stamps who sent each message, so a session cannot pass itself off as you or as another session. `ListSessions` lists sessions, and `RenameSession` lets the agent rename its own session (#239). - **Sessions are nested in the sidebar.** Sessions the agent started, and conversations you forked, appear under the session they came from, with an icon for each kind and a count that collapses or expands them. Messages from another session appear in the conversation as a one-line row with the sender, which expands to the full text (#239). - **Project board.** Each project gets a persistent board of tasks and sub-tasks that you and your sessions share; every worktree of the project uses the same board. Open it from the project in the sidebar. A task records its owner, reviewer and creator, acceptance criteria, priority, dependencies, progress, and the owner's and reviewer's reports. Sessions read and update the board with four tools (`KanbanList`, `KanbanGet`, `KanbanCreate`, `KanbanUpdate`): they split work into sub-tasks, record progress, block a task with a question, submit their work and review it. The board notifies the sessions involved when they are assigned, when work is submitted, blocked, sent back, reset or cancelled, and when you comment. `StartSession` can start a session as a task's owner or reviewer. The board page has a board view and a hierarchy view, opens a task in the side panel, and lists what waits on you under "Needs me": blocked tasks, deliveries to accept and tasks whose owner session is gone. You approve every time a session creates the board, starts a session on a task, cancels a task, changes acceptance criteria it did not set, or makes itself a reviewer; only a task's creator or you choose its reviewer (#242). +- **Side chats.** Start a side chat from the side panel's new-tab page to ask about something without interrupting the session: it continues from the session's latest message, in the same working folder, with the same tools, and opens as a tab in the session's side panel. A session can have several. Pages, files and browser tabs a side chat opens appear in the same panel. The tab is named `btw: ` plus your first message; right-click it to rename it, or to detach it into a regular forked session in the sidebar. Closing the tab deletes the side chat, and deleting a session deletes its side chats. Side chats stay out of the sidebar, search and board pickers; `ListSessions` shows a session its own side chats so it can message them. Cmd+. stops the conversation that has the focus. ### Changed @@ -27,6 +28,8 @@ All notable changes to DreamCoder will be documented in this file. - The reply-to-selection button appears when a text selection in a message ends outside the message. - Permission prompts that ask every time, such as starting a session or editing files under `.git/`, no longer offer "Allow for this session", which could not take effect (#242). - Tools sent to providers through the OpenAI Responses API are no longer in strict mode, so their optional parameters stay optional (#242). +- Sessions started on a chosen branch or in a new worktree, and the forks and side chats of such sessions, start their agent in the background again when opened, like other sessions, so the first reply is quicker. Only a new session whose branch or worktree has not been set up yet still waits for its first message. +- Discarding a forked session that failed to start no longer removes the worktree of the session it was forked from. The fork copies the parent's worktree record; only the session that created a worktree removes it now. - Confirmation dialogs keep long workspace paths inside their bounds, so Cancel and Enable remain visible when enabling bypass permissions (#226). Thanks @imshah-id. - Reading environment files, credential files, and SSH private keys now requires explicit approval through both the Read tool and read-only Bash commands. Recursive directory reads, Grep tool glob filters, and files read from Git history are not covered yet (#235). Thanks @AIR-Xie. - The exact shell no-op `:` is recognized as read-only and no longer requires approval (#235). Thanks @AIR-Xie. diff --git a/desktop/src/api/sessions.ts b/desktop/src/api/sessions.ts index cd77fdfa..aa782f57 100644 --- a/desktop/src/api/sessions.ts +++ b/desktop/src/api/sessions.ts @@ -6,14 +6,17 @@ import type { WorkspaceArtifactsResult } from '../types/artifact' type SessionsResponse = { sessions: SessionListItem[]; total: number } type CreateSessionResponse = { sessionId: string; workDir?: string } +export type DeleteSessionFailure = { + sessionId: string + message: string + code?: string +} + export type BatchDeleteSessionsResponse = { ok: boolean successes: string[] - failures: Array<{ - sessionId: string - message: string - code?: string - }> + failures: DeleteSessionFailure[] + sideChatFailures: DeleteSessionFailure[] } export type SessionGitWorktreeInfo = { enabled: boolean @@ -40,16 +43,15 @@ export type CreateSessionRequest = { permissionMode?: PermissionMode runtime?: RuntimeSelection } -export type BranchSessionRequest = { - targetMessageId: string - title?: string -} +export type BranchSessionRequest = + | { targetMessageId: string; title?: string } + | { kind: 'side' } export type BranchSessionResponse = { sessionId: string title: string workDir: string | null sourceSessionId: string - targetMessageId: string + targetMessageId?: string } export type RepositoryBranchInfo = { name: string @@ -348,8 +350,16 @@ export const sessionsApi = { return api.post(`/api/sessions/${sessionId}/branch`, body) }, + listSideChats(sessionId: string) { + return api.get<{ sessions: SessionListItem[] }>(`/api/sessions/${sessionId}/side-chats`) + }, + + detach(sessionId: string) { + return api.patch<{ ok: true }>(`/api/sessions/${sessionId}`, { detach: true }) + }, + delete(sessionId: string) { - return api.delete<{ ok: true }>(`/api/sessions/${sessionId}`) + return api.delete<{ ok: true; sideChatFailures: DeleteSessionFailure[] }>(`/api/sessions/${sessionId}`) }, batchDelete(sessionIds: string[]) { diff --git a/desktop/src/components/chat/AskUserQuestion.test.tsx b/desktop/src/components/chat/AskUserQuestion.test.tsx index 1d1d92b6..5aab46ee 100644 --- a/desktop/src/components/chat/AskUserQuestion.test.tsx +++ b/desktop/src/components/chat/AskUserQuestion.test.tsx @@ -71,11 +71,12 @@ describe('AskUserQuestion', () => { }) it('renders nothing for empty input and then shows questions once they stream in', () => { - const view = render() + const view = render() expect(view.container.innerHTML).toBe('') view.rerender( , @@ -86,6 +87,7 @@ describe('AskUserQuestion', () => { it('submits answers through permission_response updatedInput instead of sending a chat message', () => { render( { it('allows multiple selections when a question is marked multiSelect', () => { render( { it('preserves multiSelect for single-question input shape', () => { render( { render( , @@ -332,6 +337,7 @@ describe('AskUserQuestion', () => { it('uses a multiline custom response box and submits it with Ctrl+Enter', () => { render( { render( { it('steps through multiple questions with progress and submits once all are answered', () => { render( { it('marks multi-select questions and shows the answered record without an edit action', () => { const { rerender } = render( , @@ -449,6 +458,7 @@ describe('AskUserQuestion', () => { rerender( s.respondToPermission) - const activeTabId = useTabStore((s) => s.activeTabId) - const targetSessionId = sessionId ?? activeTabId const pendingRequestId = useChatStore((s) => { - const pending = targetSessionId ? s.sessions[targetSessionId]?.pendingPermission : undefined + const pending = s.sessions[sessionId]?.pendingPermission return pending?.toolUseId === toolUseId ? pending.requestId : null }) const t = useTranslation() @@ -173,7 +170,7 @@ export function AskUserQuestion({ sessionId, toolUseId, input, result }: Props) const response = parts.join('; ') if (!response) return - if (!targetSessionId || !pendingRequestId) return + if (!pendingRequestId) return const answers = questions.reduce>((acc, question, index) => { const freeText = freeTexts[index]?.trim() @@ -187,7 +184,7 @@ export function AskUserQuestion({ sessionId, toolUseId, input, result }: Props) }, {}) setHasSubmitted(true) - respondToPermission(targetSessionId, pendingRequestId, true, { + respondToPermission(sessionId, pendingRequestId, true, { updatedInput: { ...inputObject, answers, diff --git a/desktop/src/components/chat/ChatInput.test.tsx b/desktop/src/components/chat/ChatInput.test.tsx index f62874cd..44ce2f83 100644 --- a/desktop/src/components/chat/ChatInput.test.tsx +++ b/desktop/src/components/chat/ChatInput.test.tsx @@ -177,7 +177,7 @@ describe('ChatInput file mentions', () => { mocks.getRepositoryContext.mockResolvedValue(okRepositoryContext()) mocks.getRecentProjects.mockResolvedValue({ projects: [] }) mocks.create.mockResolvedValue({ sessionId: 'created-session', workDir: '/repo' }) - mocks.delete.mockResolvedValue({ ok: true }) + mocks.delete.mockResolvedValue({ ok: true, sideChatFailures: [] }) mocks.list.mockResolvedValue({ sessions: [], total: 0 }) mocks.getTranscript.mockResolvedValue({ items: [], agentNotifications: {}, lastTodos: null, hasMessagesAfterTaskCompletion: false }) mocks.getInspection.mockResolvedValue({ errors: {} }) @@ -253,7 +253,7 @@ describe('ChatInput file mentions', () => { }, }) - render() + const view = render() const input = screen.getByRole('textbox') as HTMLTextAreaElement fireEvent.change(input, { @@ -261,9 +261,7 @@ describe('ChatInput file mentions', () => { }) expect(input.value).toBe('new tab draft') - act(() => { - useTabStore.setState({ activeTabId: historySessionId }) - }) + view.rerender() await waitFor(() => { expect(input.value).toBe('') @@ -273,17 +271,13 @@ describe('ChatInput file mentions', () => { target: { value: 'history tab draft', selectionStart: 17 }, }) - act(() => { - useTabStore.setState({ activeTabId: sessionId }) - }) + view.rerender() await waitFor(() => { expect(input.value).toBe('new tab draft') }) - act(() => { - useTabStore.setState({ activeTabId: historySessionId }) - }) + view.rerender() await waitFor(() => { expect(input.value).toBe('history tab draft') @@ -291,7 +285,7 @@ describe('ChatInput file mentions', () => { }) it('restores an unsent composer draft after the composer unmounts', async () => { - const { unmount } = render() + const { unmount } = render() const input = screen.getByRole('textbox') as HTMLTextAreaElement fireEvent.change(input, { @@ -300,7 +294,7 @@ describe('ChatInput file mentions', () => { expect(input.value).toBe('keep this prompt while I inspect another tab') unmount() - render() + render() await waitFor(() => { expect(screen.getByRole('textbox')).toHaveValue('keep this prompt while I inspect another tab') @@ -341,7 +335,7 @@ describe('ChatInput file mentions', () => { }, }) - render() + render() const panel = screen.getByTestId('chat-input-panel') expect(panel).toHaveClass('rounded-2xl') @@ -359,6 +353,20 @@ describe('ChatInput file mentions', () => { expect(branchButton.parentElement).toHaveClass('bg-transparent') }) + it('never offers new-session launch controls in a side chat whose history has not loaded yet', async () => { + const sideId = 'side-loading' + useChatStore.setState((state) => ({ + sessions: { ...state.sessions, [sideId]: { ...state.sessions[sessionId]!, messages: [] } }, + })) + + render() + + await waitFor(() => expect(mocks.getGitInfo).toHaveBeenCalledWith(sideId)) + expect(screen.queryByRole('button', { name: /Select branch/ })).not.toBeInTheDocument() + expect(screen.queryByText('Select a project...')).not.toBeInTheDocument() + expect(screen.getByRole('textbox')).toHaveAttribute('placeholder', 'Ask Claude to edit, debug or explain...') + }) + it('uses the persisted message count to keep reopened sessions in context mode while history loads', async () => { useSessionStore.setState({ sessions: [{ @@ -393,7 +401,7 @@ describe('ChatInput file mentions', () => { }, }) - render() + render() expect(await screen.findByText('repo')).toBeInTheDocument() expect(screen.getByText('main')).toBeInTheDocument() @@ -419,7 +427,7 @@ describe('ChatInput file mentions', () => { }, }) - render() + render() const trigger = await screen.findByRole('button', { name: /21%/ }) fireEvent.click(trigger) @@ -448,7 +456,7 @@ describe('ChatInput file mentions', () => { }, }) - render() + render() fireEvent.click(await screen.findByRole('button', { name: /21%/ })) @@ -489,7 +497,7 @@ describe('ChatInput file mentions', () => { }, }) - render() + render() const notice = await screen.findByTestId('workspace-missing-notice') expect(notice).toHaveTextContent('/repo/deleted-app') @@ -532,7 +540,7 @@ describe('ChatInput file mentions', () => { }, }) - render() + render() fireEvent.click(await screen.findByRole('button', { name: /Select branch: main/ })) fireEvent.click(await screen.findByRole('option', { name: /feature\/a/ })) @@ -596,7 +604,7 @@ describe('ChatInput file mentions', () => { }, }) - render() + render() fireEvent.click(await screen.findByRole('button', { name: /Select branch: main/ })) fireEvent.click(await screen.findByRole('option', { name: /feature\/a/ })) @@ -635,7 +643,7 @@ describe('ChatInput file mentions', () => { ], }) - render() + render() const input = screen.getByRole('textbox') as HTMLTextAreaElement const mention = '@backend/src/conditions.py' @@ -680,7 +688,7 @@ describe('ChatInput file mentions', () => { }) it('inserts queued inline workspace citations at the current cursor and keeps file context attached', async () => { - render() + render() const input = screen.getByRole('textbox') as HTMLTextAreaElement fireEvent.change(input, { @@ -753,7 +761,7 @@ describe('ChatInput file mentions', () => { ], }) - render() + render() const input = screen.getByRole('textbox') as HTMLTextAreaElement fireEvent.change(input, { @@ -831,7 +839,7 @@ describe('ChatInput file mentions', () => { mocks.syncMarks.mockResolvedValue(['12']) useWorkspaceChatContextStore.getState().addReference(sessionId, pickedElement()) - render() + render() const input = screen.getByRole('textbox') as HTMLTextAreaElement fireEvent.change(input, { target: { value: 'fix this' } }) @@ -864,7 +872,7 @@ describe('ChatInput file mentions', () => { mocks.syncMarks.mockResolvedValue([]) useWorkspaceChatContextStore.getState().addReference(sessionId, pickedElement()) - render() + render() const input = screen.getByRole('textbox') as HTMLTextAreaElement fireEvent.change(input, { target: { value: 'fix this' } }) @@ -882,7 +890,7 @@ describe('ChatInput file mentions', () => { mocks.syncMarks.mockRejectedValue(new Error('the sidecar is not connected')) useWorkspaceChatContextStore.getState().addReference(sessionId, pickedElement()) - render() + render() const input = screen.getByRole('textbox') as HTMLTextAreaElement fireEvent.change(input, { target: { value: 'fix this' } }) @@ -903,7 +911,7 @@ describe('ChatInput file mentions', () => { browser: { url: 'https://example.com/a', title: 'Example', text: 'quoted', truncated: false }, }) - render() + render() const input = screen.getByRole('textbox') as HTMLTextAreaElement fireEvent.change(input, { target: { value: 'fix this' } }) @@ -913,6 +921,50 @@ describe('ChatInput file mentions', () => { expect(mocks.syncMarks).not.toHaveBeenCalled() }) + it('sends to the session it is given, not to the active tab', async () => { + const sideId = 'side-session' + useChatStore.setState((state) => ({ + sessions: { ...state.sessions, [sideId]: { ...state.sessions[sessionId]!, messages: [{ id: 'side', type: 'assistant_text', content: 'side', timestamp: 1 }] } }, + })) + + render() + + const input = screen.getByRole('textbox') as HTMLTextAreaElement + fireEvent.change(input, { target: { value: 'side question' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + + expect(mocks.wsSend).toHaveBeenCalledWith(sideId, expect.objectContaining({ type: 'user_message', content: 'side question' })) + expect(mocks.wsSend).not.toHaveBeenCalledWith(sessionId, expect.anything()) + }) + + it('leaves typing elsewhere on the page alone in a side chat', () => { + const sideId = 'side-typing' + useChatStore.setState((state) => ({ sessions: { ...state.sessions, [sideId]: state.sessions[sessionId]! } })) + render() + + fireEvent.keyDown(document.body, { key: 'a' }) + + expect(screen.getByRole('textbox')).not.toHaveFocus() + }) + + it('keeps focus where it is when a side chat starts or finishes a reply', () => { + const sideId = 'side-running' + useChatStore.setState((state) => ({ sessions: { ...state.sessions, [sideId]: state.sessions[sessionId]! } })) + render( + <> + + + , + ) + const elsewhere = screen.getByRole('button', { name: 'elsewhere' }) + elsewhere.focus() + + act(() => useChatStore.setState((state) => ({ sessions: { ...state.sessions, [sideId]: { ...state.sessions[sideId]!, chatState: 'streaming' } } }))) + expect(elsewhere).toHaveFocus() + act(() => useChatStore.setState((state) => ({ sessions: { ...state.sessions, [sideId]: { ...state.sessions[sideId]!, chatState: 'idle' } } }))) + expect(elsewhere).toHaveFocus() + }) + it('blocks sending while a picked element is still being read, and says why', async () => { useWorkspaceChatContextStore.getState().addReference(sessionId, pickedElement()) useWorkspaceChatContextStore.getState().addReference(sessionId, { @@ -923,7 +975,7 @@ describe('ChatInput file mentions', () => { browser: { url: '', title: '', tabId: 'tab-1', text: '', truncated: false, pendingPickId: 'p1' }, }) - render() + render() expect(screen.getByText('Picking…')).toBeInTheDocument() const input = screen.getByRole('textbox') as HTMLTextAreaElement @@ -946,7 +998,7 @@ describe('ChatInput file mentions', () => { mocks.syncMarks.mockReturnValue(new Promise((resolve) => { finishCheck = resolve })) useWorkspaceChatContextStore.getState().addReference(sessionId, pickedElement()) - render() + render() const input = screen.getByRole('textbox') as HTMLTextAreaElement fireEvent.change(input, { target: { value: 'fix this' } }) @@ -988,7 +1040,7 @@ describe('ChatInput file mentions', () => { }, }) - render() + render() expect(screen.getByText('Password and card fields are never carried; only where the element is.')).toBeInTheDocument() const input = screen.getByRole('textbox') as HTMLTextAreaElement @@ -1013,7 +1065,7 @@ describe('ChatInput file mentions', () => { 'C:\\Users\\Nanmi\\Desktop\\large-b.zip', ]) - render() + render() fireEvent.keyDown(screen.getByLabelText('Open composer tools'), { key: 'Enter' }) fireEvent.click(screen.getByText('Add files or photos')) @@ -1063,7 +1115,7 @@ describe('ChatInput file mentions', () => { }) const dataTransfer = { types: ['Files'], files: [droppedFile], dropEffect: '' } - render() + render() const panel = screen.getByTestId('chat-input-panel') fireEvent.dragOver(panel, { dataTransfer }) @@ -1108,7 +1160,7 @@ describe('ChatInput file mentions', () => { ], }) - render() + render() const panel = screen.getByTestId('chat-input-panel') const input = screen.getByRole('textbox') as HTMLTextAreaElement @@ -1145,7 +1197,7 @@ describe('ChatInput file mentions', () => { ], }) - render() + render() await waitFor(() => { expect(mocks.getGitInfo).toHaveBeenCalledWith(sessionId) @@ -1176,7 +1228,7 @@ describe('ChatInput file mentions', () => { }) it('keeps the controls row below the input box so a multiline caret cannot render behind it', async () => { - render() + render() await waitFor(() => { expect(mocks.getGitInfo).toHaveBeenCalledWith(sessionId) @@ -1196,7 +1248,7 @@ describe('ChatInput file mentions', () => { }) it('replaces the composer with the provider card and keeps the draft', async () => { - render() + render() fireEvent.change(screen.getByRole('textbox'), { target: { value: 'unsent draft', selectionStart: 12 }, @@ -1248,7 +1300,7 @@ describe('ChatInput file mentions', () => { }, }) - render() + render() await waitFor(() => { expect(mocks.getGitInfo).toHaveBeenCalledWith(sessionId) diff --git a/desktop/src/components/chat/ChatInput.tsx b/desktop/src/components/chat/ChatInput.tsx index 405bc040..f2caaa3a 100644 --- a/desktop/src/components/chat/ChatInput.tsx +++ b/desktop/src/components/chat/ChatInput.tsx @@ -62,8 +62,10 @@ type GitInfo = SessionGitInfo type Attachment = ComposerAttachment type ChatInputProps = { + sessionId: string variant?: 'default' | 'hero' compact?: boolean + primary?: boolean } const EMPTY_WORKSPACE_REFERENCES: WorkspaceChatReference[] = [] @@ -106,7 +108,7 @@ function insertComposerTokenAtRange(value: string, start: number, end: number, t } } -export function ChatInput({ variant = 'default', compact = false }: ChatInputProps) { +export function ChatInput({ sessionId, variant = 'default', compact = false, primary = true }: ChatInputProps) { const t = useTranslation() const isMobileComposer = useMobileViewport() && !isDesktopRuntime() const [input, setInput] = useState('') @@ -128,12 +130,12 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro const [noticeSlot, setNoticeSlot] = useState(null) const composingRef = useRef(false) const textareaRef = useRef(null) - useTypeToFocus(textareaRef, !isMobileComposer) + useTypeToFocus(textareaRef, primary && !isMobileComposer) const panelRef = useRef(null) const fileInputRef = useRef(null) const fileSearchRef = useRef(null) const slashItemRefs = useRef<(HTMLButtonElement | null)[]>([]) - const previousActiveTabIdRef = useRef(null) + const previousSessionIdRef = useRef(null) const inputRef = useRef(input) const attachmentsRef = useRef(attachments) const setComposerInput = useCallback((value: string) => { @@ -151,54 +153,53 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro const stopGeneration = useChatStore((s) => s.stopGeneration) const clearComposerInsertion = useChatStore((s) => s.clearComposerInsertion) const setSessionPermissionMode = useChatStore((s) => s.setSessionPermissionMode) - const activeTabId = useTabStore((s) => s.activeTabId) - const chatState = useSessionField(activeTabId, 'chatState') ?? 'idle' - const slashCommands = useSessionField(activeTabId, 'slashCommands') ?? EMPTY_SLASH_COMMANDS - const composerPrefill = useSessionField(activeTabId, 'composerPrefill') ?? null - const composerInsertion = useSessionField(activeTabId, 'composerInsertion') ?? null + const chatState = useSessionField(sessionId, 'chatState') ?? 'idle' + const slashCommands = useSessionField(sessionId, 'slashCommands') ?? EMPTY_SLASH_COMMANDS + const composerPrefill = useSessionField(sessionId, 'composerPrefill') ?? null + const composerInsertion = useSessionField(sessionId, 'composerInsertion') ?? null const defaultPermissionMode = useSettingsStore((s) => s.permissionMode) - const permissionMode = useSessionField(activeTabId, 'permissionMode') ?? defaultPermissionMode + const permissionMode = useSessionField(sessionId, 'permissionMode') ?? defaultPermissionMode const effectivePermissionMode = useChatStore((s) => - activeTabId ? s.sessions[activeTabId]?.mirror?.permission.effective ?? undefined : undefined, + s.sessions[sessionId]?.mirror?.permission.effective ?? undefined, ) - const runtimeSelection = useSessionRuntimeSelection(activeTabId) + const runtimeSelection = useSessionRuntimeSelection(sessionId) const currentModel = useSettingsStore((state) => state.currentModel) const runtimeSelectionKey = runtimeSelection ? `${runtimeSelection.providerId ?? 'none'}:${runtimeSelection.modelId}` : undefined const providerMissing = useProviderMissing(runtimeSelection) const runtimeModelLabel = runtimeSelection?.modelId || currentModel?.name || currentModel?.id - const activeSession = useSessionStore((state) => activeTabId ? state.sessions.find((session) => session.id === activeTabId) ?? null : null) - const loadedMessageCount = useChatStore((s) => activeTabId ? s.sessions[activeTabId]?.messages?.length ?? 0 : 0) + const activeSession = useSessionStore((state) => state.sessions.find((session) => session.id === sessionId) ?? null) + const loadedMessageCount = useChatStore((s) => s.sessions[sessionId]?.messages?.length ?? 0) const messageCount = Math.max(loadedMessageCount, activeSession?.messageCount ?? 0) - const memberInfo = useTeamStore((s) => activeTabId ? s.getMemberBySessionId(activeTabId) : null) + const memberInfo = useTeamStore((s) => s.getMemberBySessionId(sessionId)) const [gitInfo, setGitInfo] = useState(null) const workspaceReferences = useWorkspaceChatContextStore( - (s) => activeTabId ? s.referencesBySession[activeTabId] ?? EMPTY_WORKSPACE_REFERENCES : EMPTY_WORKSPACE_REFERENCES, + (s) => s.referencesBySession[sessionId] ?? EMPTY_WORKSPACE_REFERENCES, ) const addWorkspaceReference = useWorkspaceChatContextStore((s) => s.addReference) const removeWorkspaceReference = useWorkspaceChatContextStore((s) => s.removeReference) const clearWorkspaceReferences = useWorkspaceChatContextStore((s) => s.clearReferences) - const saveComposerDraft = useCallback((sessionId: string) => { + const saveComposerDraft = useCallback((draftSessionId: string) => { const draft = { input: inputRef.current, attachments: attachmentsRef.current, } const chatStore = useChatStore.getState() if (draft.input.length === 0 && draft.attachments.length === 0) { - chatStore.clearComposerDraft(sessionId) + chatStore.clearComposerDraft(draftSessionId) return } - chatStore.setComposerDraft(sessionId, draft) + chatStore.setComposerDraft(draftSessionId, draft) }, []) const isMemberSession = !!memberInfo const isActive = chatState !== 'idle' const isWorkspaceMissing = activeSession?.workDirExists === false const hasWorkspaceReferences = !isMemberSession && workspaceReferences.length > 0 - const isHeroComposer = variant === 'hero' && !isMemberSession && !compact + const isHeroComposer = variant === 'hero' && primary && !isMemberSession && !compact const resolvedWorkDir = activeSession?.workDir || gitInfo?.workDir || undefined - const showLaunchControls = !isMemberSession && messageCount === 0 + const showLaunchControls = primary && !isMemberSession && messageCount === 0 const useCompactControls = compact || isMobileComposer const activeLaunchWorkDir = showLaunchControls ? (launchWorkDir || resolvedWorkDir || '') : (resolvedWorkDir || '') const pendingSlashUiAction = !isMemberSession && input.trim().startsWith('/') @@ -227,15 +228,15 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro }, [attachments]) useEffect(() => { - const previousActiveTabId = previousActiveTabIdRef.current + const previousSessionId = previousSessionIdRef.current - if (previousActiveTabId === activeTabId) return + if (previousSessionId === sessionId) return - if (previousActiveTabId) { - saveComposerDraft(previousActiveTabId) + if (previousSessionId) { + saveComposerDraft(previousSessionId) } - const nextDraft = activeTabId ? useChatStore.getState().sessions[activeTabId]?.composerDraft : undefined + const nextDraft = useChatStore.getState().sessions[sessionId]?.composerDraft setComposerInput(nextDraft?.input ?? '') setComposerAttachments(nextDraft?.attachments ?? []) setPlusMenuOpen(false) @@ -246,19 +247,19 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro setAtFilter('') setAtCursorPos(-1) setLaunchError(null) - previousActiveTabIdRef.current = activeTabId - }, [activeTabId, saveComposerDraft, setComposerAttachments, setComposerInput]) + previousSessionIdRef.current = sessionId + }, [sessionId, saveComposerDraft, setComposerAttachments, setComposerInput]) useEffect(() => { return () => { - const currentActiveTabId = previousActiveTabIdRef.current - if (currentActiveTabId) saveComposerDraft(currentActiveTabId) + const currentSessionId = previousSessionIdRef.current + if (currentSessionId) saveComposerDraft(currentSessionId) } }, [saveComposerDraft]) useEffect(() => { - textareaRef.current?.focus() - }, [isActive]) + if (primary) textareaRef.current?.focus() + }, [isActive, primary]) useEffect(() => { if (!composerPrefill) return @@ -292,7 +293,7 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro }, [composerPrefill, setComposerAttachments, setComposerInput]) useEffect(() => { - if (!composerInsertion || !activeTabId || isMemberSession) return + if (!composerInsertion || isMemberSession) return const el = textareaRef.current const currentInput = inputRef.current @@ -301,21 +302,21 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro const next = insertComposerTokenAtRange(currentInput, start, end, composerInsertion.text) if (composerInsertion.reference) { - addWorkspaceReference(activeTabId, composerInsertion.reference) + addWorkspaceReference(sessionId, composerInsertion.reference) } setComposerInput(next.value) setFileSearchOpen(false) setSlashMenuOpen(false) setAtFilter('') setAtCursorPos(-1) - clearComposerInsertion(activeTabId, composerInsertion.nonce) + clearComposerInsertion(sessionId, composerInsertion.nonce) requestAnimationFrame(() => { textareaRef.current?.focus() textareaRef.current?.setSelectionRange(next.cursorPos, next.cursorPos) }) }, [ - activeTabId, + sessionId, addWorkspaceReference, clearComposerInsertion, composerInsertion, @@ -324,26 +325,22 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro ]) const refreshGitInfo = useCallback(() => { - if (!activeTabId) { - setGitInfo(null) - return - } if (isMemberSession) { setGitInfo(null) return } - sessionsApi.getGitInfo(activeTabId).then(setGitInfo).catch(() => setGitInfo(null)) - }, [activeTabId, isMemberSession]) + sessionsApi.getGitInfo(sessionId).then(setGitInfo).catch(() => setGitInfo(null)) + }, [sessionId, isMemberSession]) useEffect(() => { refreshGitInfo() }, [refreshGitInfo]) useEffect(() => { - if (!activeTabId || isMemberSession || messageCount === 0) return + if (isMemberSession || messageCount === 0) return const timeout = setTimeout(refreshGitInfo, chatState === 'idle' ? 0 : 500) return () => clearTimeout(timeout) - }, [activeTabId, chatState, isMemberSession, messageCount, refreshGitInfo, slashCommandCount]) + }, [sessionId, chatState, isMemberSession, messageCount, refreshGitInfo, slashCommandCount]) useEffect(() => { if (!isMemberSession) return @@ -351,7 +348,7 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro setPlusMenuOpen(false) setSlashMenuOpen(false) setFileSearchOpen(false) - }, [isMemberSession, activeTabId]) + }, [isMemberSession, sessionId]) useEffect(() => { if (!showLaunchControls) return @@ -363,7 +360,7 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro setLaunchReady(!nextWorkDir) return nextWorkDir }) - }, [activeSession?.workDir, activeTabId, gitInfo?.workDir, showLaunchControls]) + }, [activeSession?.workDir, sessionId, gitInfo?.workDir, showLaunchControls]) useEffect(() => { resizeComposerTextarea(textareaRef.current) @@ -475,8 +472,7 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro workDir: string, repository?: { branch?: string | null; worktree?: boolean }, ) => { - if (!activeTabId) return null - const oldId = activeTabId + const oldId = sessionId const { createSession, deleteSession } = useSessionStore.getState() const { replaceTabSession } = useTabStore.getState() const { disconnectSession, connectToSession, sessions } = useChatStore.getState() @@ -492,7 +488,7 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro connectToSession(newId) deleteSession(oldId).catch(() => {}) return newId - }, [activeTabId]) + }, [sessionId]) const handleLaunchWorkDirChange = useCallback(async (newWorkDir: string) => { setLaunchWorkDir(newWorkDir) @@ -500,7 +496,6 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro setLaunchUseWorktree(false) setLaunchReady(!newWorkDir) setLaunchError(null) - if (!activeTabId) return setLaunchTransitioning(true) try { @@ -513,7 +508,7 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro } finally { setLaunchTransitioning(false) } - }, [activeTabId, replaceEmptySession, t]) + }, [replaceEmptySession, t]) const handleSubmit = async () => { const text = input.trim() @@ -553,9 +548,9 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro if (hasWorkspaceReferences && blockedByPendingPick(workspaceReferences)) return if (hasWorkspaceReferences && workspaceReferences.some((reference) => reference.browser?.element)) { - await refreshBrowserMarksBeforeSend(activeTabId!) + await refreshBrowserMarksBeforeSend(sessionId) } - const references = useWorkspaceChatContextStore.getState().referencesBySession[activeTabId!] ?? EMPTY_WORKSPACE_REFERENCES + const references = useWorkspaceChatContextStore.getState().referencesBySession[sessionId] ?? EMPTY_WORKSPACE_REFERENCES if (blockedByPendingPick(references)) return const workspaceReferencePrompt = !isMemberSession @@ -615,7 +610,7 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro }), ] - let targetSessionId = activeTabId! + let targetSessionId = sessionId if (showLaunchControls && activeLaunchWorkDir && launchBranch) { const shouldReplaceForRepositoryLaunch = launchUseWorktree || @@ -652,11 +647,11 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro }) setComposerInput('') setComposerAttachments([]) - useChatStore.getState().clearComposerDraft(activeTabId!) - if (targetSessionId !== activeTabId) useChatStore.getState().clearComposerDraft(targetSessionId) + useChatStore.getState().clearComposerDraft(sessionId) + if (targetSessionId !== sessionId) useChatStore.getState().clearComposerDraft(targetSessionId) if (!isMemberSession) { - clearWorkspaceReferences(activeTabId!) - if (targetSessionId !== activeTabId) clearWorkspaceReferences(targetSessionId) + clearWorkspaceReferences(sessionId) + if (targetSessionId !== sessionId) clearWorkspaceReferences(targetSessionId) } setPlusMenuOpen(false) setSlashMenuOpen(false) @@ -798,7 +793,7 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro const removeAttachment = (id: string) => { setComposerAttachments((prev) => prev.filter((attachment) => attachment.id !== id)) - if (activeTabId) removeWorkspaceReference(activeTabId, id) + removeWorkspaceReference(sessionId, id) } const insertSlashCommand = () => { @@ -870,15 +865,13 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro const spacer = beforeToken && afterToken && !/\s$/.test(beforeToken) && !/^\s/.test(afterToken) ? ' ' : '' const newValue = `${beforeToken}${spacer}${afterToken}` const newCursorPos = atCursorPos + spacer.length - if (activeTabId) { - addWorkspaceReference(activeTabId, { - kind: 'file', - path, - absolutePath: path, - name: isDirectory ? `${referenceName}/` : referenceName, - isDirectory, - }) - } + addWorkspaceReference(sessionId, { + kind: 'file', + path, + absolutePath: path, + name: isDirectory ? `${referenceName}/` : referenceName, + isDirectory, + }) setComposerInput(newValue) setFileSearchOpen(false) setAtFilter('') @@ -895,7 +888,7 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro {!isMemberSession && localSlashPanel && ( setLocalSlashPanel(null)}> setLocalSlashPanel(null)} @@ -1022,7 +1015,7 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro action={{ mode: isStopAction ? 'stop' : 'send', disabled: isStopAction ? false : !canSubmit, - onClick: isStopAction ? () => stopGeneration(activeTabId!) : () => { void handleSubmit() }, + onClick: isStopAction ? () => stopGeneration(sessionId) : () => { void handleSubmit() }, label: actionLabel, title: isStopAction ? t('chat.stopTitle') : actionLabel, }} @@ -1060,20 +1053,21 @@ export function ChatInput({ variant = 'default', compact = false }: ChatInputPro /> )} { - if (activeTabId) setSessionPermissionMode(activeTabId, mode) + setSessionPermissionMode(sessionId, mode) }} /> )} - right={activeTabId ? ( + right={( <> - + - ) : null} + )} /> )}
diff --git a/desktop/src/components/chat/MessageList.test.tsx b/desktop/src/components/chat/MessageList.test.tsx index a853195d..63cab834 100644 --- a/desktop/src/components/chat/MessageList.test.tsx +++ b/desktop/src/components/chat/MessageList.test.tsx @@ -144,7 +144,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() expect(screen.getByText('assistant transcript line 219')).toBeTruthy() expect(screen.queryByText('assistant transcript line 0')).toBeNull() @@ -175,7 +175,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const renderItems = container.querySelectorAll('.chat-render-item') expect(renderItems).toHaveLength(2) @@ -195,7 +195,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const column = container.querySelector('.chat-render-item')?.parentElement expect(column?.className).toContain('shrink-0') expect(column?.className).toContain('w-full') @@ -225,7 +225,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() expect(container.querySelector('[data-virtual-message-item]')).not.toBeNull() expect(screen.getByText('latest assistant reply')).toBeTruthy() @@ -417,7 +417,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.getByText('Goal set')).toBeTruthy() expect(screen.getByText('Objective: ship the smoke test')).toBeTruthy() @@ -442,7 +442,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.getByText('Goal set')).toBeTruthy() expect(screen.getByText('Objective: ship the replacement target')).toBeTruthy() @@ -490,7 +490,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const card = screen.getByTestId('background-task-event-card') expect(card.textContent).toContain('Background command') @@ -522,7 +522,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const card = screen.getByTestId('background-task-event-card') expect(card.getAttribute('data-status')).toBe('stopped') @@ -565,7 +565,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const cards = screen.getAllByTestId('background-task-event-card') expect(cards).toHaveLength(2) @@ -595,7 +595,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.queryByTestId('background-task-event-card')).toBeNull() expect(screen.queryByText('local_agent')).toBeNull() @@ -615,7 +615,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scrollArea = container.querySelector('.chat-scroll-area') as HTMLElement Object.defineProperty(scrollArea, 'clientHeight', { configurable: true, value: 500 }) Object.defineProperty(scrollArea, 'scrollHeight', { configurable: true, value: 220 * 112 }) @@ -663,7 +663,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scrollArea = container.querySelector('.chat-scroll-area') as HTMLElement Object.defineProperty(scrollArea, 'clientHeight', { configurable: true, value: 500 }) Object.defineProperty(scrollArea, 'scrollHeight', { configurable: true, value: 222 * 112 }) @@ -696,7 +696,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scrollArea = container.querySelector('.chat-scroll-area') as HTMLElement Object.defineProperty(scrollArea, 'clientHeight', { configurable: true, value: 500 }) Object.defineProperty(scrollArea, 'scrollHeight', { configurable: true, value: 240 * 200 }) @@ -758,7 +758,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() expect(screen.getAllByText('Running').length).toBeGreaterThan(0) expect(screen.getByText(/Read .*example\.ts.*done/i)).toBeTruthy() @@ -775,7 +775,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const divider = screen.getByTestId('compact-status-divider') expect(within(divider).getByText('Compacting context')).toBeTruthy() @@ -799,7 +799,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.getByTestId('api-retry-indicator')).toBeTruthy() expect(screen.getByText('Request failed, retrying')).toBeTruthy() @@ -827,7 +827,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const divider = screen.getByTestId('compact-status-divider') expect(within(divider).getByText('Context automatically compacted')).toBeTruthy() @@ -893,7 +893,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const groupSummary = screen.getByText('TaskUpdate (1), ran a command') const groupButton = groupSummary.closest('button') @@ -934,7 +934,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() expect(container.querySelectorAll('[data-message-shell="assistant"]')).toHaveLength(0) }) @@ -1307,7 +1307,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.getByText('Failed')).toBeTruthy() expect(screen.getByText('Explore agent unavailable in this session')).toBeTruthy() @@ -1350,7 +1350,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.getByText('Done')).toBeTruthy() expect(screen.getByRole('button', { name: 'View result' })).toBeTruthy() @@ -1391,7 +1391,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.getAllByText('Running').length).toBeGreaterThan(0) expect(screen.queryByText('Done')).toBeNull() @@ -1436,7 +1436,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.getByText('Done')).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: 'View result' })) @@ -1490,7 +1490,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.getByText(/最终报告应该按 Markdown 展示。/)).toBeTruthy() expect(screen.queryByText(/raw structured JSON should not be shown/)).toBeNull() @@ -1553,7 +1553,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.getByText(/git:v0\.2\.6\.\.v0\.2\.7:0/)).toBeTruthy() expect(screen.queryByText(/\{"results"/)).toBeNull() @@ -1602,7 +1602,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.getByRole('button', { name: 'Copy prompt' })).toBeTruthy() @@ -1629,7 +1629,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const userText = screen.getByText('Please inspect the workspace selection behavior.') await selectMessageText(userText, 'workspace selection behavior') @@ -1667,7 +1667,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const assistantText = screen.getByText(/First inspect the file tree/) await selectMessageText(assistantText, 'quote the selected lines') @@ -1699,7 +1699,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const assistantText = screen.getByText(/Clicking outside should clear/) await selectMessageText(assistantText, 'selected reply') @@ -1718,7 +1718,7 @@ describe('MessageList nested tool calls', () => { useChatStore.setState({ sessions: { [ACTIVE_TAB]: makeSessionState({ messages: [{ id: 'assistant-1', type: 'assistant_text', content: 'Reply to this selection.', timestamp: 1 }] }), } }) - render() + render() await selectMessageText(screen.getByText('Reply to this selection.'), 'this selection') const button = screen.getByRole('button', { name: 'Reply' }) await act(async () => { @@ -1752,7 +1752,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const firstText = screen.getByText(/First assistant reply/) const secondText = screen.getByText(/Second assistant reply/) @@ -1799,7 +1799,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement let scrollTop = 120 Object.defineProperty(scroller, 'scrollHeight', { configurable: true, value: 1000 }) @@ -1858,7 +1858,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement let scrollTop = 552 Object.defineProperty(scroller, 'scrollHeight', { configurable: true, value: 1000 }) @@ -1913,7 +1913,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement const readScrollHeight = vi.fn(() => { throw new Error('scrollHeight should not be read while pinning to bottom') @@ -1991,7 +1991,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement let scrollTop = 552 let scrollHeight = 1000 @@ -2075,7 +2075,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement let scrollTop = 552 let scrollHeight = 1000 @@ -2147,7 +2147,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement let scrollTop = 600 let scrollTopWriteCount = 0 @@ -2250,7 +2250,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement let scrollTop = 180 let scrollHeight = 1400 @@ -2332,7 +2332,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement let scrollTop = 260 let scrollHeight = 1800 @@ -2394,7 +2394,8 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const view = render() + const { container } = view const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement let scrollTop = 180 Object.defineProperty(scroller, 'scrollHeight', { configurable: true, value: 1200 }) @@ -2411,9 +2412,7 @@ describe('MessageList nested tool calls', () => { fireEvent.scroll(scroller) expect(screen.getByRole('button', { name: 'Latest' })).toBeTruthy() - act(() => { - useTabStore.setState({ activeTabId: 'session-b' }) - }) + view.rerender() await waitFor(() => { expect(screen.getByText('B response')).toBeTruthy() }) @@ -2422,9 +2421,7 @@ describe('MessageList nested tool calls', () => { await waitForProgrammaticScrollReset() fireEvent.scroll(scroller) - act(() => { - useTabStore.setState({ activeTabId: 'session-a' }) - }) + view.rerender() await waitFor(() => { expect(screen.getByText('A response')).toBeTruthy() }) @@ -2464,7 +2461,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container, rerender } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement Object.defineProperty(scroller, 'scrollHeight', { configurable: true, value: 1200 }) Object.defineProperty(scroller, 'clientHeight', { configurable: true, value: 400 }) @@ -2477,9 +2474,7 @@ describe('MessageList nested tool calls', () => { fireEvent.scroll(scroller) scrollIntoView.mockClear() - act(() => { - useTabStore.setState({ activeTabId: 'session-fresh' }) - }) + rerender() await waitFor(() => { expect(screen.getByText('Fresh latest response')).toBeTruthy() @@ -2512,7 +2507,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement let scrollTop = 120 Object.defineProperty(scroller, 'scrollHeight', { configurable: true, value: 1000 }) @@ -2582,7 +2577,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement let scrollTop = 120 Object.defineProperty(scroller, 'scrollHeight', { configurable: true, value: 1000 }) @@ -2657,7 +2652,7 @@ describe('MessageList nested tool calls', () => { }, }) - const { container } = render() + const { container } = render() const scroller = container.querySelector('.overflow-y-auto') as HTMLDivElement let scrollTop = 120 Object.defineProperty(scroller, 'scrollHeight', { configurable: true, value: 1000 }) @@ -2743,7 +2738,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const userShell = screen.getByText('请把这条 prompt 放在右侧').closest('[data-message-shell="user"]') const assistantShell = screen.getByText('这条回复应该停在左侧。').closest('[data-message-shell="assistant"]') @@ -2789,7 +2784,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const assistantShell = screen.getByText('交付结果').closest('[data-message-shell="assistant"]') expect(assistantShell?.getAttribute('data-layout')).toBe('document') @@ -2837,7 +2832,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(await screen.findByRole('button', { name: 'Undo current turn changes' })).toBeTruthy() expect(screen.queryByRole('button', { name: 'Rewind to here' })).toBeNull() @@ -2888,7 +2883,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const branchButtons = screen.getAllByRole('button', { name: 'Fork a new conversation' }) expect(branchButtons).toHaveLength(2) @@ -2942,7 +2937,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.queryByRole('button', { name: 'Fork a new conversation' })).toBeNull() }) @@ -2971,7 +2966,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(await screen.findByText('两个文件均已优化完成,功能保持不变。')).toBeTruthy() await waitFor(() => { @@ -3071,7 +3066,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const cards = await screen.findAllByLabelText('Turn changed files') expect(cards).toHaveLength(2) @@ -3155,7 +3150,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() fireEvent.click(await screen.findByRole('button', { name: 'Show diff for src/first.ts' })) @@ -3224,7 +3219,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() fireEvent.click(await screen.findByRole('button', { name: 'Show diff for src/first.ts' })) @@ -3289,7 +3284,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(await screen.findByText('src/live.ts')).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: 'Show diff for src/live.ts' })) @@ -3342,7 +3337,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(await screen.findByText('src/blank-response.ts')).toBeTruthy() }) @@ -3387,7 +3382,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(await screen.findByText('src/first.ts')).toBeTruthy() @@ -3510,7 +3505,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const historicalCard = (await screen.findAllByRole('region', { name: 'Turn changed files' })).find((card) => within(card).queryByText('src/first.ts')) expect(historicalCard).toBeTruthy() @@ -3609,7 +3604,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() const cards = await screen.findAllByLabelText('Turn changed files') expect(cards).toHaveLength(1) @@ -3635,7 +3630,7 @@ describe('MessageList nested tool calls', () => { }, }) - render() + render() expect(screen.getByText('Failed to start CLI process.')).toBeTruthy() expect( diff --git a/desktop/src/components/chat/MessageList.tsx b/desktop/src/components/chat/MessageList.tsx index e9967adf..b6ae08b8 100644 --- a/desktop/src/components/chat/MessageList.tsx +++ b/desktop/src/components/chat/MessageList.tsx @@ -6,7 +6,6 @@ import { sessionsApi, type SessionTurnCheckpoint } from '../../api/sessions' import { useChatStore, useSessionField } from '../../stores/chatStore' import { useSessionStore } from '../../stores/sessionStore' import { useWorkspaceChatContextStore } from '../../stores/workspaceChatContextStore' -import { useTabStore } from '../../stores/tabStore' import { openSessionTab } from '../../lib/sessionNavigation' import { useTeamStore } from '../../stores/teamStore' import { useUIStore } from '../../stores/uiStore' @@ -361,7 +360,7 @@ function SelectableChatMessage({ content, children, }: { - sessionId?: string | null + sessionId: string messageId: string role: ChatMessageRole content: string @@ -376,7 +375,7 @@ function SelectableChatMessage({ : t('chat.userMessageReference') const addCurrentSelectionToChat = () => { - if (!sessionId || !quote.selection) return + if (!quote.selection) return addReference(sessionId, { kind: 'chat-selection', path: `chat://${role}/${messageId}`, @@ -853,7 +852,7 @@ function MemoryEventCard({ message }: { message: MemoryEvent }) { } type MessageListProps = { - sessionId?: string | null + sessionId: string compact?: boolean } @@ -1268,31 +1267,29 @@ const MeasuredRenderItem = memo(function MeasuredRenderItem({ ) }) -export function MessageList({ sessionId, compact = false }: MessageListProps = {}) { - const activeTabId = useTabStore((s) => s.activeTabId) - const resolvedSessionId = sessionId ?? activeTabId +export function MessageList({ sessionId, compact = false }: MessageListProps) { const branchSession = useSessionStore((s) => s.branchSession) const stopGeneration = useChatStore((s) => s.stopGeneration) const reloadHistory = useChatStore((s) => s.reloadHistory) const queueComposerPrefill = useChatStore((s) => s.queueComposerPrefill) const isMemberSession = useTeamStore((s) => - resolvedSessionId ? Boolean(s.getMemberBySessionId(resolvedSessionId)) : false, + Boolean(s.getMemberBySessionId(sessionId)), ) const addToast = useUIStore((s) => s.addToast) - const messages = useSessionField(resolvedSessionId, 'messages') ?? EMPTY_MESSAGES - const chatState = useSessionField(resolvedSessionId, 'chatState') ?? 'idle' + const messages = useSessionField(sessionId, 'messages') ?? EMPTY_MESSAGES + const chatState = useSessionField(sessionId, 'chatState') ?? 'idle' const hasStreamingText = useChatStore((s) => { - const text = resolvedSessionId ? s.sessions[resolvedSessionId]?.streamingText : undefined + const text = s.sessions[sessionId]?.streamingText return Boolean(text && /\S/.test(text)) }) - const activeThinkingId = useSessionField(resolvedSessionId, 'activeThinkingId') ?? null - const agentTaskNotifications = useSessionField(resolvedSessionId, 'agentTaskNotifications') ?? EMPTY_AGENT_TASK_NOTIFICATIONS + const activeThinkingId = useSessionField(sessionId, 'activeThinkingId') ?? null + const agentTaskNotifications = useSessionField(sessionId, 'agentTaskNotifications') ?? EMPTY_AGENT_TASK_NOTIFICATIONS const activeAskUserQuestionToolUseId = useChatStore((s) => { - const pending = resolvedSessionId ? s.sessions[resolvedSessionId]?.pendingPermission : undefined + const pending = s.sessions[sessionId]?.pendingPermission return isInlineQuestionTool(pending?.toolName) ? pending?.toolUseId ?? null : null }) const hasActiveTool = useChatStore((s) => { - const sessionState = resolvedSessionId ? s.sessions[resolvedSessionId] : undefined + const sessionState = s.sessions[sessionId] return Boolean(sessionState?.activeToolUseId) || Boolean(sessionState?.activeToolName) }) const shouldFollowContentResize = @@ -1304,10 +1301,10 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { const scrollContainerRef = useRef(null) const scrollContentRef = useRef(null) const virtualItemHeightsRef = useRef>( - resolvedSessionId ? getHeightsForSession(resolvedSessionId) : new Map(), + getHeightsForSession(sessionId), ) const virtualItemMetricCacheRef = useRef>( - resolvedSessionId ? getMetricsForSession(resolvedSessionId) : new Map(), + getMetricsForSession(sessionId), ) const pendingMeasuredHeightsRef = useRef(false) const measureFlushFrameRef = useRef(null) @@ -1322,7 +1319,7 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { const isProgrammaticScrollingRef = useRef(false) const ignoreProgrammaticScrollUntilRef = useRef(0) const ignoreProgrammaticScrollTopRef = useRef(null) - const lastSessionIdRef = useRef(resolvedSessionId) + const lastSessionIdRef = useRef(sessionId) const lastTailMessageIdBySessionRef = useRef(new Map()) const t = useTranslation() const [turnChangeCards, setTurnChangeCards] = useState([]) @@ -1390,8 +1387,8 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { scrollTop: SCROLL_BOTTOM_SENTINEL, viewportHeight: current.viewportHeight, })) - if (container && resolvedSessionId) { - sessionScrollSnapshots.set(resolvedSessionId, { + if (container && sessionId) { + sessionScrollSnapshots.set(sessionId, { scrollTop: container.scrollTop, wasAtBottom: true, }) @@ -1408,16 +1405,14 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { ) ) { setScrollToBottomWithoutLayoutRead(latestContainer, 'auto') - if (resolvedSessionId) { - sessionScrollSnapshots.set(resolvedSessionId, { - scrollTop: latestContainer.scrollTop, - wasAtBottom: true, - }) - } + sessionScrollSnapshots.set(sessionId, { + scrollTop: latestContainer.scrollTop, + wasAtBottom: true, + }) } isProgrammaticScrollingRef.current = false }) - }, [resolvedSessionId]) + }, [sessionId]) const scheduleStickToBottom = useCallback(() => { if (!shouldAutoScrollRef.current) { @@ -1438,14 +1433,12 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { ? current : { scrollTop: SCROLL_BOTTOM_SENTINEL, viewportHeight: current.viewportHeight }) } - if (resolvedSessionId) { - sessionScrollSnapshots.set(resolvedSessionId, { - scrollTop: container.scrollTop, - wasAtBottom: true, - }) - } + sessionScrollSnapshots.set(sessionId, { + scrollTop: container.scrollTop, + wasAtBottom: true, + }) }) - }, [resolvedSessionId]) + }, [sessionId]) const flushMeasuredHeightVersion = useCallback(() => { if (!pendingMeasuredHeightsRef.current) return @@ -1491,21 +1484,19 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { shouldAutoScrollRef.current = isAtBottom setShowJumpToLatest(!isAtBottom) - if (resolvedSessionId) { - rememberSessionScroll(resolvedSessionId, container) - } - }, [resolvedSessionId, syncVirtualViewportFromContainer]) + rememberSessionScroll(sessionId, container) + }, [sessionId, syncVirtualViewportFromContainer]) useLayoutEffect(() => { - if (lastSessionIdRef.current !== resolvedSessionId) { - const snapshot = resolvedSessionId ? sessionScrollSnapshots.get(resolvedSessionId) : undefined + if (lastSessionIdRef.current !== sessionId) { + const snapshot = sessionScrollSnapshots.get(sessionId) shouldAutoScrollRef.current = snapshot?.wasAtBottom ?? true - lastSessionIdRef.current = resolvedSessionId - virtualItemHeightsRef.current = resolvedSessionId - ? getHeightsForSession(resolvedSessionId) + lastSessionIdRef.current = sessionId + virtualItemHeightsRef.current = sessionId + ? getHeightsForSession(sessionId) : new Map() - virtualItemMetricCacheRef.current = resolvedSessionId - ? getMetricsForSession(resolvedSessionId) + virtualItemMetricCacheRef.current = sessionId + ? getMetricsForSession(sessionId) : new Map() pendingMeasuredHeightsRef.current = false lastContentResizeFollowHeightRef.current = null @@ -1536,33 +1527,29 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { viewportHeight: container.clientHeight || current.viewportHeight || VIRTUAL_DEFAULT_VIEWPORT_HEIGHT, })) setShowJumpToLatest(false) - if (resolvedSessionId) { - sessionScrollSnapshots.set(resolvedSessionId, { - scrollTop: container.scrollTop, - wasAtBottom: true, - }) - } + sessionScrollSnapshots.set(sessionId, { + scrollTop: container.scrollTop, + wasAtBottom: true, + }) } else { scrollToBottom('auto') } } - }, [resolvedSessionId, scrollToBottom]) + }, [sessionId, scrollToBottom]) const tailMessage = messages[messages.length - 1] ?? null const tailMessageId = tailMessage?.id ?? null const tailMessageType = tailMessage?.type ?? null useEffect(() => { - if (!resolvedSessionId) return - - const previousTailMessageId = lastTailMessageIdBySessionRef.current.get(resolvedSessionId) - lastTailMessageIdBySessionRef.current.set(resolvedSessionId, tailMessageId) + const previousTailMessageId = lastTailMessageIdBySessionRef.current.get(sessionId) + lastTailMessageIdBySessionRef.current.set(sessionId, tailMessageId) if (previousTailMessageId === undefined || previousTailMessageId === tailMessageId) return if (tailMessageType === 'user_text') { scrollToBottom('auto') } - }, [resolvedSessionId, scrollToBottom, tailMessageId, tailMessageType]) + }, [sessionId, scrollToBottom, tailMessageId, tailMessageType]) useEffect(() => { if (!shouldAutoScrollRef.current) { @@ -1571,7 +1558,7 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { } scrollToBottom('auto') - }, [messages.length, resolvedSessionId, scrollToBottom]) + }, [messages.length, sessionId, scrollToBottom]) const handleJumpToLatest = useCallback(() => { scrollToBottom('auto') @@ -1703,7 +1690,7 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { }, [renderItemKeys]) useEffect(() => { - if (!resolvedSessionId || completedTurnTargets.length === 0 || isMemberSession) { + if (completedTurnTargets.length === 0 || isMemberSession) { setTurnChangeCards([]) setTurnChangeLoadError(null) setIsLoadingTurnChangeCards(false) @@ -1721,8 +1708,8 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { setTurnChangeLoadError(null) Promise.all([ - sessionsApi.getTurnCheckpoints(resolvedSessionId), - sessionsApi.getWorkspaceStatus(resolvedSessionId).catch(() => null), + sessionsApi.getTurnCheckpoints(sessionId), + sessionsApi.getWorkspaceStatus(sessionId).catch(() => null), ]) .then(([checkpointResponse, workspaceStatus]) => { if (cancelled) return @@ -1764,10 +1751,10 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { return () => { cancelled = true } - }, [chatState, completedTurnTargets, isMemberSession, latestCompletedTurnId, resolvedSessionId]) + }, [chatState, completedTurnTargets, isMemberSession, latestCompletedTurnId, sessionId]) const handleUndoCurrentTurn = useCallback(async () => { - if (!resolvedSessionId || !confirmTurnCard || rewindingTurnId) return + if (!confirmTurnCard || rewindingTurnId) return const target = confirmTurnCard.target setRewindingTurnId(target.messageId) @@ -1780,17 +1767,17 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { try { if (chatState !== 'idle') { - stopGeneration(resolvedSessionId) + stopGeneration(sessionId) } - const result = await sessionsApi.rewind(resolvedSessionId, { + const result = await sessionsApi.rewind(sessionId, { targetUserMessageId: target.messageId, userMessageIndex: target.userMessageIndex, expectedContent: target.expectedContent, }) - await reloadHistory(resolvedSessionId) - queueComposerPrefill(resolvedSessionId, { + await reloadHistory(sessionId) + queueComposerPrefill(sessionId, { text: target.content, attachments: target.attachments, }) @@ -1822,18 +1809,18 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { confirmTurnCard, queueComposerPrefill, reloadHistory, - resolvedSessionId, + sessionId, rewindingTurnId, stopGeneration, t, ]) const handleBranchMessage = useCallback(async (target: BranchableMessageTarget) => { - if (!resolvedSessionId || branchingMessageId) return + if (branchingMessageId) return setBranchingMessageId(target.uiMessageId) try { - const result = await branchSession(resolvedSessionId, target.transcriptMessageId) + const result = await branchSession(sessionId, target.transcriptMessageId) const title = result.title.trim() || t('sidebar.newSession') openSessionTab(result.sessionId, title) addToast({ @@ -1848,7 +1835,7 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { } finally { setBranchingMessageId(null) } - }, [addToast, branchSession, branchingMessageId, resolvedSessionId, t]) + }, [addToast, branchSession, branchingMessageId, sessionId, t]) const branchActionByMessageId = useMemo(() => { if (branchableMessageTargets.size === 0) { @@ -1886,7 +1873,7 @@ export function MessageList({ sessionId, compact = false }: MessageListProps = { /> ) : ( )} - {resolvedSessionId && cardsForItem.map((card) => ( + {cardsForItem.map((card) => ( ) : null} - + - + {chatState === 'compacting' && !hasCompactingDivider && ( )} {(chatState === 'tool_executing' || (chatState === 'thinking' && !activeThinkingId)) && ( - + )} {!isLoadingTurnChangeCards && turnChangeCards.length === 0 && turnChangeLoadError && ( @@ -2029,7 +2016,7 @@ export const MessageBlock = memo(function MessageBlock({ branchAction, replyCopyText, }: { - sessionId?: string | null + sessionId: string message: UIMessage activeThinkingId: string | null agentTaskNotifications: Record @@ -2081,7 +2068,7 @@ export const MessageBlock = memo(function MessageBlock({ case 'thinking': return case 'tool_use': - if (message.toolName === CHOOSE_DESIGN_TEMPLATE_TOOL && sessionId && !message.isPending) { + if (message.toolName === CHOOSE_DESIGN_TEMPLATE_TOOL && !message.isPending) { return ( ) } - if (message.toolName === 'ShowUI' && sessionId) { + if (message.toolName === 'ShowUI') { return } return ( diff --git a/desktop/src/components/chat/PermissionDialog.tsx b/desktop/src/components/chat/PermissionDialog.tsx index f8681d80..ff3a3a19 100644 --- a/desktop/src/components/chat/PermissionDialog.tsx +++ b/desktop/src/components/chat/PermissionDialog.tsx @@ -7,7 +7,6 @@ import { useState, type ReactNode } from 'react' import { useChatStore } from '../../stores/chatStore' import { boardForProject, useKanbanStore } from '../../stores/kanbanStore' import { useSessionStore } from '../../stores/sessionStore' -import { useTabStore } from '../../stores/tabStore' import { useTranslation } from '../../i18n' import type { TranslationKey } from '../../i18n' import { Button } from '../shared/ui/button' @@ -17,7 +16,7 @@ import { getCuaToolDisplay } from '../../lib/cuaToolDisplay' import type { PermissionResolution } from '../../types/chat' type Props = { - sessionId?: string | null + sessionId: string requestId: string toolName: string input: unknown @@ -204,14 +203,12 @@ function resolutionLabelKey(resolution: PermissionResolution | undefined): Trans export function PermissionDialog({ sessionId, requestId, toolName, input, description, alwaysAsks, resolution }: Props) { const respondToPermission = useChatStore((s) => s.respondToPermission) - const activeTabId = useTabStore((s) => s.activeTabId) - const targetSessionId = sessionId ?? activeTabId const isPending = useChatStore((s) => - targetSessionId ? s.sessions[targetSessionId]?.pendingPermission?.requestId === requestId : false, + s.sessions[sessionId]?.pendingPermission?.requestId === requestId, ) const t = useTranslation() const [showRaw, setShowRaw] = useState(false) - const projectRoot = useSessionStore((s) => s.sessions.find((session) => session.id === targetSessionId)?.projectRoot) + const projectRoot = useSessionStore((s) => s.sessions.find((session) => session.id === sessionId)?.projectRoot) const assign = kanbanAssign(toolName, input) const cancel = kanbanCancel(toolName, input) const acceptance = kanbanAcceptance(toolName, input) @@ -324,7 +321,7 @@ export function PermissionDialog({ sessionId, requestId, toolName, input, descri
} + {allCompleted && }
diff --git a/desktop/src/components/chat/StreamingIndicator.test.tsx b/desktop/src/components/chat/StreamingIndicator.test.tsx index 50f0caa5..1532a3ca 100644 --- a/desktop/src/components/chat/StreamingIndicator.test.tsx +++ b/desktop/src/components/chat/StreamingIndicator.test.tsx @@ -91,7 +91,7 @@ describe('StreamingIndicator elapsed time', () => { }) it('counts from the turn start the server reported and ticks every second', () => { - render() + render() expect(screen.getByText('1m 5s')).toBeInTheDocument() act(() => { @@ -101,15 +101,15 @@ describe('StreamingIndicator elapsed time', () => { }) it('shows the time of the session switched to', () => { - render() - showTab('b') + const view = render() + view.rerender() expect(screen.getByText('3s')).toBeInTheDocument() expect(screen.queryByText('1m 5s')).not.toBeInTheDocument() }) it('keeps counting from the same start after a reconnect snapshot', () => { - render() + render() act(() => { vi.advanceTimersByTime(2000) useChatStore.setState({ @@ -125,7 +125,7 @@ describe('StreamingIndicator elapsed time', () => { it('shows no time when the server has not started a turn', () => { useChatStore.setState({ sessions: { a: sessionWithTurn('a', { phase: 'idle' }) } }) - render() + render() act(() => { vi.advanceTimersByTime(5000) diff --git a/desktop/src/components/chat/StreamingIndicator.tsx b/desktop/src/components/chat/StreamingIndicator.tsx index 1575ee25..3e942a0b 100644 --- a/desktop/src/components/chat/StreamingIndicator.tsx +++ b/desktop/src/components/chat/StreamingIndicator.tsx @@ -2,7 +2,6 @@ import { Tooltip as HintTooltip } from '../shared/Tooltip' import { useEffect, useState } from 'react' import { RefreshCw } from 'lucide-react' import { useChatStore, useSessionField } from '../../stores/chatStore' -import { useTabStore } from '../../stores/tabStore' import { useTranslation, type TranslationKey } from '../../i18n' import { ElapsedTime } from './ElapsedTime' @@ -27,18 +26,17 @@ function formatErrorType(errorType: string | undefined): string | null { .trim() } -export function StreamingIndicator() { +export function StreamingIndicator({ sessionId }: { sessionId: string }) { const t = useTranslation() const [now, setNow] = useState(() => Date.now()) - const activeTabId = useTabStore((s) => s.activeTabId) - const chatState = useSessionField(activeTabId, 'chatState') ?? 'idle' - const statusVerb = useSessionField(activeTabId, 'statusVerb') ?? '' - const apiRetry = useSessionField(activeTabId, 'apiRetry') ?? null + const chatState = useSessionField(sessionId, 'chatState') ?? 'idle' + const statusVerb = useSessionField(sessionId, 'statusVerb') ?? '' + const apiRetry = useSessionField(sessionId, 'apiRetry') ?? null const turnStartedAt = useChatStore((s) => { - const turn = activeTabId ? s.sessions[activeTabId]?.mirror?.turn : undefined + const turn = s.sessions[sessionId]?.mirror?.turn return turn && turn.phase !== 'idle' ? turn.startedAt : undefined }) - const outputTokens = useChatStore((s) => activeTabId ? s.sessions[activeTabId]?.tokenUsage?.output_tokens ?? 0 : 0) + const outputTokens = useChatStore((s) => s.sessions[sessionId]?.tokenUsage?.output_tokens ?? 0) useEffect(() => { if (!apiRetry) return undefined diff --git a/desktop/src/components/chat/chatBlocks.test.tsx b/desktop/src/components/chat/chatBlocks.test.tsx index a496a544..0035ae52 100644 --- a/desktop/src/components/chat/chatBlocks.test.tsx +++ b/desktop/src/components/chat/chatBlocks.test.tsx @@ -226,6 +226,7 @@ describe('chat blocks', () => { await act(async () => { container = render( { await act(async () => { container = render( { it('uses the generic Computer Use permission title for click', async () => { let container!: HTMLElement await act(async () => { - container = render().container + container = render().container await Promise.resolve() }) expect(container.textContent).toContain('Allow Computer Use to click?') diff --git a/desktop/src/components/chat/streamingRenderCounts.test.tsx b/desktop/src/components/chat/streamingRenderCounts.test.tsx index 0a488707..0e79402b 100644 --- a/desktop/src/components/chat/streamingRenderCounts.test.tsx +++ b/desktop/src/components/chat/streamingRenderCounts.test.tsx @@ -120,8 +120,8 @@ describe('render counts during one streaming reply', () => { it('re-renders each component only when the fields it shows change', () => { render( <> - - + + @@ -169,7 +169,7 @@ describe('components still update on the fields they use', () => { }) it('ChatInput follows permissionMode, the effective mode and composerPrefill', () => { - render() + render() patchSession({ permissionMode: 'plan' }) expect(screen.getByTestId('permission-mode')).toHaveAttribute('data-value', 'plan') @@ -185,7 +185,7 @@ describe('components still update on the fields they use', () => { }) it('ChatInput follows slashCommands and chatState', () => { - render() + render() patchSession({ slashCommands: [{ name: 'deploy-now', description: 'Ship it' }] }) fireEvent.change(screen.getByRole('textbox'), { target: { value: '/deploy', selectionStart: 7 } }) @@ -198,7 +198,7 @@ describe('components still update on the fields they use', () => { it('StreamingIndicator follows statusVerb, tokenUsage and apiRetry', () => { patchSession({ chatState: 'thinking' }) - render() + render() patchSession({ statusVerb: 'Pondering' }) expect(screen.getByText('Pondering...')).toBeInTheDocument() diff --git a/desktop/src/components/controls/PermissionModeSelector.test.tsx b/desktop/src/components/controls/PermissionModeSelector.test.tsx index 7aea8c17..312b9439 100644 --- a/desktop/src/components/controls/PermissionModeSelector.test.tsx +++ b/desktop/src/components/controls/PermissionModeSelector.test.tsx @@ -126,7 +126,7 @@ describe('PermissionModeSelector', () => { expect(document.getElementById(controlled!)).toBe(screen.getByRole('menu')) }) - it('uses the active tab workspace when showing the bypass confirmation path', async () => { + it('shows the workspace it is given in the bypass confirmation, not the active tab one', async () => { useSessionStore.setState({ activeSessionId: 'previous-session', sessions: [ @@ -155,11 +155,11 @@ describe('PermissionModeSelector', () => { ], }) useTabStore.setState({ - activeTabId: 'current-tab', - tabs: [{ sessionId: 'current-tab', title: 'Current', type: 'session', status: 'idle' }], + activeTabId: 'previous-session', + tabs: [{ sessionId: 'previous-session', title: 'Previous', type: 'session', status: 'idle' }], }) - renderSelector({ compact: true }) + renderSelector({ compact: true, workDir: 'C:\\Users\\LinTan\\MyScript\\test5' }) fireEvent.keyDown(screen.getByRole('button', { name: 'Manual' }), { key: 'ArrowDown' }) fireEvent.click(screen.getByRole('menuitemradio', { name: /Bypass permissions/ })) diff --git a/desktop/src/components/controls/PermissionModeSelector.tsx b/desktop/src/components/controls/PermissionModeSelector.tsx index c32e1bdd..f8412d6f 100644 --- a/desktop/src/components/controls/PermissionModeSelector.tsx +++ b/desktop/src/components/controls/PermissionModeSelector.tsx @@ -1,8 +1,6 @@ import { useState, useEffect, useCallback } from 'react' import DOMPurify from 'dompurify' import { useSettingsStore } from '../../stores/settingsStore' -import { useSessionStore } from '../../stores/sessionStore' -import { useTabStore } from '../../stores/tabStore' import { useTranslation } from '../../i18n' import { computerUseApi } from '../../api/computerUse' import type { PermissionMode } from '../../types/settings' @@ -37,8 +35,6 @@ export function PermissionModeSelector({ workDir: workDirProp, compact = false, const t = useTranslation() const isMobile = useMobileViewport() && !isDesktopRuntime() const defaultMode = useSettingsStore((s) => s.permissionMode) - const activeTabId = useTabStore((s) => s.activeTabId) - const sessions = useSessionStore((s) => s.sessions) const [open, setOpen] = useState(false) const [confirmDialog, setConfirmDialog] = useState(false) const [computerUseEnabled, setComputerUseEnabled] = useState(false) @@ -82,10 +78,7 @@ export function PermissionModeSelector({ workDir: workDirProp, compact = false, dontAsk: t('permMode.label.dontAsk'), } - const activeSession = activeTabId - ? sessions.find((s) => s.id === activeTabId) - : null - const workDir = workDirProp || activeSession?.workDir || '~' + const workDir = workDirProp || '~' const triggerSize = compact ? (isMobile ? 'icon-xl' : 'icon-sm') : 'toolbar' const CurrentIcon = MODE_ICONS[currentMode] const menuId = 'permission-mode-menu' diff --git a/desktop/src/components/layout/RenameSessionDialog.tsx b/desktop/src/components/layout/RenameSessionDialog.tsx new file mode 100644 index 00000000..3665ae36 --- /dev/null +++ b/desktop/src/components/layout/RenameSessionDialog.tsx @@ -0,0 +1,57 @@ +import { useEffect, useState } from 'react' +import { useTranslation } from '../../i18n' +import { useSessionStore } from '../../stores/sessionStore' +import { Modal } from '../shared/Modal' +import { Button } from '../shared/ui/button' +import { Input } from '../shared/ui/input' + +type RenameSessionDialogProps = { + sessionId: string + title: string + open: boolean + onClose: () => void +} + +export function RenameSessionDialog({ sessionId, title, open, onClose }: RenameSessionDialogProps) { + const t = useTranslation() + const [value, setValue] = useState(title) + + useEffect(() => { + if (open) setValue(title) + }, [open, title]) + + const submit = async () => { + const next = value.trim() + if (!next) return + await useSessionStore.getState().renameSession(sessionId, next) + onClose() + } + + return ( + + + +
+ )} + > + setValue(event.target.value)} + onKeyDown={(event) => { + if (event.key === 'Enter' && !event.nativeEvent.isComposing) void submit() + }} + /> + + ) +} diff --git a/desktop/src/components/layout/SessionHeaderMenu.tsx b/desktop/src/components/layout/SessionHeaderMenu.tsx index 6a6735f6..4fcc4849 100644 --- a/desktop/src/components/layout/SessionHeaderMenu.tsx +++ b/desktop/src/components/layout/SessionHeaderMenu.tsx @@ -8,9 +8,8 @@ import { useUIStore } from '../../stores/uiStore' import { ActionMenu, type MenuAction } from '../shared/ActionMenu' import { Button } from '../shared/ui/button' import { ConfirmDialog } from '../shared/ConfirmDialog' -import { Modal } from '../shared/Modal' -import { Input } from '../shared/ui/input' import { ExportSessionDialog } from './ExportSessionDialog' +import { RenameSessionDialog } from './RenameSessionDialog' type SessionHeaderMenuProps = { sessionId: string @@ -20,17 +19,9 @@ type SessionHeaderMenuProps = { export function SessionHeaderMenu({ sessionId, title }: SessionHeaderMenuProps) { const t = useTranslation() const [renaming, setRenaming] = useState(false) - const [renameValue, setRenameValue] = useState('') const [confirmingDelete, setConfirmingDelete] = useState(false) const [exporting, setExporting] = useState(false) - const submitRename = async () => { - const next = renameValue.trim() - if (!next) return - await useSessionStore.getState().renameSession(sessionId, next) - setRenaming(false) - } - const confirmDelete = async () => { await useSessionStore.getState().deleteSession(sessionId) useChatStore.getState().disconnectSession(sessionId) @@ -39,7 +30,7 @@ export function SessionHeaderMenu({ sessionId, title }: SessionHeaderMenuProps) } const actions: MenuAction[] = [ - { id: 'rename', label: t('common.rename'), icon: