From df83c1d72c81a61f7e6650069afbefd302314322 Mon Sep 17 00:00:00 2001 From: Diao Shengjia <104132148+GoDiao@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:48:48 +0800 Subject: [PATCH 1/5] feat(side-chat): hide inherited messages and start a side chat from selected text A side chat's page now shows only its own messages; the model still reads the whole fork. Selecting text in the main conversation offers "Start a side chat | Reply"; the first opens a new side chat with the selection quoted in its composer. --- CHANGELOG.md | 2 +- desktop/src/components/README.md | 2 +- .../src/components/chat/MessageList.test.tsx | 81 ++++++++++++++++++- desktop/src/components/chat/MessageList.tsx | 47 ++++++++--- .../components/chat/SessionConversation.tsx | 4 +- .../shared/SelectionPopover.test.tsx | 25 +++++- .../components/shared/SelectionPopover.tsx | 25 ++++-- .../workspace/WorkspacePanel.test.tsx | 22 ++++- .../components/workspace/WorkspacePanel.tsx | 18 +---- .../workspace/WorkspaceQuotePopover.tsx | 11 ++- desktop/src/i18n/locales/en.ts | 2 + desktop/src/i18n/locales/zh.ts | 2 + desktop/src/lib/sideChats.test.ts | 12 +++ desktop/src/lib/sideChats.ts | 21 +++++ desktop/src/pages/ActiveSession.test.tsx | 6 +- desktop/src/pages/ActiveSession.tsx | 1 + .../src/stores/workspacePanelStore.test.ts | 2 +- desktop/src/stores/workspacePanelStore.ts | 3 +- docs/features/side-chat/tech-design.md | 37 ++++++++- src/server/__tests__/session-links.test.ts | 56 +++++++++++++ src/server/services/sessionService.ts | 6 +- src/server/transcript/entries.ts | 17 ++++ 22 files changed, 351 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24e5a188..31917f48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +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. +- **Side chats.** Start a side chat from the side panel's new-tab page, or select text in the conversation and choose **Start a side chat** to quote it in a new one, 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. It shows only its own messages; the model still has the whole conversation. 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 diff --git a/desktop/src/components/README.md b/desktop/src/components/README.md index 5b332252..df1bbe82 100644 --- a/desktop/src/components/README.md +++ b/desktop/src/components/README.md @@ -112,7 +112,7 @@ picker through `ui/input`. | `settings/SettingsDisclosureRow`, `chat/LocalSlashCommandPanel` | Collapsible and Tabs with shared buttons; existing content and loading behavior | | `chat/MessageActionBar`, `chat/ImageGalleryModal`, `chat/ToolResultBlock` | Shared buttons and CopyButton; existing copy, fork, navigation and expand actions | | `tasks/TaskRow` | Action Menu + Confirm Dialog; keyboard navigation, focus return, pending requests and retryable errors | -| `shared/SelectionPopover` | Shared Popover + Button for chat replies and plain-code, Markdown and Pierre selection quotes; portals outside transformed message containers and preserves captured text and line coordinates | +| `shared/SelectionPopover` | Shared Popover with a row of action buttons for chat selections (Start a side chat, Reply) and plain-code, Markdown and Pierre selection quotes; portals outside transformed message containers and preserves captured text and line coordinates | | `workspace/PreviewLimitBar` | Sticky bar with the shown/total line count and a show-all toggle, shared by the code and diff previews | | `workspace/WorkspaceQuotePopover` | SelectionPopover with the workspace "add to chat" action, shared by the code, Markdown and Pierre diff surfaces | | `CommandPalette/CommandPalette`, `layout/ShortcutsDialog` | Command and Kbd respectively, with existing navigation and shortcut data | diff --git a/desktop/src/components/chat/MessageList.test.tsx b/desktop/src/components/chat/MessageList.test.tsx index 63cab834..9acebdb1 100644 --- a/desktop/src/components/chat/MessageList.test.tsx +++ b/desktop/src/components/chat/MessageList.test.tsx @@ -5,6 +5,7 @@ import { relativizeWorkspacePath } from './CurrentTurnChangeCard' import { sessionsApi } from '../../api/sessions' import { useChatStore } from '../../stores/chatStore' import { useWorkspaceChatContextStore } from '../../stores/workspaceChatContextStore' +import { useWorkspacePanelStore } from '../../stores/workspacePanelStore' import { useSettingsStore } from '../../stores/settingsStore' import { useSessionStore } from '../../stores/sessionStore' import { useTabStore } from '../../stores/tabStore' @@ -1635,7 +1636,7 @@ describe('MessageList nested tool calls', () => { await selectMessageText(userText, 'workspace selection behavior') const floatingAddButton = screen.getByRole('button', { name: 'Reply' }) - expect(screen.getByRole('dialog', { name: 'Reply' }).parentElement?.parentElement).toBe(document.body) + expect(screen.getByRole('dialog', { name: 'Selected text' }).parentElement?.parentElement).toBe(document.body) expect(userText.closest('[data-message-shell]')?.contains(floatingAddButton)).toBe(false) fireEvent.click(floatingAddButton) @@ -1685,6 +1686,84 @@ describe('MessageList nested tool calls', () => { ]) }) + describe('starting a side chat from a selection', () => { + function showAssistantReply() { + useChatStore.setState({ + sessions: { + [ACTIVE_TAB]: makeSessionState({ + messages: [{ id: 'assistant-1', type: 'assistant_text', content: 'Ask about this part later.', timestamp: 1 }], + }), + }, + }) + } + + beforeEach(() => { + useWorkspacePanelStore.setState(useWorkspacePanelStore.getInitialState(), true) + localStorage.clear() + }) + + it('offers it before Reply in the main conversation', async () => { + showAssistantReply() + render() + + await selectMessageText(screen.getByText(/Ask about this part/), 'this part') + + const actions = within(screen.getByRole('dialog', { name: 'Selected text' })).getAllByRole('button') + expect(actions.map((button) => button.textContent)).toEqual(['Start a side chat', 'Reply']) + }) + + it('offers only Reply inside a side chat', async () => { + showAssistantReply() + render() + + await selectMessageText(screen.getByText(/Ask about this part/), 'this part') + + expect(within(screen.getByRole('dialog', { name: 'Selected text' })).getAllByRole('button').map((button) => button.textContent)).toEqual(['Reply']) + }) + + it('opens a new side chat with the selection quoted in its composer', async () => { + showAssistantReply() + const branch = vi.spyOn(sessionsApi, 'branch').mockResolvedValue({ sessionId: 'side-1', title: 'btw', workDir: '/repo', sourceSessionId: ACTIVE_TAB }) + render() + + await selectMessageText(screen.getByText(/Ask about this part/), 'this part') + fireEvent.click(screen.getByRole('button', { name: 'Start a side chat' })) + + await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Selected text' })).toBeNull()) + expect(branch).toHaveBeenCalledWith(ACTIVE_TAB, { kind: 'side' }) + expect(useWorkspacePanelStore.getState().panelByTab[ACTIVE_TAB]?.tabs).toMatchObject([{ kind: 'sideChat', sessionId: 'side-1' }]) + expect(useWorkspaceChatContextStore.getState().referencesBySession).toEqual({ + 'side-1': [expect.objectContaining({ kind: 'chat-selection', path: 'chat://assistant/assistant-1', messageId: 'assistant-1', quote: 'this part' })], + }) + expect(window.getSelection()?.toString()).toBe('') + }) + + it('blocks a second click while the side chat is being created', async () => { + showAssistantReply() + const branch = vi.spyOn(sessionsApi, 'branch').mockReturnValue(new Promise(() => {})) + render() + + await selectMessageText(screen.getByText(/Ask about this part/), 'this part') + fireEvent.click(screen.getByRole('button', { name: 'Start a side chat' })) + fireEvent.click(screen.getByRole('button', { name: 'Start a side chat' })) + + expect(screen.getByRole('button', { name: 'Start a side chat' })).toHaveProperty('disabled', true) + expect(branch).toHaveBeenCalledOnce() + }) + + it('says why a side chat could not be started', async () => { + showAssistantReply() + vi.spyOn(sessionsApi, 'branch').mockRejectedValue(new Error('busy')) + render() + + await selectMessageText(screen.getByText(/Ask about this part/), 'this part') + fireEvent.click(screen.getByRole('button', { name: 'Start a side chat' })) + + await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Could not start a side chat: busy')) + expect(useWorkspaceChatContextStore.getState().referencesBySession).toEqual({}) + }) + }) + it('closes the selected-message action but keeps the selection when pressing outside the popover', async () => { useChatStore.setState({ sessions: { diff --git a/desktop/src/components/chat/MessageList.tsx b/desktop/src/components/chat/MessageList.tsx index b6ae08b8..c1ee6ceb 100644 --- a/desktop/src/components/chat/MessageList.tsx +++ b/desktop/src/components/chat/MessageList.tsx @@ -32,6 +32,7 @@ import { ConfirmDialog } from '../shared/ConfirmDialog' import { getSelectionAnchor, useQuoteSelection } from '../../lib/selectionPopover' import { ASK_USER_QUESTION_TOOL, CHOOSE_DESIGN_TEMPLATE_TOOL, isInlineQuestionTool } from '../../lib/inlineQuestionTools' import { SelectionPopover } from '../shared/SelectionPopover' +import { useStartSideChat } from '../../lib/sideChats' import { getHeightsForSession, getMetricsForSession, @@ -358,42 +359,60 @@ function SelectableChatMessage({ messageId, role, content, + canStartSideChat, children, }: { sessionId: string messageId: string role: ChatMessageRole content: string + canStartSideChat: boolean children: ReactNode }) { const rootRef = useRef(null) const addReference = useWorkspaceChatContextStore((state) => state.addReference) + const sideChat = useStartSideChat(sessionId) const quote = useQuoteSelection((event) => getChatSelectionFromContainer(rootRef.current, event), `${messageId}:${content}`) const t = useTranslation() const sourceName = role === 'assistant' ? t('chat.assistantMessageReference') : t('chat.userMessageReference') + const selectionReference = () => quote.selection && { + kind: 'chat-selection' as const, + path: `chat://${role}/${messageId}`, + name: sourceName, + quote: quote.selection.text, + sourceRole: role, + messageId, + } + const addCurrentSelectionToChat = () => { - if (!quote.selection) return - addReference(sessionId, { - kind: 'chat-selection', - path: `chat://${role}/${messageId}`, - name: sourceName, - quote: quote.selection.text, - sourceRole: role, - messageId, - }) + const reference = selectionReference() + if (!reference) return + addReference(sessionId, reference) quote.dismiss() } + const startSideChatFromSelection = async () => { + const reference = selectionReference() + if (!reference) return + await sideChat.start(reference) + quote.dismiss() + } + + const replyAction = { label: t('chat.replyToSelection'), onSelect: addCurrentSelectionToChat } + const actions = canStartSideChat + ? [{ label: t('chat.startSideChat'), loading: sideChat.starting, onSelect: () => void startSideChatFromSelection() }, replyAction] + : [replyAction] + return (
{children} - +
) } @@ -854,6 +873,7 @@ function MemoryEventCard({ message }: { message: MemoryEvent }) { type MessageListProps = { sessionId: string compact?: boolean + canStartSideChat?: boolean } const AUTO_SCROLL_BOTTOM_THRESHOLD_PX = 48 @@ -1267,7 +1287,7 @@ const MeasuredRenderItem = memo(function MeasuredRenderItem({ ) }) -export function MessageList({ sessionId, compact = false }: MessageListProps) { +export function MessageList({ sessionId, compact = false, canStartSideChat = false }: MessageListProps) { const branchSession = useSessionStore((s) => s.branchSession) const stopGeneration = useChatStore((s) => s.stopGeneration) const reloadHistory = useChatStore((s) => s.reloadHistory) @@ -1884,6 +1904,7 @@ export function MessageList({ sessionId, compact = false }: MessageListProps) { } branchAction={branchActionByMessageId.get(item.message.id)} replyCopyText={replyCopyTextByMessageId.get(item.message.id)} + canStartSideChat={canStartSideChat} /> )} @@ -2015,6 +2036,7 @@ export const MessageBlock = memo(function MessageBlock({ toolResult, branchAction, replyCopyText, + canStartSideChat = false, }: { sessionId: string message: UIMessage @@ -2027,6 +2049,7 @@ export const MessageBlock = memo(function MessageBlock({ onBranch: () => void } replyCopyText?: string + canStartSideChat?: boolean }) { const t = useTranslation() @@ -2041,6 +2064,7 @@ export const MessageBlock = memo(function MessageBlock({ messageId={message.id} role="user" content={message.content} + canStartSideChat={canStartSideChat} > ) : ( - + )} {!isMemberSession && } diff --git a/desktop/src/components/shared/SelectionPopover.test.tsx b/desktop/src/components/shared/SelectionPopover.test.tsx index 5456d702..eb3e6f5f 100644 --- a/desktop/src/components/shared/SelectionPopover.test.tsx +++ b/desktop/src/components/shared/SelectionPopover.test.tsx @@ -2,11 +2,11 @@ import { useState } from 'react' import '@testing-library/jest-dom' import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' -import { SelectionPopover } from './SelectionPopover' +import { SelectionPopover, type SelectionPopoverAction } from './SelectionPopover' afterEach(cleanup) -function Harness({ onAdd = () => {}, onClear = () => {} }: { onAdd?: () => void; onClear?: () => void }) { +function Harness({ onAdd = () => {}, onClear = () => {}, actions }: { onAdd?: () => void; onClear?: () => void; actions?: SelectionPopoverAction[] }) { const [selection, setSelection] = useState<{ x: number; y: number } | null>({ x: 10, y: 10 }) const quote = { selection, @@ -15,7 +15,7 @@ function Harness({ onAdd = () => {}, onClear = () => {} }: { onAdd?: () => void; } return
setSelection(null)}>

source text

- { if (selection) onAdd() }} /> + { if (selection) onAdd() } }]} />
} @@ -59,3 +59,22 @@ it('opens above the selection', () => { render() expect(screen.getByRole('dialog', { name: 'Add to chat' })).toHaveAttribute('data-side', 'top') }) + +it('offers each action and runs only the one clicked', () => { + const first = vi.fn() + const second = vi.fn() + render() + fireEvent.click(screen.getByRole('button', { name: 'Second' })) + expect(second).toHaveBeenCalledOnce() + expect(first).not.toHaveBeenCalled() +}) + +it('blocks an action while it is loading', () => { + const first = vi.fn() + render( {} }]} />) + const button = screen.getByRole('button', { name: 'First' }) + fireEvent.click(button) + expect(button).toBeDisabled() + expect(first).not.toHaveBeenCalled() + expect(screen.getByRole('button', { name: 'Second' })).toBeEnabled() +}) diff --git a/desktop/src/components/shared/SelectionPopover.tsx b/desktop/src/components/shared/SelectionPopover.tsx index 3993abd4..b03d04a7 100644 --- a/desktop/src/components/shared/SelectionPopover.tsx +++ b/desktop/src/components/shared/SelectionPopover.tsx @@ -1,4 +1,4 @@ -import { useMemo } from 'react' +import { Fragment, useMemo } from 'react' import { Popover, PopoverAnchor, PopoverContent } from './ui/popover' import { Button } from './ui/button' @@ -8,10 +8,16 @@ export type SelectionPopoverQuote = { clear: () => void } -export function SelectionPopover({ quote, label, onAdd }: { +export type SelectionPopoverAction = { + label: string + onSelect: () => void + loading?: boolean +} + +export function SelectionPopover({ quote, label, actions }: { quote: SelectionPopoverQuote label: string - onAdd: () => void + actions: SelectionPopoverAction[] }) { const { selection } = quote const x = selection?.x ?? 0 @@ -26,9 +32,16 @@ export function SelectionPopover({ quote, label, onAdd }: { onMouseUp={(event) => event.stopPropagation()} onPointerUp={(event) => event.stopPropagation()} onInteractOutside={(event) => { if (quote.contains(event.target)) event.preventDefault() }} onOpenAutoFocus={(event) => event.preventDefault()} onCloseAutoFocus={(event) => event.preventDefault()}> - +
+ {actions.map((action, index) => ( + + {index > 0 && + ))} +
) diff --git a/desktop/src/components/workspace/WorkspacePanel.test.tsx b/desktop/src/components/workspace/WorkspacePanel.test.tsx index 0f694848..711ac1ec 100644 --- a/desktop/src/components/workspace/WorkspacePanel.test.tsx +++ b/desktop/src/components/workspace/WorkspacePanel.test.tsx @@ -346,7 +346,7 @@ vi.mock('../chat/SessionConversation', () => ({ const sideChatActions = vi.hoisted(() => ({ closeSideChat: vi.fn(async () => {}), detachSideChat: vi.fn(async () => {}) })) -vi.mock('../../lib/sideChats', () => sideChatActions) +vi.mock('../../lib/sideChats', async (importOriginal) => ({ ...(await importOriginal()), ...sideChatActions })) vi.mock('../../api/sessions', () => ({ sessionsApi: (() => { @@ -2007,6 +2007,26 @@ describe('WorkspacePanel', () => { }) }) + it.each([ + ['starts', undefined, null], + ['says why it could not start', new Error('busy'), 'Could not start a side chat: busy'], + ] as const)('%s a side chat from the new tab page', async (_name, failure, message) => { + await setWorkspaceState((state) => ({ + ...state, + panelByTab: { ...state.panelByTab, 'session-launcher': panelState({ id: 'launcher', kind: 'launcher' }) }, + })) + const create = vi.spyOn(useWorkspacePanelStore.getState(), 'createSideChat') + if (failure) create.mockRejectedValue(failure) + else create.mockResolvedValue('side-1') + + const view = await renderPanel('session-launcher') + await clickElement(within(view.getByTestId('workspace-launcher')).getByRole('button', { name: 'Side chat' })) + + expect(create).toHaveBeenCalledWith('session-launcher') + if (message) await waitFor(() => expect(toast.error).toHaveBeenCalledWith(message)) + else expect(toast.error).not.toHaveBeenCalled() + }) + it('opens tools and recent pages and files from the new tab page', async () => { useChatStore.setState({ sessions: { diff --git a/desktop/src/components/workspace/WorkspacePanel.tsx b/desktop/src/components/workspace/WorkspacePanel.tsx index cd43a604..432be7c2 100644 --- a/desktop/src/components/workspace/WorkspacePanel.tsx +++ b/desktop/src/components/workspace/WorkspacePanel.tsx @@ -47,7 +47,7 @@ import { BrowserView } from './BrowserView' import { UiPageFrame } from '../chat/UiPageFrame' import { SessionConversation } from '../chat/SessionConversation' import { RenameSessionDialog } from '../layout/RenameSessionDialog' -import { closeSideChat, detachSideChat } from '../../lib/sideChats' +import { closeSideChat, detachSideChat, useStartSideChat } from '../../lib/sideChats' import { isDesktopRuntime } from '../../lib/desktopRuntime' import { SearchField } from '../shared/SearchField' import { useCopyAndNotify } from '../../hooks/useCopyAndNotify' @@ -1069,9 +1069,8 @@ const EMPTY_UI_PAGES: UiPageSummary[] = [] function LauncherView({ sessionId, projectRoot }: { sessionId: string; projectRoot: string | null }) { const t = useTranslation() const [draft, setDraft] = useState('') - const [creatingSideChat, setCreatingSideChat] = useState(false) + const sideChat = useStartSideChat(sessionId) const openTab = useWorkspacePanelStore((state) => state.openTab) - const createSideChat = useWorkspacePanelStore((state) => state.createSideChat) const openAddress = useWorkspacePanelStore((state) => state.openAddress) const selectFile = useWorkspacePanelStore((state) => state.selectFile) const recentFiles = useWorkspacePanelStore((state) => state.panelByTab[sessionId]?.recentFiles ?? EMPTY_IDS) @@ -1107,17 +1106,6 @@ function LauncherView({ sessionId, projectRoot }: { sessionId: string; projectRo }) } - const startSideChat = async () => { - setCreatingSideChat(true) - try { - await createSideChat(sessionId) - } catch (error) { - toast.error(t('workspace.sideChat.createFailed', { error: error instanceof Error ? error.message : String(error) })) - } finally { - setCreatingSideChat(false) - } - } - return (
@@ -1146,7 +1134,7 @@ function LauncherView({ sessionId, projectRoot }: { sessionId: string; projectRo ) })} - diff --git a/desktop/src/components/workspace/WorkspaceQuotePopover.tsx b/desktop/src/components/workspace/WorkspaceQuotePopover.tsx index 88e35fc9..aa840457 100644 --- a/desktop/src/components/workspace/WorkspaceQuotePopover.tsx +++ b/desktop/src/components/workspace/WorkspaceQuotePopover.tsx @@ -11,10 +11,13 @@ export function WorkspaceQuotePopover({ quote, onAddSelection }: { { - if (quote.selection) onAddSelection({ text: quote.selection.text, startLine: quote.selection.startLine, endLine: quote.selection.endLine }) - quote.dismiss() - }} + actions={[{ + label: t('workspace.addSelectionToChat'), + onSelect: () => { + if (quote.selection) onAddSelection({ text: quote.selection.text, startLine: quote.selection.startLine, endLine: quote.selection.endLine }) + quote.dismiss() + }, + }]} /> ) } diff --git a/desktop/src/i18n/locales/en.ts b/desktop/src/i18n/locales/en.ts index 543d2fa0..533f09fd 100644 --- a/desktop/src/i18n/locales/en.ts +++ b/desktop/src/i18n/locales/en.ts @@ -1334,6 +1334,8 @@ export const en = { 'chat.browserPickPending': 'An element you picked is still being read. Send again in a moment.', 'chat.attachmentFailed': 'Could not attach {name}.', 'chat.replyToSelection': 'Reply', + 'chat.startSideChat': 'Start a side chat', + 'chat.selectionActions': 'Selected text', 'chat.branchFromHere': 'Fork a new conversation', 'chat.branchSuccess': 'Created forked conversation "{title}".', 'chat.branchError': 'Failed to branch from this message. Detail: {detail}', diff --git a/desktop/src/i18n/locales/zh.ts b/desktop/src/i18n/locales/zh.ts index 94a987b0..3d53ca81 100644 --- a/desktop/src/i18n/locales/zh.ts +++ b/desktop/src/i18n/locales/zh.ts @@ -1336,6 +1336,8 @@ export const zh: Record = { 'chat.browserPickPending': '你选取的元素还在读取中,请稍后再发送。', 'chat.attachmentFailed': '无法添加附件 {name}。', 'chat.replyToSelection': '回复', + 'chat.startSideChat': '新建 side chat', + 'chat.selectionActions': '选中的文字', 'chat.branchFromHere': 'Fork 一个新对话', 'chat.branchSuccess': '已 Fork 新对话“{title}”。', 'chat.branchError': '从该消息 Fork 新对话失败。详情:{detail}', diff --git a/desktop/src/lib/sideChats.test.ts b/desktop/src/lib/sideChats.test.ts index c2c6e6d3..1c5f23c6 100644 --- a/desktop/src/lib/sideChats.test.ts +++ b/desktop/src/lib/sideChats.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' +import { useChatStore } from '../stores/chatStore' import { useSessionStore } from '../stores/sessionStore' import { useWorkspacePanelStore, type WorkspaceTab } from '../stores/workspacePanelStore' import { closeSideChat, detachSideChat } from './sideChats' @@ -21,6 +22,7 @@ describe.each([ afterEach(() => { vi.restoreAllMocks() useWorkspacePanelStore.setState(useWorkspacePanelStore.getInitialState(), true) + useChatStore.setState({ sessions: {} }) localStorage.clear() }) @@ -34,6 +36,16 @@ describe.each([ expect(openTabIds()).toEqual([]) }) + it('drops the side chat messages it loaded, so opening the session again reads its history afresh', async () => { + const tab = openSideChat() + useChatStore.setState({ sessions: { side: { ...useChatStore.getState().getSession('side'), messages: [{ id: 'own', type: 'user_text', content: 'own', timestamp: 1 }] } } }) + vi.spyOn(useSessionStore.getState(), storeAction).mockResolvedValue() + + await action('parent', tab) + + expect(useChatStore.getState().sessions.side).toBeUndefined() + }) + it('keeps the tab when the server refuses the change', async () => { const tab = openSideChat() vi.spyOn(useSessionStore.getState(), storeAction).mockRejectedValue(new Error('refused')) diff --git a/desktop/src/lib/sideChats.ts b/desktop/src/lib/sideChats.ts index 9f9fdb5f..e0414c12 100644 --- a/desktop/src/lib/sideChats.ts +++ b/desktop/src/lib/sideChats.ts @@ -1,4 +1,8 @@ +import { useState } from 'react' +import { toast } from 'sonner' +import { useTranslation } from '../i18n' import { useSessionStore } from '../stores/sessionStore' +import { useWorkspaceChatContextStore, type WorkspaceChatReference } from '../stores/workspaceChatContextStore' import { useWorkspacePanelStore, type WorkspaceTab } from '../stores/workspacePanelStore' type SideChatTab = Extract @@ -12,3 +16,20 @@ export async function detachSideChat(parentId: string, tab: SideChatTab) { await useSessionStore.getState().detachSession(tab.sessionId) useWorkspacePanelStore.getState().closeTab(parentId, tab.id) } + +export function useStartSideChat(parentId: string) { + const t = useTranslation() + const [starting, setStarting] = useState(false) + const start = async (reference?: Omit) => { + setStarting(true) + try { + const sideChatId = await useWorkspacePanelStore.getState().createSideChat(parentId) + if (reference) useWorkspaceChatContextStore.getState().addReference(sideChatId, reference) + } catch (error) { + toast.error(t('workspace.sideChat.createFailed', { error: error instanceof Error ? error.message : String(error) })) + } finally { + setStarting(false) + } + } + return { starting, start } +} diff --git a/desktop/src/pages/ActiveSession.test.tsx b/desktop/src/pages/ActiveSession.test.tsx index a8d5bf88..d7c773c4 100644 --- a/desktop/src/pages/ActiveSession.test.tsx +++ b/desktop/src/pages/ActiveSession.test.tsx @@ -45,8 +45,8 @@ vi.mock('../hooks/useMobileViewport', () => ({ })) vi.mock('../components/chat/MessageList', () => ({ - MessageList: ({ compact }: { compact?: boolean }) => ( -
+ MessageList: ({ compact, canStartSideChat }: { compact?: boolean; canStartSideChat?: boolean }) => ( +
), })) @@ -612,6 +612,7 @@ describe('ActiveSession task polling', () => { expect(within(contentRow).getByTestId('message-list')).toBeInTheDocument() expect(within(contentRow).getByTestId('message-list')).toHaveAttribute('data-compact', 'true') + expect(within(contentRow).getByTestId('message-list')).toHaveAttribute('data-side-chats', 'true') expect(within(contentRow).getByTestId('workspace-panel')).toHaveTextContent(`workspace:${sessionId}`) expect(within(chatColumn).getByTestId('chat-input')).toBeInTheDocument() expect(within(chatColumn).getByTestId('chat-input')).toHaveAttribute('data-compact', 'true') @@ -794,6 +795,7 @@ describe('ActiveSession task polling', () => { expect(screen.getByTestId('active-session-chat-column')).toHaveClass('min-w-0') expect(screen.getByTestId('message-list')).toHaveAttribute('data-compact', 'false') + expect(screen.getByTestId('message-list')).toHaveAttribute('data-side-chats', 'false') expect(screen.getByTestId('chat-input')).toHaveAttribute('data-compact', 'false') expect(screen.queryByRole('heading', { name: 'Mobile Session' })).not.toBeInTheDocument() expect(screen.queryByTestId('workspace-panel')).not.toBeInTheDocument() diff --git a/desktop/src/pages/ActiveSession.tsx b/desktop/src/pages/ActiveSession.tsx index 8b4ded3b..f1cc4c39 100644 --- a/desktop/src/pages/ActiveSession.tsx +++ b/desktop/src/pages/ActiveSession.tsx @@ -196,6 +196,7 @@ export function ActiveSession() { } />
diff --git a/desktop/src/stores/workspacePanelStore.test.ts b/desktop/src/stores/workspacePanelStore.test.ts index 0a64b466..929037a3 100644 --- a/desktop/src/stores/workspacePanelStore.test.ts +++ b/desktop/src/stores/workspacePanelStore.test.ts @@ -989,7 +989,7 @@ describe('artifact tabs', () => { it('starts a side chat from the parent and shows it as a tab', async () => { mocks.branchMock.mockResolvedValue({ sessionId: 'side-created', title: 'btw', workDir: '/repo', sourceSessionId: 'parent' }) - await useWorkspacePanelStore.getState().createSideChat('parent') + await expect(useWorkspacePanelStore.getState().createSideChat('parent')).resolves.toBe('side-created') expect(mocks.branchMock).toHaveBeenCalledWith('parent', { kind: 'side' }) const panel = useWorkspacePanelStore.getState().panelByTab.parent! diff --git a/desktop/src/stores/workspacePanelStore.ts b/desktop/src/stores/workspacePanelStore.ts index bc67d4d8..abc28576 100644 --- a/desktop/src/stores/workspacePanelStore.ts +++ b/desktop/src/stores/workspacePanelStore.ts @@ -127,7 +127,7 @@ type WorkspacePanelStore = { refreshPreviews: (sessionId: string) => Promise releaseSession: (sessionId: string) => void clearSession: (sessionId: string) => void - createSideChat: (sessionId: string) => Promise + createSideChat: (sessionId: string) => Promise syncSideChats: (sessionId: string) => Promise } @@ -874,6 +874,7 @@ export const useWorkspacePanelStore = create((set, get) => createSideChat: async (sessionId) => { const created = await sessionsApi.branch(sessionId, { kind: 'side' }) get().openTab(sessionId, { kind: 'sideChat', sessionId: created.sessionId }) + return created.sessionId }, syncSideChats: async (sessionId) => { diff --git a/docs/features/side-chat/tech-design.md b/docs/features/side-chat/tech-design.md index fcd313c0..19dbca68 100644 --- a/docs/features/side-chat/tech-design.md +++ b/docs/features/side-chat/tech-design.md @@ -1,6 +1,6 @@ # Side chat:技术设计 -状态:已实现,在 `feat/side-chat` 分支上,基于 `main` 的 `2d145753`。文中的行号以这个分支合并时的代码为准,之后代码变了,行号可能对不上。 +状态:已实现。第一版随 PR #251 合并(`ee90358d`);隐藏继承的消息和从选中文字新建在 `feat/side-chat-selection-entry` 分支上。文中的行号以这个分支的代码为准,之后代码变了,行号可能对不上。 ## 背景 @@ -12,6 +12,8 @@ - side chat 是从父会话最新位置完整分叉出来的会话。工具、MCP、卡片、附件都和普通会话一样,和父会话共用同一个工作目录,没有自己的 worktree。 - 显示在父会话右侧面板里,作为一个标签页,和终端、浏览器、文件并列。一个会话可以开多个。 +- side chat 页面只显示它自己的消息,不显示从父会话继承来的部分。模型的上下文仍然是完整的分叉。 +- 两个入口:面板新标签页里的 "Side chat";在主会话里选中文字,弹出条点 "Start a side chat",选中的内容作为引用放进 side chat 的输入框。 - 标签菜单可以重命名、Detach(变成普通的分叉会话,出现在左侧列表),以及关闭。关闭就是删除,不二次确认,正在运行的会先停掉。 - 删除父会话时,它的 side chat 一起删除,不做归档。 - 标题是 `btw: <第一条用户输入>`。 @@ -42,6 +44,18 @@ - side chat 用 `SIDE_CHAT_NOTE`(`sessionLinksService.ts:32`,`always: true`),告诉模型父会话会继续执行上面那一轮,它只管下一条消息让它做的事。StartSession 的 fork 用 `always: false`,行为和以前一样。 - 接口沿用 `POST /api/sessions/:id/branch`。body 带 `kind: 'side'` 时 `targetMessageId` 可以不传,从最新位置分叉,标题用 `exactTitle` 原样写成 `btw`,不加 "(Branch)"。 +### 显示:只显示 side chat 自己的消息 + +- 分叉时复制来的每条记录都带 `forkedFrom`(`sessionBranching.ts:566`)。结尾的分叉说明和之后新写的记录不带。 +- `getSessionTranscript`(`sessionService.ts:1830`)发现会话的父关系是 `side` 时,先用 `withoutInheritedEntries`(`transcript/entries.ts:369`)去掉继承的记录,再转换成显示条目。去掉的有两类: + - 带 `forkedFrom` 的记录; + - 只回答继承来的工具调用的 `tool_result` 消息。分叉点正好在一次工具调用中间时,分叉说明就是这样一条消息,它对应的工具调用已经去掉了,不能单独显示出来。 + - 另一条说明(isMeta 说明和 "No response requested.")本来就不显示。 +- 任务通知、子 agent 消息、最后的待办都从过滤后的记录里取,父会话的这些内容不带进 side chat。 +- 只过滤显示。模型的上下文来自 CLI 读的文件,不受影响。`getSessionMessages`(回退、从某条消息分叉、工作区用)也不过滤。 +- 导出(`GET /api/sessions/:id/export`)同样调用 `getSessionTranscript`,side chat 的导出也只含它自己的消息。导出入口只在主页面的会话标题栏菜单里,side chat 标签没有这个入口。 +- Detach 之后父关系变成 `forked`,不再过滤,显示完整历史。桌面端在 Detach 成功后关掉标签,关标签会断开连接并清掉这个会话的本地消息(`disposeTab` → `disconnectSession`)。之后在左侧列表打开它,会重新连接并重新读取,读到的是完整历史。 + ### 会话列表:服务端默认不返回 side chat - `listSessions`(`sessionService.ts:1068`)按文件修改时间排序,先切出 `[offset, offset + limit)` 这一页,再去掉 side chat;`total` 是文件总数。一页因此可能不满。分页读取的调用方都按 `total` 循环,所以能读完。 @@ -127,13 +141,26 @@ side chat 标签: - 只在请求发出时已有的标签里判断哪些过期,请求期间新开的标签不会被删掉。 - 刚在本地删除的会话不会被补回来(`isDeletedSession`)。 - `disposeTab` 遇到 side chat 标签时断开它的连接。父会话被释放或删除时,每个标签都会经过它。 -- 新建:面板的新标签页里有 "Side chat" 入口,调用 `createSideChat`。 +- 新建:两个入口都通过 `useStartSideChat`(`lib/sideChats.ts:20`)调用 `createSideChat`。它负责创建期间的 loading 状态和失败提示,`createSideChat` 返回新会话的 id。见下一节。 - 标签菜单(`SideChatTabTrigger`,`WorkspacePanel.tsx:1218`): - 重命名:用 `RenameSessionDialog`,和会话标题栏菜单共用; - Detach:运行中禁用,接口成功后关掉标签; - 关闭:接口成功后关掉标签。标签上的 × 也是关闭。 - 失败时标签保留,并弹出带原因的提示(`lib/sideChats.ts`)。 +从选中文字新建: + +- `SelectionPopover` 接收一组动作,按顺序显示,中间有分隔线。动作在 loading 时禁用,防止重复点击。工作区的"添加到对话"弹出条也用它,只有一个动作。 +- 主会话的消息里选中文字时,弹出条是 "Start a side chat | Reply"(`SelectableChatMessage`,`MessageList.tsx:357`)。点前者: + 1. 新建 side chat,标签在面板里打开; + 2. 把和 Reply 相同的 `chat-selection` 引用加到新 side chat 名下,它出现在 side chat 输入框上方; + 3. 关闭弹出条。不自动发送,等用户输入。 +- 每次点都新建一个 side chat,不复用已打开的。 +- 是否提供这个动作由 `canStartSideChat` 决定,`ActiveSession` 传入 `canUsePanel`(`ActiveSession.tsx:199`),也就是这个会话能不能用右侧面板。所以: + - side chat 自己的消息里只有 Reply,不再开一层; + - 手机布局(H5)和团队成员会话没有面板,也不提供。新标签页里的入口在这两种情况下同样看不到。 +- 新建后不把焦点移进 side chat 的输入框。side chat 的输入框不抢焦点(见上文 `primary`),要做到需要给它加一个"新建后聚焦"的信号,现有结构里没有。 + 面板归属:side chat 的面板就是父会话的面板。 - `findSideChatParent`(`workspacePanelStore.ts:304`)从已打开的 side chat 标签推出 side chat 对应的父会话。不能从桌面端的会话列表推:列表只取最近 100 个会话,而且服务端本来就不返回 side chat。 @@ -157,6 +184,7 @@ side chat 标签: - 删除或 Detach 期间有消息要启动这个会话:被启动拦截挡住,报 `SESSION_DELETED` 或 `SESSION_DETACHING`。 - 两个客户端同时开着:A 把 side chat 分离成普通会话后,B 上的标签要到下次打开面板才消失。这期间 B 点关闭,会删掉这个已经是普通会话的会话。这是接受的情况,见"考虑过但没有采用的做法"。 - 会话列表一页可能不满:side chat 占着文件下标但被过滤掉。侧栏只取第一页 100 个,side chat 多时,侧栏能显示的会话会相应少一些。 +- 从选中文字新建失败:弹出条关闭,弹出带原因的提示,引用不会加到任何会话名下。 ## 测试 @@ -164,6 +192,7 @@ side chat 标签: - `session-links.test.ts` 的 "side chats" 组: - 分叉:没有未完成的工具调用时也追加说明,有时给它们补结果; + - 显示:只显示自己的消息,不带父会话的任务通知和待办,模型读到的消息仍完整;在工具调用中间分叉时说明不显示;Detach 后显示完整历史; - 分叉路由和 `side-chats` 路由,以及 branch 路由的三种 400; - 分页和 side chat 过滤; - 只读关系; @@ -193,6 +222,10 @@ side chat 标签: - Detach 运行中禁用; - 菜单的 Detach、重命名,以及失败提示; - × 关闭。 +- `WorkspacePanel.test.tsx` 的新标签页:新建 side chat 和失败提示。 +- `MessageList.test.tsx` 的 "starting a side chat from a selection" 组:主会话里先 Start a side chat 再 Reply,side chat 里只有 Reply;新建后引用在新会话名下、弹出条关闭;创建期间不能重复点;失败提示。 +- `SelectionPopover.test.tsx`:多个动作各自生效,loading 的动作禁用。 +- `ActiveSession.test.tsx`:能用面板时提供入口,手机布局不提供。 - `WorkspacePanel.sideChatPrewarm.test.tsx`:全部连接,只预热当前显示的那个。 - `workspacePanelStore.test.ts` 的 "side chats" 组: - 各入口落到父会话面板; diff --git a/src/server/__tests__/session-links.test.ts b/src/server/__tests__/session-links.test.ts index 37e670bf..13d1d32a 100644 --- a/src/server/__tests__/session-links.test.ts +++ b/src/server/__tests__/session-links.test.ts @@ -344,6 +344,62 @@ describe('side chats', () => { expect(sentinel?.message).toMatchObject({ content: [{ type: 'text', text: 'No response requested.' }] }) }) + async function appendToTranscript(sessionId: string, entries: Entry[]): Promise { + const found = await sessionService.findSessionFile(sessionId) + await fs.appendFile(found!.filePath, entries.map((entry) => JSON.stringify(entry)).join('\n') + '\n', 'utf-8') + } + + function visibleTexts(items: Array<{ type: string; content?: unknown }>) { + return items.filter((item) => item.type === 'user_text' || item.type === 'assistant_text').map((item) => item.content) + } + + it('shows only its own messages, while the model keeps the inherited ones', async () => { + const parentId = crypto.randomUUID() + const user = userEntry(parentId, 'parent question') + const reply = assistantEntry(parentId, 'parent answer', user.uuid) + const todos = toolUseEntry(parentId, 'todo-1', reply.uuid) + ;((todos.message as Entry).content as Entry[])[0] = { type: 'tool_use', id: 'todo-1', name: 'TodoWrite', input: { todos: [{ content: 'parent task', status: 'pending', activeForm: 'Doing it' }] } } + const todosDone = toolResultEntry(parentId, 'todo-1', todos.uuid) + const notification = userEntry(parentId, '\nbg-1\ntoolu_bg\ncompleted\nBackground command completed\n', { parentUuid: todosDone.uuid }) + await writeTranscript(parentId, [metaEntry(), user, reply, todos, todosDone, notification]) + const sideId = await sideChatOf(parentId) + const forkEnd = conversationMessages(await readEntries(sideId)).at(-1)! + const sideQuestion = userEntry(sideId, 'side question', { parentUuid: forkEnd.uuid, timestamp: '2026-01-01T00:05:00.000Z' }) + await appendToTranscript(sideId, [sideQuestion, assistantEntry(sideId, 'side answer', sideQuestion.uuid)]) + + const transcript = await sessionService.getSessionTranscript(sideId) + + expect(visibleTexts(transcript.items)).toEqual(['side question', 'side answer']) + expect(transcript.items.some((item) => item.type === 'tool_use' || item.type === 'tool_result')).toBe(false) + expect(transcript.agentNotifications).toEqual({}) + expect(transcript.lastTodos).toBeNull() + expect(JSON.stringify(await sessionService.getSessionMessages(sideId))).toContain('parent question') + const parentTranscript = await sessionService.getSessionTranscript(parentId) + expect(visibleTexts(parentTranscript.items)).toEqual(['parent question', 'parent answer']) + expect(Object.keys(parentTranscript.agentNotifications)).toEqual(['toolu_bg']) + expect(parentTranscript.lastTodos).toHaveLength(1) + }) + + it('hides the note that answers a tool call the parent left open', async () => { + const parentId = crypto.randomUUID() + const user = userEntry(parentId, 'run it') + await writeTranscript(parentId, [metaEntry(), user, toolUseEntry(parentId, 'tool-open', user.uuid)]) + + const sideId = await sideChatOf(parentId) + + expect((await sessionService.getSessionTranscript(sideId)).items).toEqual([]) + }) + + it('shows the whole history once detached', async () => { + const parentId = crypto.randomUUID() + await writeConversation(parentId) + const sideId = await sideChatOf(parentId) + + await detachSideChat(sideId) + + expect(visibleTexts((await sessionService.getSessionTranscript(sideId)).items)).toEqual(['hello there', 'hi']) + }) + it('creates a side chat through the branch route without a target message', async () => { const parentId = crypto.randomUUID() await writeConversation(parentId, {}, 'Parent') diff --git a/src/server/services/sessionService.ts b/src/server/services/sessionService.ts index a009d0bc..87cb02ab 100644 --- a/src/server/services/sessionService.ts +++ b/src/server/services/sessionService.ts @@ -33,6 +33,7 @@ import { findSubagentLinks, shouldHideTranscriptEntry, subagentEntriesToMessages, + withoutInheritedEntries, type MessageEntry, } from '../transcript/entries.js' import { buildSessionTranscript } from '../transcript/history.js' @@ -1832,7 +1833,10 @@ export class SessionService { throw ApiError.notFound(`Session not found: ${sessionId}`) } - const entries = await this.readJsonlFile(found.filePath) + const allEntries = await this.readJsonlFile(found.filePath) + const entries = sessionRelationFromEntries(allEntries).parent?.kind === 'side' + ? withoutInheritedEntries(allEntries) + : allEntries const messages = await this.appendSubagentToolMessages( found.projectDir, sessionId, diff --git a/src/server/transcript/entries.ts b/src/server/transcript/entries.ts index ea3718ce..a3f63359 100644 --- a/src/server/transcript/entries.ts +++ b/src/server/transcript/entries.ts @@ -360,6 +360,23 @@ export function pendingReportsFromEntries(entries: TranscriptEntry[]): SessionRe } /** Terminal background-task notifications recorded in the transcript. */ +function blocksOfType(entry: TranscriptEntry, type: string): ContentBlock[] { + const content = entry.message?.content + if (!Array.isArray(content)) return [] + return content.filter((block): block is ContentBlock => !!block && typeof block === 'object' && (block as ContentBlock).type === type) +} + +export function withoutInheritedEntries(entries: T[]): T[] { + const inheritedToolUseIds = new Set( + entries.filter((entry) => entry.forkedFrom).flatMap((entry) => blocksOfType(entry, 'tool_use').map((block) => block.id)), + ) + const answersInheritedToolUses = (entry: T) => { + const results = blocksOfType(entry, 'tool_result') + return results.length > 0 && results.every((block) => inheritedToolUseIds.has(block.tool_use_id)) + } + return entries.filter((entry) => !entry.forkedFrom && !answersInheritedToolUses(entry)) +} + export function collectTaskNotifications(entries: TranscriptEntry[]): TaskNotification[] { const notifications: TaskNotification[] = [] for (const entry of entries) { From 843e83eafedc8416bb4ef07acc2de3f87015a321 Mon Sep 17 00:00:00 2001 From: Diao Shengjia <104132148+GoDiao@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:52:55 +0800 Subject: [PATCH 2/5] refactor(side-chat): keep the task notification comment on its function --- docs/features/side-chat/tech-design.md | 4 ++-- src/server/transcript/entries.ts | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/features/side-chat/tech-design.md b/docs/features/side-chat/tech-design.md index 19dbca68..ecc258c9 100644 --- a/docs/features/side-chat/tech-design.md +++ b/docs/features/side-chat/tech-design.md @@ -1,6 +1,6 @@ # Side chat:技术设计 -状态:已实现。第一版随 PR #251 合并(`ee90358d`);隐藏继承的消息和从选中文字新建在 `feat/side-chat-selection-entry` 分支上。文中的行号以这个分支的代码为准,之后代码变了,行号可能对不上。 +状态:已实现。第一版随 PR #251 合并(`ee90358d`);隐藏继承的消息和从选中文字新建随 PR #252 加入。文中的行号以 PR #252 的代码为准,之后代码变了,行号可能对不上。 ## 背景 @@ -47,7 +47,7 @@ ### 显示:只显示 side chat 自己的消息 - 分叉时复制来的每条记录都带 `forkedFrom`(`sessionBranching.ts:566`)。结尾的分叉说明和之后新写的记录不带。 -- `getSessionTranscript`(`sessionService.ts:1830`)发现会话的父关系是 `side` 时,先用 `withoutInheritedEntries`(`transcript/entries.ts:369`)去掉继承的记录,再转换成显示条目。去掉的有两类: +- `getSessionTranscript`(`sessionService.ts:1830`)发现会话的父关系是 `side` 时,先用 `withoutInheritedEntries`(`transcript/entries.ts:379`)去掉继承的记录,再转换成显示条目。去掉的有两类: - 带 `forkedFrom` 的记录; - 只回答继承来的工具调用的 `tool_result` 消息。分叉点正好在一次工具调用中间时,分叉说明就是这样一条消息,它对应的工具调用已经去掉了,不能单独显示出来。 - 另一条说明(isMeta 说明和 "No response requested.")本来就不显示。 diff --git a/src/server/transcript/entries.ts b/src/server/transcript/entries.ts index a3f63359..9bca00dd 100644 --- a/src/server/transcript/entries.ts +++ b/src/server/transcript/entries.ts @@ -360,6 +360,16 @@ export function pendingReportsFromEntries(entries: TranscriptEntry[]): SessionRe } /** Terminal background-task notifications recorded in the transcript. */ +export function collectTaskNotifications(entries: TranscriptEntry[]): TaskNotification[] { + const notifications: TaskNotification[] = [] + for (const entry of entries) { + if (entry.message?.role !== 'user') continue + const notification = parseTaskNotification(entry.message.content, entry.timestamp) + if (notification) notifications.push(notification) + } + return notifications +} + function blocksOfType(entry: TranscriptEntry, type: string): ContentBlock[] { const content = entry.message?.content if (!Array.isArray(content)) return [] @@ -377,16 +387,6 @@ export function withoutInheritedEntries(entries: T[]) return entries.filter((entry) => !entry.forkedFrom && !answersInheritedToolUses(entry)) } -export function collectTaskNotifications(entries: TranscriptEntry[]): TaskNotification[] { - const notifications: TaskNotification[] = [] - for (const entry of entries) { - if (entry.message?.role !== 'user') continue - const notification = parseTaskNotification(entry.message.content, entry.timestamp) - if (notification) notifications.push(notification) - } - return notifications -} - function textOf(content: unknown): string { if (typeof content === 'string') return content if (!Array.isArray(content)) return '' From 1b77e5920a37118f11a34ef478902386ac457766 Mon Sep 17 00:00:00 2001 From: Diao Shengjia <104132148+GoDiao@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:58:26 +0800 Subject: [PATCH 3/5] feat(side-chat): focus the composer of a side chat the user just started --- .../src/components/chat/ChatInput.test.tsx | 13 +++++ desktop/src/components/chat/ChatInput.tsx | 7 +-- .../src/components/chat/MessageList.test.tsx | 2 + .../chat/SessionConversation.test.tsx | 10 +++- .../components/chat/SessionConversation.tsx | 3 ++ .../workspace/WorkspacePanel.test.tsx | 50 +++++++++++++++++-- .../components/workspace/WorkspacePanel.tsx | 11 +++- .../src/stores/workspacePanelStore.test.ts | 20 ++++++++ desktop/src/stores/workspacePanelStore.ts | 8 +++ docs/features/side-chat/tech-design.md | 10 ++-- 10 files changed, 122 insertions(+), 12 deletions(-) diff --git a/desktop/src/components/chat/ChatInput.test.tsx b/desktop/src/components/chat/ChatInput.test.tsx index 44ce2f83..c86ebbe5 100644 --- a/desktop/src/components/chat/ChatInput.test.tsx +++ b/desktop/src/components/chat/ChatInput.test.tsx @@ -937,6 +937,19 @@ describe('ChatInput file mentions', () => { expect(mocks.wsSend).not.toHaveBeenCalledWith(sessionId, expect.anything()) }) + it('takes the focus in a side chat when asked to', () => { + const sideId = 'side-focus' + useChatStore.setState((state) => ({ sessions: { ...state.sessions, [sideId]: state.sessions[sessionId]! } })) + render( + <> + + + , + ) + + expect(screen.getByRole('textbox')).toHaveFocus() + }) + 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]! } })) diff --git a/desktop/src/components/chat/ChatInput.tsx b/desktop/src/components/chat/ChatInput.tsx index f2caaa3a..46894448 100644 --- a/desktop/src/components/chat/ChatInput.tsx +++ b/desktop/src/components/chat/ChatInput.tsx @@ -66,6 +66,7 @@ type ChatInputProps = { variant?: 'default' | 'hero' compact?: boolean primary?: boolean + autoFocus?: boolean } const EMPTY_WORKSPACE_REFERENCES: WorkspaceChatReference[] = [] @@ -108,7 +109,7 @@ function insertComposerTokenAtRange(value: string, start: number, end: number, t } } -export function ChatInput({ sessionId, variant = 'default', compact = false, primary = true }: ChatInputProps) { +export function ChatInput({ sessionId, variant = 'default', compact = false, primary = true, autoFocus = false }: ChatInputProps) { const t = useTranslation() const isMobileComposer = useMobileViewport() && !isDesktopRuntime() const [input, setInput] = useState('') @@ -258,8 +259,8 @@ export function ChatInput({ sessionId, variant = 'default', compact = false, pri }, [saveComposerDraft]) useEffect(() => { - if (primary) textareaRef.current?.focus() - }, [isActive, primary]) + if (primary || autoFocus) textareaRef.current?.focus() + }, [isActive, primary, autoFocus]) useEffect(() => { if (!composerPrefill) return diff --git a/desktop/src/components/chat/MessageList.test.tsx b/desktop/src/components/chat/MessageList.test.tsx index 9acebdb1..61848293 100644 --- a/desktop/src/components/chat/MessageList.test.tsx +++ b/desktop/src/components/chat/MessageList.test.tsx @@ -1732,6 +1732,7 @@ describe('MessageList nested tool calls', () => { await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Selected text' })).toBeNull()) expect(branch).toHaveBeenCalledWith(ACTIVE_TAB, { kind: 'side' }) expect(useWorkspacePanelStore.getState().panelByTab[ACTIVE_TAB]?.tabs).toMatchObject([{ kind: 'sideChat', sessionId: 'side-1' }]) + expect(useWorkspacePanelStore.getState().sideChatToFocus).toBe('side-1') expect(useWorkspaceChatContextStore.getState().referencesBySession).toEqual({ 'side-1': [expect.objectContaining({ kind: 'chat-selection', path: 'chat://assistant/assistant-1', messageId: 'assistant-1', quote: 'this part' })], }) @@ -1761,6 +1762,7 @@ describe('MessageList nested tool calls', () => { await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Could not start a side chat: busy')) expect(useWorkspaceChatContextStore.getState().referencesBySession).toEqual({}) + expect(useWorkspacePanelStore.getState().sideChatToFocus).toBeNull() }) }) diff --git a/desktop/src/components/chat/SessionConversation.test.tsx b/desktop/src/components/chat/SessionConversation.test.tsx index 4d7bf65d..e5ad753c 100644 --- a/desktop/src/components/chat/SessionConversation.test.tsx +++ b/desktop/src/components/chat/SessionConversation.test.tsx @@ -3,8 +3,8 @@ import { cleanup, render, screen } from '@testing-library/react' import '@testing-library/jest-dom' vi.mock('./ChatInput', () => ({ - ChatInput: ({ sessionId, compact, primary }: { sessionId: string; compact?: boolean; primary?: boolean }) => ( -
+ ChatInput: ({ sessionId, compact, primary, autoFocus }: { sessionId: string; compact?: boolean; primary?: boolean; autoFocus?: boolean }) => ( +
), })) @@ -65,6 +65,12 @@ describe('SessionConversation', () => { expect(container.querySelector('[data-session-view="side"]')).not.toBeNull() }) + it('passes a focus request on to its composer', () => { + render() + + expect(screen.getByTestId('chat-input').dataset.autoFocus).toBe('true') + }) + it('shows the conversation, not the new-session placeholder, while a side chat’s history loads', () => { useChatStore.setState((state) => ({ sessions: { ...state.sessions, side: { ...state.sessions.side!, messages: [] } } })) diff --git a/desktop/src/components/chat/SessionConversation.tsx b/desktop/src/components/chat/SessionConversation.tsx index 65df406b..1b219abd 100644 --- a/desktop/src/components/chat/SessionConversation.tsx +++ b/desktop/src/components/chat/SessionConversation.tsx @@ -113,12 +113,14 @@ export function SessionConversation({ compact = false, primary = true, canStartSideChat = false, + focusInput = false, beforeInput, }: { sessionId: string compact?: boolean primary?: boolean canStartSideChat?: boolean + focusInput?: boolean beforeInput?: ReactNode }) { const t = useTranslation() @@ -190,6 +192,7 @@ export function SessionConversation({ variant={isEmpty && !isMemberSession && !compact ? 'hero' : 'default'} compact={compact} primary={primary} + autoFocus={focusInput} />
) diff --git a/desktop/src/components/workspace/WorkspacePanel.test.tsx b/desktop/src/components/workspace/WorkspacePanel.test.tsx index 711ac1ec..f496e22b 100644 --- a/desktop/src/components/workspace/WorkspacePanel.test.tsx +++ b/desktop/src/components/workspace/WorkspacePanel.test.tsx @@ -34,6 +34,7 @@ type WorkspaceApiMocks = { getWorkspaceFileMock: ReturnType getWorkspaceDiffMock: ReturnType listSideChatsMock: ReturnType + branchMock: ReturnType } var mocks: WorkspaceApiMocks | undefined @@ -338,10 +339,13 @@ vi.mock('../chat/UiPageFrame', async (importOriginal) => { } }) +const sideChatRenders = vi.hoisted(() => [] as Array<{ sessionId: string; focusInput: boolean }>) + vi.mock('../chat/SessionConversation', () => ({ - SessionConversation: ({ sessionId, compact, primary }: { sessionId: string; compact?: boolean; primary?: boolean }) => ( -
- ), + SessionConversation: ({ sessionId, compact, primary, focusInput = false }: { sessionId: string; compact?: boolean; primary?: boolean; focusInput?: boolean }) => { + sideChatRenders.push({ sessionId, focusInput }) + return
+ }, })) const sideChatActions = vi.hoisted(() => ({ closeSideChat: vi.fn(async () => {}), detachSideChat: vi.fn(async () => {}) })) @@ -357,6 +361,7 @@ vi.mock('../../api/sessions', () => ({ getWorkspaceFileMock: vi.fn(), getWorkspaceDiffMock: vi.fn(), listSideChatsMock: vi.fn(async () => ({ sessions: [] })), + branchMock: vi.fn(), } } @@ -366,6 +371,7 @@ vi.mock('../../api/sessions', () => ({ getWorkspaceFile: mocks.getWorkspaceFileMock, getWorkspaceDiff: mocks.getWorkspaceDiffMock, listSideChats: mocks.listSideChatsMock, + branch: mocks.branchMock, } })(), })) @@ -2121,6 +2127,44 @@ describe('WorkspacePanel', () => { return renderPanel('parent') } + function focusRequests(sessionId: string) { + return sideChatRenders.filter((render) => render.sessionId === sessionId && render.focusInput) + } + + it('focuses the composer of a side chat the user just started, once', async () => { + sideChatRenders.length = 0 + await setWorkspaceState((state) => ({ ...state, sideChatToFocus: 'side' })) + + const view = await renderParent(sideChatTab) + + expect(view.getByTestId('side-chat-conversation').dataset.session).toBe('side') + expect(focusRequests('side')).toHaveLength(1) + expect(sideChatRenders.at(-1)).toEqual({ sessionId: 'side', focusInput: false }) + expect(useWorkspacePanelStore.getState().sideChatToFocus).toBeNull() + }) + + it('focuses the side chat started from the new tab page', async () => { + sideChatRenders.length = 0 + getMocks().branchMock.mockResolvedValue({ sessionId: 'side-new', title: 'btw', workDir: '/repo', sourceSessionId: 'parent' }) + await setWorkspaceState((state) => ({ ...state, panelByTab: { ...state.panelByTab, parent: panelState({ id: 'launcher', kind: 'launcher' }) } })) + const view = await renderPanel('parent') + + await clickElement(within(view.getByTestId('workspace-launcher')).getByRole('button', { name: 'Side chat' })) + + await waitFor(() => expect(focusRequests('side-new')).toHaveLength(1)) + }) + + it('leaves the focus alone for a side chat tab brought back by syncing', async () => { + sideChatRenders.length = 0 + getMocks().listSideChatsMock.mockResolvedValue({ sessions: [{ id: 'side' }] }) + await setWorkspaceState((state) => ({ ...state, panelByTab: { ...state.panelByTab, parent: panelState() } })) + + const view = await renderPanel('parent') + + await waitFor(() => expect(view.getByTestId('side-chat-conversation').dataset.session).toBe('side')) + expect(focusRequests('side')).toEqual([]) + }) + it('keeps a side chat browser tab under the side chat when it mounts again in the parent panel', async () => { const view = await renderParent({ id: 'browser-tab', kind: 'browser', url: 'http://localhost:3000/', title: 'Dev', sessionId: 'side' }) diff --git a/desktop/src/components/workspace/WorkspacePanel.tsx b/desktop/src/components/workspace/WorkspacePanel.tsx index 432be7c2..ae76f121 100644 --- a/desktop/src/components/workspace/WorkspacePanel.tsx +++ b/desktop/src/components/workspace/WorkspacePanel.tsx @@ -1236,6 +1236,15 @@ function SideChatTabTrigger({ ) } +function SideChatView({ sessionId }: { sessionId: string }) { + const focusInput = useWorkspacePanelStore((state) => state.sideChatToFocus === sessionId) + const clearSideChatFocus = useWorkspacePanelStore((state) => state.clearSideChatFocus) + useEffect(() => { + if (focusInput) clearSideChatFocus(sessionId) + }, [clearSideChatFocus, focusInput, sessionId]) + return +} + function WorkspaceRefresh({ sessionId }: { sessionId: string }) { useWorkspaceRefresh(sessionId) return null @@ -1326,7 +1335,7 @@ function OpenWorkspacePanel({ panelId: sessionId, sessionTitle, titleRowStyle, t case 'uiPage': return case 'sideChat': - return + return case 'task': return case 'inbox': diff --git a/desktop/src/stores/workspacePanelStore.test.ts b/desktop/src/stores/workspacePanelStore.test.ts index 929037a3..b52aef21 100644 --- a/desktop/src/stores/workspacePanelStore.test.ts +++ b/desktop/src/stores/workspacePanelStore.test.ts @@ -878,6 +878,7 @@ describe('artifact tabs', () => { const panel = useWorkspacePanelStore.getState().panelByTab.parent! expect(panel.tabs.map((tab) => tab.kind === 'sideChat' ? tab.sessionId : tab.kind)).toEqual(['side-kept', 'files', 'side-new']) + expect(useWorkspacePanelStore.getState().sideChatToFocus).toBeNull() expect(panel.activeTabId).toBe(kept) expect(mocks.disconnectSession).toHaveBeenCalledWith('side-gone') }) @@ -991,12 +992,31 @@ describe('artifact tabs', () => { await expect(useWorkspacePanelStore.getState().createSideChat('parent')).resolves.toBe('side-created') + expect(useWorkspacePanelStore.getState().sideChatToFocus).toBe('side-created') + expect(mocks.branchMock).toHaveBeenCalledWith('parent', { kind: 'side' }) const panel = useWorkspacePanelStore.getState().panelByTab.parent! expect(panel.isOpen).toBe(true) expect(panel.tabs).toMatchObject([{ kind: 'sideChat', sessionId: 'side-created' }]) }) + it('asks for no focus when the side chat could not be started', async () => { + mocks.branchMock.mockRejectedValue(new Error('busy')) + + await expect(useWorkspacePanelStore.getState().createSideChat('parent')).rejects.toThrow('busy') + + expect(useWorkspacePanelStore.getState().sideChatToFocus).toBeNull() + }) + + it('clears the focus request only for the side chat it names', () => { + useWorkspacePanelStore.setState({ sideChatToFocus: 'side-a' }) + + useWorkspacePanelStore.getState().clearSideChatFocus('side-b') + expect(useWorkspacePanelStore.getState().sideChatToFocus).toBe('side-a') + useWorkspacePanelStore.getState().clearSideChatFocus('side-a') + expect(useWorkspacePanelStore.getState().sideChatToFocus).toBeNull() + }) + it('disconnects the side chats of a parent that is released', () => { openSideChat('parent', 'side') diff --git a/desktop/src/stores/workspacePanelStore.ts b/desktop/src/stores/workspacePanelStore.ts index abc28576..0951d9fd 100644 --- a/desktop/src/stores/workspacePanelStore.ts +++ b/desktop/src/stores/workspacePanelStore.ts @@ -95,6 +95,7 @@ type WorkspacePanelErrorState = { type WorkspacePanelStore = { panelByTab: Record width: number + sideChatToFocus: string | null statusBySession: Record treeBySessionPath: Record | undefined> previewsBySession: Record | undefined> @@ -128,6 +129,7 @@ type WorkspacePanelStore = { releaseSession: (sessionId: string) => void clearSession: (sessionId: string) => void createSideChat: (sessionId: string) => Promise + clearSideChatFocus: (sessionId: string) => void syncSideChats: (sessionId: string) => Promise } @@ -447,6 +449,7 @@ function writeStoredPanels(panelByTab: Record((set, get) => ({ panelByTab: readStoredPanels(), width: WORKSPACE_PANEL_DEFAULT_WIDTH, + sideChatToFocus: null, statusBySession: {}, treeBySessionPath: {}, previewsBySession: {}, @@ -874,9 +877,14 @@ export const useWorkspacePanelStore = create((set, get) => createSideChat: async (sessionId) => { const created = await sessionsApi.branch(sessionId, { kind: 'side' }) get().openTab(sessionId, { kind: 'sideChat', sessionId: created.sessionId }) + set({ sideChatToFocus: created.sessionId }) return created.sessionId }, + clearSideChatFocus: (sessionId) => { + if (get().sideChatToFocus === sessionId) set({ sideChatToFocus: null }) + }, + syncSideChats: async (sessionId) => { const listed = new Set(sideChatIds(get().panelByTab[sessionId]?.tabs ?? [])) const sessions = (await sessionsApi.listSideChats(sessionId)).sessions.filter((session) => !isDeletedSession(session.id)) diff --git a/docs/features/side-chat/tech-design.md b/docs/features/side-chat/tech-design.md index ecc258c9..22f52527 100644 --- a/docs/features/side-chat/tech-design.md +++ b/docs/features/side-chat/tech-design.md @@ -159,7 +159,10 @@ side chat 标签: - 是否提供这个动作由 `canStartSideChat` 决定,`ActiveSession` 传入 `canUsePanel`(`ActiveSession.tsx:199`),也就是这个会话能不能用右侧面板。所以: - side chat 自己的消息里只有 Reply,不再开一层; - 手机布局(H5)和团队成员会话没有面板,也不提供。新标签页里的入口在这两种情况下同样看不到。 -- 新建后不把焦点移进 side chat 的输入框。side chat 的输入框不抢焦点(见上文 `primary`),要做到需要给它加一个"新建后聚焦"的信号,现有结构里没有。 +- 用户新建 side chat 后(两个入口都算),焦点进入它的输入框,可以直接打字: + - `createSideChat` 成功后把新会话 id 记进面板 store 的 `sideChatToFocus`。这个字段不写进 localStorage,失败时不设置。 + - 面板里的 `SideChatView`(`WorkspacePanel.tsx`)发现它指向自己时,把 `focusInput` 传给 `SessionConversation`,再在 effect 里清掉。`ChatInput` 收到 `autoFocus`,在已有的自动聚焦 effect 里聚焦。子组件的 effect 先于父组件运行,所以聚焦发生在清除之前,之后不会再聚焦。 + - 只有 `createSideChat` 设置这个信号。`syncSideChats` 补回的标签、重启后恢复的标签、切换标签、side chat 打开的页面都不会让输入框抢焦点;side chat 输入框平时仍然不抢焦点(见上文 `primary`)。 面板归属:side chat 的面板就是父会话的面板。 @@ -222,7 +225,8 @@ side chat 标签: - Detach 运行中禁用; - 菜单的 Detach、重命名,以及失败提示; - × 关闭。 -- `WorkspacePanel.test.tsx` 的新标签页:新建 side chat 和失败提示。 +- `WorkspacePanel.test.tsx` 的新标签页:新建 side chat 和失败提示。"side chats" 组:新建的 side chat 聚焦一次,从新标签页新建后聚焦,对账补回的标签不聚焦。 +- `workspacePanelStore.test.ts`:新建后记下要聚焦的 side chat,失败和对账时不记,清除只清自己。 - `MessageList.test.tsx` 的 "starting a side chat from a selection" 组:主会话里先 Start a side chat 再 Reply,side chat 里只有 Reply;新建后引用在新会话名下、弹出条关闭;创建期间不能重复点;失败提示。 - `SelectionPopover.test.tsx`:多个动作各自生效,loading 的动作禁用。 - `ActiveSession.test.tsx`:能用面板时提供入口,手机布局不提供。 @@ -233,7 +237,7 @@ side chat 标签: - 对账:补上、删掉、空列表关闭面板、激活标签失效时改激活最后一个、请求期间删除和新建; - 重启后从 localStorage 恢复。 - 其他测试文件: - - `ChatInput.test.tsx`:`primary` 为假时不抢焦点、不显示启动控件,发送到传入的会话; + - `ChatInput.test.tsx`:`primary` 为假时不抢焦点、不显示启动控件,发送到传入的会话;传入 `autoFocus` 时获得焦点; - `lib/sideChats.test.ts`:接口失败时标签保留; - `sessionStore.test.ts`:Detach 后刷新列表;单个和批量删除的 side chat 警告; - `Sidebar.test.tsx`:批量删除的成功数只数选中的会话; From 7972ff8e8693221ad201ab154800ac1fdc6cf6b2 Mon Sep 17 00:00:00 2001 From: Diao Shengjia <104132148+GoDiao@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:03:27 +0800 Subject: [PATCH 4/5] feat(side-chat): keep the side chat composer to the message box --- .../src/components/chat/ChatInput.test.tsx | 39 +++++++++++++++++++ desktop/src/components/chat/ChatInput.tsx | 15 +++---- docs/features/side-chat/tech-design.md | 8 +++- 3 files changed, 53 insertions(+), 9 deletions(-) diff --git a/desktop/src/components/chat/ChatInput.test.tsx b/desktop/src/components/chat/ChatInput.test.tsx index c86ebbe5..7aa63b94 100644 --- a/desktop/src/components/chat/ChatInput.test.tsx +++ b/desktop/src/components/chat/ChatInput.test.tsx @@ -950,6 +950,45 @@ describe('ChatInput file mentions', () => { expect(screen.getByRole('textbox')).toHaveFocus() }) + it.each([ + ['the main composer', true, true], + ['a side chat composer', false, false], + ] as const)('shows the tools menu and the controls row in %s: %s', (_name, primary, shown) => { + render() + + expect(screen.queryByRole('button', { name: 'Open composer tools' }) !== null).toBe(shown) + expect(screen.queryByTestId('chat-input-controls') !== null).toBe(shown) + }) + + it.each([ + ['the main composer', true, true], + ['a side chat composer', false, false], + ] as const)('takes dropped and pasted files in %s: %s', async (_name, primary, accepted) => { + Object.defineProperty(window, 'dreamcoderShell', { configurable: true, value: {} }) + const droppedFile = new File(['log'], 'dropped.log', { type: 'text/plain' }) + Object.defineProperty(droppedFile, 'path', { configurable: true, value: '/tmp/dropped.log' }) + const dataTransfer = { types: ['Files'], files: [droppedFile], dropEffect: '' } + const image = new File(['png'], 'shot.png', { type: 'image/png' }) + const imageItem = { kind: 'file', type: 'image/png', getAsFile: () => image } + render() + + const panel = screen.getByTestId('chat-input-panel') + fireEvent.dragOver(panel, { dataTransfer }) + expect(screen.queryByTestId('chat-input-drop-overlay') !== null).toBe(accepted) + fireEvent.drop(panel, { dataTransfer }) + const imagePasteKept = fireEvent.paste(screen.getByRole('textbox'), { clipboardData: { items: [imageItem] } }) + const textPasteKept = fireEvent.paste(screen.getByRole('textbox'), { clipboardData: { items: [{ kind: 'string', type: 'text/plain', getAsFile: () => null }] } }) + + expect(imagePasteKept).toBe(!accepted) + expect(textPasteKept).toBe(true) + if (accepted) expect(await screen.findByText('dropped.log')).toBeInTheDocument() + else { + await act(async () => { await Promise.resolve() }) + expect(screen.queryByText('dropped.log')).not.toBeInTheDocument() + expect(screen.queryByText(/pasted-image/)).not.toBeInTheDocument() + } + }) + 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]! } })) diff --git a/desktop/src/components/chat/ChatInput.tsx b/desktop/src/components/chat/ChatInput.tsx index 46894448..29711ce9 100644 --- a/desktop/src/components/chat/ChatInput.tsx +++ b/desktop/src/components/chat/ChatInput.tsx @@ -198,6 +198,7 @@ export function ChatInput({ sessionId, variant = 'default', compact = false, pri const isActive = chatState !== 'idle' const isWorkspaceMissing = activeSession?.workDirExists === false const hasWorkspaceReferences = !isMemberSession && workspaceReferences.length > 0 + const fullComposer = primary && !isMemberSession const isHeroComposer = variant === 'hero' && primary && !isMemberSession && !compact const resolvedWorkDir = activeSession?.workDir || gitInfo?.workDir || undefined const showLaunchControls = primary && !isMemberSession && messageCount === 0 @@ -338,10 +339,10 @@ export function ChatInput({ sessionId, variant = 'default', compact = false, pri }, [refreshGitInfo]) useEffect(() => { - if (isMemberSession || messageCount === 0) return + if (!fullComposer || messageCount === 0) return const timeout = setTimeout(refreshGitInfo, chatState === 'idle' ? 0 : 500) return () => clearTimeout(timeout) - }, [sessionId, chatState, isMemberSession, messageCount, refreshGitInfo, slashCommandCount]) + }, [sessionId, chatState, fullComposer, messageCount, refreshGitInfo, slashCommandCount]) useEffect(() => { if (!isMemberSession) return @@ -730,7 +731,7 @@ export function ChatInput({ sessionId, variant = 'default', compact = false, pri } const handlePaste = (event: React.ClipboardEvent) => { - if (isMemberSession) return + if (!fullComposer) return const items = event.clipboardData?.items if (!items) return const files = clipboardImageFiles(items) @@ -756,7 +757,7 @@ export function ChatInput({ sessionId, variant = 'default', compact = false, pri }, [setComposerAttachments]) const { isDragActive, dragHandlers } = useComposerFileDrop({ - disabled: isMemberSession || isWorkspaceMissing, + disabled: !fullComposer || isWorkspaceMissing, onAttachments: appendAttachments, onError: (error) => { console.warn('[attachments] Failed to read dropped files', error) @@ -991,7 +992,7 @@ export function ChatInput({ sessionId, variant = 'default', compact = false, pri dragHandlers={dragHandlers} overlays={overlays} mobile={isMobileComposer} - plusMenu={isMemberSession ? undefined : { + plusMenu={fullComposer ? { open: plusMenuOpen, onToggle: () => setPlusMenuOpen((value) => !value), onClose: () => setPlusMenuOpen(false), @@ -1000,7 +1001,7 @@ export function ChatInput({ sessionId, variant = 'default', compact = false, pri addFilesLabel, slashCommandsLabel, toggleLabel: t('chat.composerTools'), - }} + } : undefined} textareaRef={textareaRef} textareaProps={{ value: input, @@ -1022,7 +1023,7 @@ export function ChatInput({ sessionId, variant = 'default', compact = false, pri }} /> - {!isMemberSession && ( + {fullComposer && ( Date: Sun, 15 Nov 2026 12:10:54 +0800 Subject: [PATCH 5/5] fix(composer): measure the input height again when its width changes --- desktop/src/components/chat/ChatInput.tsx | 10 +-- .../components/chat/ComposerShell.test.tsx | 65 ++++++++++++++++++- desktop/src/components/chat/ComposerShell.tsx | 26 +++++++- desktop/src/pages/EmptySession.tsx | 6 +- 4 files changed, 91 insertions(+), 16 deletions(-) diff --git a/desktop/src/components/chat/ChatInput.tsx b/desktop/src/components/chat/ChatInput.tsx index 29711ce9..a7deffc0 100644 --- a/desktop/src/components/chat/ChatInput.tsx +++ b/desktop/src/components/chat/ChatInput.tsx @@ -35,7 +35,7 @@ import { FileSearchMenu, type FileSearchMenuHandle } from './FileSearchMenu' import { LocalSlashCommandPanel, type LocalSlashCommandName } from './LocalSlashCommandPanel' import { ContextUsageIndicator } from './ContextUsageIndicator' import { ProviderGateCard, useProviderMissing } from './ProviderRequiredNotice' -import { ComposerBox, ComposerControls, resizeComposerTextarea } from './ComposerShell' +import { ComposerBox, ComposerControls } from './ComposerShell' import { ProjectLabel } from './ProjectLabel' import { FALLBACK_SLASH_COMMANDS, @@ -199,9 +199,9 @@ export function ChatInput({ sessionId, variant = 'default', compact = false, pri const isWorkspaceMissing = activeSession?.workDirExists === false const hasWorkspaceReferences = !isMemberSession && workspaceReferences.length > 0 const fullComposer = primary && !isMemberSession - const isHeroComposer = variant === 'hero' && primary && !isMemberSession && !compact + const isHeroComposer = variant === 'hero' && fullComposer && !compact const resolvedWorkDir = activeSession?.workDir || gitInfo?.workDir || undefined - const showLaunchControls = primary && !isMemberSession && messageCount === 0 + const showLaunchControls = fullComposer && messageCount === 0 const useCompactControls = compact || isMobileComposer const activeLaunchWorkDir = showLaunchControls ? (launchWorkDir || resolvedWorkDir || '') : (resolvedWorkDir || '') const pendingSlashUiAction = !isMemberSession && input.trim().startsWith('/') @@ -364,10 +364,6 @@ export function ChatInput({ sessionId, variant = 'default', compact = false, pri }) }, [activeSession?.workDir, sessionId, gitInfo?.workDir, showLaunchControls]) - useEffect(() => { - resizeComposerTextarea(textareaRef.current) - }, [input, providerMissing]) - diff --git a/desktop/src/components/chat/ComposerShell.test.tsx b/desktop/src/components/chat/ComposerShell.test.tsx index 73a3dd84..855c6fac 100644 --- a/desktop/src/components/chat/ComposerShell.test.tsx +++ b/desktop/src/components/chat/ComposerShell.test.tsx @@ -1,7 +1,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { createRef, useRef, useState } from 'react' import '@testing-library/jest-dom' -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { ComposerBox } from './ComposerShell' function Harness({ onOuterEscape }: { onOuterEscape: () => void }) { @@ -89,3 +89,66 @@ describe('ComposerBox plus menu', () => { expect(screen.getByRole('textbox', { name: 'Message' })).toHaveFocus() }) }) + +describe('ComposerBox height', () => { + afterEach(() => vi.unstubAllGlobals()) + + function renderBox(value: string) { + const textareaRef = createRef() + const box = (text: string) => ( + ()} + testId="composer" + textareaRef={textareaRef} + textareaProps={{ 'aria-label': 'Message', value: text, onChange: () => {} }} + action={{ mode: 'send', disabled: true, onClick: () => {}, label: 'Send' }} + /> + ) + const view = render(box(value)) + return { textarea: screen.getByRole('textbox', { name: 'Message' }), rerender: (text: string) => view.rerender(box(text)) } + } + + function observeResizes() { + const callbacks: ResizeObserverCallback[] = [] + vi.stubGlobal('ResizeObserver', class { + constructor(callback: ResizeObserverCallback) { callbacks.push(callback) } + observe() {} + unobserve() {} + disconnect() {} + }) + return (width: number) => { + for (const callback of callbacks) callback([{ contentRect: { width } } as ResizeObserverEntry], {} as ResizeObserver) + } + } + + function setScrollHeight(textarea: HTMLElement, height: number) { + Object.defineProperty(textarea, 'scrollHeight', { configurable: true, value: height }) + } + + it('measures again when the box gets wider, and only then', () => { + const resize = observeResizes() + const { textarea } = renderBox('') + setScrollHeight(textarea, 154) + resize(40) + expect(textarea.style.height).toBe('154px') + + setScrollHeight(textarea, 32) + resize(400) + expect(textarea.style.height).toBe('32px') + + setScrollHeight(textarea, 60) + resize(400) + expect(textarea.style.height).toBe('32px') + }) + + it('grows with its text up to the maximum height', () => { + const { textarea, rerender } = renderBox('') + setScrollHeight(textarea, 54) + rerender('two\nlines') + expect(textarea.style.height).toBe('54px') + + setScrollHeight(textarea, 900) + rerender('many\nlines') + expect(textarea.style.height).toBe('200px') + }) +}) diff --git a/desktop/src/components/chat/ComposerShell.tsx b/desktop/src/components/chat/ComposerShell.tsx index ddef4672..3473596b 100644 --- a/desktop/src/components/chat/ComposerShell.tsx +++ b/desktop/src/components/chat/ComposerShell.tsx @@ -1,5 +1,5 @@ import { Tooltip as HintTooltip } from '../shared/Tooltip' -import { type DragEventHandler, type ReactNode, type RefObject, type TextareaHTMLAttributes } from 'react' +import { useEffect, type DragEventHandler, type ReactNode, type RefObject, type TextareaHTMLAttributes } from 'react' import { ArrowUp, Paperclip, Plus, Square } from 'lucide-react' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '../shared/ui/dropdown-menu' import { Button } from '../shared/ui/button' @@ -61,6 +61,7 @@ export function ComposerBox({ }: ComposerBoxProps) { const ActionIcon = action.mode === 'stop' ? Square : ArrowUp const actionActive = action.mode === 'stop' || !action.disabled + useComposerTextareaHeight(textareaRef, textareaProps.value) return (
, value: unknown) { + useEffect(() => { + if (textareaRef.current) resizeComposerTextarea(textareaRef.current) + }, [textareaRef, value]) + + useEffect(() => { + const el = textareaRef.current + if (!el || typeof ResizeObserver === 'undefined') return + let width: number | undefined + const observer = new ResizeObserver(([entry]) => { + const nextWidth = entry?.contentRect.width + if (nextWidth === undefined || nextWidth === width) return + width = nextWidth + resizeComposerTextarea(el) + }) + observer.observe(el) + return () => observer.disconnect() + }, [textareaRef]) +} + function ComposerPlusMenu({ open, diff --git a/desktop/src/pages/EmptySession.tsx b/desktop/src/pages/EmptySession.tsx index 8d4d920d..cb01d738 100644 --- a/desktop/src/pages/EmptySession.tsx +++ b/desktop/src/pages/EmptySession.tsx @@ -11,7 +11,7 @@ import { RepositoryLaunchControls, type RepositoryLaunchError } from '../compone import { PermissionModeSelector } from '../components/controls/PermissionModeSelector' import { ModelSelector } from '../components/controls/ModelSelector' import { ProviderGateCard, useProviderMissing } from '../components/chat/ProviderRequiredNotice' -import { ComposerBox, ComposerControls, resizeComposerTextarea } from '../components/chat/ComposerShell' +import { ComposerBox, ComposerControls } from '../components/chat/ComposerShell' import { AttachmentGallery } from '../components/chat/AttachmentGallery' import { ComposerDropOverlay } from '../components/chat/ComposerDropOverlay' import { ContextUsageIndicator } from '../components/chat/ContextUsageIndicator' @@ -98,10 +98,6 @@ export function EmptySession() { textareaRef.current?.focus() }, []) - useEffect(() => { - resizeComposerTextarea(textareaRef.current) - }, [input, providerMissing]) - useEffect(() => { let cancelled = false