From 2c3b698ec136bc8f188c03f781066a519e74f525 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 10:36:06 +0800 Subject: [PATCH 01/91] fix(startup): wait for the local service before loading a session Refresh on the desktop client raced the background opencode service: startApp renders first and fires the restored session's message.list while the local serve is still starting / its registry address has not been written back yet, so the request fails at the transport layer and the session is stuck in loadState 'error' with input disabled. Two changes close it: - useSessionManager skips the load while serviceStore.starting is true for a local-server session, and re-runs once starting flips back to false (address already applied). - reconnectServerSSE now flags a first successful connection after an endpoint change so it also broadcasts onReconnected, letting the failed initial fetch self-heal. A dedicated endpointReconnectFlags is used instead of serverSwitchFlags so subscribeToEvents' server-switch path (refreshed by server-change listeners) does not double-fetch. --- src/api/events.test.ts | 29 +++++++++++++++++++++++ src/api/events.ts | 23 ++++++++++++++++--- src/hooks/useSessionManager.ts | 42 ++++++++++++++++++++++------------ 3 files changed, 77 insertions(+), 17 deletions(-) diff --git a/src/api/events.test.ts b/src/api/events.test.ts index 679356da4..963bd0fba 100644 --- a/src/api/events.test.ts +++ b/src/api/events.test.ts @@ -352,4 +352,33 @@ describe('v2 event dispatch', () => { unsubscribe() }) + + /** + * 从未连上过(本地 serve 启动竞态:初始拉取在端点就绪前已失败), + * 端点变更强制重连后的首个成功连接也必须广播补偿,否则失败态不自愈。 + */ + it('broadcasts onReconnected on first connect after reconnectServerSSE when never connected', async () => { + const harnesses: Array> = [] + subscribeMock.mockImplementation(() => { + const harness = createEventStream() + harnesses.push(harness) + return harness.stream + }) + + const { subscribeToServerEvents, reconnectServerSSE } = await import('./events') + const onReconnected = vi.fn() + const unsubscribe = subscribeToServerEvents('test-server', { onReconnected }) + await Promise.resolve() + + // 首条流不推任何事件 → hasConnectedBefore 保持 false(从未连上) + reconnectServerSSE('test-server') + await Promise.resolve() + expect(harnesses.length).toBe(2) + + harnesses[1].emit(v2Event('session.idle', { sessionID: 's1' })) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(onReconnected).toHaveBeenCalledWith('server-switch') + + unsubscribe() + }) }) diff --git a/src/api/events.ts b/src/api/events.ts index 0122f1ed4..e42d73ec8 100644 --- a/src/api/events.ts +++ b/src/api/events.ts @@ -66,6 +66,15 @@ const connectionListeners = new Map void>> /** 是否因为切换服务器而触发的重连(按 serverId) */ const serverSwitchFlags = new Map() +/** + * 端点变更(reconnectServerSSE)触发、但此前从未成功连接过的重连(按 serverId)。 + * 与 serverSwitchFlags 分开:subscribeToEvents 切服务器也用后者,那条链路的 + * 数据刷新由 server-change 监听器负责,首个连接不能重复广播;而这里针对的是 + * 「本地 serve 就绪地址回写 / WSL 换端口后,初始拉取已在端点就绪前失败」, + * 首个成功连接必须广播让订阅者补偿拉取,否则失败态没有重试入口。 + */ +const endpointReconnectFlags = new Map() + let lifecycleListenersRegistered = false let isInBackground = false let keepaliveTimer: ReturnType | null = null @@ -563,15 +572,20 @@ async function connectServer(serverId: string): Promise { if (!conn.hasConnectedBefore) { conn.hasConnectedBefore = true - // 首次连接不广播 onReconnected:初始加载由各订阅方自己拉取; - // 若本次连接是服务器切换后的重连,清掉标记即可(切服务器的 - // 数据刷新由 server-change 链路负责) + // 首次连接一般不广播 onReconnected:初始加载由各订阅方自己拉取。 + // 但端点变更触发的重连(本地 serve 就绪 / WSL 换端口),此前的初始 + // 拉取可能已在端点就绪前失败,必须广播让订阅者补偿拉取。 + const endpointReconnect = endpointReconnectFlags.get(serverId) === true + endpointReconnectFlags.delete(serverId) serverSwitchFlags.delete(serverId) updateConnectionState(serverId, { state: 'connected', reconnectAttempt: 0, error: undefined, }) + if (endpointReconnect) { + broadcastReconnected(conn, 'server-switch') + } } else if (conn.info.state !== 'connected') { updateConnectionState(serverId, { state: 'connected', reconnectAttempt: 0, error: undefined }) // 掉线后的**重连成功**:断线窗口错过的事件协议明确不补发, @@ -730,6 +744,9 @@ export function reconnectServerSSE(serverId: string): void { if (hadConnected) { conn.hasConnectedBefore = true serverSwitchFlags.set(serverId, true) + } else { + // 此前从未连上:首个成功连接也要走补偿广播(见 endpointReconnectFlags 注释) + endpointReconnectFlags.set(serverId, true) } if (conn.subscribers.size > 0) { connectServer(serverId) diff --git a/src/hooks/useSessionManager.ts b/src/hooks/useSessionManager.ts index 3aaf0df33..58dba031e 100644 --- a/src/hooks/useSessionManager.ts +++ b/src/hooks/useSessionManager.ts @@ -10,6 +10,8 @@ import { useCallback, useEffect, useRef } from 'react' import { logger } from '../utils/logger' import { messageStore, type RevertState } from '../store' +import { LOCAL_SERVER_ID } from '../store/serverStore' +import { useServiceStore } from '../store/serviceStore' import { sessionKeyToServerId } from '../utils/sessionKey' import { getSessionMessagesPage, getSession, revertMessage, unrevertSession } from '../api' import { sessionErrorHandler } from '../utils' @@ -76,6 +78,10 @@ export function useSessionManager({ /** 每个 session 的历史翻页 in-flight 守卫(官方 messageLoads 同款,防止并发翻页) */ const historyLoadsRef = useRef>>(new Map()) const loadSessionRef = useRef<(sid: string, options?: { force?: boolean }) => Promise>(async () => {}) + // 桌面端本地 serve 的拉起 / registry 地址回写状态(main.tsx 的 + // initializeNativeDesktopService 期间为 true)。此刻本地地址未就绪, + // 向本地服务器发请求必在传输层失败。 + const { starting: localServiceStarting } = useServiceStore() /** * 用游标翻一页更老的历史并前插(官方 message.loadMore 同款)。 @@ -402,22 +408,30 @@ export function useSessionManager({ // focused pane / URL 的同步由 App 顶层统一负责, // 这里不再写任何“全局当前 session”状态。 useEffect(() => { - if (sessionId) { - const cached = messageStore.getSessionState(sessionId) - const canUseCached = !!cached && cached.loadState === 'loaded' && !cached.isStale && cached.messages.length > 0 - - if (canUseCached) { - logger.log('[SessionManager] switch:use-cached', { - sessionId, - cachedCount: cached.messages.length, - }) - return - } + if (!sessionId) return + + const cached = messageStore.getSessionState(sessionId) + const canUseCached = !!cached && cached.loadState === 'loaded' && !cached.isStale && cached.messages.length > 0 - logger.log('[SessionManager] switch:fetch-session', { sessionId }) - void loadSessionRef.current(sessionId) + if (canUseCached) { + logger.log('[SessionManager] switch:use-cached', { + sessionId, + cachedCount: cached.messages.length, + }) + return } - }, [sessionId]) + + // 本地 serve 还在拉起 / registry 地址回写:此刻向本地服务器发请求必在 + // 传输层失败(ClientError: Transport),且失败态没有重试入口会卡住。 + // 等 starting 翻回 false(地址已就绪)再加载。 + if (localServiceStarting && sessionKeyToServerId(sessionId) === LOCAL_SERVER_ID) { + logger.log('[SessionManager] switch:wait-local-service', { sessionId }) + return + } + + logger.log('[SessionManager] switch:fetch-session', { sessionId }) + void loadSessionRef.current(sessionId) + }, [sessionId, localServiceStarting]) return { loadSession, From 1ca87a18999e855c6f995c7a1f06cdf95127f1cb Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 10:45:54 +0800 Subject: [PATCH 02/91] fix(permissions): show the diff preview before approving edit/write v2 sends the edit/write preview as metadata.files: [FileDiff.Info] ({ file, patch, additions, deletions, status }), but both permission components only read the v1 metadata.diff / metadata.filediff fields, and ToolPartView also hid the ToolBody that could have derived the diff from the tool input. Together the approval card rendered blank. - Add extractPermissionDiff() reading filediff > files[].patch > diff, shared by InlinePermission and PermissionDialog. - ToolPartView now only hides ToolBody when the permission metadata actually carries a diff; otherwise ToolBody renders the input-derived diff as a fallback, so the diff shows exactly once either way. --- src/features/chat/InlinePermission.tsx | 21 ++----- src/features/chat/PermissionDialog.tsx | 21 +------ src/features/chat/permissionDiff.test.ts | 65 +++++++++++++++++++++ src/features/chat/permissionDiff.ts | 57 ++++++++++++++++++ src/features/message/parts/ToolPartView.tsx | 12 +++- 5 files changed, 139 insertions(+), 37 deletions(-) create mode 100644 src/features/chat/permissionDiff.test.ts create mode 100644 src/features/chat/permissionDiff.ts diff --git a/src/features/chat/InlinePermission.tsx b/src/features/chat/InlinePermission.tsx index 3ce3d0e7f..61f311a67 100644 --- a/src/features/chat/InlinePermission.tsx +++ b/src/features/chat/InlinePermission.tsx @@ -12,6 +12,7 @@ import type { ApiPermissionRequest, PermissionReply } from '../../api' import { ContentBlock } from '../../components' import { autoApproveStore } from '../../store' import { themeStore } from '../../store/themeStore' +import { extractPermissionDiff } from './permissionDiff' interface InlinePermissionProps { request: ApiPermissionRequest @@ -34,23 +35,9 @@ export const InlinePermission = memo(function InlinePermission({ const { toolCardStyle } = useSyncExternalStore(themeStore.subscribe, themeStore.getSnapshot) const isCompact = toolCardStyle === 'compact' - const metadata = request.metadata - const diff = metadata?.diff as string | undefined - const filepath = metadata?.filepath as string | undefined - - let diffData: { before: string; after: string } | string | undefined - if (metadata?.filediff && typeof metadata.filediff === 'object') { - const fd = metadata.filediff as Record - // 上游优先返回 patch 格式 - if (typeof fd.patch === 'string') { - diffData = fd.patch - } else if (fd.before !== undefined && fd.after !== undefined) { - diffData = { before: String(fd.before), after: String(fd.after) } - } - } - if (!diffData && diff) { - diffData = diff - } + const { diff, before, after, filePath: filepath } = extractPermissionDiff(request.metadata) + const diffData: { before: string; after: string } | string | undefined = + diff ?? (before !== undefined && after !== undefined ? { before, after } : undefined) const isFileEdit = request.action === 'edit' || request.action === 'write' const hasPatterns = request.resources && request.resources.length > 0 diff --git a/src/features/chat/PermissionDialog.tsx b/src/features/chat/PermissionDialog.tsx index ac7d72a69..a59416942 100644 --- a/src/features/chat/PermissionDialog.tsx +++ b/src/features/chat/PermissionDialog.tsx @@ -5,6 +5,7 @@ import { DiffView } from '../../components/DiffView' import { ContentBlock } from '../../components' import { childSessionStore, autoApproveStore } from '../../store' import { makeSessionKey, splitSessionKey } from '../../utils/sessionKey' +import { extractPermissionDiff } from './permissionDiff' import { usePresence } from '../../hooks' import { useChatViewport } from './chatViewport' @@ -32,24 +33,8 @@ export function PermissionDialog({ const { t } = useTranslation(['chat', 'common']) const { presentation } = useChatViewport() const isCompact = presentation.isCompact - // 从 metadata 中提取 diff 信息 - const metadata = request.metadata - const filepath = metadata?.filepath as string | undefined - let diffData = metadata?.diff as string | undefined - - // Extract structured filediff if available - let before: string | undefined - let after: string | undefined - - if (metadata?.filediff && typeof metadata.filediff === 'object') { - const fd = metadata.filediff as Record - // 上游优先返回 patch 格式 - if (typeof fd.patch === 'string') { - diffData = fd.patch - } - before = fd.before !== undefined ? String(fd.before) : undefined - after = fd.after !== undefined ? String(fd.after) : undefined - } + // 从 metadata 中提取 diff 信息(兼容 v1 diff/filediff 与 v2 files[].patch) + const { diff: diffData, before, after, filePath: filepath } = extractPermissionDiff(request.metadata) // 判断是否是文件编辑类权限 const isFileEdit = request.action === 'edit' || request.action === 'write' diff --git a/src/features/chat/permissionDiff.test.ts b/src/features/chat/permissionDiff.test.ts new file mode 100644 index 000000000..fa3a13dd7 --- /dev/null +++ b/src/features/chat/permissionDiff.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import { extractPermissionDiff } from './permissionDiff' + +describe('extractPermissionDiff', () => { + it('returns empty when metadata is missing', () => { + expect(extractPermissionDiff(undefined)).toEqual({}) + }) + + it('reads v1 unified diff string', () => { + expect(extractPermissionDiff({ diff: '@@ -1 +1 @@', filepath: 'a.ts' })).toEqual({ + diff: '@@ -1 +1 @@', + filePath: 'a.ts', + }) + }) + + it('prefers v1 filediff patch over diff string', () => { + const result = extractPermissionDiff({ + filediff: { patch: 'PATCH', additions: 1, deletions: 1 }, + diff: 'DIFF', + }) + expect(result.diff).toBe('PATCH') + }) + + it('reads v1 filediff before/after when no patch', () => { + const result = extractPermissionDiff({ filediff: { before: 'old', after: 'new' } }) + expect(result).toEqual({ before: 'old', after: 'new' }) + }) + + it('reads v2 files[].patch and file (FileDiff.Info)', () => { + const result = extractPermissionDiff({ + files: [{ file: 'src/a.ts', patch: 'PATCH2', additions: 2, deletions: 0, status: 'modified' }], + }) + expect(result).toEqual({ diff: 'PATCH2', filePath: 'src/a.ts' }) + }) + + it('prefers filediff over files, and files over top-level diff', () => { + // filediff 优先 + expect( + extractPermissionDiff({ + filediff: { patch: 'FD' }, + files: [{ file: 'a', patch: 'F' }], + }).diff, + ).toBe('FD') + // files 优先于顶层 diff + expect( + extractPermissionDiff({ + files: [{ file: 'a', patch: 'F' }], + diff: 'D', + }).diff, + ).toBe('F') + }) + + it('skips files entries without a patch and falls back to top-level diff', () => { + const result = extractPermissionDiff({ files: [{ file: 'a' }], diff: 'D' }) + expect(result.diff).toBe('D') + }) + + it('uses files[].file over top-level filepath', () => { + const result = extractPermissionDiff({ + files: [{ file: 'from-files.ts', patch: 'P' }], + filepath: 'top-level.ts', + }) + expect(result.filePath).toBe('from-files.ts') + }) +}) diff --git a/src/features/chat/permissionDiff.ts b/src/features/chat/permissionDiff.ts new file mode 100644 index 000000000..0840877f0 --- /dev/null +++ b/src/features/chat/permissionDiff.ts @@ -0,0 +1,57 @@ +/** + * 权限请求 metadata 的 diff 提取。 + * + * v1 时代是 `metadata.diff`(unified diff 字符串)或 `metadata.filediff` + * (`{ patch }` 或 `{ before, after }`);v2 改为 + * `metadata.files: [FileDiff.Info]`(官方 edit.ts:180 / write.ts:82 的 + * permission.assert),单文件形状是 `{ file, patch, additions, deletions, status }`。 + * + * 三条来源按优先级取:filediff > files[].patch > diff。 + */ + +export interface PermissionDiffData { + /** unified / patch 字符串 */ + diff?: string + before?: string + after?: string + filePath?: string +} + +export function extractPermissionDiff(metadata: Record | undefined): PermissionDiffData { + const result: PermissionDiffData = {} + if (!metadata) return result + + // v1.4.0+:filediff(优先 patch 字符串,其次 before/after) + if (metadata.filediff && typeof metadata.filediff === 'object') { + const fd = metadata.filediff as Record + if (typeof fd.patch === 'string') result.diff = fd.patch + if (fd.before !== undefined) result.before = String(fd.before) + if (fd.after !== undefined) result.after = String(fd.after) + } + + // v2:files: [FileDiff.Info],取第一个带 patch/diff 的文件 + if (!result.diff && Array.isArray(metadata.files)) { + for (const entry of metadata.files as Record[]) { + if (!entry || typeof entry !== 'object') continue + const patch = + typeof entry.patch === 'string' ? entry.patch : typeof entry.diff === 'string' ? entry.diff : undefined + if (!patch) continue + result.diff = patch + const file = entry.file ?? entry.filePath + if (typeof file === 'string') result.filePath = file + break + } + } + + // v1 旧:unified diff 字符串 + if (!result.diff && typeof metadata.diff === 'string') { + result.diff = metadata.diff + } + + // filePath 兜底:v1 顶层 filepath + if (!result.filePath && typeof metadata.filepath === 'string') { + result.filePath = metadata.filepath + } + + return result +} diff --git a/src/features/message/parts/ToolPartView.tsx b/src/features/message/parts/ToolPartView.tsx index 317f5e8cc..8576685b7 100644 --- a/src/features/message/parts/ToolPartView.tsx +++ b/src/features/message/parts/ToolPartView.tsx @@ -16,6 +16,7 @@ import { } from '../../chat/InlineToolRequestContext' import { InlinePermission } from '../../chat/InlinePermission' import { InlineQuestion } from '../../chat/InlineQuestion' +import { extractPermissionDiff } from '../../chat/permissionDiff' import { getToolIcon, extractToolData, @@ -122,13 +123,20 @@ export const ToolPartView = memo(function ToolPartView({ // 精简模式:非 edit/write 权限时不隐藏 ToolBody(ToolBody 已经渲染了命令内容) const isEditWritePermission = permissionRequest?.action === 'edit' || permissionRequest?.action === 'write' || permissionResolved - const hideToolBodyForPermission = isEditWritePermission + // metadata 里有 diff → 交给 InlinePermission 显示(藏 ToolBody,避免重复渲染); + // metadata 缺 diff(官方 edit 多匹配未给 preview)→ ToolBody 用 input 派生兜底。 + const permissionDiff = isEditWritePermission ? extractPermissionDiff(effectivePermissionRequest?.metadata) : null + const permissionHasDiff = !!( + permissionDiff && + (permissionDiff.diff || (permissionDiff.before !== undefined && permissionDiff.after !== undefined)) + ) + const hideToolBodyForPermission = isEditWritePermission && permissionHasDiff // 精简模式:ToolBody 已渲染时,InlinePermission 只显示按钮 // task/subagent 工具除外:其 renderer 无法显示详细的工具请求内容,需要完整展示权限信息 const toolNameLower = toolName.toLowerCase() const isTaskTool = toolNameLower === 'task' || toolNameLower === 'subagent' const permissionContentHidden = - compactInlinePermission && !isEditWritePermission && !isTaskTool && !!permissionRequest + compactInlinePermission && !isTaskTool && !!permissionRequest && (isEditWritePermission ? !permissionHasDiff : true) const isReadable = isReadableTool(toolName) const shouldStartExpanded = isActive || From b9dcdd7edb636eccaa7546cf5681210c3dfabd1a Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 10:51:29 +0800 Subject: [PATCH 03/91] fix(chat): truncate the load-error stack shown in the UI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit toLoadMessageError stuffed the whole error.stack into response.body, so a failed session load rendered a wall of frames in the error card. Keep the first few frames — enough to locate the problem without the noise. --- src/hooks/useSessionManager.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/hooks/useSessionManager.ts b/src/hooks/useSessionManager.ts index 58dba031e..ecc553bcf 100644 --- a/src/hooks/useSessionManager.ts +++ b/src/hooks/useSessionManager.ts @@ -48,10 +48,12 @@ const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)) function toLoadMessageError(error: unknown): APIError { const message = error instanceof Error ? error.message : String(error || 'Failed to load session') const stack = error instanceof Error ? error.stack : undefined + // 截断堆栈:完整堆栈整段塞进 UI 详情太吓人,留前几帧足够定位问题 + const shortStack = stack?.split('\n').slice(0, 6).join('\n') return { type: 'APIError', message, - ...(stack ? { response: { body: stack } } : {}), + ...(shortStack ? { response: { body: shortStack } } : {}), } } From 6833baa48a05cb0eb343d087a7e5f8e3a2675bdb Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 11:34:12 +0800 Subject: [PATCH 04/91] =?UTF-8?q?fix(diff):=20=E6=8C=89=20patch=20?= =?UTF-8?q?=E7=9A=84=20@@=20=E7=BB=9D=E5=AF=B9=E8=A1=8C=E5=8F=B7=E8=BF=98?= =?UTF-8?q?=E5=8E=9F=20before/after?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前 DiffView 拿到 unified diff 后走 extractContentFromUnifiedDiff,把 @@ 头 丢弃只拼 +/- 行成 before/after 再重新 diffLines,行号永远从 1 开始,看不出 改动落在原文件第几行。 新增 reconstructBeforeAfterFromPatch:解析 @@ hunk 头,hunk 之间未变化的行 用空行占位补齐成带绝对行号的完整 before/after,再沿用现有 diffLines/折叠/ 高亮管线(开头 context 段 isFirst 时 keepBefore=0 会被完全折叠,hunk 间隙也 被折叠),行号、高亮、折叠全部自动对齐,无需改渲染组件。解析失败或超大时 退回旧的片段提取。 配套单测覆盖单 hunk/多 hunk/纯新增/非法 patch,以及 DiffView 集成测试验证 深处变更产生前导折叠条(旧行为无此条)。 --- src/components/DiffView.test.tsx | 21 ++++++++ src/components/DiffView.tsx | 6 ++- src/utils/diffUtils.test.ts | 85 ++++++++++++++++++++++++++++++++ src/utils/diffUtils.ts | 64 ++++++++++++++++++++++++ 4 files changed, 174 insertions(+), 2 deletions(-) create mode 100644 src/utils/diffUtils.test.ts diff --git a/src/components/DiffView.test.tsx b/src/components/DiffView.test.tsx index 64888777b..28bfbbc3b 100644 --- a/src/components/DiffView.test.tsx +++ b/src/components/DiffView.test.tsx @@ -1,5 +1,6 @@ import type { ReactNode } from 'react' import { fireEvent, render, screen } from '@testing-library/react' +import { createTwoFilesPatch } from 'diff' import { describe, expect, it, vi } from 'vitest' import { DiffView } from './DiffView' import { FullscreenProvider } from '../contexts' @@ -36,4 +37,24 @@ describe('DiffView', () => { fireEvent.click(screen.getByTitle('Fullscreen')) expect(screen.getByTestId('fullscreen-viewer')).toBeInTheDocument() }) + + it('按 patch 的绝对行号还原:深处变更产生前导折叠条(旧的片段提取不会)', () => { + // 构造一个 40 行文件、第 30 行改一处的 patch(createTwoFilesPatch context=4) + const before = Array.from({ length: 40 }, (_, i) => `line${i + 1}`).join('\n') + const after = before.replace('line30', 'CHANGED30') + const patch = createTwoFilesPatch('app.ts', 'app.ts', before, after) + + const { container } = render( + + + , + ) + + // 变更内容渲染出来 + expect(screen.getByText('CHANGED30')).toBeInTheDocument() + // 前导未变化行被折叠成分隔条(绝对行号还原的标志;旧的片段提取从第 1 行开始、无此条) + expect(container.querySelector('[data-separator="line-info"]')).not.toBeNull() + // 行号列出现真实行号 30,而不是从 1 开始 + expect(container.textContent).toContain('30') + }) }) diff --git a/src/components/DiffView.tsx b/src/components/DiffView.tsx index 6664a8a0b..5daacc5be 100644 --- a/src/components/DiffView.tsx +++ b/src/components/DiffView.tsx @@ -4,7 +4,7 @@ import { diffLines } from 'diff' import { ChevronDownIcon, MaximizeIcon } from './Icons' import { clsx } from 'clsx' import { detectLanguage } from '../utils/languageUtils' -import { extractContentFromUnifiedDiff } from '../utils/diffUtils' +import { extractContentFromUnifiedDiff, reconstructBeforeAfterFromPatch } from '../utils/diffUtils' import { ViewModeSwitch } from './FullscreenViewer' import { DiffViewer, useDiffViewerData, type ViewMode } from './DiffViewer' import { useFullscreenLayer } from '../contexts' @@ -59,7 +59,9 @@ export const DiffView = memo(function DiffView({ return { before, after } } if (diff) { - return extractContentFromUnifiedDiff(diff) + // 优先按 patch 的 @@ 绝对行号还原完整 before/after(行号正确); + // 失败(非标准 patch、超大等)退回片段提取(行号从 1 开始) + return reconstructBeforeAfterFromPatch(diff) ?? extractContentFromUnifiedDiff(diff) } return null }, [before, after, diff]) diff --git a/src/utils/diffUtils.test.ts b/src/utils/diffUtils.test.ts new file mode 100644 index 000000000..ba988a0be --- /dev/null +++ b/src/utils/diffUtils.test.ts @@ -0,0 +1,85 @@ +import { createTwoFilesPatch, diffLines } from 'diff' +import { describe, expect, it } from 'vitest' +import { reconstructBeforeAfterFromPatch } from './diffUtils' + +/** 构造 n 行文件,changes 里指定某些行的内容 */ +function makeFile(lineCount: number, changes: Record = {}): string { + const lines: string[] = [] + for (let i = 1; i <= lineCount; i++) lines.push(changes[i] ?? `line${i}`) + return lines.join('\n') +} + +/** 对还原结果重算 diff,返回所有变更的绝对行号(old/new 两侧) */ +function changePositions(before: string, after: string) { + const positions: { kind: 'del' | 'add'; line: number; text: string; count: number }[] = [] + let oldIdx = 0 + let newIdx = 0 + for (const change of diffLines(before, after)) { + const count = change.count ?? 0 + const firstLine = change.value.split('\n')[0] + if (change.removed) { + positions.push({ kind: 'del', line: oldIdx + 1, text: firstLine, count }) + } else if (change.added) { + positions.push({ kind: 'add', line: newIdx + 1, text: firstLine, count }) + } + if (!change.added) oldIdx += count + if (!change.removed) newIdx += count + } + return positions +} + +describe('reconstructBeforeAfterFromPatch', () => { + it('单 hunk:变更落在绝对行号,而不是从 1 开始', () => { + const before = makeFile(100) + const after = makeFile(100, { 40: 'CHANGED40' }) + const patch = createTwoFilesPatch('f.ts', 'f.ts', before, after) + + const result = reconstructBeforeAfterFromPatch(patch) + expect(result).not.toBeNull() + + const positions = changePositions(result!.before, result!.after) + expect(positions).toEqual([ + { kind: 'del', line: 40, text: 'line40', count: 1 }, + { kind: 'add', line: 40, text: 'CHANGED40', count: 1 }, + ]) + }) + + it('多 hunk:间隙补齐后各 hunk 的变更都落在绝对行号', () => { + const before = makeFile(100) + const after = makeFile(100, { 10: 'CHANGED10', 50: 'CHANGED50', 100: 'CHANGED100' }) + const patch = createTwoFilesPatch('f.ts', 'f.ts', before, after) + + const result = reconstructBeforeAfterFromPatch(patch) + expect(result).not.toBeNull() + + const positions = changePositions(result!.before, result!.after) + expect(positions).toEqual([ + { kind: 'del', line: 10, text: 'line10', count: 1 }, + { kind: 'add', line: 10, text: 'CHANGED10', count: 1 }, + { kind: 'del', line: 50, text: 'line50', count: 1 }, + { kind: 'add', line: 50, text: 'CHANGED50', count: 1 }, + { kind: 'del', line: 100, text: 'line100', count: 1 }, + { kind: 'add', line: 100, text: 'CHANGED100', count: 1 }, + ]) + }) + + it('纯新增(新文件):行号与内容对齐', () => { + const after = makeFile(5) + const patch = createTwoFilesPatch('f.ts', 'f.ts', '', after) + + const result = reconstructBeforeAfterFromPatch(patch) + expect(result).not.toBeNull() + + const positions = changePositions(result!.before, result!.after) + expect(positions).toEqual([{ kind: 'add', line: 1, text: 'line1', count: 5 }]) + }) + + it('非法 patch 返回 null', () => { + expect(reconstructBeforeAfterFromPatch('not a diff at all')).toBeNull() + expect(reconstructBeforeAfterFromPatch('')).toBeNull() + }) + + it('无 hunk 的 patch 返回 null', () => { + expect(reconstructBeforeAfterFromPatch('--- a.ts\n+++ a.ts\n')).toBeNull() + }) +}) diff --git a/src/utils/diffUtils.ts b/src/utils/diffUtils.ts index 82f1ff0ea..4562893aa 100644 --- a/src/utils/diffUtils.ts +++ b/src/utils/diffUtils.ts @@ -1,3 +1,67 @@ +import { parsePatch } from 'diff' + +/** 重建行数上限:超出则退回片段提取,避免超大文件的 diff/高亮开销 */ +const MAX_RECONSTRUCTED_LINES = 20000 + +/** + * 把 unified diff(带 `@@ -oldStart,n +newStart,n @@` 绝对行号)还原成"完整" before/after: + * hunk 之间未变化的行用空行占位补齐,使后续 diffLines 重算后变更落在真实行号上, + * 且折叠/高亮/行号宽度全部沿用现有管线,无需改渲染组件。 + * + * 解析失败、hunk 乱序/重叠、或超出行数上限时返回 null,调用方退回 extractContentFromUnifiedDiff。 + */ +export function reconstructBeforeAfterFromPatch(patch: string): { before: string; after: string } | null { + let files + try { + files = parsePatch(patch) + } catch { + return null + } + const file = files?.[0] + if (!file || !file.hunks || file.hunks.length === 0) return null + + const beforeLines: string[] = [] + const afterLines: string[] = [] + let oldPos = 1 + let newPos = 1 + + for (const hunk of file.hunks) { + // hunk 之前的未变化行(前导 + hunk 间隙)用空行占位,保持绝对行号对齐。 + // 正常 patch 中 gapOld === gapNew(未变化段两侧行数相同),不等则说明 patch 异常。 + const gapOld = hunk.oldStart - oldPos + const gapNew = hunk.newStart - newPos + if (gapOld < 0 || gapNew < 0) return null + for (let i = 0; i < gapOld; i++) beforeLines.push('') + for (let i = 0; i < gapNew; i++) afterLines.push('') + oldPos += gapOld + newPos += gapNew + + for (const raw of hunk.lines) { + const tag = raw[0] + const text = raw.slice(1) + if (tag === ' ') { + beforeLines.push(text) + afterLines.push(text) + oldPos++ + newPos++ + } else if (tag === '-') { + beforeLines.push(text) + oldPos++ + } else if (tag === '+') { + afterLines.push(text) + newPos++ + } + // '\'(No newline at end of file)标记忽略 + } + } + + if (beforeLines.length > MAX_RECONSTRUCTED_LINES || afterLines.length > MAX_RECONSTRUCTED_LINES) { + return null + } + + return { before: beforeLines.join('\n'), after: afterLines.join('\n') } +} + export function extractContentFromUnifiedDiff(diff: string): { before: string; after: string } { let before = '' let after = '' From bafeb95dd3ce3871f7450c83a010a6a30829e294 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 12:17:51 +0800 Subject: [PATCH 05/91] =?UTF-8?q?fix(diff):=20ContentBlock/SessionChangesP?= =?UTF-8?q?anel=20=E4=B9=9F=E6=8C=89=20@@=20=E7=BB=9D=E5=AF=B9=E8=A1=8C?= =?UTF-8?q?=E5=8F=B7=E8=BF=98=E5=8E=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上一个提交只改了 DiffView,但 edit 卡片实际渲染链路是 DefaultRenderer → ContentBlock → DiffViewer,ContentBlock.resolvedDiff 里仍用旧的 extractContentFromUnifiedDiff,导致 edit/write 工具卡片行号 依然从 1 开始。SessionChangesPanel 同样的问题。 两处都改为优先 reconstructBeforeAfterFromPatch,失败退回旧逻辑。 已用服务端真实 patch(edit DiffView.test.tsx,@@ -36,5 +36,25 @@)验证 还原后变更落在第 40 行。 --- src/components/ContentBlock.tsx | 6 ++++-- src/components/SessionChangesPanel.tsx | 6 +++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/components/ContentBlock.tsx b/src/components/ContentBlock.tsx index d9692e50c..2ebd7a0dc 100644 --- a/src/components/ContentBlock.tsx +++ b/src/components/ContentBlock.tsx @@ -16,7 +16,7 @@ import { DiffViewer, useDiffViewerData, type ViewMode } from './DiffViewer' import { CodePreview } from './CodePreview' import { detectLanguage } from '../utils/languageUtils' import { ViewModeSwitch } from './FullscreenViewer' -import { extractContentFromUnifiedDiff } from '../utils/diffUtils' +import { extractContentFromUnifiedDiff, reconstructBeforeAfterFromPatch } from '../utils/diffUtils' import { useCompositorExpand } from '../hooks/useCompositorExpand' import { useDelayedRender } from '../hooks/useDelayedRender' import { useResponsiveMaxHeight } from '../hooks/useResponsiveMaxHeight' @@ -152,7 +152,9 @@ export const ContentBlock = memo(function ContentBlock({ const resolvedDiff = useMemo(() => { if (!diff) return null if (typeof diff === 'object') return diff - return extractContentFromUnifiedDiff(diff) + // 优先按 patch 的 @@ 绝对行号还原完整 before/after(行号正确); + // 失败(非标准 patch、超大等)退回片段提取(行号从 1 开始) + return reconstructBeforeAfterFromPatch(diff) ?? extractContentFromUnifiedDiff(diff) }, [diff]) const diffViewerData = useDiffViewerData(resolvedDiff?.before ?? '', resolvedDiff?.after ?? '', lang, false, isDiff) diff --git a/src/components/SessionChangesPanel.tsx b/src/components/SessionChangesPanel.tsx index 08de5f8c9..5cc654271 100644 --- a/src/components/SessionChangesPanel.tsx +++ b/src/components/SessionChangesPanel.tsx @@ -16,7 +16,7 @@ import { getSessionDiff } from '../api/session' import { getVcsDiff, getVcsInfo } from '../api/vcs' import type { ApiProject, FileDiff, VcsInfo } from '../api/types' import { detectLanguage } from '../utils/languageUtils' -import { extractContentFromUnifiedDiff } from '../utils/diffUtils' +import { extractContentFromUnifiedDiff, reconstructBeforeAfterFromPatch } from '../utils/diffUtils' import { sessionErrorHandler } from '../utils' import { PreviewTabsBar, type PreviewTabsBarItem } from './PreviewTabsBar' import { useVerticalSplitResize } from '../hooks/useVerticalSplitResize' @@ -929,9 +929,9 @@ const DiffPreviewPanel = memo(function DiffPreviewPanel({ onClose, }: DiffPreviewPanelProps) { const language = detectLanguage(diff.file) || 'text' - // 优先用 patch 提取 before/after,回退到直接的 before/after 字段(旧版后端兼容) + // 优先用 patch 还原 before/after(带 @@ 绝对行号),回退到直接的 before/after 字段(旧版后端兼容) const { before, after } = useMemo(() => { - if (diff.patch) return extractContentFromUnifiedDiff(diff.patch) + if (diff.patch) return reconstructBeforeAfterFromPatch(diff.patch) ?? extractContentFromUnifiedDiff(diff.patch) if (diff.before !== undefined && diff.after !== undefined) return { before: diff.before, after: diff.after } return { before: '', after: '' } }, [diff.patch, diff.before, diff.after]) From f3a563767511cc1c28defbd9f0082bfe15d483ef Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 12:53:44 +0800 Subject: [PATCH 06/91] =?UTF-8?q?fix(diff):=20patch=20=E8=BF=98=E5=8E=9F?= =?UTF-8?q?=E7=9A=84=E5=90=88=E6=88=90=E9=97=B4=E9=9A=99=E5=8C=BA=E5=9F=9F?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E6=B8=B2=E6=9F=93=E6=8A=98=E5=8F=A0=E6=9D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 还原 before/after 时 hunk 间隙用占位行补齐保住行号,这些占位行形成的 折叠条('N 行未修改')展开后露出的不是真实代码(patch 里根本没有), 对使用者是噪音。 改为:占位行用私有区字符标记(SYNTHETIC_PAD_LINE),collapseContext 检测到被折叠段含占位行时直接不生成折叠条——两侧真实 context 行相邻, 靠行号跳跃体现不连续,与 git diff 一致。真实 before/after diff 的折叠条 (有真实内容可展开)不受影响。 测试覆盖:合成区域无折叠条且行号为绝对行号;真实 diff 折叠条正常可展开。 --- src/components/DiffView.test.tsx | 22 +++++++++++++--------- src/components/DiffViewer.test.tsx | 30 ++++++++++++++++++++++++++++++ src/components/DiffViewer.tsx | 26 ++++++++++++++++++++++++-- src/utils/diffUtils.ts | 15 +++++++++++++-- 4 files changed, 80 insertions(+), 13 deletions(-) diff --git a/src/components/DiffView.test.tsx b/src/components/DiffView.test.tsx index 28bfbbc3b..d03e421de 100644 --- a/src/components/DiffView.test.tsx +++ b/src/components/DiffView.test.tsx @@ -38,10 +38,14 @@ describe('DiffView', () => { expect(screen.getByTestId('fullscreen-viewer')).toBeInTheDocument() }) - it('按 patch 的绝对行号还原:深处变更产生前导折叠条(旧的片段提取不会)', () => { - // 构造一个 40 行文件、第 30 行改一处的 patch(createTwoFilesPatch context=4) - const before = Array.from({ length: 40 }, (_, i) => `line${i + 1}`).join('\n') - const after = before.replace('line30', 'CHANGED30') + it('按 patch 的绝对行号还原:深处变更显示真实行号(旧的片段提取从 1 开始)', () => { + // 40 行文件、第 30 行改一处;内容纯字母,行号只出现在 gutter 里 + const lines = Array.from( + { length: 40 }, + (_, i) => `item_${String.fromCharCode(65 + Math.floor(i / 26))}${String.fromCharCode(65 + (i % 26))}`, + ) + const before = lines.join('\n') + const after = [...lines.slice(0, 29), 'REPLACED', ...lines.slice(30)].join('\n') const patch = createTwoFilesPatch('app.ts', 'app.ts', before, after) const { container } = render( @@ -51,10 +55,10 @@ describe('DiffView', () => { ) // 变更内容渲染出来 - expect(screen.getByText('CHANGED30')).toBeInTheDocument() - // 前导未变化行被折叠成分隔条(绝对行号还原的标志;旧的片段提取从第 1 行开始、无此条) - expect(container.querySelector('[data-separator="line-info"]')).not.toBeNull() - // 行号列出现真实行号 30,而不是从 1 开始 - expect(container.textContent).toContain('30') + expect(screen.getByText('REPLACED')).toBeInTheDocument() + // gutter 出现真实行号 30(旧的片段提取从 1 开始,最大只到 9,不会有 30) + expect(screen.getAllByText('30').length).toBeGreaterThan(0) + // 合成前导区域不渲染折叠条(展开了也没有真实内容) + expect(container.querySelector('[data-separator="line-info"]')).toBeNull() }) }) diff --git a/src/components/DiffViewer.test.tsx b/src/components/DiffViewer.test.tsx index e61609d83..69019b3cd 100644 --- a/src/components/DiffViewer.test.tsx +++ b/src/components/DiffViewer.test.tsx @@ -1,6 +1,8 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { createTwoFilesPatch } from 'diff' import { describe, expect, it, vi } from 'vitest' import { DiffViewer } from './DiffViewer' +import { reconstructBeforeAfterFromPatch } from '../utils/diffUtils' vi.mock('../store/themeStore', async importOriginal => { const actual = await importOriginal() @@ -94,4 +96,32 @@ describe('DiffViewer', () => { expect(container.textContent).toContain('if (!enabled) return') expect(container.textContent).not.toContain('returnn') }) + + it('patch 还原的合成区域不渲染折叠条,真实 diff 的折叠条正常', () => { + // 40 行文件、第 30 行改一处;内容纯字母,行号只出现在 gutter 里 + const lines = Array.from( + { length: 40 }, + (_, i) => `item_${String.fromCharCode(65 + Math.floor(i / 26))}${String.fromCharCode(65 + (i % 26))}`, + ) + const before = lines.join('\n') + const after = [...lines.slice(0, 29), 'REPLACED', ...lines.slice(30)].join('\n') + const patch = createTwoFilesPatch('a.ts', 'a.ts', before, after) + const rec = reconstructBeforeAfterFromPatch(patch)! + + const { container: synthetic } = render( + , + ) + // 变更内容渲染出来,且 gutter 是绝对行号 30 + expect(synthetic.textContent).toContain('REPLACED') + expect(screen.getAllByText('30').length).toBeGreaterThan(0) + // 合成区域不渲染折叠条(展开了也没有真实内容) + expect(synthetic.querySelector('[data-separator="line-info"]')).toBeNull() + + // 同样的变更,但给的是完整 before/after(真实内容)→ 折叠条正常且可展开 + const { container: real } = render( + , + ) + expect(real.querySelector('[data-separator="line-info"]')).not.toBeNull() + expect(real.querySelector('[data-expand-button]')).not.toBeNull() + }) }) diff --git a/src/components/DiffViewer.tsx b/src/components/DiffViewer.tsx index 8bc964efe..cb762bdb0 100644 --- a/src/components/DiffViewer.tsx +++ b/src/components/DiffViewer.tsx @@ -17,6 +17,7 @@ import { useDynamicVirtualScroll } from '../hooks/useDynamicVirtualScroll' import { themeStore } from '../store/themeStore' import type { DiffStyle } from '../store/themeStore' import { getLineCount, getLineNumberColumnWidth } from '../utils/lineNumberUtils' +import { isSyntheticPadLine } from '../utils/diffUtils' import { useUiState } from '../utils/uiDisclosureState' // ============================================ @@ -137,6 +138,15 @@ interface ExpansionRegion { function collapseContextPaired(lines: PairedLine[], expandedRegions?: ReadonlyMap): PairedLineOrCollapsed[] { if (lines.length === 0) return [] + // 被折叠区间是否含 patch 还原的合成占位行(展开了也没有真实内容) + const rangeHasSynthetic = (start: number, end: number): boolean => { + for (let j = start; j < end; j++) { + const line = lines[j] + if (isSyntheticPadLine(line.left.content) || isSyntheticPadLine(line.right.content)) return true + } + return false + } + const result: PairedLineOrCollapsed[] = [] let contextStart = -1 @@ -159,7 +169,9 @@ function collapseContextPaired(lines: PairedLine[], expandedRegions?: ReadonlyMa const suffixStart = Math.max(prefixCount, ctxLen - keepAfter - expanded.fromEnd) for (let j = contextStart; j < contextStart + prefixCount; j++) result.push(lines[j]) - if (suffixStart > prefixCount) { + // 合成区域(patch 还原的间隙占位行)不渲染折叠条:展开了也没有真实内容, + // 直接让两侧真实 context 行相邻,靠行号跳跃体现不连续(与 git diff 一致) + if (suffixStart > prefixCount && !rangeHasSynthetic(contextStart + prefixCount, contextStart + suffixStart)) { const count = suffixStart - prefixCount result.push({ collapsed: true, @@ -186,6 +198,14 @@ function collapseContextPaired(lines: PairedLine[], expandedRegions?: ReadonlyMa function collapseContextUnified(lines: UnifiedLine[], expandedRegions?: ReadonlyMap): UnifiedLineOrCollapsed[] { if (lines.length === 0) return [] + // 被折叠区间是否含 patch 还原的合成占位行(展开了也没有真实内容) + const rangeHasSynthetic = (start: number, end: number): boolean => { + for (let j = start; j < end; j++) { + if (isSyntheticPadLine(lines[j].content)) return true + } + return false + } + const result: UnifiedLineOrCollapsed[] = [] let contextStart = -1 @@ -208,7 +228,9 @@ function collapseContextUnified(lines: UnifiedLine[], expandedRegions?: Readonly const suffixStart = Math.max(prefixCount, ctxLen - keepAfter - expanded.fromEnd) for (let j = contextStart; j < contextStart + prefixCount; j++) result.push(lines[j]) - if (suffixStart > prefixCount) { + // 合成区域(patch 还原的间隙占位行)不渲染折叠条:展开了也没有真实内容, + // 直接让两侧真实 context 行相邻,靠行号跳跃体现不连续(与 git diff 一致) + if (suffixStart > prefixCount && !rangeHasSynthetic(contextStart + prefixCount, contextStart + suffixStart)) { const count = suffixStart - prefixCount result.push({ collapsed: true, diff --git a/src/utils/diffUtils.ts b/src/utils/diffUtils.ts index 4562893aa..e079ace8e 100644 --- a/src/utils/diffUtils.ts +++ b/src/utils/diffUtils.ts @@ -3,6 +3,17 @@ import { parsePatch } from 'diff' /** 重建行数上限:超出则退回片段提取,避免超大文件的 diff/高亮开销 */ const MAX_RECONSTRUCTED_LINES = 20000 +/** + * 占位行的标记内容:私有使用区字符,真实代码行不可能恰好是它。 + * 折叠逻辑据此识别"合成区域"(patch 里不存在的内容),渲染成不可展开的折叠条—— + * 展开了也没有真实内容可看(官方同样不提供这种展开)。 + */ +export const SYNTHETIC_PAD_LINE = '' + +export function isSyntheticPadLine(content: string): boolean { + return content === SYNTHETIC_PAD_LINE +} + /** * 把 unified diff(带 `@@ -oldStart,n +newStart,n @@` 绝对行号)还原成"完整" before/after: * hunk 之间未变化的行用空行占位补齐,使后续 diffLines 重算后变更落在真实行号上, @@ -31,8 +42,8 @@ export function reconstructBeforeAfterFromPatch(patch: string): { before: string const gapOld = hunk.oldStart - oldPos const gapNew = hunk.newStart - newPos if (gapOld < 0 || gapNew < 0) return null - for (let i = 0; i < gapOld; i++) beforeLines.push('') - for (let i = 0; i < gapNew; i++) afterLines.push('') + for (let i = 0; i < gapOld; i++) beforeLines.push(SYNTHETIC_PAD_LINE) + for (let i = 0; i < gapNew; i++) afterLines.push(SYNTHETIC_PAD_LINE) oldPos += gapOld newPos += gapNew From 77f8ac0c7d22c891588c2c520644df8994064506 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 13:22:58 +0800 Subject: [PATCH 07/91] =?UTF-8?q?fix(permissions):=20=E4=BB=96=E7=AB=AF?= =?UTF-8?q?=E6=89=B9=E5=87=86=E6=9D=83=E9=99=90=E5=90=8E=E9=9D=9E=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E6=9D=83=E9=99=90=E5=8D=A1=E7=89=87=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E6=AE=8B=E7=95=99=E6=8C=89=E9=92=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 权限被另一台设备批准后,服务端广播 permission.replied,本端 pending 列表随即清空。但 ToolPartView 的延迟卸载缓存对所有权限一律保留到工具 完成,而 permissionResolved 又要求 isFilePermission,于是 bash 这类非 文件权限在命令跑完前一直以 resolved=false 渲染,允许/拒绝按钮残留。 现在权限消失时按动作类型分流:edit/write 保留缓存等工具完成(避免 diff 预览跳动,期间显示 Applying… 无按钮);其余权限立即清缓存让卡片消失, 命令/输出交给 ToolBody。 --- .../parts/ToolPartView.permission.test.tsx | 145 ++++++++++++++++++ src/features/message/parts/ToolPartView.tsx | 11 +- 2 files changed, 154 insertions(+), 2 deletions(-) create mode 100644 src/features/message/parts/ToolPartView.permission.test.tsx diff --git a/src/features/message/parts/ToolPartView.permission.test.tsx b/src/features/message/parts/ToolPartView.permission.test.tsx new file mode 100644 index 000000000..a89b7e289 --- /dev/null +++ b/src/features/message/parts/ToolPartView.permission.test.tsx @@ -0,0 +1,145 @@ +import { act, render, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ToolPartView } from './ToolPartView' +import type { ToolViewPart } from '../tools' +import type { ApiPermissionRequest } from '../../../api' + +// 可控 mock:按用例决定当前是否还有待批准权限,并记录 InlinePermission 收到的 props +const { findPermissionMock, inlinePermissionSpy } = vi.hoisted(() => ({ + findPermissionMock: vi.fn<() => ApiPermissionRequest | undefined>(() => undefined), + inlinePermissionSpy: vi.fn(), +})) + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})) + +vi.mock('../../../hooks', () => ({ + useDelayedRender: (show: boolean) => show, + useDisclosureScrollLock: () => ({ + rootRef: () => undefined, + headerRef: () => undefined, + withScrollLock: (action: () => void) => action(), + }), + useCompositorExpand: (open: boolean) => ({ + contentRef: { current: null }, + layoutOpen: open, + keepMounted: open, + panelClassName: '', + }), +})) + +vi.mock('../../../hooks/useTheme', () => ({ + useTheme: () => ({ + inlineToolRequests: true, + immersiveMode: false, + compactInlinePermission: false, + }), +})) + +vi.mock('../../../store/serverStore', () => ({ + serverStore: { getActiveCalibratedNow: () => undefined }, +})) + +vi.mock('../../chat/InlineToolRequestContext', () => ({ + useInlineToolRequests: () => ({ + serverId: 'local', + pendingPermissions: [], + pendingQuestions: [], + onPermissionReply: vi.fn(), + onFormReply: vi.fn(), + onFormCancel: vi.fn(), + isReplying: false, + }), + findPermissionRequestForTool: () => findPermissionMock(), + findQuestionRequestForTool: () => undefined, +})) + +vi.mock('../../chat/InlinePermission', () => ({ + InlinePermission: (props: { resolved?: boolean }) => { + inlinePermissionSpy(props) + return
+ }, +})) + +vi.mock('../../chat/InlineQuestion', () => ({ + InlineQuestion: () => null, +})) + +vi.mock('../tools', () => ({ + getToolIcon: () => , + extractToolData: () => ({}), + getToolConfig: () => undefined, + DefaultRenderer: () => null, + TaskRenderer: () => null, +})) + +function createRunningTool(name: string): ToolViewPart { + return { + type: 'tool', + id: 'tool-1', + name, + messageID: 'message-1', + state: { status: 'running', input: {}, metadata: {} }, + time: { created: 0 }, + } +} + +function createPermission(action: string): ApiPermissionRequest { + return { id: 'perm-1', sessionID: 'session-1', action, resources: [] } as unknown as ApiPermissionRequest +} + +const CONTEXT = { messageID: 'message-1', created: 0 } + +describe('ToolPartView 权限他端批准后的残留', () => { + beforeEach(() => { + findPermissionMock.mockReset() + inlinePermissionSpy.mockClear() + // rAF 同步执行,让缓存 effect 立即落地 + vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { + cb(0) + return 0 + }) + vi.stubGlobal('cancelAnimationFrame', () => {}) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('bash 权限被他端批准后卡片立即消失(不再残留按钮)', () => { + const part = createRunningTool('bash') + findPermissionMock.mockReturnValue(createPermission('bash')) + + const { rerender } = render() + expect(screen.queryByTestId('inline-permission')).not.toBeNull() + + // 他端批准:服务端广播 permission.replied,pending 列表不再有该请求。 + // 真实应用里靠 context 变化触发重渲染;测试里用新 context 引用破掉 memo。 + findPermissionMock.mockReturnValue(undefined) + act(() => { + rerender() + }) + + // 非文件权限立即清缓存 → 权限组件卸载 + expect(screen.queryByTestId('inline-permission')).toBeNull() + }) + + it('edit 权限批准后保留 resolved 预览直到工具完成', () => { + const part = createRunningTool('edit') + findPermissionMock.mockReturnValue(createPermission('edit')) + + const { rerender } = render() + expect(screen.queryByTestId('inline-permission')).not.toBeNull() + + findPermissionMock.mockReturnValue(undefined) + act(() => { + rerender() + }) + + // edit 保留缓存避免画面跳动:仍渲染,且为 resolved 态(无按钮) + expect(screen.queryByTestId('inline-permission')).not.toBeNull() + const lastProps = inlinePermissionSpy.mock.calls.at(-1)?.[0] as { resolved?: boolean } + expect(lastProps?.resolved).toBe(true) + }) +}) diff --git a/src/features/message/parts/ToolPartView.tsx b/src/features/message/parts/ToolPartView.tsx index 8576685b7..28ce7ea77 100644 --- a/src/features/message/parts/ToolPartView.tsx +++ b/src/features/message/parts/ToolPartView.tsx @@ -102,9 +102,16 @@ export const ToolPartView = memo(function ToolPartView({ frameId = requestAnimationFrame(() => { setCachedPermissionRequest(permissionRequest) }) - } else if (toolDone) { + } else { + // 权限已处理(本端或他端批准/拒绝):edit/write 等工具完成再清缓存, + // 避免 "权限消失→空白→结果出现" 的跳动;其余权限立即清缓存让卡片消失, + // 命令/输出交给 ToolBody 展示,否则按钮会一直残留到工具跑完。 frameId = requestAnimationFrame(() => { - setCachedPermissionRequest(undefined) + setCachedPermissionRequest(prev => { + if (!prev) return prev + const cachedIsFile = prev.action === 'edit' || prev.action === 'write' + return cachedIsFile && !toolDone ? prev : undefined + }) }) } From 49c63e645f91bfe04ad1c7229ba4a4deb1a78b07 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 13:43:06 +0800 Subject: [PATCH 08/91] =?UTF-8?q?feat(message):=20=E4=B8=8A=E4=B8=8B?= =?UTF-8?q?=E6=96=87=E5=8E=8B=E7=BC=A9=E6=94=B9=E4=B8=BA=E5=8D=95=E6=A0=87?= =?UTF-8?q?=E8=AF=86=20+=20=E5=8F=AF=E6=94=B6=E8=B5=B7=20+=20=E7=BB=93?= =?UTF-8?q?=E6=9D=9F=E5=90=8E=E8=87=AA=E5=8A=A8=E6=94=B6=E8=B5=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原压缩消息有两条分隔线(开始 + 结果)和流式中的转圈指示,内容也无法 收起。现在: - 头部是唯一标识:running 时显示「开始压缩上下文」,结束后变为 「结果 · 用量」,不再渲染第二条分隔线和转圈行 - 摘要/错误详情可点击头部收起展开 - 流式输出结束后默认自动收起(respectUser,尊重手动操作),新增设置项 compactionAutoCollapse 可关闭,默认开 --- .../message/parts/CompactionPartView.test.tsx | 43 +++++++-- .../message/parts/SystemPartViews.tsx | 93 +++++++++++++------ .../settings/components/AgentSettings.tsx | 15 +++ .../settings/settingsSearchCatalog.ts | 1 + src/hooks/useTheme.ts | 6 ++ src/locales/en/settings.json | 2 + src/locales/zh-CN/settings.json | 2 + src/store/themeStore.ts | 24 +++++ 8 files changed, 148 insertions(+), 38 deletions(-) diff --git a/src/features/message/parts/CompactionPartView.test.tsx b/src/features/message/parts/CompactionPartView.test.tsx index 2aaf2a9e3..5742ac4ff 100644 --- a/src/features/message/parts/CompactionPartView.test.tsx +++ b/src/features/message/parts/CompactionPartView.test.tsx @@ -1,8 +1,21 @@ -import { describe, expect, it } from 'vitest' -import { render, screen } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { fireEvent, render, screen } from '@testing-library/react' import { CompactionPartView } from './SystemPartViews' import type { SessionMessageCompaction } from '@opencode/client/promise' +// 隔离滚动锁定(jsdom 不需要),但保留 useDelayedRender 真实以还原收起/展开行为 +vi.mock('../../../hooks', async importOriginal => { + const actual = await importOriginal() + return { + ...actual, + useDisclosureScrollLock: () => ({ + rootRef: () => undefined, + headerRef: () => undefined, + withScrollLock: (action: () => void) => action(), + }), + } +}) + function compaction(overrides: Record): SessionMessageCompaction { return { id: 'msg-c1', @@ -13,18 +26,20 @@ function compaction(overrides: Record): SessionMessageCompactio } as unknown as SessionMessageCompaction } -describe('CompactionPartView(官方 SessionCompactionMessage 同款)', () => { - it('running:started 分隔线 + 流式摘要 + 进行中指示', () => { - render() +// 每个用例用独立 id,避免 disclosure 缓存跨用例泄漏 +describe('CompactionPartView(单标识 + 可收起)', () => { + it('running:started 标识 + 流式摘要,不再有转圈指示', () => { + render() expect(screen.getByText('Compacting context', { selector: 'span' })).toBeInTheDocument() expect(screen.getByText('正在总结前半段…')).toBeInTheDocument() - expect(screen.getByRole('status')).toHaveTextContent('Compacting context…') + expect(screen.queryByRole('status')).not.toBeInTheDocument() }) - it('completed:结果分隔线 + token 用量(含 cache)', () => { + it('completed:标识变成结果+用量,摘要默认收起、点击展开', () => { render( ) // input = 1000+2000+500=3500 → 3.5K;output = 200+100=300 expect(screen.getByText(/History compacted · 3\.5K in · 300 out/)).toBeInTheDocument() + // 默认自动收起:摘要不在 DOM + expect(screen.queryByText('压缩完成')).not.toBeInTheDocument() + // 点击标识展开 + fireEvent.click(screen.getByRole('button', { name: /History compacted/ })) expect(screen.getByText('压缩完成')).toBeInTheDocument() }) @@ -41,6 +60,7 @@ describe('CompactionPartView(官方 SessionCompactionMessage 同款)', () => render( expect(screen.getByText('Provider compaction')).toBeInTheDocument() }) - it('failed:失败标签 + 错误详情,不显示摘要', () => { + it('failed:失败标签,点击展开看错误详情,不显示摘要', () => { render( , ) expect(screen.getByText(/Compaction failed/)).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: /Compaction failed/ })) expect(screen.getByText('provider 503')).toBeInTheDocument() }) - it('failed + aborted → 已取消且不显示错误详情', () => { + it('failed + aborted → 已取消,无内容为纯分隔线(不可点)', () => { render( ) expect(screen.getByText('Compaction cancelled')).toBeInTheDocument() expect(screen.queryByText('user cancelled')).not.toBeInTheDocument() + expect(screen.queryByRole('button')).not.toBeInTheDocument() }) it('failed + interrupted → 被中断标签', () => { render( - + // 唯一标识:running 时是"开始压缩上下文",结束后变成"结果 · 用量" + const headerLabel = isRunning ? t('system.compactionStarted') : outcomeLabel + const hasContent = !!(summary.trim() || failureDetail) - {summary.trim() && ( -
- -
- )} + // 收起状态:running 时展开看流式;结束后默认收起(可在设置里关掉自动收起) + const stateKey = `message:compaction:${message.id}` + const [expanded, setExpanded] = useUiDisclosureState(stateKey, isRunning || !compactionAutoCollapse) + const shouldRenderBody = useMessageExpandRender(expanded) + const { rootRef, headerRef, withScrollLock } = useDisclosureScrollLock() - {isRunning && ( -
- - {t('system.compactionRunning')} -
- )} - - {!isRunning && ( - <> - - {failureDetail && ( -
{failureDetail}
- )} - - )} + // 流式结束(running → done)自动收起;respectUser 尊重用户手动展开/收起 + const wasRunningRef = useRef(isRunning) + useEffect(() => { + const wasRunning = wasRunningRef.current + wasRunningRef.current = isRunning + if (wasRunning && !isRunning && compactionAutoCollapse) { + setExpanded(false, { touched: false, respectUser: true }) + } + }, [isRunning, compactionAutoCollapse, setExpanded]) + + // 无内容可收起(如 aborted 空消息)→ 纯分隔线 + if (!hasContent) { + return ( +
+ +
+ ) + } + + return ( +
+ + + + {shouldRenderBody && ( + <> + {summary.trim() && ( +
+ +
+ )} + {failureDetail && ( +
{failureDetail}
+ )} + + )} +
) }) diff --git a/src/features/settings/components/AgentSettings.tsx b/src/features/settings/components/AgentSettings.tsx index 8d4597200..dc1bac115 100644 --- a/src/features/settings/components/AgentSettings.tsx +++ b/src/features/settings/components/AgentSettings.tsx @@ -16,6 +16,7 @@ export function AgentSettings() { const [toolCardStyle, setToolCardStyle] = useState(themeStore.toolCardStyle) const [immersiveMode, setImmersiveMode] = useState(themeStore.immersiveMode) const [compactInlinePermission, setCompactInlinePermission] = useState(themeStore.compactInlinePermission) + const [compactionAutoCollapse, setCompactionAutoCollapse] = useState(themeStore.compactionAutoCollapse) const [processCollapseEnabled, setProcessCollapseEnabled] = useState(themeStore.processCollapseEnabled) const handleAlwaysAllowModeChange = (mode: AlwaysAllowMode) => { @@ -83,6 +84,12 @@ export function AgentSettings() { themeStore.setCompactInlinePermission(next) } + const toggleCompactionAutoCollapse = () => { + const next = !compactionAutoCollapse + setCompactionAutoCollapse(next) + themeStore.setCompactionAutoCollapse(next) + } + return (
@@ -165,6 +172,14 @@ export function AgentSettings() { + + + +
{ + themeStore.setCompactionAutoCollapse(enabled) + }, []), + // 毛玻璃效果 glassEffect: state.glassEffect, setGlassEffect: useCallback((enabled: boolean) => { diff --git a/src/locales/en/settings.json b/src/locales/en/settings.json index 18d74b174..8567bd899 100644 --- a/src/locales/en/settings.json +++ b/src/locales/en/settings.json @@ -202,6 +202,8 @@ "inlineToolRequestsDesc": "Show pending permission and question requests under the related tool call instead of floating dialogs", "compactInlinePermission": "Compact Inline Permission", "compactInlinePermissionDesc": "When the tool already shows content, only display action buttons for permissions to avoid duplication", + "compactionAutoCollapse": "Auto-collapse Compaction", + "compactionAutoCollapseDesc": "Automatically collapse the compaction summary once it finishes streaming; turn off to keep it expanded", "toolCardStyle": "Tool Output Style", "toolCardStyleDesc": "Choose how tool call results are displayed", "toolCardClassic": "Classic", diff --git a/src/locales/zh-CN/settings.json b/src/locales/zh-CN/settings.json index d02a854fe..1da122f4c 100644 --- a/src/locales/zh-CN/settings.json +++ b/src/locales/zh-CN/settings.json @@ -202,6 +202,8 @@ "inlineToolRequestsDesc": "把待处理的权限和提问显示在对应工具下方,而不是浮层弹窗", "compactInlinePermission": "精简内嵌权限", "compactInlinePermissionDesc": "工具已有内容时,内嵌权限只显示操作按钮,避免重复", + "compactionAutoCollapse": "自动收起压缩结果", + "compactionAutoCollapseDesc": "上下文压缩的摘要流式输出结束后自动收起,关闭则保持展开", "toolCardStyle": "工具输出风格", "toolCardStyleDesc": "选择工具调用结果的展示方式", "toolCardClassic": "经典", diff --git a/src/store/themeStore.ts b/src/store/themeStore.ts index d77e2745c..5a339f11d 100644 --- a/src/store/themeStore.ts +++ b/src/store/themeStore.ts @@ -159,6 +159,7 @@ export type ToolCardStyle = 'classic' | 'compact' const DEFAULT_TOOL_CARD_STYLE: ToolCardStyle = 'compact' const DEFAULT_IMMERSIVE_MODE = true const DEFAULT_COMPACT_INLINE_PERMISSION = true +const DEFAULT_COMPACTION_AUTO_COLLAPSE = true const DEFAULT_GLASS_EFFECT = true const DEFAULT_QUEUE_FOLLOWUP_MESSAGES = false /** 输入框 busy 投递 chip(插队/排队)默认显示 */ @@ -216,6 +217,8 @@ export interface ThemeState { immersiveMode: boolean /** 内嵌权限精简模式:ToolBody 有内容时只显示操作按钮 */ compactInlinePermission: boolean + /** 压缩结果流式输出结束后自动收起(可在设置中关闭) */ + compactionAutoCollapse: boolean /** 毛玻璃效果开关(backdrop-filter blur) */ glassEffect: boolean /** 忙碌时后续消息是否进入队列 */ @@ -268,6 +271,7 @@ const STORAGE_KEY_CODE_FONT_SCALE = 'code-font-scale' const STORAGE_KEY_TOOL_CARD_STYLE = 'tool-card-style' const STORAGE_KEY_IMMERSIVE_MODE = 'immersive-mode' const STORAGE_KEY_COMPACT_INLINE_PERMISSION = 'compact-inline-permission' +const STORAGE_KEY_COMPACTION_AUTO_COLLAPSE = 'compaction-auto-collapse' const STORAGE_KEY_GLASS_EFFECT = 'glass-effect' const STORAGE_KEY_QUEUE_FOLLOWUP_MESSAGES = 'queue-followup-messages' const STORAGE_KEY_QUEUE_DELIVERY_CHIP_VISIBLE = 'queue-delivery-chip-visible' @@ -391,6 +395,10 @@ class ThemeStore { ? DEFAULT_COMPACT_INLINE_PERMISSION : savedCompactInlinePermission === 'true' + const savedCompactionAutoCollapse = localStorage.getItem(STORAGE_KEY_COMPACTION_AUTO_COLLAPSE) + const compactionAutoCollapse = + savedCompactionAutoCollapse === null ? DEFAULT_COMPACTION_AUTO_COLLAPSE : savedCompactionAutoCollapse === 'true' + const savedGlassEffect = localStorage.getItem(STORAGE_KEY_GLASS_EFFECT) const glassEffect = savedGlassEffect === null ? DEFAULT_GLASS_EFFECT : savedGlassEffect === 'true' @@ -470,6 +478,7 @@ class ThemeStore { toolCardStyle, immersiveMode, compactInlinePermission, + compactionAutoCollapse, glassEffect, queueFollowupMessages, queueDeliveryChipVisible, @@ -551,6 +560,9 @@ class ThemeStore { get compactInlinePermission() { return this.state.compactInlinePermission } + get compactionAutoCollapse() { + return this.state.compactionAutoCollapse + } get glassEffect() { return this.state.glassEffect } @@ -870,6 +882,13 @@ class ThemeStore { this.emit() } + setCompactionAutoCollapse(enabled: boolean) { + if (this.state.compactionAutoCollapse === enabled) return + this.state = { ...this.state, compactionAutoCollapse: enabled } + localStorage.setItem(STORAGE_KEY_COMPACTION_AUTO_COLLAPSE, String(enabled)) + this.emit() + } + setGlassEffect(enabled: boolean) { if (this.state.glassEffect === enabled) return this.state = { ...this.state, glassEffect: enabled } @@ -1190,6 +1209,10 @@ function normalizeThemeBackup(raw: unknown): ThemeBackup { typeof parsed?.compactInlinePermission === 'boolean' ? parsed.compactInlinePermission : DEFAULT_COMPACT_INLINE_PERMISSION, + compactionAutoCollapse: + typeof parsed?.compactionAutoCollapse === 'boolean' + ? parsed.compactionAutoCollapse + : DEFAULT_COMPACTION_AUTO_COLLAPSE, glassEffect: typeof parsed?.glassEffect === 'boolean' ? parsed.glassEffect : DEFAULT_GLASS_EFFECT, queueFollowupMessages: typeof parsed?.queueFollowupMessages === 'boolean' @@ -1268,6 +1291,7 @@ export function importThemeBackup(raw: unknown): void { localStorage.setItem(STORAGE_KEY_TOOL_CARD_STYLE, backup.toolCardStyle) localStorage.setItem(STORAGE_KEY_IMMERSIVE_MODE, String(backup.immersiveMode)) localStorage.setItem(STORAGE_KEY_COMPACT_INLINE_PERMISSION, String(backup.compactInlinePermission)) + localStorage.setItem(STORAGE_KEY_COMPACTION_AUTO_COLLAPSE, String(backup.compactionAutoCollapse)) localStorage.setItem(STORAGE_KEY_GLASS_EFFECT, String(backup.glassEffect)) localStorage.setItem(STORAGE_KEY_QUEUE_FOLLOWUP_MESSAGES, String(backup.queueFollowupMessages)) localStorage.setItem(STORAGE_KEY_QUEUE_DELIVERY_CHIP_VISIBLE, String(backup.queueDeliveryChipVisible)) From e3d4c6f30cfc6ec5d93ada55ef8b5cb9886a94e5 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 14:19:07 +0800 Subject: [PATCH 09/91] =?UTF-8?q?feat(message):=20=E5=8E=8B=E7=BC=A9?= =?UTF-8?q?=E7=BB=93=E6=9E=9C=E5=B1=95=E5=BC=80=E5=90=8E=E6=94=AF=E6=8C=81?= =?UTF-8?q?=20undo=20/=20=E5=88=86=E5=8F=89=20/=20=E5=A4=8D=E5=88=B6?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E6=9D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit v1 时代 compaction 是挂在 user 消息上的 part,天然随该消息带 undo;v2 改 为独立消息后这些操作全没了。现在给压缩结果(展开后)补回一条与助手消 息一致的操作条: - undo:revert 到这条压缩消息的边界(revert.stage 接受任意 messageID) - 分叉:fork handler 新增 compaction 分支,新 session 包含该压缩消息 - 复制:复制压缩摘要 为避免 SystemPartViews 反向 import MessageRenderer 造成循环依赖,把 useMessageActionBarClass / ForkActionButton 抽到共享模块 MessageActionBar, 并新增 UndoActionButton 供用户消息与压缩消息共用。操作条仅压缩结束且展 开时显示。 --- src/features/message/MessageActionBar.tsx | 82 +++++++++++++++++++ src/features/message/MessageRenderer.tsx | 71 +++------------- .../message/parts/CompactionPartView.test.tsx | 30 +++++++ .../message/parts/SystemPartViews.tsx | 27 +++++- src/hooks/useChatSession.ts | 12 +++ 5 files changed, 158 insertions(+), 64 deletions(-) create mode 100644 src/features/message/MessageActionBar.tsx diff --git a/src/features/message/MessageActionBar.tsx b/src/features/message/MessageActionBar.tsx new file mode 100644 index 000000000..0b6ceb562 --- /dev/null +++ b/src/features/message/MessageActionBar.tsx @@ -0,0 +1,82 @@ +import { memo, useCallback, useState } from 'react' +import { useTranslation } from 'react-i18next' +import { SpinnerIcon, SplitIcon, UndoIcon } from '../../components/Icons' +import { useInputCapabilities } from '../../hooks/useInputCapabilities' +import type { SessionMessageInfo } from '@opencode/client/promise' + +/** + * 消息操作条(undo / fork / copy)共享样式与按钮。 + * + * 从 MessageRenderer 抽出来,供 UserMessageView / AssistantMessageView / + * CompactionPartView 共用——后者不能反向 import MessageRenderer(循环依赖)。 + */ + +/** PC 精细指针:默认隐藏,悬浮消息/聚焦时显示;触控优先设备始终显示 */ +export function useMessageActionBarClass() { + const { preferTouchUi } = useInputCapabilities() + return preferTouchUi + ? 'flex items-center gap-1 transition-opacity' + : 'flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-within:opacity-100 pointer-events-none group-hover:pointer-events-auto group-focus-within:pointer-events-auto focus-within:pointer-events-auto transition-opacity' +} + +interface UndoActionButtonProps { + /** 回退目标消息 id(用户消息或 compaction 等可回退边界) */ + messageId: string + onUndo?: (messageId: string) => void + canUndo?: boolean +} + +/** 回退到这条消息(revert 边界) */ +export const UndoActionButton = memo(function UndoActionButton({ messageId, onUndo, canUndo }: UndoActionButtonProps) { + const { t } = useTranslation('message') + if (!canUndo || !onUndo) return null + return ( + + ) +}) + +interface ForkActionButtonProps { + message: SessionMessageInfo + onFork?: (message: SessionMessageInfo, forkMessageId?: string) => Promise | void + forkMessageId?: string +} + +export const ForkActionButton = memo(function ForkActionButton({ message, onFork, forkMessageId }: ForkActionButtonProps) { + const { t } = useTranslation('message') + const [isForking, setIsForking] = useState(false) + + const handleFork = useCallback(async () => { + if (!onFork || isForking) return + + setIsForking(true) + + try { + await onFork(message, forkMessageId) + } catch { + // 业务错误由上层统一处理 + } finally { + setIsForking(false) + } + }, [forkMessageId, isForking, message, onFork]) + + if (!onFork) return null + + return ( + + ) +}) diff --git a/src/features/message/MessageRenderer.tsx b/src/features/message/MessageRenderer.tsx index b212dfd4e..f681fab50 100644 --- a/src/features/message/MessageRenderer.tsx +++ b/src/features/message/MessageRenderer.tsx @@ -2,11 +2,10 @@ import { memo, useState, useRef, useEffect, useLayoutEffect, useMemo, useCallbac import { useTranslation } from 'react-i18next' import { diffLines } from 'diff' import { animate } from 'motion/mini' -import { ChevronDownIcon, ChevronRightIcon, SplitIcon, SpinnerIcon, UndoIcon } from '../../components/Icons' +import { ChevronDownIcon, ChevronRightIcon } from '../../components/Icons' import { CopyButton, SmoothHeight } from '../../components/ui' import { MarkdownRenderer } from '../../components/MarkdownRenderer' import { useCompositorExpand, useDisclosureScrollLock } from '../../hooks' -import { useInputCapabilities } from '../../hooks/useInputCapabilities' import { useNow } from '../../hooks/useNow' import { useTheme } from '../../hooks/useTheme' import { useDirectory } from '../../hooks' @@ -30,6 +29,7 @@ import { type StepFinishInfo, } from './parts' import { extractToolData, type ToolViewPart } from './tools' +import { ForkActionButton, UndoActionButton, useMessageActionBarClass } from './MessageActionBar' import { MSG_SPACING } from './messageSpacing' import { MessageExpandPanel, useMessageExpandRender } from './messageExpand' import type { AssistantContent, AssistantMessage, SessionMessageInfo, UserMessage } from '../../types/api/message' @@ -310,7 +310,13 @@ export const MessageRenderer = memo(function MessageRenderer({ if (message.type === 'compaction') { return (
- +
) } @@ -583,45 +589,6 @@ const CollapsibleUserText = memo(function CollapsibleUserText({ ) }) -interface ForkActionButtonProps { - message: SessionMessageInfo - onFork?: (message: SessionMessageInfo, forkMessageId?: string) => Promise | void - forkMessageId?: string -} - -const ForkActionButton = memo(function ForkActionButton({ message, onFork, forkMessageId }: ForkActionButtonProps) { - const { t } = useTranslation('message') - const [isForking, setIsForking] = useState(false) - - const handleFork = useCallback(async () => { - if (!onFork || isForking) return - - setIsForking(true) - - try { - await onFork(message, forkMessageId) - } catch { - // 业务错误由上层统一处理 - } finally { - setIsForking(false) - } - }, [forkMessageId, isForking, message, onFork]) - - if (!onFork) return null - - return ( - - ) -}) - // ============================================ // User Message View // ============================================ @@ -635,14 +602,6 @@ interface UserMessageViewProps { onEntryGrowComplete?: (messageId: string) => void } -/** PC 精细指针:默认隐藏,悬浮消息/聚焦时显示;触控优先设备始终显示 */ -function useMessageActionBarClass() { - const { preferTouchUi } = useInputCapabilities() - return preferTouchUi - ? 'flex items-center gap-1 transition-opacity' - : 'flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-within:opacity-100 pointer-events-none group-hover:pointer-events-auto group-focus-within:pointer-events-auto focus-within:pointer-events-auto transition-opacity' -} - const UserMessageView = memo(function UserMessageView({ message, onUndo, @@ -651,7 +610,6 @@ const UserMessageView = memo(function UserMessageView({ canUndo, onEntryGrowComplete, }: UserMessageViewProps) { - const { t } = useTranslation('message') const { collapseUserMessages, renderUserMarkdown } = useTheme() const actionBarClass = useMessageActionBarClass() @@ -694,16 +652,7 @@ const UserMessageView = memo(function UserMessageView({ {/* Action buttons — PC 悬浮消息显示;触控设备始终显示 */}
- {/* Undo button */} - {canUndo && onUndo && ( - - )} + {/* Copy button */} {messageText && } diff --git a/src/features/message/parts/CompactionPartView.test.tsx b/src/features/message/parts/CompactionPartView.test.tsx index 5742ac4ff..b72d6ac13 100644 --- a/src/features/message/parts/CompactionPartView.test.tsx +++ b/src/features/message/parts/CompactionPartView.test.tsx @@ -113,4 +113,34 @@ describe('CompactionPartView(单标识 + 可收起)', () => { ) expect(screen.getByText('Compaction interrupted')).toBeInTheDocument() }) + + it('completed:展开后底部有 undo/分叉/复制操作条,undo 回传消息 id', () => { + const onUndo = vi.fn() + const onFork = vi.fn() + render( + , + ) + // 展开后才渲染操作条 + fireEvent.click(screen.getByRole('button', { name: /History compacted/ })) + const undoBtn = screen.getByRole('button', { name: 'Undo from here' }) + fireEvent.click(undoBtn) + expect(onUndo).toHaveBeenCalledWith('c-actions') + expect(screen.getByRole('button', { name: 'Fork from here' })).toBeInTheDocument() + }) + + it('collapsed 时不渲染 undo 按钮(操作条随内容收起)', () => { + render( + , + ) + expect(screen.queryByRole('button', { name: 'Undo from here' })).not.toBeInTheDocument() + }) }) diff --git a/src/features/message/parts/SystemPartViews.tsx b/src/features/message/parts/SystemPartViews.tsx index 6f3242637..e3affce12 100644 --- a/src/features/message/parts/SystemPartViews.tsx +++ b/src/features/message/parts/SystemPartViews.tsx @@ -1,13 +1,15 @@ import { memo, useEffect, useRef } from 'react' import { useTranslation } from 'react-i18next' import { RetryIcon, ChevronDownIcon } from '../../../components/Icons' +import { CopyButton } from '../../../components/ui' import { MarkdownRenderer } from '../../../components/MarkdownRenderer' import { useDisclosureScrollLock } from '../../../hooks' import { useTheme } from '../../../hooks/useTheme' -import type { SessionMessageAssistant, SessionMessageCompaction } from '@opencode/client/promise' +import type { SessionMessageAssistant, SessionMessageCompaction, SessionMessageInfo } from '@opencode/client/promise' import { useUiDisclosureState } from '../../../utils/uiDisclosureState' import { unwrapErrorMessage } from '../../../utils/errorMessage' import { chevronClass, MessageExpandPanel, useMessageExpandRender } from '../messageExpand' +import { ForkActionButton, UndoActionButton, useMessageActionBarClass } from '../MessageActionBar' // ============================================ // Retry Part View - 显示重试状态 @@ -90,6 +92,10 @@ export const RetryPartView = memo(function RetryPartView({ retry, stateKey }: Re interface CompactionPartViewProps { /** 原生压缩消息(`status` / `summary` / `tokens` / `error` …) */ message: SessionMessageCompaction + onUndo?: (messageId: string) => void + onFork?: (message: SessionMessageInfo, forkMessageId?: string) => Promise | void + forkMessageId?: string + canUndo?: boolean } /** 官方 TimelineSeparator 同款:细分隔线 + 中间标签 */ @@ -114,9 +120,16 @@ function compactNumber(value: number, locale: string): string { * 不再额外渲染第二条结果分隔线,也不显示流式中的转圈指示。 * - 摘要内容可点击头部收起/展开;流式输出结束后默认自动收起(设置里可关)。 */ -export const CompactionPartView = memo(function CompactionPartView({ message }: CompactionPartViewProps) { +export const CompactionPartView = memo(function CompactionPartView({ + message, + onUndo, + onFork, + forkMessageId, + canUndo, +}: CompactionPartViewProps) { const { t, i18n } = useTranslation('message') const { compactionAutoCollapse } = useTheme() + const actionBarClass = useMessageActionBarClass() const isRunning = message.status === 'running' const isFailed = message.status === 'failed' const summary = isFailed ? '' : message.summary @@ -186,7 +199,7 @@ export const CompactionPartView = memo(function CompactionPartView({ message }: } return ( -
+
)} + {/* 操作条:undo / 分叉 / 复制,与助手消息一致;仅展开且压缩结束后可见 */} + {!isRunning && (onUndo || onFork || summary.trim()) && ( +
+ + + {summary.trim() && } +
+ )} )} diff --git a/src/hooks/useChatSession.ts b/src/hooks/useChatSession.ts index 1ecc1ffff..cd020e2bb 100644 --- a/src/hooks/useChatSession.ts +++ b/src/hooks/useChatSession.ts @@ -1264,6 +1264,18 @@ export function useChatSession({ return } + // compaction 分叉:新 session 包含这条压缩消息(即带着压缩后的上下文继续), + // 边界传它之后的第一条消息;已是末尾则不传,fork 整个 session。 + if (message.type === 'compaction') { + const currentMessages = messagesRef.current + const idx = currentMessages.findIndex(m => m.id === targetMessageId) + const forkAtMessageId = idx >= 0 ? currentMessages[idx + 1]?.id : undefined + const forkedSession = await forkSession(routeSessionId, forkAtMessageId, effectiveDirectory, paneServerId) + setRestoredContent(null) + navigateToSession(forkedSession.id, forkedSession.location?.directory) + return + } + if (!isUserMessage(message)) return // v2 的用户消息没有 model / agent(那是会话级状态), From bc5a375cda3dbaf2ccff81054f57c9c2c8e3c930 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 14:23:55 +0800 Subject: [PATCH 10/91] =?UTF-8?q?fix(message):=20=E5=8E=8B=E7=BC=A9?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E7=9A=84=20undo=20=E6=8C=89=E9=92=AE?= =?UTF-8?q?=E7=9C=9F=E6=AD=A3=E6=8B=BF=E5=88=B0=20onUndo/canUndo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MessageBody 里 onUndo/canUndo 用 isUser 门控,compaction 拿到 undefined, UndoActionButton 因 !onUndo 直接返回 null——所以只看到分叉和复制。现在把 compaction 也列为可 undo 边界(undoable = isUser || type==='compaction')。 --- src/features/chat/ChatArea.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/features/chat/ChatArea.tsx b/src/features/chat/ChatArea.tsx index 74840a2ab..910fdb579 100644 --- a/src/features/chat/ChatArea.tsx +++ b/src/features/chat/ChatArea.tsx @@ -159,6 +159,8 @@ const MessageBody = memo(function MessageBody({ }: MessageBodyProps) { const messageId = message.id const isUser = isUserMessage(message) + // undo 边界:用户消息,或 v2 的独立压缩消息(revert.stage 接受任意 messageID) + const undoable = isUser || message.type === 'compaction' return (
registerMessage?.(messageId, node as HTMLDivElement | null)} @@ -173,10 +175,10 @@ const MessageBody = memo(function MessageBody({ turnDuration={turnDuration} isTurnLatestAssistant={isTurnLatestAssistant} processContentScope={processContentScope} - onUndo={isUser ? onUndo : undefined} + onUndo={undoable ? onUndo : undefined} onFork={onFork} forkMessageId={forkMessageId} - canUndo={isUser ? canUndo : undefined} + canUndo={undoable ? canUndo : undefined} onEntryGrowComplete={isUser ? onEntryGrowComplete : undefined} />
From 474c529c6056a8eeb2e17bb3c47ac639ffa4f950 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 14:45:48 +0800 Subject: [PATCH 11/91] =?UTF-8?q?feat(message):=20=E5=8E=8B=E7=BC=A9?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E8=A1=A5=20step=20=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E4=BF=A1=E6=81=AF=EF=BC=8C=E6=93=8D=E4=BD=9C=E6=9D=A1=E6=8C=89?= =?UTF-8?q?=E5=85=B6=E4=B8=8B=E6=8E=92=E5=88=97=EF=BC=88=E5=AF=B9=E9=BD=90?= =?UTF-8?q?=E5=8A=A9=E6=89=8B=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 压缩消息现在和助手消息同一布局逻辑:内容(可收起的摘要)→ step 完成信 息 → 操作条,三者顺序一致,step 信息与操作条都始终显示(操作条悬浮显 现),不再把操作条收进折叠区、也不再把 step 信息压到最底。 step 信息复用 StepFinishPartView,显示 model + tokens + cost。注意 v2 压 缩消息只持久化 time.created(官方不存完成时间),所以助手那种耗时/完 成时刻没有数据,不显示。 --- .../message/parts/CompactionPartView.test.tsx | 21 ++++++--- .../message/parts/SystemPartViews.tsx | 45 +++++++++++++++---- 2 files changed, 52 insertions(+), 14 deletions(-) diff --git a/src/features/message/parts/CompactionPartView.test.tsx b/src/features/message/parts/CompactionPartView.test.tsx index b72d6ac13..fb1544844 100644 --- a/src/features/message/parts/CompactionPartView.test.tsx +++ b/src/features/message/parts/CompactionPartView.test.tsx @@ -114,7 +114,7 @@ describe('CompactionPartView(单标识 + 可收起)', () => { expect(screen.getByText('Compaction interrupted')).toBeInTheDocument() }) - it('completed:展开后底部有 undo/分叉/复制操作条,undo 回传消息 id', () => { + it('completed:undo/分叉/复制操作条不随摘要收起,undo 回传消息 id', () => { const onUndo = vi.fn() const onFork = vi.fn() render( @@ -125,22 +125,31 @@ describe('CompactionPartView(单标识 + 可收起)', () => { canUndo />, ) - // 展开后才渲染操作条 - fireEvent.click(screen.getByRole('button', { name: /History compacted/ })) + // 与助手消息同一逻辑:操作条始终渲染(悬浮显现),不随摘要收起 const undoBtn = screen.getByRole('button', { name: 'Undo from here' }) fireEvent.click(undoBtn) expect(onUndo).toHaveBeenCalledWith('c-actions') expect(screen.getByRole('button', { name: 'Fork from here' })).toBeInTheDocument() }) - it('collapsed 时不渲染 undo 按钮(操作条随内容收起)', () => { + it('step 完成信息在操作条上面(与助手消息同一顺序)', () => { render( , ) - expect(screen.queryByRole('button', { name: 'Undo from here' })).not.toBeInTheDocument() + // step 信息:tokens 总数 1000+200+100+2000+500=3800 → 3.8k + const stepInfo = screen.getByText('3.8k tokens') + const undoBtn = screen.getByRole('button', { name: 'Undo from here' }) + // step 信息在 undo 按钮之前(内容 → step 信息 → 操作条) + expect(stepInfo.compareDocumentPosition(undoBtn) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() }) }) diff --git a/src/features/message/parts/SystemPartViews.tsx b/src/features/message/parts/SystemPartViews.tsx index e3affce12..220f6ee7c 100644 --- a/src/features/message/parts/SystemPartViews.tsx +++ b/src/features/message/parts/SystemPartViews.tsx @@ -10,6 +10,7 @@ import { useUiDisclosureState } from '../../../utils/uiDisclosureState' import { unwrapErrorMessage } from '../../../utils/errorMessage' import { chevronClass, MessageExpandPanel, useMessageExpandRender } from '../messageExpand' import { ForkActionButton, UndoActionButton, useMessageActionBarClass } from '../MessageActionBar' +import { StepFinishPartView, type StepFinishInfo } from './StepFinishPartView' // ============================================ // Retry Part View - 显示重试状态 @@ -173,6 +174,26 @@ export const CompactionPartView = memo(function CompactionPartView({ const headerLabel = isRunning ? t('system.compactionStarted') : outcomeLabel const hasContent = !!(summary.trim() || failureDetail) + // step 完成信息(对齐助手消息):model + tokens + cost。 + // 注意 v2 压缩消息只记录 time.created(官方不持久化完成时间), + // 所以助手那种"耗时 / 完成时刻"没有数据,这里不显示。 + const stepFinish = ((): StepFinishInfo | undefined => { + if (isRunning) return undefined + const tokens = message.tokens + const cost = message.cost ?? 0 + if (!tokens && cost <= 0) return undefined + return { + tokens: { + input: tokens?.input ?? 0, + output: tokens?.output ?? 0, + reasoning: tokens?.reasoning ?? 0, + cache: { read: tokens?.cache?.read ?? 0, write: tokens?.cache?.write ?? 0 }, + }, + cost, + } + })() + const stepFinishModel = message.status === 'completed' ? message.model?.id : undefined + // 收起状态:running 时展开看流式;结束后默认收起(可在设置里关掉自动收起) const stateKey = `message:compaction:${message.id}` const [expanded, setExpanded] = useUiDisclosureState(stateKey, isRunning || !compactionAutoCollapse) @@ -224,17 +245,25 @@ export const CompactionPartView = memo(function CompactionPartView({ {failureDetail && (
{failureDetail}
)} - {/* 操作条:undo / 分叉 / 复制,与助手消息一致;仅展开且压缩结束后可见 */} - {!isRunning && (onUndo || onFork || summary.trim()) && ( -
- - - {summary.trim() && } -
- )} )} + + {/* step 完成信息(model + tokens + cost),与助手消息一致:内容下方、始终显示 */} + {stepFinish && ( +
+ +
+ )} + + {/* 操作条:undo / 分叉 / 复制,在 step 信息下面(与助手消息同一逻辑,悬浮显现) */} + {!isRunning && (onUndo || onFork || summary.trim()) && ( +
+ + + {summary.trim() && } +
+ )}
) }) From b9780d495eee30483bcc03d71ef07ead513bc8af Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 14:57:43 +0800 Subject: [PATCH 12/91] =?UTF-8?q?fix(session):=20=E5=88=B7=E6=96=B0?= =?UTF-8?q?=E5=90=8E=E4=BB=8E=20Session.Info.revert=20=E9=87=8D=E5=BB=BA?= =?UTF-8?q?=20undo/redo=20=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前加载会话时把 revertState 写死为 null(注释误以为 v2 SessionInfo 不携 带 revert),于是 undo 后一刷新 redo 图标就消失,像没 undo 过。实际上服 务端把回退边界持久化在 Session.Info.revert(schema session.ts:58),而 messageStore.setMessages 本就有从 messageID 重建 redo 历史的逻辑,只是没 被喂数据。现在加载时把 sessionInfo.revert 传进去,刷新后 redo 状态保留。 --- src/hooks/useSessionManager.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/hooks/useSessionManager.ts b/src/hooks/useSessionManager.ts index ecc553bcf..b6c847767 100644 --- a/src/hooks/useSessionManager.ts +++ b/src/hooks/useSessionManager.ts @@ -234,9 +234,9 @@ export function useSessionManager({ title: sessionInfo?.title, hasMoreHistory: nextCursor !== null, historyCursor: nextCursor, - // v2 的 SessionInfo 不再携带 revert / share: - // 回退状态由 session.revert 接口与事件维护,分享改为导出 - revertState: null, + // 服务端把回退边界持久化在 Session.Info.revert(schema session.ts), + // 刷新后据此重建 redo 历史,否则刷新就像没 undo 过。 + revertState: sessionInfo?.revert ?? null, // 会话级 agent/model 的 durable 来源(官方 selection.tsx 同款): // 新鲜客户端没有 live SSE 历史时,composer 从这里恢复 agent: sessionInfo?.agent, From 17979ef29333dfbdffb701543e77eb3cf52fab02 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 15:22:42 +0800 Subject: [PATCH 13/91] =?UTF-8?q?fix(chat):=20fork=20=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E5=90=8E=E6=96=B0=E4=BC=9A=E8=AF=9D=E8=BE=93?= =?UTF-8?q?=E5=85=A5=E6=A1=86=E9=A2=84=E5=A1=AB=E6=81=A2=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fork 接口返回原始会话 id(ses_x),restoredContent.sessionId 存的是它;但路由 里的 routeSessionId 是带服务器前缀的复合 key(local::ses_x)。activeRestoredContent 用全等比较两者,永远不匹配,于是 fork 后输入框预填丢失。改为按原始 id 比较 (splitSessionKey 取 route 的原始段),对带前缀/不带前缀的 route 都成立。 补回归测试:fork 后 rerender 到带前缀的新会话,断言预填文本能恢复(已验证改回 全等比较时该测试失败)。 --- src/hooks/useChatSession.test.tsx | 40 +++++++++++++++++++++++++++++++ src/hooks/useChatSession.ts | 6 ++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/hooks/useChatSession.test.tsx b/src/hooks/useChatSession.test.tsx index 5560d4209..ceeb1fac8 100644 --- a/src/hooks/useChatSession.test.tsx +++ b/src/hooks/useChatSession.test.tsx @@ -86,6 +86,8 @@ vi.mock('../store', () => ({ handlePartUpdated: vi.fn(), upsertLocalMessage: vi.fn(), removeMessage: vi.fn(), + extractUserText: vi.fn(() => 'forked prompt text'), + extractUserAttachments: vi.fn(() => []), }, useSessionFamily: (sessionId: string | null) => useSessionFamilyMock(sessionId), useSessionState: (sessionId: string | null) => useSessionStateMock(sessionId), @@ -394,6 +396,44 @@ describe('useChatSession handleCommand', () => { expect(executeCommandMock).not.toHaveBeenCalled() }) + it('fork 用户消息后,带服务器前缀的新会话能恢复输入框预填内容', async () => { + useSessionStateMock.mockReturnValue({ + isStreaming: false, + canRedo: false, + messages: [{ id: 'u1', type: 'user', text: 'forked prompt text', time: { created: 1 } }], + } as never) + const navigateToSession = vi.fn() + + const { result, rerender } = renderHook( + ({ sessionId }: { sessionId: string }) => + useChatSession({ + paneId: 'pane-1', + chatAreaRef: { current: null }, + currentModel: { id: 'model-1', providerID: 'provider-1', variants: [] } as never, + refetchModels: vi.fn(async () => {}), + sessionId, + navigateToSession, + navigateHome: vi.fn(), + }), + { initialProps: { sessionId: 'session-1' } }, + ) + + // fork 一条用户消息 → fork 接口返回原始 id(ses-forked),并跳转到新会话 + await act(async () => { + await result.current.handleForkMessage({ id: 'u1', type: 'user', sessionID: 'session-1' } as never) + }) + expect(forkSessionMock).toHaveBeenCalledWith('session-1', 'u1', '/workspace/demo', 'local') + expect(navigateToSession).toHaveBeenCalledWith('ses-forked', '/workspace/demo') + + // 模拟导航完成:route 变为带服务器前缀的复合 key(local::ses-forked) + rerender({ sessionId: 'local::ses-forked' }) + + // 预填内容应能按原始 id 匹配上。 + // 回归:restoredContent.sessionId(原始 ses-forked)与 routeSessionId(local::ses-forked) + // 直接全等比较永远不匹配,导致 fork 后输入框预填丢失。 + expect(result.current.restoredContent?.text).toBe('forked prompt text') + }) + it('/undo 在无用户消息时不动作;/redo 在不可 redo 时不动作', async () => { useSessionStateMock.mockReturnValue({ isStreaming: false, diff --git a/src/hooks/useChatSession.ts b/src/hooks/useChatSession.ts index cd020e2bb..9cc20762a 100644 --- a/src/hooks/useChatSession.ts +++ b/src/hooks/useChatSession.ts @@ -1556,7 +1556,11 @@ export function useChatSession({ }, [clearRevert]) const activeRestoredContent = useMemo(() => { - if (!restoredContent || restoredContent.sessionId !== routeSessionId) return null + if (!restoredContent || !routeSessionId) return null + // restoredContent.sessionId 是 fork 接口返回的原始 id(ses_x),而 routeSessionId + // 是带服务器前缀的复合 key(local::ses_x),直接全等比较永远不匹配,导致 fork 后 + // 输入框预填丢失。按原始 id 比较,对带前缀/不带前缀的 routeSessionId 都成立。 + if (restoredContent.sessionId !== splitSessionKey(routeSessionId).sessionId) return null return restoredContent.content }, [restoredContent, routeSessionId]) From 4efc8b602fb2cbe7d572a1a571a6a3e504440107 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 15:57:02 +0800 Subject: [PATCH 14/91] =?UTF-8?q?fix(session):=20deep=20undo=20=E5=88=B7?= =?UTF-8?q?=E6=96=B0=E5=90=8E=E6=AD=A3=E7=A1=AE=E9=9A=90=E8=97=8F=E5=B7=B2?= =?UTF-8?q?=E6=92=A4=E9=94=80=E6=B6=88=E6=81=AF=E5=B9=B6=E4=BF=9D=E7=95=99?= =?UTF-8?q?=20redo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前 deep undo(撤销的消息很深、不在首屏)刷新后有两个问题: 1. getVisibleMessages 用 findIndex 找边界,边界没加载就返回全部消息, 已撤销的消息全部「复活」; 2. revertState 重建失败(保持 null),redo 状态彻底丢失。 参照官方设计分两层处理(官方 selectVisibleSessionUserMessages + revert.clear): - 可见性改用消息 id 比较(id 单调递增,边界没加载也能正确隐藏,修掉「复活」); - setMessages 始终存边界标记 messageId(可见性、redo 全恢复只依赖它,不需边界本体); - canRedo 改为看边界标记,history 为空时 handleRedo 退化为全恢复(revert.clear, 官方 redo 同款); - loadSession 在边界不在首屏时往回翻页补齐,rebuildRevertHistory 重建逐条 redo 历史 + 预填,保留我们比官方更细的逐条 redo 体验。 补回归测试覆盖 deep undo 的隐藏 / 标记 / 翻页重建 / 预填全链路。 --- src/hooks/useSessionManager.ts | 27 +++++++++++++++-- src/store/messageStore.test.ts | 31 +++++++++++++++++++ src/store/messageStore.ts | 54 ++++++++++++++++++++++++++-------- 3 files changed, 97 insertions(+), 15 deletions(-) diff --git a/src/hooks/useSessionManager.ts b/src/hooks/useSessionManager.ts index b6c847767..06eda114a 100644 --- a/src/hooks/useSessionManager.ts +++ b/src/hooks/useSessionManager.ts @@ -37,6 +37,8 @@ export function leadingTurnNeedsParent(messages: SessionMessageInfo[]): boolean /** enrichLeadingTurn 的上限与节奏(官方 leadingTurnPageLimit / Delay 同款) */ const LEADING_TURN_PAGE_LIMIT = 3 const LEADING_TURN_PAGE_DELAY = 200 +// deep undo 往回翻页补边界的安全上限;正常靠 hasMoreHistory 耗尽提前终止,这只是兜底 +const REVERT_BOUNDARY_PAGE_LIMIT = 50 const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)) /** @@ -257,6 +259,21 @@ export function useSessionManager({ } } + // deep undo:回退边界不在首屏时(undo 的消息很深),往回翻页把边界补进内存, + // 重建逐条 redo 历史 + 预填内容。边界一加载 rebuildRevertHistory 就返回 true 提前终止; + // 正常情况下同一页里边界之前的消息也一并带出来,当前(撤销后的)视图就有了。 + if (sessionInfo?.revert?.messageID) { + for (let pages = 0; pages < REVERT_BOUNDARY_PAGE_LIMIT; pages++) { + if (messageStore.rebuildRevertHistory(sid)) break + const state = messageStore.getSessionState(sid) + if (!state?.hasMoreHistory) break + await pause(LEADING_TURN_PAGE_DELAY) + if (isStale()) return + const more = await prependHistoryPage(sid).catch(() => false) + if (!more) break + } + } + // force 模式(如 SSE 重连)只静默刷新数据,不触发滚动 if (!force) { onLoadComplete?.() @@ -348,11 +365,17 @@ export function useSessionManager({ if (!state?.revertState) return const { history } = state.revertState - if (history.length === 0) return - const dir = state.directory || directoryRef.current try { + // 边界还没加载进来(deep undo 翻页失败/进行中):没有逐条历史可退, + // 退化为全恢复(revert.clear,官方 redo 同款,不需要边界消息本体)。 + if (history.length === 0) { + await unrevertSession(sessionId, dir, sessionKeyToServerId(sessionId)) + messageStore.setRevertState(sessionId, null) + return + } + // 移除第一条历史记录(最早撤销的) const newHistory = history.slice(1) diff --git a/src/store/messageStore.test.ts b/src/store/messageStore.test.ts index fb80af75a..8597dd5ab 100644 --- a/src/store/messageStore.test.ts +++ b/src/store/messageStore.test.ts @@ -877,6 +877,37 @@ describe('messageStore(原生 v2 消息)', () => { expect(messageIds(SESSION)).toEqual(['message-1']) }) + it('deep undo:边界不在首屏时按 id 隐藏已撤销消息,翻页补齐后重建逐条 redo 历史', () => { + // 首屏只有最近三条(m3/m4/m5),回退边界 m2 在更深的历史里 + messageStore.setMessages( + SESSION, + [createUserMessage('m3', 3), createUserMessage('m4', 4), createUserMessage('m5', 5)], + { revertState: { messageID: 'm2' } }, + ) + + // 边界没加载也要存边界标记,并按 id 比较隐藏已撤销消息(不「复活」) + expect(messageStore.getRevertState(SESSION)?.messageId).toBe('m2') + expect(messageStore.getRevertState(SESSION)?.history).toEqual([]) + expect(messageStore.getVisibleMessages(SESSION).map(m => m.id)).toEqual([]) + // 有边界标记即可 redo(全恢复兜底,不需要边界本体) + expect(messageStore.canRedo(SESSION)).toBe(true) + + // 边界消息没翻进来前,rebuildRevertHistory 返回 false(还需继续翻) + expect(messageStore.rebuildRevertHistory(SESSION)).toBe(false) + + // 往回翻一页,把 m1/m2 补进内存 + messageStore.prependMessages(SESSION, [createUserMessage('m1', 1), createUserMessage('m2', 2)], false, null) + + // 重建逐条 redo 历史 + expect(messageStore.rebuildRevertHistory(SESSION)).toBe(true) + expect(messageStore.getRevertState(SESSION)?.history.map(h => h.messageId)).toEqual(['m2', 'm3', 'm4', 'm5']) + + // 边界加载后:可见 = 边界之前(m1),边界及之后(m2 起)仍隐藏 + expect(messageStore.getVisibleMessages(SESSION).map(m => m.id)).toEqual(['m1']) + expect(messageStore.getRedoSteps(SESSION)).toBe(4) + expect(messageStore.getCurrentRevertedContent(SESSION)?.messageId).toBe('m2') + }) + it('prependMessages 去重后前插历史页', () => { messageStore.setMessages(SESSION, [createAssistantMessage('message-2', textContent('two'))]) diff --git a/src/store/messageStore.ts b/src/store/messageStore.ts index c5825cbc1..eb3be274e 100644 --- a/src/store/messageStore.ts +++ b/src/store/messageStore.ts @@ -427,8 +427,11 @@ class MessageStore { const { messages, revertState } = state if (!revertState) return messages - const revertIndex = messages.findIndex(message => message.id === revertState.messageId) - return revertIndex === -1 ? messages : messages.slice(0, revertIndex) + // 消息 id 单调递增(msg_ + 大端时间戳前缀),字符串比较即时间比较。 + // 边界之前(id 更小)的可见,边界及之后的已撤销隐藏。 + // 用 id 比较而非 findIndex:边界消息还没加载进内存时(undo 很深)也能正确隐藏, + // 否则刷新后已撤销的消息会全部「复活」(对齐官方 selectVisibleSessionUserMessages)。 + return messages.filter(message => message.id < revertState.messageId) } getIsStreaming(sessionId: string | null): boolean { @@ -737,16 +740,12 @@ class MessageStore { // Revert 状态 const revert = options?.revertState if (revert?.messageID) { - const revertIndex = state.messages.findIndex(message => message.id === revert.messageID) - if (revertIndex !== -1) { - const revertedUserMessages = state.messages.slice(revertIndex).filter(isUserMessage) - state.revertState = { - messageId: revert.messageID, - // buildRevertHistoryItem 在 session 不存在时返回 undefined;此处 state 必然存在 - history: revertedUserMessages - .map(message => this.buildRevertHistoryItem(sessionId, message)) - .filter((item): item is RevertHistoryItem => item !== undefined), - } + // 始终先存边界标记:可见性(id 比较)与 redo 全恢复(revert.clear)只依赖 messageId, + // 不需要边界消息本体。边界不在首屏时(undo 很深)history 先留空, + // 由 loadSession 往回翻页补齐后调 rebuildRevertHistory 重建。 + state.revertState = { + messageId: revert.messageID, + history: this.computeRevertHistory(state, sessionId, revert.messageID), } } else { state.revertState = null @@ -1601,7 +1600,9 @@ class MessageStore { if (!sessionId) return false const state = this.sessions.get(sessionId) if (!state || state.isStreaming) return false - return (state.revertState?.history.length ?? 0) > 0 + // 有边界标记就能 redo:逐条 redo 依赖 history(边界已加载);history 为空时 + // (deep undo 边界还没翻进来)退化为全恢复(revert.clear,官方 redo 同款,不需要边界本体)。 + return state.revertState !== null } getRedoSteps(sessionId: string | null): number { @@ -1697,6 +1698,33 @@ class MessageStore { } } + /** 从已加载消息里构建逐条 redo 历史;边界消息还没加载进来(undo 很深)时返回空数组 */ + private computeRevertHistory(state: SessionState, sessionId: string, messageID: string): RevertHistoryItem[] { + const revertIndex = state.messages.findIndex(message => message.id === messageID) + if (revertIndex === -1) return [] + return state.messages + .slice(revertIndex) + .filter(isUserMessage) + .map(message => this.buildRevertHistoryItem(sessionId, message)) + .filter((item): item is RevertHistoryItem => item !== undefined) + } + + /** + * deep undo 往回翻页把边界消息补进内存后,重建逐条 redo 历史。 + * 返回 true 表示无需再翻(没有 undo / 历史已建好 / 刚建好),false 表示边界仍未加载。 + */ + rebuildRevertHistory(sessionId: string): boolean { + const state = this.sessions.get(sessionId) + const revertState = state?.revertState + if (!state || !revertState) return true + if (revertState.history.length > 0) return true + const history = this.computeRevertHistory(state, sessionId, revertState.messageId) + if (history.length === 0) return false + revertState.history = history + this.notify([sessionId]) + return true + } + /** 官方 `message.append`:按 id 去重后追加(保持创建顺序) */ private appendMessage(state: SessionState, item: SessionMessageInfo): void { if (state.messages.some(message => message.id === item.id)) return From 62b01d927e06f8efd07dc97097416f3f55bd5511 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 16:12:18 +0800 Subject: [PATCH 15/91] =?UTF-8?q?fix(sessions):=20fork=20=E5=87=BA?= =?UTF-8?q?=E7=9A=84=E6=96=B0=E4=BC=9A=E8=AF=9D=E5=AE=9E=E6=97=B6=E8=BF=9B?= =?UTF-8?q?=E5=88=97=E8=A1=A8=EF=BC=8C=E4=B8=8D=E7=94=A8=E6=89=8B=E5=8A=A8?= =?UTF-8?q?=E5=88=B7=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 服务端 fork 只发 session.forked 事件、不发 session.created(core/session.ts:352), 而 useSessions 只订阅了 onSessionCreated,所以 fork 的会话进不了列表,非得手动刷新。 补一个 onSessionForked 处理:fork 的是用户可见的新顶层会话(DB 里 parent_id=null, 来源记在 fork 字段,跟 subagent 子会话不同),必须进列表。注意负载里的 parentID 是 「fork 自哪个会话」,不能套用 onSessionCreated 那个 subagent 过滤。抽共享的 prependSessionById 给两个事件复用(回读完整 SessionInfo 再入列表)。 --- src/hooks/useSessions.test.tsx | 29 +++++++++++++++++++ src/hooks/useSessions.ts | 53 ++++++++++++++++++++-------------- 2 files changed, 61 insertions(+), 21 deletions(-) diff --git a/src/hooks/useSessions.test.tsx b/src/hooks/useSessions.test.tsx index 3b1269edb..56f9fc053 100644 --- a/src/hooks/useSessions.test.tsx +++ b/src/hooks/useSessions.test.tsx @@ -85,6 +85,19 @@ function makeCreatedPayload(id: string, directory = '/workspace/demo', parentID? } } +/** + * session.forked 负载(session-event.ts:187):sessionID 是新会话,parentID 是「fork 自 + * 哪个会话」(不是 subagent 标记),boundary 是 fork 边界。 + */ +function makeForkedPayload(id: string, directory = '/workspace/demo', parentID = 'parent-1') { + createdDirectories.set(id, directory) + return { + sessionID: id, + parentID, + boundary: { type: 'through', messageID: 'msg-1' }, + } +} + describe('useSessions', () => { beforeEach(() => { vi.useFakeTimers() @@ -178,6 +191,22 @@ describe('useSessions', () => { expect(result.current.sessions.map(session => session.id)).toEqual(['session-1']) }) + it('adds forked sessions from session.forked events(fork 负载也带 parentID,但那是 fork 来源不是 subagent,不能跳过)', async () => { + const { result } = renderHook(() => useSessions({ directory: '/workspace/demo' })) + + await act(async () => { + vi.runAllTimers() + await Promise.resolve() + }) + + await act(async () => { + latestEventCallbacks.onSessionForked?.(makeForkedPayload('session-fork') as never) + latestEventCallbacks.onSessionForked?.(makeForkedPayload('session-fork-other', '/workspace/other') as never) + }) + + expect(result.current.sessions.map(session => session.id)).toEqual(['session-fork']) + }) + it('queues a reconnect refresh while a newer request is still in flight', async () => { const firstRequest = createDeferred[]>() const secondRequest = createDeferred[]>() diff --git a/src/hooks/useSessions.ts b/src/hooks/useSessions.ts index 722c87aed..0a91c18b7 100644 --- a/src/hooks/useSessions.ts +++ b/src/hooks/useSessions.ts @@ -242,30 +242,41 @@ export function useSessions(options: UseSessionsOptions = {}): UseSessionsResult ? (cb: Parameters[1]) => subscribeToServerEvents(serverId, cb) : subscribeToEvents + // 回读完整会话并插到列表头部(session.created / session.forked 的负载都不是完整 + // SessionInfo,都得回读一次)。去重靠 setSessions 里的 some 判断。 + const prependSessionById = (sessionID: string) => { + void getSession(sessionID, undefined, serverId) + .then(session => { + if (!session || !matchesDirectory(session)) return + + if (searchRef.current) { + void fetchSessionsRef.current({ search: searchRef.current || undefined }) + return + } + + setSessions(prev => { + if (prev.some(item => item.id === session.id)) return prev + return [session, ...prev] + }) + }) + .catch(() => { + // 回读失败退回整表刷新 + void fetchSessionsRef.current({ search: searchRef.current || undefined }) + }) + } + const unsubscribe = subscribe({ onSessionCreated: data => { + // subagent 子会话(Task 工具 spawn,parentID 非空)不进主列表 if (data.parentID) return - - // v2 的 session.created 负载是创建记录(以 sessionID 为键、带 slug/version), - // 不是 SessionInfo,回读一次拿到完整会话再入列表。 - void getSession(data.sessionID, undefined, serverId) - .then(session => { - if (!session || !matchesDirectory(session)) return - - if (searchRef.current) { - void fetchSessionsRef.current({ search: searchRef.current || undefined }) - return - } - - setSessions(prev => { - if (prev.some(item => item.id === session.id)) return prev - return [session, ...prev] - }) - }) - .catch(() => { - // 回读失败退回整表刷新 - void fetchSessionsRef.current({ search: searchRef.current || undefined }) - }) + prependSessionById(data.sessionID) + }, + // fork 出来的是用户可见的新顶层会话,必须进列表:DB 里 parent_id=null(来源记在 + // fork 字段,不是 subagent),且服务端 fork 只发 session.forked 不发 session.created, + // 所以走 onSessionCreated 永远接不到。负载里的 parentID 是「fork 自哪个会话」, + // 不是 subagent 标记,不能据此跳过。 + onSessionForked: data => { + prependSessionById(data.sessionID) }, onSessionRenamed: data => { // v2 把 v1 的 session.updated 收敛成 session.renamed(只有标题变化) From e3650e309a650903cdd169e2cd4236061ad1ab3c Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 16:53:29 +0800 Subject: [PATCH 16/91] =?UTF-8?q?feat(changes):=20=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=8F=98=E6=9B=B4=E9=9D=A2=E6=9D=BF=E6=94=B9=E4=B8=BA=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E9=A9=B1=E5=8A=A8=E5=88=B7=E6=96=B0=EF=BC=8C=E5=88=B7?= =?UTF-8?q?=E6=96=B0=E6=97=A0=E6=84=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对比官方 watcher 驱动重做右侧文件变更面板的刷新机制,修掉「频繁刷新 + 刷新有感」: 降频(对齐官方事件驱动,去掉轮询): - 删掉「窗口聚焦 / 可见性变化」触发(每次 alt-tab 都刷,是频繁的根因); - 改用 filesystem.changed(文件真变了才刷,跳过 .git 内部、按会话目录过滤), 并额外订阅 vcs.branch.updated(commit/checkout/切分支不改文件但变 diff,比官方覆盖更全); - 保留 session idle / SSE 重连;filesystem.changed / vcs.branch.updated 经 useGlobalEvents 广播给所有 consumer(沿用 onReconnected 的全局分发模式)。 无感: - loading 拆出 initialLoading(仅首次无数据时):刷新时保留现有文件列表与 diff 预览, 新数据到了就地更新,不再整片换成「加载中」; - 目录展开状态刷新时保留:首次全展开,之后只默认展开新出现的目录, 不再把用户手动折叠的目录撑开。 useAutoRefresh 统一改走 session consumer 机制(不再单独发原始 SSE 订阅)。 --- src/components/SessionChangesPanel.tsx | 30 +++++++++-- src/hooks/useAutoRefresh.ts | 69 +++++++++++++++++--------- src/hooks/useFileExplorer.ts | 6 ++- src/hooks/useGlobalEvents.ts | 19 +++++++ 4 files changed, 93 insertions(+), 31 deletions(-) diff --git a/src/components/SessionChangesPanel.tsx b/src/components/SessionChangesPanel.tsx index 5cc654271..850f0098d 100644 --- a/src/components/SessionChangesPanel.tsx +++ b/src/components/SessionChangesPanel.tsx @@ -106,6 +106,8 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ // 展开的目录 const [expandedDirs, setExpandedDirs] = useState>(new Set()) + // 已经出现过的目录路径:刷新时只把「新出现的目录」默认展开,不动用户手动展开/折叠的状态 + const seenDirPathsRef = useRef>(new Set()) const [fileContextMenu, setFileContextMenu] = useState<{ x: number; y: number; file: string } | null>(null) const projectRequestIdRef = useRef(0) @@ -162,6 +164,9 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ [branchDiffs, changeMode, gitDiffs, turnDiffs], ) const loading = projectLoading || loadingModes[changeMode] + // 仅「首次加载(还没数据)」才把内容区换成 loading 占位; + // 已有数据时的自动刷新保留现有列表与预览,新数据到了就地更新——刷新无感。 + const initialLoading = loading && diffs.length === 0 const focusChangeMenuOption = useCallback((mode: ChangeMode) => { changeMenuOptionRefs.current[mode]?.focus() @@ -399,6 +404,7 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ setSelectedFile(null) setMountedPreviewFiles(new Set()) setExpandedDirs(new Set()) + seenDirPathsRef.current = new Set() setChangeMenuOpen(false) resetSplitHeight() @@ -418,7 +424,19 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ }, [changeMode, changeOptions, loadDiffMode, project?.vcs]) useEffect(() => { - setExpandedDirs(collectExpandedDirPaths(buildChangesTree(diffs))) + // 刷新时保留用户手动展开/折叠:首次(seen 为空)全部默认展开; + // 之后只把「新出现的目录」默认展开,已有的展开/折叠状态不动。 + const currentDirs = collectExpandedDirPaths(buildChangesTree(diffs)) + const seen = seenDirPathsRef.current + setExpandedDirs(prev => { + const next = new Set(prev) + for (const dir of currentDirs) { + if (!seen.has(dir)) next.add(dir) + } + return next + }) + seenDirPathsRef.current = new Set([...seen, ...currentDirs]) + const { nextOpenFiles, nextActiveFile } = reconcileDiffPreviewState( diffs, openDiffFilesRef.current, @@ -438,8 +456,10 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ await loadDiffMode(changeMode, { force: true, project: nextProject }) }, [changeMode, loadDiffMode, loadProjectState]) - // 自动刷新:session idle / 窗口聚焦 / SSE 重连 - useAutoRefresh(consumerId, sessionId ?? null, handleRefresh, !!sessionId) + // 自动刷新:文件/分支变更事件 + session idle + SSE 重连(见 useAutoRefresh) + useAutoRefresh(consumerId, sessionId ?? null, handleRefresh, !!sessionId, { + watchDirectory: directory, + }) // 选中文件 const handleSelectFile = useCallback((file: string) => { @@ -548,7 +568,7 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ () => previewDiffs.filter(diff => diff.file === selectedFile || mountedPreviewFiles.has(diff.file)), [mountedPreviewFiles, previewDiffs, selectedFile], ) - const showPreview = !loading && selectedDiff !== null && !(error && diffs.length === 0) + const showPreview = !initialLoading && selectedDiff !== null && !(error && diffs.length === 0) if (projectLoading && !project) { return
{t('sessionChanges.loadingChanges')}
@@ -785,7 +805,7 @@ export const SessionChangesPanel = memo(function SessionChangesPanel({ {/* File List */}
- {loading ? ( + {initialLoading ? (
{t('sessionChanges.loadingChanges')}
) : error && diffs.length === 0 ? (
{error}
diff --git a/src/hooks/useAutoRefresh.ts b/src/hooks/useAutoRefresh.ts index 3d461cb0f..3b6ca03b0 100644 --- a/src/hooks/useAutoRefresh.ts +++ b/src/hooks/useAutoRefresh.ts @@ -1,21 +1,45 @@ import { useCallback, useEffect, useRef } from 'react' import { registerSessionConsumer } from './useGlobalEvents' +import { canonicalizePath } from '../utils/pathUtils' + +/** 是否为 git 内部路径(.git/ 下的内部变更不触发刷新,对齐官方 watcher 的 .git 过滤) */ +function isGitInternalPath(file: string): boolean { + const normalized = file.replace(/\\/g, '/') + return normalized.startsWith('.git/') || normalized.includes('/.git/') || normalized.endsWith('/.git') +} + +/** file 是否位于 directory 之下(折叠 ..、统一分隔符后做前缀判断) */ +function isWithinDirectory(directory: string, file: string): boolean { + const dir = canonicalizePath(directory).replace(/\/+$/, '') + if (!dir) return true + const target = canonicalizePath(file) + return target === dir || target.startsWith(`${dir}/`) +} /** - * 自动刷新 hook:在合理的时机触发面板数据刷新。 + * 自动刷新 hook:在「数据真的可能变了」的时机触发面板刷新,而不是轮询。 + * + * 触发时机(事件驱动,对齐官方 watcher 驱动,且比官方多覆盖 git 分支操作): + * 1. filesystem.changed — 工作区文件真变了(跳过 .git 内部,按 watchDirectory 过滤)。 + * 覆盖「外部编辑器改文件」「工具写文件」等场景,是主要触发源。 + * 2. vcs.branch.updated — commit / checkout / 切分支等 git 操作(不改文件但会变 diff)。 + * 3. Session idle — AI 完成一轮对话后刷新,用户最想看改了什么。 + * 4. SSE 重连 — 断线重连后数据可能过期。 * - * 触发时机: - * 1. Session idle — AI 完成一轮对话后刷新,用户最想看改了什么。 - * 2. 窗口重新聚焦 — 用户可能在外部编辑器改了文件,切回时刷新。 - * 3. SSE 重连 — 断线重连后数据可能过期。 + * 不再用「窗口聚焦 / 可见性变化」轮询:那不靠事件、每次 alt-tab 都刷新(即使啥也没改), + * 是「频繁刷新」的根因;filesystem.changed 已能更准地覆盖外部改动。 * - * 防抖:多次触发在 500ms 内只执行一次,避免请求风暴。 + * 防抖:多次触发在 500ms 内只执行一次,避免请求风暴(如 git checkout 一次性改大量文件)。 */ export function useAutoRefresh( consumerId: string, sessionId: string | null, refresh: () => void | Promise, enabled: boolean = true, + options?: { + /** 文件变更事件按此目录过滤(只关心该目录下的改动);缺省则任何文件变更都触发 */ + watchDirectory?: string + }, ): void { const refreshRef = useRef(refresh) refreshRef.current = refresh @@ -30,33 +54,30 @@ export function useAutoRefresh( }, 500) }, []) - // Session idle + SSE reconnected + // 一次注册:会话级 idle/reconnect + 全局文件/分支变更(经 useGlobalEvents 广播)。 + const watchDirectory = options?.watchDirectory useEffect(() => { if (!enabled) return return registerSessionConsumer(consumerId, sessionId, { onSessionIdle: () => scheduleRefresh(), onReconnected: () => scheduleRefresh(), + onFilesystemChanged: data => { + if (isGitInternalPath(data.file)) return + if (watchDirectory && !isWithinDirectory(watchDirectory, data.file)) return + scheduleRefresh() + }, + onVcsBranchUpdated: () => scheduleRefresh(), }) - }, [consumerId, sessionId, enabled, scheduleRefresh]) - - // Window focus / visibility change - useEffect(() => { - if (!enabled) return - - const onFocus = () => scheduleRefresh() - const onVisibility = () => { - if (document.visibilityState === 'visible') scheduleRefresh() - } + }, [consumerId, sessionId, enabled, scheduleRefresh, watchDirectory]) - window.addEventListener('focus', onFocus) - document.addEventListener('visibilitychange', onVisibility) - return () => { - window.removeEventListener('focus', onFocus) - document.removeEventListener('visibilitychange', onVisibility) + // 卸载时清掉待执行的刷新,避免在已卸载组件上 setState + useEffect( + () => () => { if (pendingRef.current !== null) { clearTimeout(pendingRef.current) pendingRef.current = null } - } - }, [enabled, scheduleRefresh]) + }, + [], + ) } diff --git a/src/hooks/useFileExplorer.ts b/src/hooks/useFileExplorer.ts index 482b02c32..3aa90a23b 100644 --- a/src/hooks/useFileExplorer.ts +++ b/src/hooks/useFileExplorer.ts @@ -366,8 +366,10 @@ export function useFileExplorer(options: UseFileExplorerOptions = {}): UseFileEx await Promise.all([loadRoot(), loadStatuses()]) }, [loadRoot, loadStatuses]) - // 自动刷新:session idle / 窗口聚焦 / SSE 重连 - useAutoRefresh(consumerId, sessionId ?? null, softRefresh, !!effectiveDirectory) + // 自动刷新:文件/分支变更事件 + session idle + SSE 重连(见 useAutoRefresh) + useAutoRefresh(consumerId, sessionId ?? null, softRefresh, !!effectiveDirectory, { + watchDirectory: effectiveDirectory, + }) // 初始加载 useEffect(() => { diff --git a/src/hooks/useGlobalEvents.ts b/src/hooks/useGlobalEvents.ts index beb07e922..655969d33 100644 --- a/src/hooks/useGlobalEvents.ts +++ b/src/hooks/useGlobalEvents.ts @@ -39,6 +39,7 @@ import { outboxConfirm } from '../api/sendAdmission' import { autoApproveStore } from '../store/autoApproveStore' import { multiServerStore } from '../store/multiServerStore' import type { ApiFormInfo, ApiPermissionRequest } from '../api/types' +import type { FilesystemChangedPayload, VcsBranchUpdatedPayload } from '../types/api' import type { SessionStatusMap } from '../types/api/session' import { INITIAL_MESSAGE_LIMIT } from '../constants' @@ -59,6 +60,10 @@ export interface SessionEventCallbacks { onFormCancelled?: (data: { sessionID: string; formID: string }) => void onScrollRequest?: () => void onSessionIdle?: (sessionID: string) => void + /** 全局:工作区文件变更(广播给所有消费者,由消费者按目录过滤) */ + onFilesystemChanged?: (data: FilesystemChangedPayload) => void + /** 全局:git 分支变化(commit / checkout / 切分支,广播给所有消费者) */ + onVcsBranchUpdated?: (data: VcsBranchUpdatedPayload) => void /** v2:会话错误由 execution.failed 表达 */ onExecutionFailed?: (sessionID: string) => void onReconnected?: (reason: 'network' | 'server-switch') => void @@ -1078,6 +1083,20 @@ export function useGlobalEvents(directories?: string[]) { dispatchToConsumers(scopedId, cb => cb.onSessionIdle?.(scopedId)) }, + // 全局事件(无 sessionId):广播给所有消费者,由消费者按自己关心的目录过滤。 + // filesystem.changed = 工作区文件真变了;vcs.branch.updated = commit/checkout/切分支。 + onFilesystemChanged: data => { + for (const consumer of sessionConsumers.values()) { + consumer.callbacks.onFilesystemChanged?.(data) + } + }, + + onVcsBranchUpdated: data => { + for (const consumer of sessionConsumers.values()) { + consumer.callbacks.onVcsBranchUpdated?.(data) + } + }, + onExecutionFailed: (data, facts) => { // v2 用 execution.failed 表达会话级失败(取代 v1 的 session.error) const scopedId = scope(data.sessionID) From 56e7ffb2eb4924a3d6027bc1557e831570c43426 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 17:07:01 +0800 Subject: [PATCH 17/91] =?UTF-8?q?feat(plugins):=20=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E9=9D=A2=E6=9D=BF=E6=98=BE=E7=A4=BA=E6=89=80=E6=9C=89=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E7=9A=84=E6=9D=A5=E6=BA=90=E4=BD=8D=E7=BD=AE=EF=BC=8C?= =?UTF-8?q?=E5=A4=B4=E9=83=A8=E6=A8=AA=E7=BA=BF=E5=AF=B9=E9=BD=90=20MCP=20?= =?UTF-8?q?=E9=9D=A2=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 正常加载的插件副标题显示来源位置:local → 路径、package → target@version、 sdk → 类型标签;之前只有 package 带版本时才显示,local 插件只显示「本地」。 位置与标题相同(无 id 的 local 插件标题本身就是路径)时不重复,退回类型标签; 副标题加 title 提示,长路径可悬停看全。 - 头部横线改为 McpPanel 同款:h-10 固定高度 + 独立 h-px 细线 (inset-x-3 两侧内缩、bg-border-200/30),替代整宽 border-b border-border-200/40。 --- src/components/PluginsPanel.tsx | 44 ++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsx index c1059546f..74a10900d 100644 --- a/src/components/PluginsPanel.tsx +++ b/src/components/PluginsPanel.tsx @@ -67,11 +67,11 @@ export const PluginsPanel = memo(function PluginsPanel({ isResizing: _isResizing return (
- {/* Header */} -
-
+ {/* Header(横线风格与 McpPanel 一致:独立 h-px 细线、两侧内缩) */} +
+
- {t('pluginsPanel.title')} + {t('pluginsPanel.title')}
+
{/* List */} @@ -105,14 +106,27 @@ export const PluginsPanel = memo(function PluginsPanel({ isResizing: _isResizing
) : (
- {plugins.map(plugin => { - const label = pluginLabel(plugin) - const state = plugin.state - const failed = state.status === 'failed' - const source = plugin.source - const pkg = source.type === 'package' ? source : null - const outdated = pkg?.outdated === true - const updatingThis = updating !== null && pkg?.target === updating + {plugins.map(plugin => { + const label = pluginLabel(plugin) + const state = plugin.state + const failed = state.status === 'failed' + const source = plugin.source + const pkg = source.type === 'package' ? source : null + const outdated = pkg?.outdated === true + const updatingThis = updating !== null && pkg?.target === updating + // 来源位置:local → 路径;package → target@version;sdk → 类型标签。 + // 加载失败的插件没有 id,标题本身已回退成路径(即位置),所以失败时副标题留给错误信息; + // 正常加载的插件标题是 id(名字),位置要在副标题显示出来。 + const location = + source.type === 'local' + ? source.path + : pkg + ? pkg.version + ? `${pkg.target}@${pkg.version}` + : pkg.target + : t(`pluginsPanel.source.${source.type}`) + // 位置与标题相同(如无 id 的 local 插件)时不重复,退回类型标签 + const secondary = location === label ? t(`pluginsPanel.source.${source.type}`) : location return (
@@ -128,8 +142,8 @@ export const PluginsPanel = memo(function PluginsPanel({ isResizing: _isResizing {t('pluginsPanel.failed')}: {state.error} ) : ( - - {pkg?.version ? `${pkg.target}@${pkg.version}` : t(`pluginsPanel.source.${source.type}`)} + + {secondary} )}
From 054e554aa934c1d68a2d8171dd79e759d1450ac1 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 17:36:14 +0800 Subject: [PATCH 18/91] =?UTF-8?q?fix(chat):=20=E4=BC=9A=E8=AF=9D=E7=BA=A7?= =?UTF-8?q?=E9=94=99=E8=AF=AF=EF=BC=88=E5=A4=B1=E8=B4=A5=20idle=20?= =?UTF-8?q?=E6=A0=87=E8=AE=B0=EF=BC=89=E6=B8=B2=E6=9F=93=E6=88=90=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E5=8D=A1=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 这个 session 的错误不渲染,是三层断点叠加: 1. live 路径:handleExecutionFailed 只关闭执行,把 session.execution.failed 负载里的 error 丢了(官方是 idle("failed", error),错误挂在 idle 标记上)。 2. 过程时间线:buildProcessTimeline 把所有非 user/assistant/shell 消息直接跳过, 失败 idle 标记永远不渲染。 3. 平铺模式:MessageRenderer 对非 assistant 消息一律 return null。 会话级失败(pre-promotion failure:prompt 没能提升成 assistant 工作)没有任何 assistant 消息,错误只在这条失败 idle 标记里——三层一叠,错误彻底不可见。 修复(对齐官方 session-ui projection.ts 的 isFailedIdle → Error 卡片): - closeExecution 把 error 挂到 idle 标记上(服务端投影本就带 error, 是 @opencode/client 生成类型漏了该字段,用交叉类型取回); - 时间线把失败 idle 标记记到当前回合、回合末追加错误卡片;不重开回合分组, 重试的后续 assistant 仍归本回合; - 去重与官方一致:末尾 assistant 已显示非中断错误时跳过 idle 卡片, 中断(abort)不算已显示; - MessageRenderer 渲染失败 idle 为 MessageErrorView,成功/中断标记仍不渲染。 --- src/features/chat/ChatArea.test.ts | 100 ++++++++++++++++++++++- src/features/chat/chatPageModel.ts | 33 +++++++- src/features/message/MessageRenderer.tsx | 17 +++- src/store/messageStore.test.ts | 3 +- src/store/messageStore.ts | 19 ++++- src/types/api/message.ts | 29 +++++++ 6 files changed, 192 insertions(+), 9 deletions(-) diff --git a/src/features/chat/ChatArea.test.ts b/src/features/chat/ChatArea.test.ts index 914b84eef..0ea1b3e7c 100644 --- a/src/features/chat/ChatArea.test.ts +++ b/src/features/chat/ChatArea.test.ts @@ -19,7 +19,7 @@ import { getStreamingHotIndexes, getTimelineRowYClass, mergeVirtualRangeIndexes import { buildVisibleMessageEntries, getVisibleMessageForkTargetId } from './chatAreaVisibility' import { buildChatPageViewModel } from './useChatPageViewModel' import type { AssistantContent, AssistantMessage, SessionMessageInfo, UserMessage } from '../../types/api/message' -import { isAssistantMessage } from '../../types/api/message' +import { isAssistantMessage, isFailedIdleMessage, idleMessageError } from '../../types/api/message' /** 助手消息的 content(非助手返回空数组,测试断言里方便用) */ function contentOf(message: SessionMessageInfo): AssistantContent[] { @@ -614,6 +614,104 @@ describe('buildProcessTimeline', () => { expect(timeline[0]).toMatchObject({ kind: 'message', key: 'user-1' }) }) + it('renders a failed idle marker as an error item (pre-promotion failure)', () => { + // 会话级失败:prompt 没能提升成 assistant 工作,只剩一条带 error 的失败 idle 标记。 + // 不渲染它,错误就永远不可见(官方 session-ui projection.ts 的 isFailedIdle)。 + const failedIdle = { + id: 'idle-1', + type: 'idle', + outcome: 'failed', + error: { type: 'provider.auth', message: 'Invalid API key' }, + time: { created: 1001 }, + } as SessionMessageInfo + const messages = [createUserMessage('user-1', 1000), failedIdle] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + const errorItem = timeline.find(item => item.kind === 'message' && item.key === 'idle-1') + expect(errorItem).toBeTruthy() + if (errorItem?.kind === 'message') { + expect(isFailedIdleMessage(errorItem.message)).toBe(true) + expect(idleMessageError(errorItem.message)).toMatchObject({ type: 'provider.auth' }) + } + }) + + it('does not duplicate the error card when the last assistant already shows it', () => { + // assistant.error 已由 MessageErrorView 渲染 → idle 卡片跳过(官方同款去重) + const failedAssistant = createAssistantMessage( + 'assistant-1', + [createTextPart('text-1', 'assistant-1', 'oops')], + 1001, + 1002, + { type: 'provider', message: 'boom' }, + ) + const failedIdle = { + id: 'idle-1', + type: 'idle', + outcome: 'failed', + error: { type: 'provider', message: 'boom' }, + time: { created: 1003 }, + } as SessionMessageInfo + const messages = [createUserMessage('user-1', 1000), failedAssistant, failedIdle] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + expect(timeline.some(item => item.kind === 'message' && item.key === 'idle-1')).toBe(false) + }) + + it('still shows the idle error card when the assistant error was an interruption', () => { + // assistant 是被中断的(abort)→ 不算「已显示错误」,idle 卡片仍要渲染 + const aborted = createAssistantMessage( + 'assistant-1', + [createTextPart('text-1', 'assistant-1', 'partial')], + 1001, + 1002, + { type: 'MessageAbortedError', message: 'aborted' }, + ) + const failedIdle = { + id: 'idle-1', + type: 'idle', + outcome: 'failed', + error: { type: 'provider', message: 'boom' }, + time: { created: 1003 }, + } as SessionMessageInfo + const messages = [createUserMessage('user-1', 1000), aborted, failedIdle] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + expect(timeline.some(item => item.kind === 'message' && item.key === 'idle-1')).toBe(true) + }) + + it('ignores succeeded idle markers', () => { + const okIdle = { + id: 'idle-1', + type: 'idle', + outcome: 'succeeded', + time: { created: 1001 }, + } as SessionMessageInfo + const messages = [createUserMessage('user-1', 1000), okIdle] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + expect(timeline.some(item => item.key === 'idle-1')).toBe(false) + }) + it('keeps only the earliest pending Working shell when a later user is queued', () => { // 第一轮仍 live,第二轮 user 已发出 → 只挂 user-1 的 Working,user-2 暂不挂空壳 const mid = createAssistantMessage('assistant-1', [createToolPart('tool-1', 'assistant-1')], 1001) diff --git a/src/features/chat/chatPageModel.ts b/src/features/chat/chatPageModel.ts index cfb185c97..2ad28cd27 100644 --- a/src/features/chat/chatPageModel.ts +++ b/src/features/chat/chatPageModel.ts @@ -1,5 +1,6 @@ import type { AssistantMessage, SessionMessageInfo, ToolState, UserMessage } from '../../types/api/message' -import { contentEntries, isAssistantMessage, isUserMessage, userMessageText } from '../../types/api/message' +import { contentEntries, isAssistantMessage, isFailedIdleMessage, isUserMessage, userMessageText } from '../../types/api/message' +import { isInterruptedError } from '../../utils/errorMessage' export const PAGE_MESSAGE_COUNT = 20 export const PAGE_EXTREME_RENDER_WEIGHT = 700 @@ -900,6 +901,11 @@ export function buildProcessTimeline( assistants: AssistantMessage[] /** 独立成行的消息(shell 命令等):不进任何回合壳,按原位平铺 */ standalone?: SessionMessageInfo + /** + * 会话级失败的 idle 标记(pre-promotion failure 等,官方 isFailedIdle)。 + * 不结束回合分组(重试的后续 assistant 仍归本回合),回合转换时追加成错误卡片。 + */ + failedIdle?: SessionMessageInfo } const turns: TurnBag[] = [] @@ -921,6 +927,13 @@ export function buildProcessTimeline( turns.push({ user: null, assistants: [], standalone: message }) continue } + // 失败的 idle 标记:会话级错误(如 prompt 没能提升成 assistant 工作)只在这条 + // 标记里,跳过它错误就永远不渲染。记到当前回合(没有就独立平铺),转换时追加。 + if (isFailedIdleMessage(message)) { + if (current) current.failedIdle = message + else items.push({ kind: 'message', key: message.id, message }) + continue + } if (!isAssistantMessage(message)) continue if (!current) { // 历史续段 / 页首无 user:直接平铺,不挂壳 @@ -979,6 +992,16 @@ export function buildProcessTimeline( } } + // 回合末尾追加失败 idle 的错误卡片;错误已在末尾 assistant 上显示过就不重复 + // (官方 session-ui projection.ts:276 的同款去重:assistant.error 已渲染则跳过 idle 卡) + const appendFailedIdle = (turn: TurnBag) => { + const failedIdle = turn.failedIdle + if (!failedIdle) return + const last = turn.assistants.at(-1) + if (last?.error && !isInterruptedError(last.error)) return + items.push({ kind: 'message', key: failedIdle.id, message: failedIdle }) + } + for (const turn of turns) { if (turn.standalone) { items.push({ kind: 'message', key: turn.standalone.id, message: turn.standalone }) @@ -989,13 +1012,17 @@ export function buildProcessTimeline( } const assistants = turn.assistants - if (!turn.user && assistants.length === 0) continue + if (!turn.user && assistants.length === 0) { + appendFailedIdle(turn) + continue + } // 无 user 的续段:平铺 if (!turn.user) { for (const m of assistants) { items.push({ kind: 'message', key: m.id, message: m }) } + appendFailedIdle(turn) continue } @@ -1055,6 +1082,8 @@ export function buildProcessTimeline( items.push({ kind: 'message', key: m.id, message: m }) } } + + appendFailedIdle(turn) } return items diff --git a/src/features/message/MessageRenderer.tsx b/src/features/message/MessageRenderer.tsx index f681fab50..7c698aeae 100644 --- a/src/features/message/MessageRenderer.tsx +++ b/src/features/message/MessageRenderer.tsx @@ -34,7 +34,7 @@ import { MSG_SPACING } from './messageSpacing' import { MessageExpandPanel, useMessageExpandRender } from './messageExpand' import type { AssistantContent, AssistantMessage, SessionMessageInfo, UserMessage } from '../../types/api/message' import type { JsonValue } from '@opencode/client/promise' -import { contentEntries, hasVisibleText, userMessageText, type ContentEntry } from '../../types/api/message' +import { contentEntries, hasVisibleText, idleMessageError, userMessageText, type ContentEntry } from '../../types/api/message' import { currentToolFailed } from '../../types/api/toolState' import { resolveTaskChildSessionRef } from '../../utils/taskChildBinding' import { expandCodeModeSubCalls } from './parts/executeSubCallSummary' @@ -326,6 +326,21 @@ export const MessageRenderer = memo(function MessageRenderer({ return } + // 失败的 idle 标记:会话级错误(pre-promotion failure 等)渲染成错误卡片 + // (官方 session-ui projection.ts 的 isFailedIdle → Error 卡片)。 + // 这类失败没有任何 assistant 消息,不渲染的话错误永远不可见。 + if (message.type === 'idle') { + const idleError = idleMessageError(message) + if (message.outcome === 'failed' && idleError) { + return ( +
+ +
+ ) + } + return null + } + if (message.type !== 'assistant') return null return ( diff --git a/src/store/messageStore.test.ts b/src/store/messageStore.test.ts index 8597dd5ab..bc1edfbef 100644 --- a/src/store/messageStore.test.ts +++ b/src/store/messageStore.test.ts @@ -680,12 +680,13 @@ describe('messageStore(原生 v2 消息)', () => { expect(idle).toMatchObject({ id: 'msg_done', type: 'idle', outcome: 'succeeded', time: { created: 200 } }) }) - it('failed → outcome=failed', () => { + it('failed → outcome=failed + 错误挂到 idle 标记上(官方 idle("failed", error),丢了就永不渲染)', () => { messageStore.handleExecutionFailed({ sessionID: SESSION, error: { type: 'x', message: 'boom' } }) expect(messageStore.getSessionState(SESSION)?.messages.at(-1)).toMatchObject({ type: 'idle', outcome: 'failed', + error: { type: 'x', message: 'boom' }, }) }) diff --git a/src/store/messageStore.ts b/src/store/messageStore.ts index eb3be274e..d8ede5a37 100644 --- a/src/store/messageStore.ts +++ b/src/store/messageStore.ts @@ -22,7 +22,7 @@ // store 只读负载里的 sessionID,**从不**读事件信封上的 sessionID —— 读原始 // id 会让两个服务器上的同 id 会话串台。 -import type { ModelRef } from '@opencode/client/promise' +import type { ModelRef, SessionStructuredError } from '@opencode/client/promise' import type { AssistantContent, AssistantMessage, @@ -1193,7 +1193,10 @@ class MessageStore { } handleExecutionFailed(data: EventPayload<'session.execution.failed'>, facts?: EventFacts) { - this.closeExecution(data.sessionID, 'failed', facts) + // 官方 idle("failed", event.data.error):错误必须挂到 idle 标记上。 + // 会话级失败(pre-promotion failure)没有任何 assistant 消息, + // 错误只在这条标记里——丢了它,错误就永远不渲染。 + this.closeExecution(data.sessionID, 'failed', facts, false, data.error) } handleExecutionInterrupted(data: EventPayload<'session.execution.interrupted'>, facts?: EventFacts) { @@ -1208,7 +1211,13 @@ class MessageStore { * 它是服务端投影里就有的轮次边界,不补的话本地要等下一次 message.list * 才能对齐(期间轮次分组会错位)。 */ - private closeExecution(sessionID: string, outcome: ExecutionOutcome, facts?: EventFacts, skipIdle = false) { + private closeExecution( + sessionID: string, + outcome: ExecutionOutcome, + facts?: EventFacts, + skipIdle = false, + error?: SessionStructuredError, + ) { const state = this.ensureSession(sessionID) state.isStreaming = false @@ -1223,8 +1232,10 @@ class MessageStore { id: messageIDFromFacts(facts), type: 'idle', outcome, + // 服务端投影的 idle 带 error(客户端类型漏了该字段),与官方对齐 + ...(error ? { error } : {}), time: { created: facts?.created ?? Date.now() }, - }) + } as SessionMessageInfo) } this.notify([sessionID]) diff --git a/src/types/api/message.ts b/src/types/api/message.ts index 474c56deb..0acb4928b 100644 --- a/src/types/api/message.ts +++ b/src/types/api/message.ts @@ -45,6 +45,7 @@ import type { SessionMessageToolStateRunning as V2ToolStateRunning, SessionMessageToolStateStreaming as V2ToolStateStreaming, SessionMessagesResponse as V2MessagesResponse, + SessionStructuredError, ToolContent as V2ToolContent, } from '@opencode/client/promise' @@ -214,3 +215,31 @@ export function hasVisibleText(content: AssistantContent): boolean { export function userMessageText(message: UserMessage): string { return typeof message.text === 'string' ? message.text : '' } + +// ============================================ +// idle 标记消息 +// ============================================ + +/** + * 取 idle 消息上的错误。 + * + * 服务端投影的 idle 消息带 `error`(schema `session-message.ts` 的 Idle: + * `error: SessionError.Error.pipe(optional)`,`session.execution.failed` + * 投影成 `idle("failed", error)`),但 @opencode/client 生成的 + * `SessionMessageIdle` 类型漏了该字段——运行时有、类型没有,这里用交叉类型取回。 + */ +export function idleMessageError(message: SessionMessageInfo): SessionStructuredError | undefined { + if (message.type !== 'idle') return undefined + return (message as V2Idle & { error?: SessionStructuredError }).error +} + +/** + * 失败 idle 标记(官方 session-ui `projection.ts` 的 isFailedIdle)。 + * + * 会话级失败(如 pre-promotion failure:prompt 没能提升成 assistant 工作)时, + * 服务端只留一条带 error 的失败 idle 标记、没有任何 assistant 消息—— + * 不把它渲染出来,这个错误就永远不可见。 + */ +export function isFailedIdleMessage(message: SessionMessageInfo): boolean { + return message.type === 'idle' && message.outcome === 'failed' && idleMessageError(message) != null +} From f1470a047651f72f712fc535f205caf666fd8652 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 17:47:29 +0800 Subject: [PATCH 19/91] =?UTF-8?q?fix(chat):=20=E5=A4=B1=E8=B4=A5=20idle=20?= =?UTF-8?q?=E6=A0=87=E8=AE=B0=E4=B8=8D=E5=86=8D=E8=A2=AB=E5=8F=AF=E8=A7=81?= =?UTF-8?q?=E6=80=A7=E8=BF=87=E6=BB=A4=E6=8E=89=EF=BC=88=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E4=B8=8D=E6=B8=B2=E6=9F=93=E7=9A=84=E6=9C=80=E5=90=8E=E4=B8=80?= =?UTF-8?q?=E7=8E=AF=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上一提交修了 store 存 error、时间线追加卡片、MessageRenderer 渲染, 但 ChatArea 的 visibleMessages 来自 buildVisibleMessageEntries,其 messageHasContent 对 idle 消息一律 hasAnyContent=false——失败 idle 标记 在进时间线之前就被过滤了,所以错误依旧不渲染。 用真实服务端数据验证(该 session 消息列表里确有 {type:idle, outcome:failed, error:provider.no-route}),在 messageHasContent 里让失败 idle 标记始终可见;succeeded/interrupted 标记照旧过滤。 补 buildVisibleMessageEntries 测试:失败标记保留、成功/中断标记隐藏。 --- src/features/chat/ChatArea.test.ts | 28 +++++++++++++++++++++++++ src/features/chat/chatAreaVisibility.ts | 4 ++++ 2 files changed, 32 insertions(+) diff --git a/src/features/chat/ChatArea.test.ts b/src/features/chat/ChatArea.test.ts index 0ea1b3e7c..96e38b619 100644 --- a/src/features/chat/ChatArea.test.ts +++ b/src/features/chat/ChatArea.test.ts @@ -87,6 +87,34 @@ function createTextPart(_id: string, _messageID: string, text: string): Assistan } describe('buildVisibleMessageEntries', () => { + it('keeps failed idle markers visible (session-level error must render)', () => { + // pre-promotion failure:只有 user + 失败 idle 标记,过滤掉它错误就永远不渲染 + const failedIdle = { + id: 'idle-1', + type: 'idle', + outcome: 'failed', + error: { type: 'provider.no-route', message: 'Model unavailable' }, + time: { created: 2 }, + } as SessionMessageInfo + const entries = buildVisibleMessageEntries([createUserMessage('user-1', 1, '你好'), failedIdle]) + + expect(entries.some(e => e.message.id === 'idle-1')).toBe(true) + }) + + it('hides succeeded / interrupted idle markers', () => { + const okIdle = { id: 'idle-ok', type: 'idle', outcome: 'succeeded', time: { created: 2 } } as SessionMessageInfo + const abortedIdle = { + id: 'idle-abort', + type: 'idle', + outcome: 'interrupted', + time: { created: 3 }, + } as SessionMessageInfo + const entries = buildVisibleMessageEntries([createUserMessage('user-1', 1, '你好'), okIdle, abortedIdle]) + + expect(entries.some(e => e.message.id === 'idle-ok')).toBe(false) + expect(entries.some(e => e.message.id === 'idle-abort')).toBe(false) + }) + it('keeps source ids for merged assistant tool messages', () => { const first = createAssistantMessage('assistant-1', [createToolPart('tool-1', 'assistant-1')]) const second = createAssistantMessage('assistant-2', [createToolPart('tool-2', 'assistant-2')]) diff --git a/src/features/chat/chatAreaVisibility.ts b/src/features/chat/chatAreaVisibility.ts index 33d2f8a6e..337308138 100644 --- a/src/features/chat/chatAreaVisibility.ts +++ b/src/features/chat/chatAreaVisibility.ts @@ -3,6 +3,7 @@ import { contentEntries, hasVisibleText, isAssistantMessage, + isFailedIdleMessage, isUserMessage, userMessageText, } from '../../types/api/message' @@ -59,6 +60,9 @@ function messageHasContent(message: SessionMessageInfo): boolean { if (isAssistantMessage(message) && message.error) { return isInterruptedError(message.error) ? hasRenderable : true } + // 失败 idle 标记(会话级错误,如 pre-promotion failure)始终可见: + // 它没有 assistant 消息,错误卡片就是它唯一的内容(官方 isFailedIdle → Error 卡片) + if (isFailedIdleMessage(message)) return true if (!hasAnyContent(message)) { // 任何角色的空消息都不可见:没有内容可展示 // 内容到达后自动进入可见列表;abort 后永远不会有内容 → 永远不可见 From e253d45a39bcca83faa26eb6748c5c505fb2a3d2 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 18:06:51 +0800 Subject: [PATCH 20/91] =?UTF-8?q?feat(chat):=20=E5=8F=91=E9=80=81=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E5=AE=98=E6=96=B9=E6=97=B6=E5=BA=8F=E2=80=94=E2=80=94?= =?UTF-8?q?=E6=8F=90=E4=BA=A4=E5=8D=B3=E6=B8=85=E7=A9=BA=E3=80=81=E5=90=8E?= =?UTF-8?q?=E5=8F=B0=E5=8F=91=E9=80=81=E3=80=81=E5=A4=B1=E8=B4=A5=E6=81=A2?= =?UTF-8?q?=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前按回车后,文本要等 switchModel → switchAgent → prompt 三个串行 RTT 落定才从输入框消失(runSubmit await 完才 onSuccess 清草稿),消息早已乐观 上屏、文本却还在框里「粘」几百毫秒——这是发送不优雅的体感来源。 对齐官方 composer submit.ts 时序(clearSubmission → void sending → failSubmission(restore)): - 新增 submitOptimistically:快照草稿 → 立即清空 → 后台发送; - 失败时输入框还没被新内容占用才恢复旧草稿(不覆盖用户正在打的下一条), 失败通知仍由 sendMessageNow 负责; - 普通消息 / shell / 斜杠命令三条路径统一走这套(斜杠兜底从 onCommand+resetDraft 裸调用也收进 submitCommandOptimistically); - 顺势删掉 isSubmitting:它原本兼任「发送中禁输入/禁附件/按钮转圈」, 与「后台发送时可继续打下一条」冲突;清空后空输入天然挡住连按, 发送中的反馈由乐观消息 + 回合状态表达(与官方一致)。 --- src/features/chat/InputBox.test.tsx | 41 +++++++++-- src/features/chat/InputBox.tsx | 103 +++++++++++++++------------- 2 files changed, 90 insertions(+), 54 deletions(-) diff --git a/src/features/chat/InputBox.test.tsx b/src/features/chat/InputBox.test.tsx index 1103cd625..d183243f5 100644 --- a/src/features/chat/InputBox.test.tsx +++ b/src/features/chat/InputBox.test.tsx @@ -151,10 +151,13 @@ describe('InputBox slash command selection', () => { expect(onSend).toHaveBeenCalledWith('hello world', [], { agent: undefined, variant: undefined }) }) - expect(textarea.value).toBe('hello world') + // 官方同款失败恢复:输入框仍是空的,旧草稿被放回来 + await waitFor(() => { + expect(textarea.value).toBe('hello world') + }) }) - it('waits for send acknowledgement before clearing the draft', async () => { + it('clears the draft immediately on submit and sends in the background', async () => { let resolveSend: ((value: boolean) => void) | null = null const onSend = vi.fn( () => @@ -169,15 +172,43 @@ describe('InputBox slash command selection', () => { fireEvent.change(textarea, { target: { value: 'pending send' } }) fireEvent.click(screen.getByRole('button', { name: 'send' })) - expect(textarea.value).toBe('pending send') + // 官方 composer 时序:提交即清空,不等 POST RTT + expect(textarea.value).toBe('') await act(async () => { resolveSend?.(true) }) - await waitFor(() => { - expect(textarea.value).toBe('') + // 发送成功后草稿保持清空 + expect(textarea.value).toBe('') + }) + + it('does not clobber a newer draft when a background send fails', async () => { + let resolveSend: ((value: boolean) => void) | null = null + const onSend = vi.fn( + () => + new Promise(resolve => { + resolveSend = resolve + }), + ) + + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + fireEvent.change(textarea, { target: { value: 'first message' } }) + fireEvent.click(screen.getByRole('button', { name: 'send' })) + + expect(textarea.value).toBe('') + + // 上一条还在后台发,用户已经开始打下一条 + fireEvent.change(textarea, { target: { value: 'next draft' } }) + + // 上一条发送失败 → 不能覆盖正在打的新草稿 + await act(async () => { + resolveSend?.(false) }) + + expect(textarea.value).toBe('next draft') }) it('clears api slash command drafts immediately after keyboard submission', async () => { diff --git a/src/features/chat/InputBox.tsx b/src/features/chat/InputBox.tsx index c076db6fe..f51895490 100644 --- a/src/features/chat/InputBox.tsx +++ b/src/features/chat/InputBox.tsx @@ -260,7 +260,6 @@ function InputBoxComponent({ const [shellMode, setShellMode] = useState(false) // 附件状态(图片、文件、文件夹、agent) const [attachments, setAttachments] = useState([]) - const [isSubmitting, setIsSubmitting] = useState(false) // @ Mention 状态 const [mentionOpen, setMentionOpen] = useState(false) @@ -362,7 +361,7 @@ function InputBoxComponent({ textareaRef.current.setSelectionRange(revertedText.length, revertedText.length) } }) - } else if (prevRevertedTextRef.current !== undefined && revertedText === undefined && !isSubmitting) { + } else if (prevRevertedTextRef.current !== undefined && revertedText === undefined) { frameId = requestAnimationFrame(() => { setText('') setAttachments([]) @@ -376,7 +375,7 @@ function InputBoxComponent({ cancelAnimationFrame(frameId) } } - }, [revertedText, revertedAttachments, isSubmitting]) + }, [revertedText, revertedAttachments]) // 队列编辑草稿:装载(暂存当前输入)/ 恢复(取消编辑),nonce 为触发键 const draftStashRef = useRef<{ text: string; attachments: Attachment[] } | null>(null) @@ -561,29 +560,42 @@ function InputBoxComponent({ [attachments, onClearRevert, onCommand, resetDraft, restoreDraft, text], ) - const runSubmit = useCallback( - async (submit: () => Promise | boolean | void, onSuccess?: () => void, onFailure?: () => void) => { - if (isSubmitting) return false - - setIsSubmitting(true) - try { - const result = await submit() - if (result === false) { - onFailure?.() - return false + /** + * 提交即清空、后台发送、失败恢复(官方 composer submit.ts 同款时序: + * clearSubmission → void sending → failSubmission(restore))。 + * + * 之前用 runSubmit 等 POST 落定(switchModel → switchAgent → prompt 三个 + * 串行 RTT)才清输入框,按回车后文本要在框里「粘」几百毫秒——不优雅的 + * 体感来源。现在提交瞬间清空,发送在后台跑;失败时输入框还没被新内容 + * 占用才恢复旧草稿(sendMessageNow 另有失败通知)。 + */ + const submitOptimistically = useCallback( + (submit: () => Promise | boolean | void, opts?: { onSuccess?: () => void; onFailure?: () => void }) => { + const draftSnapshot: HistoryEntry = { text, attachments: [...attachments] } + resetDraft() + void (async () => { + let ok: boolean + try { + ok = (await submit()) !== false + } catch { + ok = false } - - onSuccess?.() - return true - } finally { - setIsSubmitting(false) - } + if (ok) { + opts?.onSuccess?.() + return + } + opts?.onFailure?.() + const currentDraft = latestDraftRef.current + if (currentDraft.text.length === 0 && currentDraft.attachments.length === 0) { + restoreDraft(draftSnapshot) + } + })() }, - [isSubmitting], + [attachments, resetDraft, restoreDraft, text], ) const handleSend = useCallback(() => { - if (!canSend || isSubmitting) return + if (!canSend) return // shell mode:原样提交命令给 session.shell,保持 shell mode(类终端连续输入) if (shellMode) { @@ -591,11 +603,9 @@ function InputBoxComponent({ if (!command || !onShell) return // shell 轨道历史记账(官方 history.add 同款:发送即记账、失败移除) promptHistoryStore.add(command, [], 'shell') - void runSubmit( - () => onShell(command), - () => setText(''), - () => promptHistoryStore.remove(command, [], 'shell'), - ) + submitOptimistically(() => onShell(command), { + onFailure: () => promptHistoryStore.remove(command, [], 'shell'), + }) return } @@ -626,20 +636,21 @@ function InputBoxComponent({ // normal 轨道历史记账(官方 history.add 同款:发送即记账、失败移除) promptHistoryStore.add(text, attachments, 'normal') - void runSubmit( + submitOptimistically( () => onSend(text, attachments, { agent: agentObj?.id ?? agentRef, variant: selectedVariant, }), - () => { - // 队列编辑草稿发送成功 → 丢弃暂存(官方 confirmEdit 同款: - // 发送的内容就是编辑结果,不再恢复旧输入) - draftStashRef.current = null - resetDraft() - onClearRevert?.() + { + onSuccess: () => { + // 队列编辑草稿发送成功 → 丢弃暂存(官方 confirmEdit 同款: + // 发送的内容就是编辑结果,不再恢复旧输入) + draftStashRef.current = null + onClearRevert?.() + }, + onFailure: () => promptHistoryStore.remove(text, attachments, 'normal'), }, - () => promptHistoryStore.remove(text, attachments, 'normal'), ) } @@ -655,8 +666,7 @@ function InputBoxComponent({ .catch(() => false) .then(isCommand => { if (isCommand) { - void onCommand(trimmedText) - resetDraft() + submitCommandOptimistically(trimmedText) } else { // 不是已知命令 → 按普通消息发送 sendCurrent() @@ -670,18 +680,16 @@ function InputBoxComponent({ agents, attachments, canSend, - isSubmitting, onCommand, onClearRevert, onSend, onShell, - resetDraft, - runSubmit, + rootPath, selectedAgent, selectedVariant, shellMode, submitCommandOptimistically, - rootPath, + submitOptimistically, text, ]) @@ -1056,7 +1064,7 @@ function InputBoxComponent({ // 通用文件上传 — 根据模型能力判断是否接受 const handleFilesSelected = useCallback( async (files: File[]) => { - if (files.length === 0 || !supportsAnyFile || isSubmitting) return + if (files.length === 0 || !supportsAnyFile) return const nextAttachments: Attachment[] = [] @@ -1085,14 +1093,12 @@ function InputBoxComponent({ setAttachments(prev => [...prev, ...nextAttachments]) } }, - [supportsAnyFile, fileCaps, isSubmitting], + [supportsAnyFile, fileCaps], ) // 删除附件 const handleRemoveAttachment = useCallback( (id: string) => { - if (isSubmitting) return - const attachment = attachments.find(a => a.id === id) if (!attachment) return @@ -1106,7 +1112,7 @@ function InputBoxComponent({ setAttachments(prev => prev.filter(a => a.id !== id)) }, - [attachments, isSubmitting, text], + [attachments, text], ) // 粘贴处理 — 根据模型能力过滤可粘贴的文件类型 @@ -1280,7 +1286,7 @@ function InputBoxComponent({ const handleTauriExternalDrop = useCallback( async (paths: string[]) => { - if (paths.length === 0 || isSubmitting) return + if (paths.length === 0) return try { const droppedPaths = await getDroppedPathsInfo(paths) @@ -1310,7 +1316,7 @@ function InputBoxComponent({ console.warn('[InputBox] Failed to process Tauri dropped paths:', err) } }, - [buildDraggedFileInfo, createUploadAttachmentFromDroppedPath, externalFileDropMode, insertDraggedFiles, isSubmitting], + [buildDraggedFileInfo, createUploadAttachmentFromDroppedPath, externalFileDropMode, insertDraggedFiles], ) const handleTauriDragDropEvent = useCallback( @@ -1531,7 +1537,7 @@ function InputBoxComponent({ attachments={attachments} onRemove={handleRemoveAttachment} variant="rail" - className={isSubmitting ? 'pr-4 pointer-events-none opacity-70' : 'pr-4'} + className="pr-4" />
@@ -1598,7 +1604,6 @@ function InputBoxComponent({ fileCapabilities={fileCaps} onFilesSelected={handleFilesSelected} isStreaming={isStreaming} - isSending={isSubmitting} busyDelivery={busyDelivery} onBusyDeliveryChange={onBusyDeliveryChange} deliveryChipVisible={queueDeliveryChipVisible} From 78c9d12f46ba53d9abbb3bfea73460fa2c94ea65 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 18:16:19 +0800 Subject: [PATCH 21/91] =?UTF-8?q?feat(chat):=20shell=20=E6=A8=A1=E5=BC=8F?= =?UTF-8?q?=E7=BB=99=E3=80=8C=E7=9C=9F=E5=BF=83=E6=83=B3=E8=BE=93=E5=85=A5?= =?UTF-8?q?=20!=E3=80=8D=E7=95=99=E9=80=80=E8=B7=AF=EF=BC=8C=E5=B9=B6?= =?UTF-8?q?=E5=86=99=E8=BF=9B=E8=BE=93=E5=85=A5=E6=A1=86=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 问题:空输入框敲 ! 会进 shell 模式且 ! 被消费,想以 ! 开头写普通消息 (如「!这个很重要」)做不到——官方同样有这个问题,且没有退路。 改进(比官方宽容): - shell 模式下空文本按退格 → 退出并把被消费的 ! 还原回输入框, 光标置于末尾好继续打(esc 仍是退出并丢弃,语义不变); - 收窄触发条件:只有「空输入框敲入 !」才进 shell 模式——从 !x 删除回 ! 是编辑普通文本,不再误触发(官方 value === "!" 就触发,会来回横跳); - 输入框提示写明这两条出路:shell 占位符改为「esc 退出 · 空命令退格还原 !」, 普通占位符补上 ! 入口(@ 提及 · / 命令 · ! Shell)。 --- src/features/chat/InputBox.test.tsx | 80 +++++++++++++++++++++++++++++ src/features/chat/InputBox.tsx | 18 +++++-- src/locales/en/chat.json | 4 +- src/locales/zh-CN/chat.json | 4 +- 4 files changed, 98 insertions(+), 8 deletions(-) diff --git a/src/features/chat/InputBox.test.tsx b/src/features/chat/InputBox.test.tsx index d183243f5..c27f8e043 100644 --- a/src/features/chat/InputBox.test.tsx +++ b/src/features/chat/InputBox.test.tsx @@ -389,3 +389,83 @@ describe('InputBox slash command selection', () => { }) }) }) + +describe('InputBox shell mode', () => { + beforeEach(() => { + slashCommands = [] + messagesMock = [] + promptHistoryStore.reset() + }) + + it('enters shell mode when typing ! into an empty input', () => { + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + fireEvent.change(textarea, { target: { value: '!' } }) + + expect(textarea.hasAttribute('data-shell-mode')).toBe(true) + // `!` 被消费,不进文本 + expect(textarea.value).toBe('') + }) + + it('restores the consumed ! when exiting shell mode with backspace on empty input', async () => { + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + fireEvent.change(textarea, { target: { value: '!' } }) + expect(textarea.hasAttribute('data-shell-mode')).toBe(true) + + // 「其实想输入 !」的退路:空命令退格 → 退模式并把 ! 还回来 + fireEvent.keyDown(textarea, { key: 'Backspace' }) + + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + expect(textarea.value).toBe('!') + + // 光标在末尾,好继续打(如 !这个很重要) + await waitFor(() => { + expect(textarea.selectionStart).toBe(1) + }) + + // 继续输入就是普通文本 + fireEvent.change(textarea, { target: { value: '!这个很重要' } }) + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + expect(textarea.value).toBe('!这个很重要') + }) + + it('does not re-enter shell mode when deleting back to a lone !', () => { + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + // 经退格还原拿到字面 ! 后,继续编辑再删回 ! 不该重新进 shell 模式 + fireEvent.change(textarea, { target: { value: '!x' } }) + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + + fireEvent.change(textarea, { target: { value: '!' } }) + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + expect(textarea.value).toBe('!') + }) + + it('exits shell mode with escape and discards the input', () => { + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + fireEvent.change(textarea, { target: { value: '!' } }) + fireEvent.change(textarea, { target: { value: 'git status' } }) + expect(textarea.hasAttribute('data-shell-mode')).toBe(true) + + fireEvent.keyDown(textarea, { key: 'Escape' }) + + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + expect(textarea.value).toBe('') + }) + + it('does not enter shell mode without onShell support', () => { + render() + + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + fireEvent.change(textarea, { target: { value: '!' } }) + + expect(textarea.hasAttribute('data-shell-mode')).toBe(false) + expect(textarea.value).toBe('!') + }) +}) diff --git a/src/features/chat/InputBox.tsx b/src/features/chat/InputBox.tsx index f51895490..75a6705ae 100644 --- a/src/features/chat/InputBox.tsx +++ b/src/features/chat/InputBox.tsx @@ -723,7 +723,7 @@ function InputBoxComponent({ if (isImeComposing && (e.key === 'Enter' || e.key === 'Tab')) return - // shell mode(官方 machine.ts:203 + submit.ts:147):Enter 直接执行, + // shell mode(官方 machine.ts:232 + submit.ts:147):Enter 直接执行, // esc / 空文本退格退回普通模式 if (shellMode) { if (e.key === 'Escape') { @@ -735,6 +735,14 @@ function InputBoxComponent({ if (e.key === 'Backspace' && text.length === 0) { e.preventDefault() setShellMode(false) + // 「其实想输入 !」的退路:删掉 shell 模式,把进入时被消费的 `!` 还回来, + // 光标放到末尾好继续打(官方只退模式不还原,这里比官方宽容) + setText('!') + requestAnimationFrame(() => { + if (!textareaRef.current) return + textareaRef.current.focus() + textareaRef.current.setSelectionRange(1, 1) + }) return } if (e.key === 'Enter' && !e.shiftKey && !isImeComposing) { @@ -851,8 +859,10 @@ function InputBoxComponent({ (e: React.ChangeEvent) => { const newText = e.target.value - // `!` 进入 shell mode(官方 machine.ts:203 同款:`!` 被消费,不进文本) - if (!shellMode && newText === '!' && onShell) { + // 空输入框敲入 `!` 进入 shell mode(官方 machine.ts:109 同款:`!` 被消费,不进文本)。 + // 额外要求之前是空文本(官方是 value === "!" 就触发):从 `!x` 删除回 `!` + // 不该重新进 shell——那是编辑普通文本,不是想跑命令。 + if (!shellMode && newText === '!' && text === '' && onShell) { setShellMode(true) setText('') setMentionOpen(false) @@ -913,7 +923,7 @@ function InputBoxComponent({ } } }, - [handleHistoryChange, shellMode, onShell], + [handleHistoryChange, shellMode, onShell, text], ) const handleCompositionStart = useCallback(() => { diff --git a/src/locales/en/chat.json b/src/locales/en/chat.json index 4c4ff9273..bf8ce72ec 100644 --- a/src/locales/en/chat.json +++ b/src/locales/en/chat.json @@ -54,8 +54,8 @@ "inputBox": { "dropFilesHere": "Drop files here", "replyToAgentMobile": "Reply to Agent...", - "replyToAgent": "Reply to Agent (type @ to mention, / for commands)", - "shellPlaceholder": "Shell command (esc to exit)", + "replyToAgent": "Reply to Agent (@ to mention · / for commands · ! for shell)", + "shellPlaceholder": "Shell command (esc to exit · ⌫ on empty restores !)", "shellMode": "Shell" }, "shellMessage": { diff --git a/src/locales/zh-CN/chat.json b/src/locales/zh-CN/chat.json index dae922920..747f8c087 100644 --- a/src/locales/zh-CN/chat.json +++ b/src/locales/zh-CN/chat.json @@ -54,8 +54,8 @@ "inputBox": { "dropFilesHere": "拖放文件到此处", "replyToAgentMobile": "回复 Agent...", - "replyToAgent": "回复 Agent(输入 @ 提及,/ 执行命令)", - "shellPlaceholder": "Shell 命令(esc 退出)", + "replyToAgent": "回复 Agent(@ 提及 · / 命令 · ! Shell)", + "shellPlaceholder": "Shell 命令(esc 退出 · 空命令退格还原 !)", "shellMode": "Shell" }, "shellMessage": { From 79db1df66207332683b94d51f44c01e048d5dbeb Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 18:42:04 +0800 Subject: [PATCH 22/91] =?UTF-8?q?feat(chat):=20=E9=98=9F=E5=88=97=E6=B6=88?= =?UTF-8?q?=E6=81=AF=E5=8F=AF=E6=8A=98=E5=8F=A0=EF=BC=8C=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E6=8A=98=E5=8F=A0/=E5=B1=95=E5=BC=80=E6=9C=89=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE=E5=BC=80=E5=85=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对齐 compact(压缩消息)的折叠模式: - QueueBubbles 的标题行改为折叠开关(chevron + MessageExpandPanel 动画), 折叠时只显示「Next turn (N)」一行摘要,点击展开气泡; - 折叠状态按会话记忆(uiDisclosureState,用户手动展开/收起后记住); - 新增设置项 queueAutoCollapse(镜像 compactionAutoCollapse 的存储/备份/ 设置页开关/搜索目录),默认开(折叠),关掉则默认展开全部气泡; - ChatArea 按 sessionId 传 stateKey。 测试:既有内容/回调用例改到展开态;新增默认折叠 + 标题点击切换 + 设置关闭时默认展开三个用例(各用独立 stateKey 避开模块级缓存串扰)。 --- src/features/chat/ChatArea.tsx | 1 + src/features/chat/QueueBubbles.test.tsx | 46 ++++- src/features/chat/QueueBubbles.tsx | 173 ++++++++++-------- .../settings/components/AgentSettings.tsx | 15 ++ .../settings/settingsSearchCatalog.ts | 1 + src/hooks/useTheme.ts | 6 + src/locales/en/settings.json | 2 + src/locales/zh-CN/settings.json | 2 + src/store/themeStore.ts | 22 +++ 9 files changed, 190 insertions(+), 78 deletions(-) diff --git a/src/features/chat/ChatArea.tsx b/src/features/chat/ChatArea.tsx index 910fdb579..b0b6ea5aa 100644 --- a/src/features/chat/ChatArea.tsx +++ b/src/features/chat/ChatArea.tsx @@ -1100,6 +1100,7 @@ export const ChatArea = memo( items={queuedFollowUps} editingId={queueEditingId} mutation={queueMutation} + stateKey={sessionId ? `queue-bubbles:${sessionId}` : undefined} onSteer={onQueueSteer} onEdit={onQueueEdit} onRemove={onQueueRemove} diff --git a/src/features/chat/QueueBubbles.test.tsx b/src/features/chat/QueueBubbles.test.tsx index 61b928b7b..6feccac1c 100644 --- a/src/features/chat/QueueBubbles.test.tsx +++ b/src/features/chat/QueueBubbles.test.tsx @@ -1,6 +1,8 @@ -import { describe, it, expect, vi } from 'vitest' -import { render, screen, fireEvent } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { QueueBubbles } from './QueueBubbles' +import { setUiDisclosureState } from '../../utils/uiDisclosureState' +import { themeStore } from '../../store/themeStore' import type { QueuedUserPrompt } from '../../store/inboxStore' function makeItem(id: string, text: string): QueuedUserPrompt { @@ -12,14 +14,22 @@ function makeItem(id: string, text: string): QueuedUserPrompt { } as unknown as QueuedUserPrompt } +/** 内容用例共用的展开态 key(折叠状态是模块级缓存,显式归位避免用例间串扰) */ +const EXPANDED_KEY = 'queue-bubbles:test-expanded' + describe('QueueBubbles(下轮队列虚线气泡)', () => { + beforeEach(() => { + themeStore.setQueueAutoCollapse(true) + setUiDisclosureState(EXPANDED_KEY, true) + }) + it('renders nothing when the queue is empty', () => { const { container } = render() expect(container.querySelector('[data-message-queue]')).not.toBeInTheDocument() }) it('renders one dashed bubble per queued item with the group label', () => { - render() + render() expect(screen.getByText('排队这条')).toBeInTheDocument() expect(screen.getByText('再排一条')).toBeInTheDocument() expect(document.querySelectorAll('[data-message-queue="queued"]')).toHaveLength(1) @@ -29,7 +39,7 @@ describe('QueueBubbles(下轮队列虚线气泡)', () => { it('prefers metadata.displayText over payload.text(官方 queuedPromptText)', () => { const item = makeItem('q1', 'raw text') ;(item.payload as Record).metadata = { displayText: '展示文本' } - render() + render() expect(screen.getByText('展示文本')).toBeInTheDocument() expect(screen.queryByText('raw text')).not.toBeInTheDocument() }) @@ -39,7 +49,7 @@ describe('QueueBubbles(下轮队列虚线气泡)', () => { const onEdit = vi.fn() const onRemove = vi.fn() const item = makeItem('q1', '排队这条') - render() + render() fireEvent.click(screen.getByTitle('Inject into current turn')) expect(onSteer).toHaveBeenCalledWith(item) fireEvent.click(screen.getByTitle('Retract to edit')) @@ -47,4 +57,30 @@ describe('QueueBubbles(下轮队列虚线气泡)', () => { fireEvent.click(screen.getByTitle('Remove from queue')) expect(onRemove).toHaveBeenCalledWith(item) }) + + it('collapses bubbles by default and toggles on header click(compact 同款)', async () => { + render() + + // 默认折叠:只有标题行,气泡不渲染 + expect(screen.queryByText('排队这条')).not.toBeInTheDocument() + const header = screen.getByRole('button', { name: 'Next turn (1)' }) + expect(header).toHaveAttribute('aria-expanded', 'false') + + // 点击标题展开 + fireEvent.click(header) + expect(screen.getByText('排队这条')).toBeInTheDocument() + expect(header).toHaveAttribute('aria-expanded', 'true') + + // 再点收起(卸载有延迟,等它结束) + fireEvent.click(header) + await waitFor(() => { + expect(screen.queryByText('排队这条')).not.toBeInTheDocument() + }) + }) + + it('expands by default when the collapse setting is off(默认展开开关)', () => { + themeStore.setQueueAutoCollapse(false) + render() + expect(screen.getByText('排队这条')).toBeInTheDocument() + }) }) diff --git a/src/features/chat/QueueBubbles.tsx b/src/features/chat/QueueBubbles.tsx index 203890da2..f27f153c9 100644 --- a/src/features/chat/QueueBubbles.tsx +++ b/src/features/chat/QueueBubbles.tsx @@ -17,10 +17,14 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' -import { ArrowUpIcon, CloseIcon, GripVerticalIcon, PencilIcon, TrashIcon } from '../../components/Icons' +import { ArrowUpIcon, ChevronDownIcon, CloseIcon, GripVerticalIcon, PencilIcon, TrashIcon } from '../../components/Icons' import { CopyButton } from '../../components/ui' import { queuedPromptText, type QueuedUserPrompt } from '../../store/inboxStore' import { projectQueueItems, type QueueMutation } from './queueProjection' +import { useDisclosureScrollLock } from '../../hooks' +import { useTheme } from '../../hooks/useTheme' +import { useUiDisclosureState } from '../../utils/uiDisclosureState' +import { chevronClass, MessageExpandPanel, useMessageExpandRender } from '../message/messageExpand' interface QueueBubblesProps { /** 下轮队列条目(delivery='queue',等当前回合结束后由服务端投递) */ @@ -37,6 +41,8 @@ interface QueueBubblesProps { editingId?: string /** 队列 mutation 投影(编辑/重排期间显示期望形态,官方 rows() 同款) */ mutation?: QueueMutation | null + /** 折叠状态的记忆 key(按会话区分;缺省全局共享一个) */ + stateKey?: string } const ACTION_BTN_CLASS = @@ -74,6 +80,7 @@ export const QueueBubbles = memo(function QueueBubbles({ onReorder, editingId, mutation, + stateKey, }: QueueBubblesProps) { const { t } = useTranslation('chat') const listRef = useRef(null) @@ -81,6 +88,13 @@ export const QueueBubbles = memo(function QueueBubbles({ const dragRef = useRef<{ id: string; startY: number; active: boolean } | null>(null) const [dragTarget, setDragTarget] = useState(null) + // 折叠(compact 同款):默认折叠/展开由设置项 queueAutoCollapse 决定, + // 用户手动展开/收起后按 key 记住(uiDisclosureState touched 语义) + const { queueAutoCollapse } = useTheme() + const [expanded, setExpanded] = useUiDisclosureState(stateKey ?? 'queue-bubbles', !queueAutoCollapse) + const shouldRenderBody = useMessageExpandRender(expanded) + const { withScrollLock } = useDisclosureScrollLock() + // mutation 投影(官方 rows() 同款):编辑/重排期间显示期望形态, // 服务端 admit/cancel 事件落地时不抖(数量/位置/文本都稳) const rows = useMemo(() => projectQueueItems(items, mutation ?? null), [items, mutation]) @@ -145,82 +159,95 @@ export const QueueBubbles = memo(function QueueBubbles({ const label = t('queue.queuedLabel', { count: rows.length }) return (
-
+ {/* 标题行兼折叠开关(compact 同款 chevron):点击展开/收起队列气泡 */} +
-
- {rows.map(({ item }, index) => { - const text = queuedPromptText(item) - const isEditing = item.id === editingId - const showInsertion = dragTarget !== null && dragTarget === index && dragRef.current?.active - return ( -
- {/* 插入指示线:拖拽指针越过该条目中线时显示在其上方 */} - {showInsertion &&
) }) diff --git a/src/features/settings/components/AgentSettings.tsx b/src/features/settings/components/AgentSettings.tsx index dc1bac115..55f0b97d7 100644 --- a/src/features/settings/components/AgentSettings.tsx +++ b/src/features/settings/components/AgentSettings.tsx @@ -17,6 +17,7 @@ export function AgentSettings() { const [immersiveMode, setImmersiveMode] = useState(themeStore.immersiveMode) const [compactInlinePermission, setCompactInlinePermission] = useState(themeStore.compactInlinePermission) const [compactionAutoCollapse, setCompactionAutoCollapse] = useState(themeStore.compactionAutoCollapse) + const [queueAutoCollapse, setQueueAutoCollapse] = useState(themeStore.queueAutoCollapse) const [processCollapseEnabled, setProcessCollapseEnabled] = useState(themeStore.processCollapseEnabled) const handleAlwaysAllowModeChange = (mode: AlwaysAllowMode) => { @@ -90,6 +91,12 @@ export function AgentSettings() { themeStore.setCompactionAutoCollapse(next) } + const toggleQueueAutoCollapse = () => { + const next = !queueAutoCollapse + setQueueAutoCollapse(next) + themeStore.setQueueAutoCollapse(next) + } + return (
@@ -180,6 +187,14 @@ export function AgentSettings() { + + + +
{ + themeStore.setQueueAutoCollapse(enabled) + }, []), + // 毛玻璃效果 glassEffect: state.glassEffect, setGlassEffect: useCallback((enabled: boolean) => { diff --git a/src/locales/en/settings.json b/src/locales/en/settings.json index 8567bd899..424eb6589 100644 --- a/src/locales/en/settings.json +++ b/src/locales/en/settings.json @@ -204,6 +204,8 @@ "compactInlinePermissionDesc": "When the tool already shows content, only display action buttons for permissions to avoid duplication", "compactionAutoCollapse": "Auto-collapse Compaction", "compactionAutoCollapseDesc": "Automatically collapse the compaction summary once it finishes streaming; turn off to keep it expanded", + "queueAutoCollapse": "Collapse queued messages", + "queueAutoCollapseDesc": "Collapse queued messages into a one-line summary that expands on click; turn off to always show all bubbles", "toolCardStyle": "Tool Output Style", "toolCardStyleDesc": "Choose how tool call results are displayed", "toolCardClassic": "Classic", diff --git a/src/locales/zh-CN/settings.json b/src/locales/zh-CN/settings.json index 1da122f4c..ea61937c1 100644 --- a/src/locales/zh-CN/settings.json +++ b/src/locales/zh-CN/settings.json @@ -204,6 +204,8 @@ "compactInlinePermissionDesc": "工具已有内容时,内嵌权限只显示操作按钮,避免重复", "compactionAutoCollapse": "自动收起压缩结果", "compactionAutoCollapseDesc": "上下文压缩的摘要流式输出结束后自动收起,关闭则保持展开", + "queueAutoCollapse": "默认折叠队列消息", + "queueAutoCollapseDesc": "排队中的消息折叠成一行摘要,点击标题展开;关闭则默认展开全部气泡", "toolCardStyle": "工具输出风格", "toolCardStyleDesc": "选择工具调用结果的展示方式", "toolCardClassic": "经典", diff --git a/src/store/themeStore.ts b/src/store/themeStore.ts index 5a339f11d..102d624eb 100644 --- a/src/store/themeStore.ts +++ b/src/store/themeStore.ts @@ -160,6 +160,7 @@ const DEFAULT_TOOL_CARD_STYLE: ToolCardStyle = 'compact' const DEFAULT_IMMERSIVE_MODE = true const DEFAULT_COMPACT_INLINE_PERMISSION = true const DEFAULT_COMPACTION_AUTO_COLLAPSE = true +const DEFAULT_QUEUE_AUTO_COLLAPSE = true const DEFAULT_GLASS_EFFECT = true const DEFAULT_QUEUE_FOLLOWUP_MESSAGES = false /** 输入框 busy 投递 chip(插队/排队)默认显示 */ @@ -219,6 +220,8 @@ export interface ThemeState { compactInlinePermission: boolean /** 压缩结果流式输出结束后自动收起(可在设置中关闭) */ compactionAutoCollapse: boolean + /** 队列消息默认折叠成一行摘要(可在设置中关闭,关闭则默认展开) */ + queueAutoCollapse: boolean /** 毛玻璃效果开关(backdrop-filter blur) */ glassEffect: boolean /** 忙碌时后续消息是否进入队列 */ @@ -272,6 +275,7 @@ const STORAGE_KEY_TOOL_CARD_STYLE = 'tool-card-style' const STORAGE_KEY_IMMERSIVE_MODE = 'immersive-mode' const STORAGE_KEY_COMPACT_INLINE_PERMISSION = 'compact-inline-permission' const STORAGE_KEY_COMPACTION_AUTO_COLLAPSE = 'compaction-auto-collapse' +const STORAGE_KEY_QUEUE_AUTO_COLLAPSE = 'queue-auto-collapse' const STORAGE_KEY_GLASS_EFFECT = 'glass-effect' const STORAGE_KEY_QUEUE_FOLLOWUP_MESSAGES = 'queue-followup-messages' const STORAGE_KEY_QUEUE_DELIVERY_CHIP_VISIBLE = 'queue-delivery-chip-visible' @@ -399,6 +403,10 @@ class ThemeStore { const compactionAutoCollapse = savedCompactionAutoCollapse === null ? DEFAULT_COMPACTION_AUTO_COLLAPSE : savedCompactionAutoCollapse === 'true' + const savedQueueAutoCollapse = localStorage.getItem(STORAGE_KEY_QUEUE_AUTO_COLLAPSE) + const queueAutoCollapse = + savedQueueAutoCollapse === null ? DEFAULT_QUEUE_AUTO_COLLAPSE : savedQueueAutoCollapse === 'true' + const savedGlassEffect = localStorage.getItem(STORAGE_KEY_GLASS_EFFECT) const glassEffect = savedGlassEffect === null ? DEFAULT_GLASS_EFFECT : savedGlassEffect === 'true' @@ -479,6 +487,7 @@ class ThemeStore { immersiveMode, compactInlinePermission, compactionAutoCollapse, + queueAutoCollapse, glassEffect, queueFollowupMessages, queueDeliveryChipVisible, @@ -563,6 +572,9 @@ class ThemeStore { get compactionAutoCollapse() { return this.state.compactionAutoCollapse } + get queueAutoCollapse() { + return this.state.queueAutoCollapse + } get glassEffect() { return this.state.glassEffect } @@ -889,6 +901,13 @@ class ThemeStore { this.emit() } + setQueueAutoCollapse(enabled: boolean) { + if (this.state.queueAutoCollapse === enabled) return + this.state = { ...this.state, queueAutoCollapse: enabled } + localStorage.setItem(STORAGE_KEY_QUEUE_AUTO_COLLAPSE, String(enabled)) + this.emit() + } + setGlassEffect(enabled: boolean) { if (this.state.glassEffect === enabled) return this.state = { ...this.state, glassEffect: enabled } @@ -1213,6 +1232,8 @@ function normalizeThemeBackup(raw: unknown): ThemeBackup { typeof parsed?.compactionAutoCollapse === 'boolean' ? parsed.compactionAutoCollapse : DEFAULT_COMPACTION_AUTO_COLLAPSE, + queueAutoCollapse: + typeof parsed?.queueAutoCollapse === 'boolean' ? parsed.queueAutoCollapse : DEFAULT_QUEUE_AUTO_COLLAPSE, glassEffect: typeof parsed?.glassEffect === 'boolean' ? parsed.glassEffect : DEFAULT_GLASS_EFFECT, queueFollowupMessages: typeof parsed?.queueFollowupMessages === 'boolean' @@ -1292,6 +1313,7 @@ export function importThemeBackup(raw: unknown): void { localStorage.setItem(STORAGE_KEY_IMMERSIVE_MODE, String(backup.immersiveMode)) localStorage.setItem(STORAGE_KEY_COMPACT_INLINE_PERMISSION, String(backup.compactInlinePermission)) localStorage.setItem(STORAGE_KEY_COMPACTION_AUTO_COLLAPSE, String(backup.compactionAutoCollapse)) + localStorage.setItem(STORAGE_KEY_QUEUE_AUTO_COLLAPSE, String(backup.queueAutoCollapse)) localStorage.setItem(STORAGE_KEY_GLASS_EFFECT, String(backup.glassEffect)) localStorage.setItem(STORAGE_KEY_QUEUE_FOLLOWUP_MESSAGES, String(backup.queueFollowupMessages)) localStorage.setItem(STORAGE_KEY_QUEUE_DELIVERY_CHIP_VISIBLE, String(backup.queueDeliveryChipVisible)) From 622c0e32ace53b6d2ac5aa55aff0628b070ea7c9 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 19:27:36 +0800 Subject: [PATCH 23/91] =?UTF-8?q?feat(chat):=20=E5=AF=B9=E8=AF=9D=E5=88=97?= =?UTF-8?q?/=E8=BE=93=E5=85=A5=E6=A1=86=E5=B7=A6=E7=BC=98=E6=8B=96?= =?UTF-8?q?=E6=8B=BD=E8=B0=83=E5=AE=BD=EF=BC=88=E4=B8=A4=E4=B8=AA=E7=8B=AC?= =?UTF-8?q?=E7=AB=8B=E6=8A=8A=E6=89=8B=EF=BC=8Cdsh=20=E6=A0=B7=E5=BC=8F?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 参考 dsh ConversationWidthControls 实现,按需求收窄: - 样式直接抄 dsh:10px 热区条带贴在内容列左缘外 24px 的 gutter, 辉光是跟随指针 Y 的 2px 短条(16px 实心核、两侧 28px 渐隐), 平时 opacity 0 完全隐藏,hover/拖拽才显示; - 只有左缘把手(dsh 左右各一);列居中,左缘外移 dx → 宽度变化 2|dx|; - 对话列和输入框两个独立把手,各调各的宽度、各存各的偏好 (themeStore.chatContentWidth / chatInputWidth); - 把手只在桌面端单 panel / pane 全屏时挂载(分屏不给拖), 但调出来的宽度对所有场景生效,分屏小 panel 也按它渲染 (装不下时 CSS min(100%,…) 收到 100%); - 宽度走 pane 根上的 CSS 变量,ChatArea 消息列/InputBox/权限·问题· websearch dock 的 max-width 全部引用,拖拽期间直接写变量零 React 渲染; - 恢复默认 = 设置里切换宽屏模式(开或关都重置两个宽度)。 测试:themeStore 持久化/独立/双重置 5 例;把手拖拽链路(2|dx| 换算、 clamp、空拖不提交、右键不启动、双把手互不干扰)5 例。 --- src/features/chat/ChatArea.tsx | 6 +- src/features/chat/ChatPane.tsx | 99 ++++++++++++- src/features/chat/ChatWidthHandle.test.tsx | 153 +++++++++++++++++++++ src/features/chat/ChatWidthHandle.tsx | 112 +++++++++++++++ src/features/chat/InputBox.tsx | 2 +- src/features/chat/PermissionDialog.tsx | 2 +- src/features/chat/QuestionDialog.tsx | 2 +- src/hooks/useTheme.ts | 12 ++ src/index.css | 38 +++++ src/locales/en/chat.json | 2 + src/locales/zh-CN/chat.json | 2 + src/store/themeStore.test.ts | 74 ++++++++++ src/store/themeStore.ts | 53 ++++++- 13 files changed, 548 insertions(+), 9 deletions(-) create mode 100644 src/features/chat/ChatWidthHandle.test.tsx create mode 100644 src/features/chat/ChatWidthHandle.tsx create mode 100644 src/store/themeStore.test.ts diff --git a/src/features/chat/ChatArea.tsx b/src/features/chat/ChatArea.tsx index b0b6ea5aa..5a14e864b 100644 --- a/src/features/chat/ChatArea.tsx +++ b/src/features/chat/ChatArea.tsx @@ -374,11 +374,13 @@ export const ChatArea = memo( ref, ) => { const { t } = useTranslation('chat') - const { isWideMode, processCollapseEnabled } = useTheme() + const { processCollapseEnabled } = useTheme() const { presentation } = useChatViewport() const atBottomThreshold = presentation.isCompact ? 150 : AT_BOTTOM_THRESHOLD_PX const paddingClass = presentation.isCompact ? 'px-3' : 'px-5' - const maxWidthClass = isWideMode ? 'max-w-[95%] xl:max-w-6xl' : 'max-w-2xl' + // 消息列宽统一引用 pane 根上的 CSS 变量(ChatPane 按 窄672/宽95%·6xl/拖拽自定义 解析), + // 变量缺席时回落 42rem(=原 max-w-2xl)。字符串恒定,VirtualRow memo 比较不受影响 + const maxWidthClass = 'max-w-[min(100%,var(--oc-chat-column-width,42rem))]' // ── 派生数据 ── const entries = useMemo( diff --git a/src/features/chat/ChatPane.tsx b/src/features/chat/ChatPane.tsx index 905e04920..7a8f39146 100644 --- a/src/features/chat/ChatPane.tsx +++ b/src/features/chat/ChatPane.tsx @@ -6,7 +6,7 @@ * compact viewport wrapper. */ -import { memo, useRef, useEffect, useState, useCallback, useMemo, useDeferredValue, useSyncExternalStore } from 'react' +import { memo, useRef, useEffect, useState, useCallback, useMemo, useDeferredValue, useSyncExternalStore, type CSSProperties } from 'react' import { Trans, useTranslation } from 'react-i18next' import { ChatArea, Header, InputBox, PermissionDialog, QuestionDialog, type ChatAreaHandle } from '.' @@ -15,6 +15,13 @@ import { type ModelSelectorHandle } from './ModelSelector' import { OutlineIndex } from '../../components/OutlineIndex' import { PaneHeader } from './PaneHeader' import { PaneDropOverlay, resolveDropZone, type DropZone, type PaneDropOverlayHandle } from './PaneDropOverlay' +import { + ChatWidthHandle, + CHAT_COLUMN_WIDTH_VAR, + CHAT_INPUT_WIDTH_VAR, + MIN_CHAT_CONTENT_WIDTH, + DEFAULT_INPUT_WIDTH, +} from './ChatWidthHandle' import { useFolderProjectDrop } from './useFolderProjectDrop' import { FolderProjectDropOverlay } from './FolderProjectDropOverlay' import { useChatSession, useModels, useModelSelection } from '../../hooks' @@ -826,7 +833,62 @@ export const ChatPane = memo(function ChatPane({ const [permissionCollapsed, setPermissionCollapsed] = useState(false) const [questionCollapsed, setQuestionCollapsed] = useState(false) - const { inlineToolRequests, outlineCurrentHighlight } = useTheme() + const { + inlineToolRequests, + outlineCurrentHighlight, + isWideMode, + chatContentWidth, + setChatContentWidth, + chatInputWidth, + setChatInputWidth, + } = useTheme() + + // ── 对话列/输入框宽度(左缘拖拽调宽,两个独立把手)── + // 样式与交互抄 dsh ConversationWidthControls,按需求收窄成左缘单把手 × 2: + // 把手(调整入口)只在桌面端单 panel / pane 全屏时挂载(分屏空间太碎不给拖), + // 但调出来的自定义宽度对所有场景生效,分屏小 panel 也按它渲染 + // (pane 装不下时由 CSS 的 min(100%,…) 收到 100%)。 + // 两个宽度走 pane 根上的两个 CSS 变量,ChatArea 消息列、InputBox、 + // 各级 dock 的 max-width 都引用它们,拖拽期间直接写变量零 React 渲染。 + // 恢复默认 = 设置里切换宽屏模式(开或关都会清掉两个自定义宽度,themeStore.setWideMode)。 + const isDesktopSurface = outerViewport ? !outerViewport.presentation.isCompact : false + const canAdjustChatWidth = isDesktopSurface && (displayMode === 'single' || isPaneFullscreen) + const [paneWidth, setPaneWidth] = useState(0) + useEffect(() => { + const el = paneRootRef.current + if (!el) return + const ro = new ResizeObserver(entries => { + const width = entries[0]?.contentRect.width + if (width) setPaneWidth(Math.round(width)) + }) + ro.observe(el) + return () => ro.disconnect() + }, []) + const outerViewportWidth = outerViewport?.layout.viewportWidth ?? 0 + // 默认宽度对齐原 Tailwind 类:窄 max-w-2xl(672);宽 max-w-[95%] xl:max-w-6xl + // (xl 断点看视口宽而非 pane 宽,≥1280 时才收 72rem=1152 的上限) + const defaultChatColumnWidth = isWideMode + ? paneWidth > 0 + ? outerViewportWidth >= 1280 + ? Math.min(paneWidth * 0.95, 1152) + : paneWidth * 0.95 + : 1152 + : 672 + const customChatColumnWidth = chatContentWidth + const customChatInputWidth = chatInputWidth + // 两侧各留 48px gutter:把手条带贴在内容列外 24px、宽 10px,拖拽到最宽时把手仍不贴边。 + // 只在可调模式 clamp——分屏等不可调场景保持原行为(CSS 的 min(100%,…) 自然兜住溢出) + const maxChatColumnWidth = + canAdjustChatWidth && paneWidth > 0 ? Math.max(MIN_CHAT_CONTENT_WIDTH, paneWidth - 96) : Number.MAX_SAFE_INTEGER + const chatColumnWidth = Math.min( + Math.max(customChatColumnWidth ?? defaultChatColumnWidth, MIN_CHAT_CONTENT_WIDTH), + maxChatColumnWidth, + ) + // 输入框宽度独立调整;默认固定 3xl(768) + const resolvedChatInputWidth = Math.min( + Math.max(customChatInputWidth ?? DEFAULT_INPUT_WIDTH, MIN_CHAT_CONTENT_WIDTH), + maxChatColumnWidth, + ) // inline 模式下未被任何工具卡片认领的 family 请求仍走底部会话级弹窗—— // 典型场景:刷新后运行中的子代理要权限(progress 不落库,metadata.sessionID @@ -1097,6 +1159,19 @@ export const ChatPane = memo(function ChatPane({ : undefined } /> + {/* 输入框左缘拖拽把手(与对话列把手独立,各调各的宽度) */} + {canAdjustChatWidth && paneWidth > 0 && ( + + )}
-
+
)} {chatContent} + {canAdjustChatWidth && paneWidth > 0 && ( + + )}
diff --git a/src/features/chat/ChatWidthHandle.test.tsx b/src/features/chat/ChatWidthHandle.test.tsx new file mode 100644 index 000000000..8cf81de3c --- /dev/null +++ b/src/features/chat/ChatWidthHandle.test.tsx @@ -0,0 +1,153 @@ +import { describe, expect, it, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import { useRef } from 'react' +import { + ChatWidthHandle, + CHAT_COLUMN_WIDTH_VAR, + CHAT_INPUT_WIDTH_VAR, + MIN_CHAT_CONTENT_WIDTH, +} from './ChatWidthHandle' + +function Harness({ + onCommit, + width = 672, + maxWidth = 1000, + cssVar = CHAT_COLUMN_WIDTH_VAR, +}: { + onCommit: (w: number) => void + width?: number + maxWidth?: number + cssVar?: string +}) { + const rootRef = useRef(null) + return ( +
+ +
+ ) +} + +// jsdom 没有 PointerEvent 构造器;React 的根监听按事件类型名分发, +// 用 MouseEvent 造 'pointerdown/move/up' 一样能走通整条链路 +function pointer(type: string, init: MouseEventInit = {}) { + return new MouseEvent(type, { bubbles: true, cancelable: true, ...init }) +} + +describe('ChatWidthHandle(左缘拖拽调宽)', () => { + it('拖拽左缘外移 → 宽度按 2|dx| 变大,写 CSS 变量,松手提交', () => { + const onCommit = vi.fn() + render() + const root = screen.getByTestId('root') + const handle = screen.getByRole('separator') + + handle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500, clientY: 100 })) + // 向左拖 50px → 宽度 672 + 100 = 772 + window.dispatchEvent(pointer('pointermove', { clientX: 450, clientY: 120 })) + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe('772px') + expect(onCommit).not.toHaveBeenCalled() + + window.dispatchEvent(pointer('pointerup')) + expect(onCommit).toHaveBeenCalledWith(772) + }) + + it('向右拖变窄,并分别 clamp 到下限 MIN 和上限 maxWidth', () => { + const onCommit = vi.fn() + render() + const root = screen.getByTestId('root') + const handle = screen.getByRole('separator') + + // 向右拖 400px → 672 - 800 = -128 → clamp 到 MIN + handle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500 })) + window.dispatchEvent(pointer('pointermove', { clientX: 900 })) + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe(`${MIN_CHAT_CONTENT_WIDTH}px`) + window.dispatchEvent(pointer('pointerup')) + expect(onCommit).toHaveBeenCalledWith(MIN_CHAT_CONTENT_WIDTH) + + // 向左拖 1000px → 672 + 2000 = 2672 → clamp 到 maxWidth 1000 + handle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500 })) + window.dispatchEvent(pointer('pointermove', { clientX: -500 })) + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe('1000px') + window.dispatchEvent(pointer('pointerup')) + expect(onCommit).toHaveBeenCalledTimes(2) + expect(onCommit).toHaveBeenLastCalledWith(1000) + }) + + it('只点不拖(宽度没变化)不提交', () => { + const onCommit = vi.fn() + render() + const handle = screen.getByRole('separator') + + handle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500 })) + window.dispatchEvent(pointer('pointerup')) + expect(onCommit).not.toHaveBeenCalled() + }) + + it('右键按下不启动拖拽', () => { + const onCommit = vi.fn() + render() + const root = screen.getByTestId('root') + const handle = screen.getByRole('separator') + + handle.dispatchEvent(pointer('pointerdown', { button: 2, clientX: 500 })) + window.dispatchEvent(pointer('pointermove', { clientX: 400 })) + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe('') + expect(onCommit).not.toHaveBeenCalled() + }) + + it('两个把手各写各的变量(对话列 / 输入框独立调整)', () => { + const onCommitChat = vi.fn() + const onCommitInput = vi.fn() + + function TwoHandles() { + const rootRef = useRef(null) + return ( +
+ + +
+ ) + } + render() + const root = screen.getByTestId('root') + const [chatHandle, inputHandle] = screen.getAllByRole('separator') + + // 拖输入框把手:只写输入框变量、只提交输入框宽度 + inputHandle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500 })) + window.dispatchEvent(pointer('pointermove', { clientX: 450 })) + expect(root.style.getPropertyValue(CHAT_INPUT_WIDTH_VAR)).toBe('868px') + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe('') + window.dispatchEvent(pointer('pointerup')) + expect(onCommitInput).toHaveBeenCalledWith(868) + expect(onCommitChat).not.toHaveBeenCalled() + + // 拖对话列把手:只写对话列变量 + chatHandle.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 500 })) + window.dispatchEvent(pointer('pointermove', { clientX: 520 })) + expect(root.style.getPropertyValue(CHAT_COLUMN_WIDTH_VAR)).toBe('632px') + expect(root.style.getPropertyValue(CHAT_INPUT_WIDTH_VAR)).toBe('868px') + window.dispatchEvent(pointer('pointerup')) + expect(onCommitChat).toHaveBeenCalledWith(632) + expect(onCommitInput).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/features/chat/ChatWidthHandle.tsx b/src/features/chat/ChatWidthHandle.tsx new file mode 100644 index 000000000..5026e5930 --- /dev/null +++ b/src/features/chat/ChatWidthHandle.tsx @@ -0,0 +1,112 @@ +// ============================================ +// ChatWidthHandle — 对话列 / 输入框左缘拖拽调宽把手 +// +// 样式与交互直接抄 dsh ConversationWidthControls: +// - 10px 热区条带贴在内容列左缘外 24px 的 gutter(right: calc(50% + 宽/2 + 24px)) +// - 辉光是 2px 短条,跟随指针 Y(16px 实心核、两侧各 28px 渐隐),不是整条竖线 +// - 平时 opacity 0 完全隐藏,hover / 拖拽中才显示 +// 与 dsh 的差异(按需求收窄): +// - 只有左缘把手(dsh 左右各一);列居中,左缘外移 dx → 宽度变化 2|dx| +// - 对话列和输入框是两个独立把手,各写各的 CSS 变量、各存各的偏好 +// - 只在桌面端单 panel / pane 全屏时由 ChatPane 挂载(分屏不调) +// - 拖拽期间直接写 pane 根上的 CSS 变量,零 React 渲染;松手才 onCommit 持久化 +// - 恢复默认 = 设置里切换宽屏模式(开或关都会清掉两个自定义宽度) +// ============================================ + +import { useEffect, useRef, useState } from 'react' + +/** pane 根上的 CSS 变量:对话列宽 / 输入框宽(ChatArea、InputBox 的 max-width 都引用它们) */ +export const CHAT_COLUMN_WIDTH_VAR = '--oc-chat-column-width' +export const CHAT_INPUT_WIDTH_VAR = '--oc-chat-input-width' +/** 把手元素上的变量:辉光跟随的指针 Y(百分比),样式在 index.css */ +const POINTER_Y_VAR = '--oc-width-handle-pointer-y' +/** 拖拽允许的最小宽度(px,对话列和输入框共用) */ +export const MIN_CHAT_CONTENT_WIDTH = 480 +/** 输入框默认宽度(px),未自定义时 = max-w-3xl */ +export const DEFAULT_INPUT_WIDTH = 768 + +export interface ChatWidthHandleProps { + /** pane 根元素:拖拽期间直接写 CSS 变量的目标 */ + rootRef: React.RefObject + /** 当前生效的宽度(已解析默认值/自定义值并 clamp) */ + width: number + /** 允许的最大宽度(pane 宽减去两侧 gutter) */ + maxWidth: number + /** 松手提交最终宽度(持久化) */ + onCommit: (width: number) => void + /** 拖拽期间写哪个 CSS 变量(对话列 / 输入框各传各的) */ + cssVar: string + /** 悬浮提示 */ + title: string + /** 纵向范围(对话列 top-10 bottom-0 避开头部;输入框 inset-y-0) */ + className?: string + /** 定位(right: calc(50% + var(宽)/2 + 24px),由调用方按目标宽度变量给出) */ + style?: React.CSSProperties +} + +export function ChatWidthHandle({ rootRef, width, maxWidth, onCommit, cssVar, title, className, style }: ChatWidthHandleProps) { + const [dragging, setDragging] = useState(false) + const stripRef = useRef(null) + const cleanupRef = useRef<(() => void) | null>(null) + + // 拖拽中途组件卸载(切会话/分屏)时摘掉全局监听 + useEffect(() => () => cleanupRef.current?.(), []) + + // 辉光跟随指针 Y(dsh 的 --dsh-width-handle-pointer-y 同款):百分比写在自己身上 + const publishPointerY = (clientY: number) => { + const el = stripRef.current + if (!el) return + const rect = el.getBoundingClientRect() + if (rect.height <= 0) return + const pct = Math.min(100, Math.max(0, ((clientY - rect.top) / rect.height) * 100)) + el.style.setProperty(POINTER_Y_VAR, `${pct}%`) + } + + const onPointerDown = (event: React.PointerEvent) => { + if (event.button !== 0) return + event.preventDefault() + const root = rootRef.current + if (!root) return + const startX = event.clientX + const base = width + let last = base + setDragging(true) + publishPointerY(event.clientY) + + const onMove = (ev: PointerEvent) => { + // 列居中:左缘左移 dx(负值)→ 左右各让出 |dx| → 宽度 +2|dx| + const dx = ev.clientX - startX + last = Math.min(Math.max(base - dx * 2, MIN_CHAT_CONTENT_WIDTH), maxWidth) + root.style.setProperty(cssVar, `${last}px`) + publishPointerY(ev.clientY) + } + const onUp = () => { + window.removeEventListener('pointermove', onMove) + window.removeEventListener('pointerup', onUp) + window.removeEventListener('pointercancel', onUp) + cleanupRef.current = null + setDragging(false) + const finalWidth = Math.round(last) + if (finalWidth !== Math.round(base)) onCommit(finalWidth) + } + cleanupRef.current = onUp + window.addEventListener('pointermove', onMove) + window.addEventListener('pointerup', onUp) + window.addEventListener('pointercancel', onUp) + } + + return ( +
publishPointerY(e.clientY)} + className={`chat-width-handle ${className ?? ''}`} + style={style} + /> + ) +} diff --git a/src/features/chat/InputBox.tsx b/src/features/chat/InputBox.tsx index 75a6705ae..4fe72ec6f 100644 --- a/src/features/chat/InputBox.tsx +++ b/src/features/chat/InputBox.tsx @@ -1415,7 +1415,7 @@ function InputBoxComponent({ return (
{ + themeStore.setChatContentWidth(width) + }, []), + + // 输入框自定义宽度(px,左缘拖拽设置;null = 默认 3xl=768) + chatInputWidth: state.chatInputWidth, + setChatInputWidth: useCallback((width: number | null) => { + themeStore.setChatInputWidth(width) + }, []), + // Diff 行标记风格 diffStyle: state.diffStyle, setDiffStyle, diff --git a/src/index.css b/src/index.css index 125e310b9..73c0622eb 100644 --- a/src/index.css +++ b/src/index.css @@ -1258,3 +1258,41 @@ body { transition: none; } } + +/* ── 对话列/输入框宽度拖拽把手(样式抄 dsh ConversationWidthControls)── + 10px 热区条带贴在内容列左缘外 24px 的 gutter;辉光是 2px 短条, + 跟随指针 Y(16px 实心核、两侧各 28px 渐隐),不是整条竖线; + 平时 opacity 0 完全隐藏,hover / 拖拽中才显示 */ +.chat-width-handle { + position: absolute; + width: 10px; + cursor: col-resize; + touch-action: none; + user-select: none; + z-index: 30; +} + +.chat-width-handle::after { + content: ''; + position: absolute; + top: 0; + bottom: 0; + right: 4px; + width: 2px; + border-radius: 2px; + background: linear-gradient( + to bottom, + transparent calc(var(--oc-width-handle-pointer-y, 50%) - 36px), + hsl(var(--border-300)) calc(var(--oc-width-handle-pointer-y, 50%) - 8px), + hsl(var(--border-300)) calc(var(--oc-width-handle-pointer-y, 50%) + 8px), + transparent calc(var(--oc-width-handle-pointer-y, 50%) + 36px) + ); + opacity: 0; + transition: opacity 120ms ease; + pointer-events: none; +} + +.chat-width-handle:hover::after, +.chat-width-handle[data-dragging]::after { + opacity: 1; +} diff --git a/src/locales/en/chat.json b/src/locales/en/chat.json index bf8ce72ec..c4a978048 100644 --- a/src/locales/en/chat.json +++ b/src/locales/en/chat.json @@ -131,6 +131,8 @@ "editCancel": "Cancel edit", "dragReorder": "Drag to reorder" }, + "widthDragHint": "Drag to adjust chat width (toggle widescreen mode to reset)", + "inputWidthDragHint": "Drag to adjust input width (toggle widescreen mode to reset)", "permissionDialog": { "permission": "Permission: {{permission}}", "moreCount": "+{{count}} more", diff --git a/src/locales/zh-CN/chat.json b/src/locales/zh-CN/chat.json index 747f8c087..a62d69aff 100644 --- a/src/locales/zh-CN/chat.json +++ b/src/locales/zh-CN/chat.json @@ -131,6 +131,8 @@ "editCancel": "取消编辑", "dragReorder": "拖拽调整顺序" }, + "widthDragHint": "拖动调整对话宽度(切换宽屏模式可恢复默认)", + "inputWidthDragHint": "拖动调整输入框宽度(切换宽屏模式可恢复默认)", "permissionDialog": { "permission": "权限:{{permission}}", "moreCount": "还有 {{count}} 个", diff --git a/src/store/themeStore.test.ts b/src/store/themeStore.test.ts new file mode 100644 index 000000000..6fa752150 --- /dev/null +++ b/src/store/themeStore.test.ts @@ -0,0 +1,74 @@ +import { beforeEach, describe, expect, it } from 'vitest' +import { themeStore } from './themeStore' + +describe('themeStore · 对话列/输入框自定义宽度(chatContentWidth / chatInputWidth)', () => { + beforeEach(() => { + localStorage.clear() + themeStore.setChatContentWidth(null) + themeStore.setChatInputWidth(null) + }) + + it('setChatContentWidth 持久化 px,null 清除', () => { + themeStore.setChatContentWidth(900) + expect(themeStore.chatContentWidth).toBe(900) + expect(localStorage.getItem('chat-content-width')).toBe('900') + + themeStore.setChatContentWidth(null) + expect(themeStore.chatContentWidth).toBeNull() + expect(localStorage.getItem('chat-content-width')).toBeNull() + }) + + it('setChatInputWidth 持久化 px,null 清除', () => { + themeStore.setChatInputWidth(820) + expect(themeStore.chatInputWidth).toBe(820) + expect(localStorage.getItem('chat-input-width')).toBe('820') + + themeStore.setChatInputWidth(null) + expect(themeStore.chatInputWidth).toBeNull() + expect(localStorage.getItem('chat-input-width')).toBeNull() + }) + + it('非法值(0/负数/NaN)一律归一为 null', () => { + themeStore.setChatContentWidth(0) + expect(themeStore.chatContentWidth).toBeNull() + themeStore.setChatInputWidth(-100) + expect(themeStore.chatInputWidth).toBeNull() + themeStore.setChatContentWidth(Number.NaN) + expect(themeStore.chatContentWidth).toBeNull() + }) + + it('两个宽度互不影响(独立调整)', () => { + themeStore.setChatContentWidth(900) + themeStore.setChatInputWidth(820) + expect(themeStore.chatContentWidth).toBe(900) + expect(themeStore.chatInputWidth).toBe(820) + + themeStore.setChatContentWidth(null) + expect(themeStore.chatContentWidth).toBeNull() + expect(themeStore.chatInputWidth).toBe(820) + }) + + it('切换宽屏模式(开或关)会把两个自定义宽度一起重置', () => { + const originalWide = themeStore.wideMode + + themeStore.setChatContentWidth(900) + themeStore.setChatInputWidth(820) + themeStore.setWideMode(!originalWide) // 切到另一档 + expect(themeStore.chatContentWidth).toBeNull() + expect(themeStore.chatInputWidth).toBeNull() + expect(localStorage.getItem('chat-content-width')).toBeNull() + expect(localStorage.getItem('chat-input-width')).toBeNull() + + themeStore.setChatContentWidth(1000) + themeStore.setChatInputWidth(860) + themeStore.setWideMode(originalWide) // 再切回来 + expect(themeStore.chatContentWidth).toBeNull() + expect(themeStore.chatInputWidth).toBeNull() + + // 同值 setWideMode 是 no-op,不应误清 + themeStore.setChatContentWidth(1000) + themeStore.setWideMode(originalWide) + expect(themeStore.chatContentWidth).toBe(1000) + themeStore.setChatContentWidth(null) + }) +}) diff --git a/src/store/themeStore.ts b/src/store/themeStore.ts index 102d624eb..21365d198 100644 --- a/src/store/themeStore.ts +++ b/src/store/themeStore.ts @@ -200,6 +200,10 @@ export interface ThemeState { reasoningDisplayMode: ReasoningDisplayMode /** 宽模式 */ wideMode: boolean + /** 对话列自定义宽度(px,左缘拖拽设置;null = 跟随宽屏模式默认) */ + chatContentWidth: number | null + /** 输入框自定义宽度(px,左缘拖拽设置;null = 默认 3xl=768) */ + chatInputWidth: number | null /** Diff 行标记风格 */ diffStyle: DiffStyle /** 是否启用带工具描述的 steps 摘要 */ @@ -265,6 +269,8 @@ const STORAGE_KEY_STEP_FINISH_DISPLAY = 'step-finish-display' const STORAGE_KEY_COMPLETED_AT_FORMAT = 'completed-at-format' const STORAGE_KEY_REASONING_DISPLAY_MODE = 'reasoning-display-mode' const STORAGE_KEY_WIDE_MODE = 'chat-wide-mode' +const STORAGE_KEY_CHAT_CONTENT_WIDTH = 'chat-content-width' +const STORAGE_KEY_CHAT_INPUT_WIDTH = 'chat-input-width' const STORAGE_KEY_DIFF_STYLE = 'diff-style' const STORAGE_KEY_DESCRIPTIVE_TOOL_STEPS = 'descriptive-tool-steps' const STORAGE_KEY_INLINE_TOOL_REQUESTS = 'inline-tool-requests' @@ -363,6 +369,12 @@ class ThemeStore { savedCompletedAtFormat === 'dateTime' ? 'dateTime' : DEFAULT_COMPLETED_AT_FORMAT const savedWideMode = localStorage.getItem(STORAGE_KEY_WIDE_MODE) === 'true' + const rawChatContentWidth = Number(localStorage.getItem(STORAGE_KEY_CHAT_CONTENT_WIDTH)) + const savedChatContentWidth = + Number.isFinite(rawChatContentWidth) && rawChatContentWidth > 0 ? rawChatContentWidth : null + const rawChatInputWidth = Number(localStorage.getItem(STORAGE_KEY_CHAT_INPUT_WIDTH)) + const savedChatInputWidth = + Number.isFinite(rawChatInputWidth) && rawChatInputWidth > 0 ? rawChatInputWidth : null const savedDiffStyle = localStorage.getItem(STORAGE_KEY_DIFF_STYLE) as DiffStyle | null const diffStyle: DiffStyle = savedDiffStyle === 'changeBars' ? 'changeBars' : DEFAULT_DIFF_STYLE @@ -477,6 +489,8 @@ class ThemeStore { completedAtFormat, reasoningDisplayMode, wideMode: savedWideMode, + chatContentWidth: savedChatContentWidth, + chatInputWidth: savedChatInputWidth, diffStyle, descriptiveToolSteps, inlineToolRequests, @@ -542,6 +556,12 @@ class ThemeStore { get wideMode() { return this.state.wideMode } + get chatContentWidth() { + return this.state.chatContentWidth + } + get chatInputWidth() { + return this.state.chatInputWidth + } get diffStyle() { return this.state.diffStyle } @@ -806,8 +826,29 @@ class ThemeStore { setWideMode(enabled: boolean) { if (this.state.wideMode === enabled) return - this.state = { ...this.state, wideMode: enabled } + // 切换宽屏模式(开或关都算)会重置左缘拖拽的自定义宽度(对话列 + 输入框),回到所选模式的默认宽度 + this.state = { ...this.state, wideMode: enabled, chatContentWidth: null, chatInputWidth: null } localStorage.setItem(STORAGE_KEY_WIDE_MODE, String(enabled)) + localStorage.removeItem(STORAGE_KEY_CHAT_CONTENT_WIDTH) + localStorage.removeItem(STORAGE_KEY_CHAT_INPUT_WIDTH) + this.emit() + } + + setChatContentWidth(width: number | null) { + const next = width !== null && Number.isFinite(width) && width > 0 ? Math.round(width) : null + if (this.state.chatContentWidth === next) return + this.state = { ...this.state, chatContentWidth: next } + if (next === null) localStorage.removeItem(STORAGE_KEY_CHAT_CONTENT_WIDTH) + else localStorage.setItem(STORAGE_KEY_CHAT_CONTENT_WIDTH, String(next)) + this.emit() + } + + setChatInputWidth(width: number | null) { + const next = width !== null && Number.isFinite(width) && width > 0 ? Math.round(width) : null + if (this.state.chatInputWidth === next) return + this.state = { ...this.state, chatInputWidth: next } + if (next === null) localStorage.removeItem(STORAGE_KEY_CHAT_INPUT_WIDTH) + else localStorage.setItem(STORAGE_KEY_CHAT_INPUT_WIDTH, String(next)) this.emit() } @@ -1209,6 +1250,12 @@ function normalizeThemeBackup(raw: unknown): ThemeBackup { ? parsed.reasoningDisplayMode : DEFAULT_REASONING_DISPLAY_MODE, wideMode: parsed?.wideMode === true, + chatContentWidth: + typeof parsed?.chatContentWidth === 'number' && parsed.chatContentWidth > 0 + ? parsed.chatContentWidth + : null, + chatInputWidth: + typeof parsed?.chatInputWidth === 'number' && parsed.chatInputWidth > 0 ? parsed.chatInputWidth : null, diffStyle: parsed?.diffStyle === 'changeBars' ? 'changeBars' : DEFAULT_DIFF_STYLE, descriptiveToolSteps: typeof parsed?.descriptiveToolSteps === 'boolean' ? parsed.descriptiveToolSteps : DEFAULT_DESCRIPTIVE_TOOL_STEPS, @@ -1303,6 +1350,10 @@ export function importThemeBackup(raw: unknown): void { localStorage.setItem(STORAGE_KEY_COMPLETED_AT_FORMAT, backup.completedAtFormat) localStorage.setItem(STORAGE_KEY_REASONING_DISPLAY_MODE, backup.reasoningDisplayMode) localStorage.setItem(STORAGE_KEY_WIDE_MODE, String(backup.wideMode)) + if (backup.chatContentWidth === null) localStorage.removeItem(STORAGE_KEY_CHAT_CONTENT_WIDTH) + else localStorage.setItem(STORAGE_KEY_CHAT_CONTENT_WIDTH, String(backup.chatContentWidth)) + if (backup.chatInputWidth === null) localStorage.removeItem(STORAGE_KEY_CHAT_INPUT_WIDTH) + else localStorage.setItem(STORAGE_KEY_CHAT_INPUT_WIDTH, String(backup.chatInputWidth)) localStorage.setItem(STORAGE_KEY_DIFF_STYLE, backup.diffStyle) localStorage.setItem(STORAGE_KEY_DESCRIPTIVE_TOOL_STEPS, String(backup.descriptiveToolSteps)) localStorage.setItem(STORAGE_KEY_INLINE_TOOL_REQUESTS, String(backup.inlineToolRequests)) From e3a79d35002051341da081c80ca7d9e2b5e3dbe6 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 19:32:41 +0800 Subject: [PATCH 24/91] =?UTF-8?q?refactor(chat):=20=E4=BC=9A=E8=AF=9D?= =?UTF-8?q?=E7=A7=BB=E5=8A=A8=E8=8F=9C=E5=8D=95=E4=BB=8E=E4=B8=8B=E6=8B=89?= =?UTF-8?q?=E6=94=B9=E6=88=90=20Dialog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 下拉面板太挤(w-56 小字 + 迷你输入框),换成成熟的 ui/Dialog: - 触发按钮不变,点开是居中的目标选择弹窗(480px); - 目标行加大:类型图标(本地=文件夹 / worktree)+ 名称主行 + 完整路径次行,移入中的行内 spinner; - 新建 worktree 独立区块:区块标题 + 正常尺寸输入框 + Button 组件, Enter 提交不变; - 业务逻辑不动:目标加载、blocked while running、moveSession / createWorktree、session.moved 事件驱动列表更新全部照旧。 --- src/features/chat/SessionMoveMenu.tsx | 136 +++++++++++++------------- src/locales/en/chat.json | 1 + src/locales/zh-CN/chat.json | 1 + 3 files changed, 71 insertions(+), 67 deletions(-) diff --git a/src/features/chat/SessionMoveMenu.tsx b/src/features/chat/SessionMoveMenu.tsx index 371787d87..48055d3cd 100644 --- a/src/features/chat/SessionMoveMenu.tsx +++ b/src/features/chat/SessionMoveMenu.tsx @@ -5,11 +5,15 @@ // - 目标列表 = 项目根(本地)+ 新建 worktree + 现有 worktree // - 会话运行中禁止移动(blocked while running) // - 成功后服务端发 session.moved,各列表据此增删 +// +// 交互是 Dialog(ui/Dialog):头部触发按钮不变, +// 点开是居中的目标选择弹窗,底部是新建 worktree 区。 // ============================================ -import { useCallback, useEffect, useRef, useState } from 'react' +import { useCallback, useState } from 'react' import { useTranslation } from 'react-i18next' -import { GitWorktreeIcon, SpinnerIcon } from '../../components/Icons' +import { FolderIcon, GitWorktreeIcon, SpinnerIcon } from '../../components/Icons' +import { Button, Dialog } from '../../components/ui' import { getCurrentProject, moveSession } from '../../api/client' import { listWorktreeEntries, createWorktree } from '../../api/worktree' import { useSessionActiveEntry } from '../../store/activeSessionStore' @@ -35,12 +39,12 @@ export function SessionMoveMenu({ sessionId, directory }: SessionMoveMenuProps) const { t } = useTranslation(['chat', 'common']) const [open, setOpen] = useState(false) const [loading, setLoading] = useState(false) - const [moving, setMoving] = useState(false) + /** 正在移入的目标目录(行内 spinner,同时禁用其它行) */ + const [movingTo, setMovingTo] = useState(null) const [targets, setTargets] = useState([]) const [projectID, setProjectID] = useState(null) const [newName, setNewName] = useState('') const [creating, setCreating] = useState(false) - const boxRef = useRef(null) // 官方 blocked():会话运行中禁止移动 const activeKey = makeSessionKey(serverStore.getActiveServerId(), sessionId) @@ -79,19 +83,9 @@ export function SessionMoveMenu({ sessionId, directory }: SessionMoveMenuProps) } }, [directory, t]) - // 点击外部关闭 - useEffect(() => { - if (!open) return - const onPointerDown = (e: PointerEvent) => { - if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false) - } - document.addEventListener('pointerdown', onPointerDown) - return () => document.removeEventListener('pointerdown', onPointerDown) - }, [open]) - const handleMove = async (destination: string) => { - if (moving) return - setMoving(true) + if (movingTo) return + setMovingTo(destination) try { await moveSession(sessionId, destination) setOpen(false) @@ -99,7 +93,7 @@ export function SessionMoveMenu({ sessionId, directory }: SessionMoveMenuProps) } catch (e) { uiErrorHandler('move session', e) } finally { - setMoving(false) + setMovingTo(null) } } @@ -119,84 +113,92 @@ export function SessionMoveMenu({ sessionId, directory }: SessionMoveMenuProps) } return ( -
+ <> - {open && ( -
e.stopPropagation()} - > -
- {t('chat:sessionMove.title')} -
-
+ setOpen(false)} title={t('chat:sessionMove.title')} width={480}> +
+ {/* 目标列表:项目根 + 现有 worktree */} +
{loading ? ( -
- +
+
) : targets.length === 0 ? ( -
{t('chat:sessionMove.empty')}
+
+ {t('chat:sessionMove.empty')} +
) : ( targets.map(target => ( )) )}
+ {/* 新建 worktree 并移入(官方菜单的 "create" 项) */} {projectID && ( -
- setNewName(e.target.value)} - onKeyDown={e => { - if (e.key === 'Enter') { - e.preventDefault() - void handleCreateAndMove() - } - }} - placeholder={t('chat:sessionMove.newWorktreePlaceholder')} - disabled={creating || moving} - className="flex-1 min-w-0 bg-bg-000 border border-border-200 rounded-md px-2 py-1 text-[length:var(--fs-xs)] text-text-100 placeholder:text-text-400/60 focus:outline-none focus:border-accent-main-100/50" - /> - +
+
{t('chat:sessionMove.newWorktreeSection')}
+
+ setNewName(e.target.value)} + onKeyDown={e => { + if (e.key === 'Enter') { + e.preventDefault() + void handleCreateAndMove() + } + }} + placeholder={t('chat:sessionMove.newWorktreePlaceholder')} + disabled={creating || movingTo !== null} + className="flex-1 min-w-0 bg-bg-000 border border-border-200 rounded-lg px-3 py-2 text-[length:var(--fs-base)] text-text-100 placeholder:text-text-400/60 focus:outline-none focus:border-accent-main-100/50" + /> + +
)}
- )} -
+
+ ) } diff --git a/src/locales/en/chat.json b/src/locales/en/chat.json index c4a978048..ffc206e13 100644 --- a/src/locales/en/chat.json +++ b/src/locales/en/chat.json @@ -15,6 +15,7 @@ "local": "Local (project root)", "empty": "No directories to move to", "newWorktree": "Create & move", + "newWorktreeSection": "New worktree", "newWorktreePlaceholder": "New worktree name", "runningTitle": "Session is running, cannot move" }, diff --git a/src/locales/zh-CN/chat.json b/src/locales/zh-CN/chat.json index a62d69aff..acabbcf9d 100644 --- a/src/locales/zh-CN/chat.json +++ b/src/locales/zh-CN/chat.json @@ -15,6 +15,7 @@ "local": "本地(项目根)", "empty": "没有可移动的目录", "newWorktree": "新建并移入", + "newWorktreeSection": "新建 Worktree", "newWorktreePlaceholder": "新 Worktree 名称", "runningTitle": "会话运行中,暂不能移动" }, From de3269d89af9039c614a79032d6ac7202e8efdd7 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 19:49:02 +0800 Subject: [PATCH 25/91] =?UTF-8?q?fix(chat):=20=E9=98=9F=E5=88=97=E6=B0=94?= =?UTF-8?q?=E6=B3=A1=E6=B8=B2=E6=9F=93=E9=99=84=E4=BB=B6=E8=83=B6=E5=9B=8A?= =?UTF-8?q?=EF=BC=8C=E5=92=8C=E6=99=AE=E9=80=9A=E7=94=A8=E6=88=B7=E6=B6=88?= =?UTF-8?q?=E6=81=AF=E5=90=8C=E6=AC=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 队列条目 payload 里本来就有 files/agents(SessionInboxUserPayload), 但 QueueBubbles 只取了 text——带附件排队的消息看起来只剩一行字。 现在气泡下方挂和普通用户消息一样的附件胶囊 (FilePartView/AgentPartView → AttachmentItem,可点开预览); skills 不渲染,对齐普通消息的行为。 测试:新增 files+agents 渲染用例(真 AttachmentItem,需包 FullscreenProvider——MessageRenderer 那个 file-part testid 其实是 mock 出来的,真组件直接渲染 displayName 文本)。 --- src/features/chat/QueueBubbles.test.tsx | 17 +++++++++++++++++ src/features/chat/QueueBubbles.tsx | 14 ++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/features/chat/QueueBubbles.test.tsx b/src/features/chat/QueueBubbles.test.tsx index 6feccac1c..93a8701ab 100644 --- a/src/features/chat/QueueBubbles.test.tsx +++ b/src/features/chat/QueueBubbles.test.tsx @@ -3,6 +3,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { QueueBubbles } from './QueueBubbles' import { setUiDisclosureState } from '../../utils/uiDisclosureState' import { themeStore } from '../../store/themeStore' +import { FullscreenProvider } from '../../contexts/FullscreenContext' import type { QueuedUserPrompt } from '../../store/inboxStore' function makeItem(id: string, text: string): QueuedUserPrompt { @@ -58,6 +59,22 @@ describe('QueueBubbles(下轮队列虚线气泡)', () => { expect(onRemove).toHaveBeenCalledWith(item) }) + it('renders attachment chips for queued files/agents(和普通用户消息同款)', () => { + const item = makeItem('q1', '带附件') + ;(item.payload as Record).files = [ + { data: 'aGVsbG8=', mime: 'text/plain', source: { type: 'uri', uri: 'file:///workspace/notes.txt' }, name: 'notes.txt' }, + ] + ;(item.payload as Record).agents = [{ name: 'reviewer' }] + // AttachmentItem 的详情弹窗要 FullscreenProvider 上下文 + render( + + + , + ) + expect(screen.getByText('notes.txt')).toBeInTheDocument() + expect(screen.getByText('reviewer')).toBeInTheDocument() + }) + it('collapses bubbles by default and toggles on header click(compact 同款)', async () => { render() diff --git a/src/features/chat/QueueBubbles.tsx b/src/features/chat/QueueBubbles.tsx index f27f153c9..99b40c150 100644 --- a/src/features/chat/QueueBubbles.tsx +++ b/src/features/chat/QueueBubbles.tsx @@ -25,6 +25,7 @@ import { useDisclosureScrollLock } from '../../hooks' import { useTheme } from '../../hooks/useTheme' import { useUiDisclosureState } from '../../utils/uiDisclosureState' import { chevronClass, MessageExpandPanel, useMessageExpandRender } from '../message/messageExpand' +import { AgentPartView, FilePartView } from '../message/parts/AttachmentPartViews' interface QueueBubblesProps { /** 下轮队列条目(delivery='queue',等当前回合结束后由服务端投递) */ @@ -178,6 +179,8 @@ export const QueueBubbles = memo(function QueueBubbles({
{rows.map(({ item }, index) => { const text = queuedPromptText(item) + const files = item.payload.files ?? [] + const agents = item.payload.agents ?? [] const isEditing = item.id === editingId const showInsertion = dragTarget !== null && dragTarget === index && dragRef.current?.active return ( @@ -192,6 +195,17 @@ export const QueueBubbles = memo(function QueueBubbles({ > {text}
+ {/* 附件胶囊:和普通用户消息同款(files + agents),挂在气泡下方 */} + {(files.length > 0 || agents.length > 0) && ( +
+ {files.map((file, fileIndex) => ( + + ))} + {agents.map((agent, agentIndex) => ( + + ))} +
+ )} {/* 操作行:气泡下方(对齐用户消息 action bar) */} {(onSteer || onEdit || onRemove || onReorder) && (
From d19c9cfa50ee883ecd9ee071bf1a9e2068d47ab2 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 19:49:02 +0800 Subject: [PATCH 26/91] =?UTF-8?q?test(chat):=20=E4=BF=AE=20RetryStatusInli?= =?UTF-8?q?ne=20=E5=80=92=E8=AE=A1=E6=97=B6=E6=B5=8B=E8=AF=95=E7=9A=84?= =?UTF-8?q?=E6=97=B6=E5=BA=8F=20flake?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 测试的 Date.now() 和组件内部的 Date.now() 之间差 >50ms, 剩余 5.0s 就会显示成 4.9s 导致正则失配——并行负载下 CPU 抢占必现。 用 fake timers 冻结时间,两边看到同一个 now。 --- src/features/chat/RetryStatusInline.test.tsx | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/features/chat/RetryStatusInline.test.tsx b/src/features/chat/RetryStatusInline.test.tsx index 6dff17c56..aaf6e73d9 100644 --- a/src/features/chat/RetryStatusInline.test.tsx +++ b/src/features/chat/RetryStatusInline.test.tsx @@ -19,11 +19,17 @@ function makeStatus(overrides: Partial = {}): RetryStatus describe('RetryStatusInline', () => { it('把 next 当成绝对时间戳,算出剩余倒计时', () => { - render() - - // 5s → formatRemaining 走 <10s 分支,显示 "5.0s" - expect(screen.getByText(/5\.\ds/)).toBeTruthy() - expect(screen.getByText(/2/)).toBeTruthy() + // 冻结时间:测试与组件各自 Date.now() 之间差 >50ms 就会少显示 0.1s(并行负载下必现的 flake) + vi.useFakeTimers() + try { + render() + + // 5s → formatRemaining 走 <10s 分支,显示 "5.0s" + expect(screen.getByText(/5\.\ds/)).toBeTruthy() + expect(screen.getByText(/2/)).toBeTruthy() + } finally { + vi.useRealTimers() + } }) it('next 已经过去时不显示倒计时', () => { From 24e90dae13b7f57dfcfeaf1b9217cbe8c8e43205 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 20:08:03 +0800 Subject: [PATCH 27/91] =?UTF-8?q?fix(chat):=20@=20=E6=8F=90=E5=8F=8A?= =?UTF-8?q?=E7=9A=84=E9=99=84=E4=BB=B6=20url=20=E8=A1=A5=20file://=20schem?= =?UTF-8?q?e=EF=BC=8C=E4=BF=AE=E5=8F=91=E9=80=81=20400?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 服务端 readFileAttachment 用 new URL + protocol==='file:' 校验附件 URI, @ 提及塞的是裸绝对路径(E:/dev/...),被解析成 e: 协议直接 InvalidRequestError: Unsupported attachment URI——而侧边栏拖入一直走 toFileUrl 所以没事。对齐官方 request.ts:109 的 file://${encodeFilePath(path)},@ 提及也过 toFileUrl。 --- src/features/chat/InputBox.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/features/chat/InputBox.tsx b/src/features/chat/InputBox.tsx index 4fe72ec6f..6ffda5ad0 100644 --- a/src/features/chat/InputBox.tsx +++ b/src/features/chat/InputBox.tsx @@ -973,13 +973,16 @@ function InputBoxComponent({ const newText = beforeAt + mentionText + ' ' + afterQuery // 创建附件(reference 按目录附件插入,值为引用目录的绝对路径——官方 mime 是 application/x-directory) + // url 必须是合法 file:// URL(服务端 readFileAttachment 用 new URL + protocol==='file:' 校验, + // 裸绝对路径 `E:/...` 会被解析成 `e:` 协议直接 400——侧边栏拖入走 toFileUrl 所以没事, + // 这里对齐官方 request.ts:109 的 `file://${encodeFilePath(path)}`) const attachType = item.type === 'reference' ? 'folder' : item.type const attachment: Attachment = { id: crypto.randomUUID(), type: attachType, displayName: item.displayName, relativePath: item.type === 'reference' ? item.value : item.relativePath, - url: item.type !== 'agent' && item.type !== 'skill' ? item.value : undefined, + url: item.type !== 'agent' && item.type !== 'skill' ? toFileUrl(item.value) : undefined, mime: item.type === 'reference' ? 'application/x-directory' : item.type !== 'agent' ? 'text/plain' : undefined, agentName: item.type === 'agent' ? item.displayName : undefined, skillId: item.type === 'skill' ? item.value : undefined, From 37a52d5e421256bfe14e7889713d06bfa05afe40 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 20:08:04 +0800 Subject: [PATCH 28/91] =?UTF-8?q?fix(chat):=20=E9=98=9F=E5=88=97=E9=95=BF?= =?UTF-8?q?=E6=96=87=E6=9C=AC=E6=8A=98=E5=8F=A0=E5=A4=8D=E7=94=A8=20Collap?= =?UTF-8?q?sibleUserText=EF=BC=8C=E4=B8=8D=E5=86=8D=E6=90=9E=E7=89=B9?= =?UTF-8?q?=E6=AE=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 队列气泡的正文原来是自己裸渲染 text,超长折叠(预览 8 行 + 展开按钮) 只有普通用户消息有。把 CollapsibleUserText 从 MessageRenderer 抽成 共享组件(气泡外壳/正文色/遮罩色可配,默认外观不变),队列气泡直接 复用:折叠行为、状态记忆、展开按钮全部同款。 - USER_HTML_ARTIFACT_PATTERN 一并导出(UserMessageView 还在用); - 遮罩加 showMask 开关:队列气泡是半透明底色(bg-300/60),渐变 from 色怎么选都和合成底色对不上、底部一道深带,队列直接关遮罩; - 测试:mock scrollHeight + --fs-base 模拟溢出,验证折叠按钮出现 和展开切换。 --- src/features/chat/QueueBubbles.test.tsx | 28 ++++ src/features/chat/QueueBubbles.tsx | 20 ++- src/features/message/CollapsibleUserText.tsx | 129 +++++++++++++++++++ src/features/message/MessageRenderer.tsx | 103 +-------------- 4 files changed, 171 insertions(+), 109 deletions(-) create mode 100644 src/features/message/CollapsibleUserText.tsx diff --git a/src/features/chat/QueueBubbles.test.tsx b/src/features/chat/QueueBubbles.test.tsx index 93a8701ab..ac45a8970 100644 --- a/src/features/chat/QueueBubbles.test.tsx +++ b/src/features/chat/QueueBubbles.test.tsx @@ -95,6 +95,34 @@ describe('QueueBubbles(下轮队列虚线气泡)', () => { }) }) + it('collapses long queued text like normal user messages(CollapsibleUserText 同款折叠)', () => { + // jsdom 的 scrollHeight 恒 0、--fs-base 读不到,mock 出"超长溢出"的环境 + const scrollHeightSpy = vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockReturnValue(9999) + const originalGetComputedStyle = window.getComputedStyle + const computedStyleSpy = vi.spyOn(window, 'getComputedStyle').mockImplementation((el, pseudo) => { + const styles = originalGetComputedStyle(el, pseudo) + return { + ...styles, + getPropertyValue: (name: string) => (name === '--fs-base' ? '14' : styles.getPropertyValue(name)), + } as CSSStyleDeclaration + }) + try { + const longText = Array.from({ length: 30 }, (_, i) => `第 ${i + 1} 行`).join('\n') + render() + + // 折叠态:展开按钮出现,正文 maxHeight 被限制(预览 8 行) + const toggle = screen.getByRole('button', { name: 'Show more' }) + expect(toggle).toBeInTheDocument() + + // 点击展开 → 按钮变 Show less + fireEvent.click(toggle) + expect(screen.getByRole('button', { name: 'Show less' })).toBeInTheDocument() + } finally { + scrollHeightSpy.mockRestore() + computedStyleSpy.mockRestore() + } + }) + it('expands by default when the collapse setting is off(默认展开开关)', () => { themeStore.setQueueAutoCollapse(false) render() diff --git a/src/features/chat/QueueBubbles.tsx b/src/features/chat/QueueBubbles.tsx index 99b40c150..2d181e844 100644 --- a/src/features/chat/QueueBubbles.tsx +++ b/src/features/chat/QueueBubbles.tsx @@ -26,6 +26,7 @@ import { useTheme } from '../../hooks/useTheme' import { useUiDisclosureState } from '../../utils/uiDisclosureState' import { chevronClass, MessageExpandPanel, useMessageExpandRender } from '../message/messageExpand' import { AgentPartView, FilePartView } from '../message/parts/AttachmentPartViews' +import { CollapsibleUserText } from '../message/CollapsibleUserText' interface QueueBubblesProps { /** 下轮队列条目(delivery='queue',等当前回合结束后由服务端投递) */ @@ -91,7 +92,7 @@ export const QueueBubbles = memo(function QueueBubbles({ // 折叠(compact 同款):默认折叠/展开由设置项 queueAutoCollapse 决定, // 用户手动展开/收起后按 key 记住(uiDisclosureState touched 语义) - const { queueAutoCollapse } = useTheme() + const { queueAutoCollapse, collapseUserMessages } = useTheme() const [expanded, setExpanded] = useUiDisclosureState(stateKey ?? 'queue-bubbles', !queueAutoCollapse) const shouldRenderBody = useMessageExpandRender(expanded) const { withScrollLock } = useDisclosureScrollLock() @@ -187,14 +188,19 @@ export const QueueBubbles = memo(function QueueBubbles({
{/* 插入指示线:拖拽指针越过该条目中线时显示在其上方 */} {showInsertion && ) diff --git a/src/features/sessions/SessionList.tsx b/src/features/sessions/SessionList.tsx index 3700249d0..d4a4fd5a2 100644 --- a/src/features/sessions/SessionList.tsx +++ b/src/features/sessions/SessionList.tsx @@ -10,7 +10,7 @@ import { useSessionActiveEntry } from '../../store/activeSessionStore' import { notificationStore, useHasUnreadCompletedNotification } from '../../store/notificationStore' import { SessionChildrenSlot } from '../chat/sidebar/SessionChildrenSlot' import { SessionShellsSlot } from '../chat/sidebar/SessionShellsSlot' -import { shellInventoryStore } from '../../store/shellInventoryStore' +import { useHasBackgroundShells } from '../../store/shellInventoryStore' import type { ApiSession } from '../../api' import { startInternalDrag } from '../../lib/internalDragCore' import { makeSessionKey, splitSessionKey } from '../../utils/sessionKey' @@ -101,20 +101,6 @@ export function SessionList({ sessionId: null, }) - // 后台 shell 库存:父会话活跃判定(后台 shell 活着 = 会话仍活跃)。 - // 挂载行由 SessionShellsSlot 自己订阅,这里只算「哪些会话有 running shell」 - const shellInventoryVersion = useSyncExternalStore(shellInventoryStore.subscribe, shellInventoryStore.getVersion) - const backgroundWorkSessionIds = useMemo(() => { - const shells = shellInventoryStore.getShells(serverId ?? '') - const ids = new Set() - for (const shell of shells) { - if (shell.status !== 'running') continue - const sessionID = shell.metadata?.sessionID - if (typeof sessionID === 'string') ids.add(sessionID) - } - return ids - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [shellInventoryVersion, serverId]) // 滚动加载 const handleScroll = useCallback(() => { @@ -265,7 +251,6 @@ export function SessionList({ isChecked={isChecked} checkedPrev={prevChecked} checkedNext={nextChecked} - hasBackgroundWork={backgroundWorkSessionIds.has(session.id)} onToggleCheck={ onToggleSessionSelection ? options => onToggleSessionSelection(session.id, options) @@ -336,7 +321,6 @@ export function SessionList({ isChecked={isChecked} checkedPrev={prevChecked} checkedNext={nextChecked} - hasBackgroundWork={backgroundWorkSessionIds.has(session.id)} onToggleCheck={ onToggleSessionSelection ? options => onToggleSessionSelection(session.id, options) : undefined } @@ -415,8 +399,6 @@ export interface SessionListItemProps { /** 下一项也选中时,去掉下圆角 */ checkedNext?: boolean onToggleCheck?: (options?: { shiftKey?: boolean }) => void - /** 有后台 shell 在跑(会话本身 idle 也算活跃,侧边栏活跃标识亮着) */ - hasBackgroundWork?: boolean } export function SessionListItem({ @@ -435,7 +417,6 @@ export function SessionListItem({ checkedPrev = false, checkedNext = false, onToggleCheck, - hasBackgroundWork = false, }: SessionListItemProps) { const { t } = useTranslation(['commands', 'common', 'chat']) const [isEditing, setIsEditing] = useState(false) @@ -455,6 +436,9 @@ export function SessionListItem({ // 单服务器模式 session.id 是原始 id,需用活动服务器合成复合 key 查询) const activeQueryKey = activeSessionKey ?? makeSessionKey(serverStore.getActiveServerId(), session.id) const activeEntry = useSessionActiveEntry(activeQueryKey) + // 后台 shell 活着 = 会话仍活跃(store 自己订阅,不用列表层层喂 props; + // 库存按工作区目录隔离,用会话自己的 location.directory 查) + const hasBackgroundWork = useHasBackgroundShells(session.id, session.location?.directory) const activeStatus = activeEntry ? activeEntry.pendingAction?.type === 'permission' ? { dot: 'bg-warning-100', label: t('chat:activeSession.awaitingPermission'), pulse: false } diff --git a/src/store/shellInventoryStore.test.ts b/src/store/shellInventoryStore.test.ts index c877dea56..0f32f9614 100644 --- a/src/store/shellInventoryStore.test.ts +++ b/src/store/shellInventoryStore.test.ts @@ -1,23 +1,22 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ShellInfo } from '@opencode/client/promise' -const listShellsMock = vi.fn<() => Promise>() +const listShellsMock = vi.fn<(directory: string) => Promise>() vi.mock('../api/shell', () => ({ - listShells: () => listShellsMock(), + listShells: (directory: string) => listShellsMock(directory), removeShell: vi.fn(), })) import { runningShellsForSession, shellInventoryStore } from './shellInventoryStore' -import { serverStore } from './serverStore' -const ACTIVE = serverStore.getActiveServerId() +const DIR = '/repo' function makeShell(id: string, sessionID: string, status: ShellInfo['status'] = 'running'): ShellInfo { return { id, status, command: `cmd-${id}`, - cwd: '/repo', + cwd: DIR, shell: 'bash', file: '', metadata: { sessionID }, @@ -39,7 +38,7 @@ describe('runningShellsForSession(挂载过滤)', () => { }) }) -describe('shellInventoryStore(事件驱动 + 兜底轮询)', () => { +describe('shellInventoryStore(按目录登记 + 事件驱动 + 兜底轮询)', () => { beforeEach(() => { vi.useFakeTimers() listShellsMock.mockReset() @@ -49,18 +48,23 @@ describe('shellInventoryStore(事件驱动 + 兜底轮询)', () => { vi.useRealTimers() }) - it('第一个订阅者出现时拉初始清单,退订干净后停止轮询', async () => { + it('目录首次登记立即拉取;退订干净后停止轮询并丢弃目录数据', async () => { listShellsMock.mockResolvedValue([makeShell('a', 's1')]) const spy = vi.fn() const unsubscribe = shellInventoryStore.subscribe(spy) + const untrack = shellInventoryStore.trackDirectory(DIR) await vi.advanceTimersByTimeAsync(0) - expect(listShellsMock).toHaveBeenCalledTimes(1) - expect(shellInventoryStore.getShells(ACTIVE).map(s => s.id)).toEqual(['a']) + expect(listShellsMock).toHaveBeenCalledWith(DIR) + expect(shellInventoryStore.getShellsForDir(DIR).map(s => s.id)).toEqual(['a']) // 有数据(从无到有的变化)→ version bump 通知订阅者 expect(spy).toHaveBeenCalled() + untrack() unsubscribe() + // 目录引用归零 → 数据丢弃 + expect(shellInventoryStore.getShellsForDir(DIR)).toEqual([]) + const callsBefore = listShellsMock.mock.calls.length await vi.advanceTimersByTimeAsync(60_000) // 没有订阅者 → 兜底轮询不再打 @@ -71,6 +75,7 @@ describe('shellInventoryStore(事件驱动 + 兜底轮询)', () => { listShellsMock.mockResolvedValue([makeShell('a', 's1')]) const spy = vi.fn() const unsubscribe = shellInventoryStore.subscribe(spy) + const untrack = shellInventoryStore.trackDirectory(DIR) await vi.advanceTimersByTimeAsync(0) expect(listShellsMock).toHaveBeenCalledTimes(1) const versionAfterInit = shellInventoryStore.getVersion() @@ -92,12 +97,15 @@ describe('shellInventoryStore(事件驱动 + 兜底轮询)', () => { await vi.advanceTimersByTimeAsync(600) expect(shellInventoryStore.getVersion()).toBe(versionAfterInit + 1) expect(spy).toHaveBeenCalled() + + untrack() unsubscribe() }) it('shell 状态流转(running → exited)也算变化', async () => { listShellsMock.mockResolvedValue([makeShell('a', 's1')]) const unsubscribe = shellInventoryStore.subscribe(() => {}) + const untrack = shellInventoryStore.trackDirectory(DIR) await vi.advanceTimersByTimeAsync(0) const v0 = shellInventoryStore.getVersion() @@ -105,6 +113,25 @@ describe('shellInventoryStore(事件驱动 + 兜底轮询)', () => { shellInventoryStore.requestRefresh() await vi.advanceTimersByTimeAsync(600) expect(shellInventoryStore.getVersion()).toBe(v0 + 1) + + untrack() + unsubscribe() + }) + + it('多个目录各自隔离拉取(serve --service 按目录隔离的现实)', async () => { + listShellsMock.mockImplementation(async (directory: string) => + directory === '/a' ? [makeShell('sh-a', 's1')] : [makeShell('sh-b', 's2')], + ) + const unsubscribe = shellInventoryStore.subscribe(() => {}) + const untrackA = shellInventoryStore.trackDirectory('/a') + const untrackB = shellInventoryStore.trackDirectory('/b') + await vi.advanceTimersByTimeAsync(0) + + expect(shellInventoryStore.getShellsForDir('/a').map(s => s.id)).toEqual(['sh-a']) + expect(shellInventoryStore.getShellsForDir('/b').map(s => s.id)).toEqual(['sh-b']) + + untrackA() + untrackB() unsubscribe() }) }) diff --git a/src/store/shellInventoryStore.ts b/src/store/shellInventoryStore.ts index 13f8ac95b..3515efb20 100644 --- a/src/store/shellInventoryStore.ts +++ b/src/store/shellInventoryStore.ts @@ -1,17 +1,21 @@ // ============================================ -// shellInventoryStore — 服务器 shell 库存(后台任务可见性的数据源) +// shellInventoryStore — shell 库存(后台任务可见性的数据源) +// +// 关键事实:serve --service 模式下 shell 按工作区目录隔离, +// listShells 必须带 location.directory(不带查的是服务根目录,永远空)。 +// 所以库存按 directory 维护,订阅者(侧边栏挂载行/活跃判定)用 +// trackDirectory 登记自己关心的目录,store 只拉登记过的目录。 // // 数据节奏(对齐文件变更面板的事件驱动模式): -// - 有订阅者时拉一次初始清单(listShells) -// - session.shell.started / ended 事件 → 500ms 防抖重取(useGlobalEvents 调 requestRefresh) +// - 目录首次被登记 → 立即拉一次 +// - session.shell.started / ended 事件 → 500ms 防抖重取全部登记目录 // - 15s 兜底轮询(事件丢失的保险) -// 消费:侧边栏把 running shell 挂载到父会话下(SessionShellsSlot)、 -// 父会话活跃判定(后台 shell 活着 = 会话仍活跃)。 +// v1 边界:只跟活动服务器(getSDKClient 缺省),多服务器会话行不挂 shell。 // ============================================ import type { ShellInfo } from '@opencode/client/promise' +import { useEffect, useMemo, useSyncExternalStore } from 'react' import { listShells } from '../api/shell' -import { serverStore } from './serverStore' type Subscriber = () => void @@ -19,22 +23,22 @@ const REFRESH_DEBOUNCE_MS = 500 const FALLBACK_POLL_MS = 15_000 class ShellInventoryStore { - /** serverId → 该服务器的 shell 清单 */ - private shellsByServer = new Map() + /** directory → 该工作区的 shell 清单 */ + private shellsByDir = new Map() + /** directory → 引用计数(多少个组件关心这个目录) */ + private dirRefs = new Map() private version = 0 private subscribers = new Set() private refreshTimer: ReturnType | null = null private pollTimer: ReturnType | null = null - private loading = false + private refreshing = false // 箭头属性:useSyncExternalStore(store.subscribe, ...) 直接引用不丢 this subscribe = (fn: Subscriber): (() => void) => { const wasEmpty = this.subscribers.size === 0 this.subscribers.add(fn) if (wasEmpty) { - // 第一个订阅者出现:拉初始清单 + 开兜底轮询 - void this.refreshNow() - this.pollTimer = setInterval(() => void this.refreshNow(), FALLBACK_POLL_MS) + this.pollTimer = setInterval(() => void this.refreshAll(), FALLBACK_POLL_MS) } return () => { this.subscribers.delete(fn) @@ -53,9 +57,24 @@ class ShellInventoryStore { getVersion = (): number => this.version - /** 缺省/空 serverId 归一到活动服务器(调用点不用各自兜底) */ - getShells = (serverId?: string): ShellInfo[] => - this.shellsByServer.get(serverId || serverStore.getActiveServerId()) ?? EMPTY_SHELLS + getShellsForDir = (directory?: string): ShellInfo[] => + (directory && this.shellsByDir.get(directory)) || EMPTY_SHELLS + + /** 登记关心的目录(引用计数)。首次登记立即拉取,归零后丢弃该目录数据 */ + trackDirectory = (directory: string): (() => void) => { + const count = this.dirRefs.get(directory) ?? 0 + this.dirRefs.set(directory, count + 1) + if (count === 0) void this.refreshDir(directory).then(changed => changed && this.bump()) + return () => { + const next = (this.dirRefs.get(directory) ?? 1) - 1 + if (next <= 0) { + this.dirRefs.delete(directory) + if (this.shellsByDir.delete(directory)) this.bump() + } else { + this.dirRefs.set(directory, next) + } + } + } /** 事件触发(shell.started/ended):防抖合并连续事件,避免一次回合启动多个 shell 时连打 */ requestRefresh = () => { @@ -63,26 +82,36 @@ class ShellInventoryStore { if (this.refreshTimer) clearTimeout(this.refreshTimer) this.refreshTimer = setTimeout(() => { this.refreshTimer = null - void this.refreshNow() + void this.refreshAll() }, REFRESH_DEBOUNCE_MS) } - private async refreshNow() { - if (this.loading) return - this.loading = true + private bump() { + this.version++ + this.subscribers.forEach(fn => fn()) + } + + private async refreshDir(directory: string): Promise { try { - const serverId = serverStore.getActiveServerId() - const list = await listShells(serverId) - const prev = this.shellsByServer.get(serverId) - if (!sameShellList(prev, list)) { - this.shellsByServer.set(serverId, list) - this.version++ - this.subscribers.forEach(fn => fn()) - } + const list = await listShells(directory) + const prev = this.shellsByDir.get(directory) + if (sameShellList(prev, list)) return false + this.shellsByDir.set(directory, list) + return true } catch { // 失败保留旧数据,下一轮再试 + return false + } + } + + private async refreshAll() { + if (this.refreshing || this.dirRefs.size === 0) return + this.refreshing = true + try { + const results = await Promise.all([...this.dirRefs.keys()].map(dir => this.refreshDir(dir))) + if (results.some(Boolean)) this.bump() } finally { - this.loading = false + this.refreshing = false } } } @@ -102,3 +131,26 @@ export const shellInventoryStore = new ShellInventoryStore() export function runningShellsForSession(shells: ShellInfo[], rawSessionId: string): ShellInfo[] { return shells.filter(shell => shell.status === 'running' && shell.metadata?.sessionID === rawSessionId) } + +/** 挂载期间登记目录 + 订阅库存版本(ShellOutputDialog 跟状态也用这份) */ +export function useShellsForDir(directory?: string): ShellInfo[] { + useEffect(() => (directory ? shellInventoryStore.trackDirectory(directory) : undefined), [directory]) + const version = useSyncExternalStore(shellInventoryStore.subscribe, shellInventoryStore.getVersion) + return useMemo( + () => shellInventoryStore.getShellsForDir(directory), + // eslint-disable-next-line react-hooks/exhaustive-deps + [version, directory], + ) +} + +/** 订阅某会话的 running shell 列表(SessionShellsSlot 用) */ +export function useRunningShellsForSession(rawSessionId: string, directory?: string): ShellInfo[] { + const shells = useShellsForDir(directory) + return useMemo(() => runningShellsForSession(shells, rawSessionId), [shells, rawSessionId]) +} + +/** 某会话是否有后台 shell 在跑(SessionListItem 活跃判定用,自己订阅不用外部喂) */ +export function useHasBackgroundShells(rawSessionId: string, directory?: string): boolean { + const shells = useShellsForDir(directory) + return useMemo(() => runningShellsForSession(shells, rawSessionId).length > 0, [shells, rawSessionId]) +} From 70db9fa8e53eddd7e7330cd613a38c4e45f72236 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 22:02:26 +0800 Subject: [PATCH 34/91] =?UTF-8?q?feat(sessions):=20=E5=90=8E=E5=8F=B0=20sh?= =?UTF-8?q?ell=20=E5=9C=A8=E8=B7=91=E7=9A=84=20idle=20=E4=BC=9A=E8=AF=9D?= =?UTF-8?q?=E4=B9=9F=E7=AE=97=E6=B4=BB=E8=B7=83=EF=BC=8C=E8=BF=9B=E6=B4=BB?= =?UTF-8?q?=E8=B7=83=20tab?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前的割裂:session 列表里主会话因后台 shell 亮「后台任务运行中」 绿点,但活跃 tab 的名单只认 busy 状态,同一会话在那边查无此人。 - shellInventoryStore.collectShellActiveSessionIds:跨已登记目录收集 有 running shell 的会话;useShellActiveSessionIds 响应式封装 - SidePanel 登记所有已知会话的目录(否则 idle 会话的目录没人拉, 先有鸡先有蛋);不在 busy 名单但 shell 活跃的会话合成 backgroundOnly 条目并入活跃树(多服务器分组自动继承) - ActiveSessionItem 渲染 backgroundOnly 分支:绿点脉冲 + 「后台任务运行中」,和 session 列表的判定同一口径 - 活跃 badge 计入合成条目;颜色语义修正为有未读通知才 accent (shell 活跃是「还在干活」不是「要你看」) --- .../chat/sidebar/ActiveSessionItem.tsx | 7 ++- src/features/chat/sidebar/SidePanel.tsx | 58 ++++++++++++++++--- src/store/activeSessionStore.ts | 5 ++ src/store/shellInventoryStore.test.ts | 21 +++++++ src/store/shellInventoryStore.ts | 22 +++++++ 5 files changed, 103 insertions(+), 10 deletions(-) diff --git a/src/features/chat/sidebar/ActiveSessionItem.tsx b/src/features/chat/sidebar/ActiveSessionItem.tsx index fbfbefbf5..79f917ea4 100644 --- a/src/features/chat/sidebar/ActiveSessionItem.tsx +++ b/src/features/chat/sidebar/ActiveSessionItem.tsx @@ -21,9 +21,10 @@ export function ActiveSessionItem({ entry, resolvedSession, isSelected, onSelect // 目录优先从 resolvedSession 取 const directory = resolvedSession?.location?.directory || entry.directory - // 状态显示:permission > question > retry > working - const statusConfig = - pending?.type === 'permission' + // 状态显示:backgroundOnly(仅后台 shell 活跃)> permission > question > retry > working + const statusConfig = entry.backgroundOnly + ? { label: t('activeSession.backgroundRunning'), color: 'text-success-100', dotColor: 'bg-success-100', pulse: true } + : pending?.type === 'permission' ? { label: t('activeSession.awaitingPermission'), color: 'text-warning-100', diff --git a/src/features/chat/sidebar/SidePanel.tsx b/src/features/chat/sidebar/SidePanel.tsx index 11938db01..b848aca18 100644 --- a/src/features/chat/sidebar/SidePanel.tsx +++ b/src/features/chat/sidebar/SidePanel.tsx @@ -5,6 +5,7 @@ import { FolderRecentList } from './FolderRecentList' import { MultiServerFolderList } from './MultiServerFolderList' import { SearchResults } from './SearchResults' import { SessionShellsSlot } from './SessionShellsSlot' +import { shellInventoryStore, useShellActiveSessionIds } from '../../../store/shellInventoryStore' import { useMultiServerStore, multiServerStore } from '../../../store/multiServerStore' import { useServerStore } from '../../../hooks/useServerStore' import { getProjectGroupIdentity } from './projectGrouping' @@ -31,7 +32,7 @@ import { import { useDirectory, useKeybindingLabel, useVcsInfo } from '../../../hooks' import { useSessionContext } from '../../../contexts/useSessionContext' import { useLayoutStore, childSessionStore } from '../../../store' -import { useBusySessions, useBusyCount } from '../../../store/activeSessionStore' +import { useBusySessions, useBusyCount, type ActiveSessionEntry } from '../../../store/activeSessionStore' import { notificationStore, useNotifications, useUnreadNotificationCount } from '../../../store/notificationStore' import { pinnedSessionsStore } from '../../../store/pinnedSessionsStore' import { serverStore } from '../../../store/serverStore' @@ -307,7 +308,6 @@ export function SidePanel({ // Notification history const notifications = useNotifications() const unreadNotificationCount = useUnreadNotificationCount() - const attentionCount = busyCount + unreadNotificationCount useEffect(() => { return subscribeToConnectionState(setConnectionState) @@ -342,6 +342,50 @@ export function SidePanel({ return map }, [sessions, fetchedSessions]) + // 活跃 tab 要发现「idle 但后台 shell 在跑」的会话:库存按目录隔离且只拉 + // 登记过的目录,挂载行只登记自己可见的——这里把所有已知会话的目录都登记上, + // 否则那些目录的库存根本不会出现(先有鸡先有蛋) + const sessionDirectoriesKey = useMemo(() => { + const dirs = new Set() + for (const session of sessionLookup.values()) { + const dir = session.location?.directory + if (dir) dirs.add(dir) + } + return [...dirs].sort().join('\n') + }, [sessionLookup]) + useEffect(() => { + if (!sessionDirectoriesKey) return + const untracks = sessionDirectoriesKey.split('\n').map(dir => shellInventoryStore.trackDirectory(dir)) + return () => untracks.forEach(untrack => untrack()) + }, [sessionDirectoriesKey]) + + // 后台 shell 在跑但不在 busy 名单里的会话 → 合成活跃条目(backgroundOnly)。 + // 会话对象必须能从 lookup 解析(否则标题/目录都没有,挂出来也是死行) + const shellActiveSessionIds = useShellActiveSessionIds() + const shellActiveEntries = useMemo(() => { + const busyRawIds = new Set(busySessions.map(entry => splitSessionKey(entry.sessionId).sessionId)) + const entries: ActiveSessionEntry[] = [] + for (const rawId of shellActiveSessionIds) { + if (busyRawIds.has(rawId)) continue + const session = sessionLookup.get(rawId) + if (!session) continue + entries.push({ + sessionId: makeSessionKey(serverStore.getActiveServerId(), rawId), + status: { type: 'idle' }, + backgroundOnly: true, + title: session.title, + directory: session.location?.directory, + }) + } + return entries + }, [shellActiveSessionIds, busySessions, sessionLookup]) + + const mergedBusySessions = useMemo( + () => [...busySessions, ...shellActiveEntries], + [busySessions, shellActiveEntries], + ) + const attentionCount = busyCount + shellActiveEntries.length + unreadNotificationCount + const orderedSessions = useMemo(() => { const pinnedSet = new Set(pinnedEntries.map(e => e.sessionId)) const pinned = pinnedEntries @@ -550,8 +594,8 @@ export function SidePanel({ ]) const activeSessionTree = useMemo( - () => buildActiveSessionTree(busySessions, findParentId), - [busySessions, findParentId], + () => buildActiveSessionTree(mergedBusySessions, findParentId), + [mergedBusySessions, findParentId], ) // worktree 不合并进项目:每个已保存目录都是独立文件夹(见 projectGrouping.ts) @@ -1344,7 +1388,7 @@ export function SidePanel({ {attentionCount > 0 && ( busyCount + unreadNotificationCount > 0 ? 'bg-accent-main-100/10 text-accent-main-100' : 'bg-success-100/10 text-success-100' }`} @@ -1460,7 +1504,7 @@ export function SidePanel({ {/* Active Sessions Tab */} {sidebarTab === 'active' && (
- {busySessions.length === 0 && notifications.length === 0 ? ( + {mergedBusySessions.length === 0 && notifications.length === 0 ? (

{t('sidebar.noActiveSessions')}

@@ -1527,7 +1571,7 @@ export function SidePanel({ {/* Divider + actions between busy and notifications */} {notifications.length > 0 && (
0 ? 'mt-2 pt-2 border-t border-border-200/30' : ''}`} + className={`flex items-center justify-between gap-2 ${mergedBusySessions.length > 0 ? 'mt-2 pt-2 border-t border-border-200/30' : ''}`} > {t('sidebar.notifications')} diff --git a/src/store/activeSessionStore.ts b/src/store/activeSessionStore.ts index 582a358c5..123e5f3e7 100644 --- a/src/store/activeSessionStore.ts +++ b/src/store/activeSessionStore.ts @@ -35,6 +35,11 @@ export interface ActiveSessionEntry { type: 'permission' | 'question' description?: string } + /** + * 合成条目标记:会话本身 idle,仅因后台 shell 在跑而被视为活跃 + * (SidePanel 活跃 tab 从 shellInventoryStore 合成,status 是 idle 占位) + */ + backgroundOnly?: boolean } interface ActiveSessionState { diff --git a/src/store/shellInventoryStore.test.ts b/src/store/shellInventoryStore.test.ts index 0f32f9614..40c323b5f 100644 --- a/src/store/shellInventoryStore.test.ts +++ b/src/store/shellInventoryStore.test.ts @@ -134,4 +134,25 @@ describe('shellInventoryStore(按目录登记 + 事件驱动 + 兜底轮询) untrackB() unsubscribe() }) + + it('collectShellActiveSessionIds:跨目录收集有 running shell 的会话(活跃 tab 合成用)', async () => { + listShellsMock.mockImplementation(async (directory: string) => + directory === '/a' + ? [makeShell('sh-a1', 's1'), makeShell('sh-a2', 's1', 'exited')] + : [makeShell('sh-b1', 's2'), makeShell('sh-b2', 's3', 'killed')], + ) + const unsubscribe = shellInventoryStore.subscribe(() => {}) + const untrackA = shellInventoryStore.trackDirectory('/a') + const untrackB = shellInventoryStore.trackDirectory('/b') + await vi.advanceTimersByTimeAsync(0) + + const ids = new Set() + shellInventoryStore.collectShellActiveSessionIds(ids) + // s1 有一个 exited 但还有一个 running → 活跃;s3 只有 killed → 不算 + expect([...ids].sort()).toEqual(['s1', 's2']) + + untrackA() + untrackB() + unsubscribe() + }) }) diff --git a/src/store/shellInventoryStore.ts b/src/store/shellInventoryStore.ts index 3515efb20..d22602ffe 100644 --- a/src/store/shellInventoryStore.ts +++ b/src/store/shellInventoryStore.ts @@ -60,6 +60,17 @@ class ShellInventoryStore { getShellsForDir = (directory?: string): ShellInfo[] => (directory && this.shellsByDir.get(directory)) || EMPTY_SHELLS + /** 收集所有已登记目录里「有 running shell」的会话 raw id(活跃 tab 合成条目用,非响应式) */ + collectShellActiveSessionIds = (out: Set): void => { + for (const shells of this.shellsByDir.values()) { + for (const shell of shells) { + if (shell.status !== 'running') continue + const sessionID = shell.metadata?.sessionID + if (typeof sessionID === 'string') out.add(sessionID) + } + } + } + /** 登记关心的目录(引用计数)。首次登记立即拉取,归零后丢弃该目录数据 */ trackDirectory = (directory: string): (() => void) => { const count = this.dirRefs.get(directory) ?? 0 @@ -154,3 +165,14 @@ export function useHasBackgroundShells(rawSessionId: string, directory?: string) const shells = useShellsForDir(directory) return useMemo(() => runningShellsForSession(shells, rawSessionId).length > 0, [shells, rawSessionId]) } + +/** 所有已登记目录里「有 running shell」的会话 raw id 集合(SidePanel 活跃 tab 合成条目用) */ +export function useShellActiveSessionIds(): Set { + const version = useSyncExternalStore(shellInventoryStore.subscribe, shellInventoryStore.getVersion) + return useMemo(() => { + const ids = new Set() + shellInventoryStore.collectShellActiveSessionIds(ids) + return ids + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [version]) +} From 146db2a39c8e5d9ea2fef778cbc533dc27028a2d Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 22:21:57 +0800 Subject: [PATCH 35/91] =?UTF-8?q?feat(sessions):=20shell=20=E8=BE=93?= =?UTF-8?q?=E5=87=BA=E5=BC=B9=E7=AA=97=E5=A4=8D=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E6=B5=81=E6=B2=89=E6=B5=B8=E6=A8=A1=E5=BC=8F=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E5=8D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 不再自己糊 pre 输出块:ShellInfo + 实时输出投影成 ToolViewPart (ShellMessageView 同款投影逻辑),交给 ToolPartView descriptive 变体渲染——头行命令/耗时/shimmer、输出体、running 展开结束折叠, 交互与信息流里的 shell 卡片完全一致。 - 折叠状态 key 用 shell.id 作 messageID,与信息流同 shell 卡片的 展开状态天然隔开互不影响 - 卡片不管的留在底部行:cwd、非零退出码高亮、运行中停止按钮 - 顺手清掉不再用的 shell.status.*/emptyOutput i18n key --- .../chat/sidebar/SessionShellsSlot.test.tsx | 18 ++-- .../chat/sidebar/ShellOutputDialog.tsx | 102 ++++++++++++------ src/locales/en/commands.json | 9 +- src/locales/zh-CN/commands.json | 9 +- 4 files changed, 83 insertions(+), 55 deletions(-) diff --git a/src/features/chat/sidebar/SessionShellsSlot.test.tsx b/src/features/chat/sidebar/SessionShellsSlot.test.tsx index b1f067b46..aa966f6d6 100644 --- a/src/features/chat/sidebar/SessionShellsSlot.test.tsx +++ b/src/features/chat/sidebar/SessionShellsSlot.test.tsx @@ -2,6 +2,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { ShellInfo } from '@opencode/client/promise' import { createSessionPlaceholder } from '../../../utils/sessionPlaceholder' +import { FullscreenProvider } from '../../../contexts/FullscreenContext' const { listShellsMock, removeShellMock, getShellOutputMock } = vi.hoisted(() => ({ listShellsMock: vi.fn(), @@ -76,21 +77,26 @@ describe('SessionShellsSlot(后台 shell 挂载)', () => { await waitFor(() => expect(listShellsMock.mock.calls.length).toBeGreaterThan(callsBefore), { timeout: 2000 }) }) - it('点击行打开输出弹窗(打开时存快照,shell 退出列表后弹窗不闪关)', async () => { + it('点击行打开输出弹窗(工具卡 UI + 快照,shell 退出列表后弹窗不闪关)', async () => { getShellOutputMock.mockResolvedValue({ output: 'hello\n', cursor: 6, size: 6, truncated: false }) listShellsMock.mockResolvedValue([makeShell('sh-1', 'session-1', 'npm run dev')]) - render() + // 工具卡的 BashRenderer 需要 FullscreenProvider(app 根部有,测试自己包) + render( + + + , + ) fireEvent.click(await screen.findByText('npm run dev')) - // 弹窗打开:状态行出现「运行中」 - await screen.findByText('Running') + // 信息流同款工具卡:running 起始展开,实时输出直接可见 + await screen.findByText(/hello/) // shell 退出 → 离开 running 列表(挂载行消失),但弹窗靠快照继续开着 listShellsMock.mockResolvedValue([{ ...makeShell('sh-1', 'session-1'), status: 'exited', exit: 0 } as ShellInfo]) shellInventoryStore.requestRefresh() await waitFor(() => expect(screen.queryByTitle('Stop this shell')).not.toBeInTheDocument(), { timeout: 2000 }) - // 弹窗仍在,状态随后续库存刷新翻成 Exited + // 弹窗仍在,底部行随后续库存刷新出现退出码 expect(screen.getByRole('dialog')).toBeInTheDocument() - await screen.findByText('Exited', {}, { timeout: 2000 }) + await screen.findByText('Exit code 0', {}, { timeout: 2000 }) }) }) diff --git a/src/features/chat/sidebar/ShellOutputDialog.tsx b/src/features/chat/sidebar/ShellOutputDialog.tsx index 31cdf5759..438f4ac6e 100644 --- a/src/features/chat/sidebar/ShellOutputDialog.tsx +++ b/src/features/chat/sidebar/ShellOutputDialog.tsx @@ -1,19 +1,22 @@ // ============================================ // ShellOutputDialog — 后台 shell 的输出查看弹窗 // -// 回答「这个后台 shell 在跑什么」: -// - 输出实时跟随(followShellOutput 游标轮询,和转写里 shell 卡片同款通道) -// - 状态随库存刷新(shellInventoryStore:running/exited/timeout/killed + 退出码) -// - 运行中可停止(shell.remove,官方 session-running-menu 的 × 同款) +// UI 直接复用信息流里的 shell 工具卡(ToolPartView): +// 把 ShellInfo + 实时输出投影成 ToolViewPart,和 ShellMessageView +// (`!` shell 命令消息)同款投影逻辑——running 展开跟输出, +// 结束后折叠、点头行展开,交互与信息流完全一致。 +// 卡片不管的事弹窗自己补:cwd 展示 + 停止按钮(shell.remove)。 // ============================================ -import { useEffect, useMemo, useRef, useState } from 'react' +import { useEffect, useMemo, useState } from 'react' import { useTranslation } from 'react-i18next' -import type { ShellInfo } from '@opencode/client/promise' +import type { JsonValue, ShellInfo } from '@opencode/client/promise' import { Button, Dialog } from '../../../components/ui' import { removeShell } from '../../../api/shell' import { shellInventoryStore, useShellsForDir } from '../../../store/shellInventoryStore' import { followShellOutput } from '../../message/shellOutput' +import { ToolPartView } from '../../message/parts' +import type { ToolViewPart } from '../../message/tools' import { uiErrorHandler } from '../../../utils' interface ShellOutputDialogProps { @@ -26,17 +29,13 @@ interface ShellOutputDialogProps { } export function ShellOutputDialog({ shell, directory, onClose, serverId }: ShellOutputDialogProps) { - const { t } = useTranslation(['commands', 'common']) + const { t } = useTranslation(['commands', 'common', 'chat']) const [output, setOutput] = useState('') const [stopping, setStopping] = useState(false) - const outputRef = useRef(null) // 状态以库存最新值为准(exited/退出码会随后台刷新到达;被 remove 后回落到传入快照) const inventory = useShellsForDir(directory) - const live = useMemo( - () => inventory.find(item => item.id === shell.id) ?? shell, - [inventory, shell], - ) + const live = useMemo(() => inventory.find(item => item.id === shell.id) ?? shell, [inventory, shell]) const running = live.status === 'running' // 实时输出跟随(游标增量;组件卸载即停) @@ -50,12 +49,6 @@ export function ShellOutputDialog({ shell, directory, onClose, serverId }: Shell }) }, [shell.id, directory, serverId]) - // 新输出自动滚到底 - useEffect(() => { - const el = outputRef.current - if (el) el.scrollTop = el.scrollHeight - }, [output]) - const handleStop = async () => { if (stopping) return setStopping(true) @@ -69,35 +62,78 @@ export function ShellOutputDialog({ shell, directory, onClose, serverId }: Shell } } - const statusLabel = t(`sessions.shell.status.${live.status}`) - const statusColor = running ? 'text-success-100' : live.status === 'exited' && live.exit === 0 ? 'text-text-400' : 'text-warning-100' + // ShellInfo → ToolViewPart 投影(ShellMessageView 同款: + // input=command、output=输出文本、metadata 带 shellID/exit) + const part = useMemo(() => { + const input = { command: live.command } + const metadata: Record = { shellID: live.id } + let state: ToolViewPart['state'] + if (live.status === 'running') { + state = { + status: 'running', + input, + metadata: output ? { ...metadata, output } : metadata, + } + } else if (live.status === 'timeout' || live.status === 'killed') { + state = { + status: 'error', + input, + error: { + type: 'ShellError', + message: t(live.status === 'timeout' ? 'chat:shellMessage.timeout' : 'chat:shellMessage.killed'), + }, + ...(output ? { content: [{ type: 'text' as const, text: output }] } : {}), + metadata, + } + } else { + if (typeof live.exit === 'number') metadata.exit = live.exit + state = { + status: 'completed', + input, + content: [{ type: 'text' as const, text: output }], + metadata, + } + } + return { + type: 'tool', + id: live.id, + name: 'shell', + // messageID 用 shell.id:折叠状态 key(message::tool:)与信息流里 + // 的同 shell 卡片(mid=消息 id)天然隔开,两边展开状态互不影响 + messageID: live.id, + state, + time: { created: live.time.started, completed: live.time.completed }, + } + }, [live, output, t]) return ( - +
- {/* 状态行:状态 + 退出码 + cwd */} + {/* 信息流沉浸模式同款 shell 工具卡:头行(名称+命令+耗时)+ 输出体 */} + + + {/* 卡片不管的:cwd + 退出码 + 停止 */}
- {statusLabel} {typeof live.exit === 'number' && ( - {t('sessions.shell.exitCode', { code: live.exit })} + + {t('commands:sessions.shell.exitCode', { code: live.exit })} + )} {live.cwd} {running && ( )}
- - {/* 输出:等宽 + 跟随滚动 */} -
-          {output || {t('sessions.shell.emptyOutput')}}
-        
) diff --git a/src/locales/en/commands.json b/src/locales/en/commands.json index f399178d9..4b48b6c9b 100644 --- a/src/locales/en/commands.json +++ b/src/locales/en/commands.json @@ -67,14 +67,7 @@ "outputTitle": "Background shell output", "stop": "Stop", "stopTitle": "Stop this shell", - "exitCode": "Exit code {{code}}", - "emptyOutput": "(no output yet)", - "status": { - "running": "Running", - "exited": "Exited", - "timeout": "Timed out", - "killed": "Killed" - } + "exitCode": "Exit code {{code}}" }, "searchChats": "Search chats...", "newChat": "New Chat", diff --git a/src/locales/zh-CN/commands.json b/src/locales/zh-CN/commands.json index 98954b5a9..c8a631b0e 100644 --- a/src/locales/zh-CN/commands.json +++ b/src/locales/zh-CN/commands.json @@ -67,14 +67,7 @@ "outputTitle": "后台 shell 输出", "stop": "停止", "stopTitle": "停止该 shell", - "exitCode": "退出码 {{code}}", - "emptyOutput": "(暂无输出)", - "status": { - "running": "运行中", - "exited": "已退出", - "timeout": "超时", - "killed": "已终止" - } + "exitCode": "退出码 {{code}}" }, "searchChats": "搜索对话...", "newChat": "新对话", From 31cb107a5ad11b60245eed91357814fd8fcd45a3 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 23:01:32 +0800 Subject: [PATCH 36/91] =?UTF-8?q?feat(message):=20bash/shell=20=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E5=8D=A1=E8=BF=90=E8=A1=8C=E4=B8=AD=E5=AE=9E=E6=97=B6?= =?UTF-8?q?=E8=BE=93=E5=87=BA=E8=B7=9F=E9=9A=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 信息流里的 bash/shell 工具卡之前只有结束后才显示输出——v2 的 shell 工具一启动就 progress({ shellID })(core/tool/plugin/shell.ts), 官方渲染器靠 metadata.shellID + shell.output 游标轮询做实时输出, 我们漏了这路。 - BashRenderer 从 state.metadata.shellID 拿句柄,running 期间 followShellOutput 游标轮询(官方 session-ui tool-renderer 同款), 存活期间以流式输出为准,结束后 content 里的最终 output 是权威 - 目录上下文用可选读取(useContext(DirectoryContext) 而非会抛错的 useDirectory):没有 provider 的环境不启用跟随而不是炸掉 - ShellOutputDialog 投影不再带 shellID:卡片里的 BashRenderer 会用 全局 currentDirectory 自己起跟随,弹窗的 shell 可能属于别的工作区, 错目录轮询会把共享缓存毒成 missing,卡死弹窗自己那路正确的跟随 --- .../chat/sidebar/ShellOutputDialog.tsx | 8 +- .../tools/renderers/BashRenderer.test.tsx | 92 +++++++++++++++++++ .../message/tools/renderers/BashRenderer.tsx | 31 ++++++- 3 files changed, 127 insertions(+), 4 deletions(-) create mode 100644 src/features/message/tools/renderers/BashRenderer.test.tsx diff --git a/src/features/chat/sidebar/ShellOutputDialog.tsx b/src/features/chat/sidebar/ShellOutputDialog.tsx index 438f4ac6e..c3dbaaecd 100644 --- a/src/features/chat/sidebar/ShellOutputDialog.tsx +++ b/src/features/chat/sidebar/ShellOutputDialog.tsx @@ -63,10 +63,14 @@ export function ShellOutputDialog({ shell, directory, onClose, serverId }: Shell } // ShellInfo → ToolViewPart 投影(ShellMessageView 同款: - // input=command、output=输出文本、metadata 带 shellID/exit) + // input=command、output=输出文本、metadata 带 exit)。 + // 注意 metadata 不放 shellID:BashRenderer 看到 shellID 会用全局 + // currentDirectory 自己起一路跟随——弹窗的 shell 可能属于别的工作区, + // 错目录轮询会把共享缓存毒成 missing,反而卡死弹窗自己这路正确的跟随。 + // 弹窗的实时输出由本组件的 followShellOutput(正确目录)喂进 metadata.output。 const part = useMemo(() => { const input = { command: live.command } - const metadata: Record = { shellID: live.id } + const metadata: Record = {} let state: ToolViewPart['state'] if (live.status === 'running') { state = { diff --git a/src/features/message/tools/renderers/BashRenderer.test.tsx b/src/features/message/tools/renderers/BashRenderer.test.tsx new file mode 100644 index 000000000..6a5e8cf22 --- /dev/null +++ b/src/features/message/tools/renderers/BashRenderer.test.tsx @@ -0,0 +1,92 @@ +import { render, screen } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { JsonValue } from '@opencode/client/promise' +import { BashRenderer } from './BashRenderer' +import { FullscreenProvider } from '../../../../contexts' +import { DirectoryContext, type DirectoryContextValue } from '../../../../contexts/DirectoryContext.shared' +import type { ToolViewPart } from '../index' + +const { getShellOutputMock } = vi.hoisted(() => ({ + getShellOutputMock: vi.fn(), +})) + +vi.mock('../../../../api/shell', () => ({ + getShellOutput: (...args: unknown[]) => getShellOutputMock(...args), + listShells: vi.fn(), + removeShell: vi.fn(), +})) + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (key: string) => key, + }), +})) + +function runningPart(metadata: Record): ToolViewPart { + return { + type: 'tool', + id: 'tool-1', + name: 'shell', + messageID: 'message-1', + state: { + status: 'running', + input: { command: 'npm run dev' }, + metadata, + }, + time: { created: 1_000 }, + } +} + +const directoryValue = { currentDirectory: '/repo' } as unknown as DirectoryContextValue + +function renderBash(part: ToolViewPart, data: Parameters[0]['data']) { + return render( + + + + + , + ) +} + +describe('BashRenderer 运行中流式输出(官方 followShellOutput 同款)', () => { + beforeEach(() => { + getShellOutputMock.mockReset() + }) + + it('running + metadata.shellID → 游标轮询实时输出并显示', async () => { + getShellOutputMock.mockResolvedValue({ output: 'vite dev ready\nlistening on 5173\n', cursor: 34, size: 34, truncated: false }) + renderBash(runningPart({ shellID: 'sh-1' }), { input: 'npm run dev' }) + + // 实时输出直接出现在输出区(不等工具结束) + await screen.findByText(/listening on 5173/) + expect(getShellOutputMock).toHaveBeenCalledWith('sh-1', 0, '/repo', undefined) + }) + + it('running 但没有 shellID → 不轮询(拿不到 shell 句柄,只能等结束)', async () => { + renderBash(runningPart({}), { input: 'npm run dev' }) + // 给可能的轮询留时间(首轮是立即发起的) + await new Promise(resolve => setTimeout(resolve, 100)) + expect(getShellOutputMock).not.toHaveBeenCalled() + }) + + it('completed → 不轮询,显示 content 里的最终输出', async () => { + const part: ToolViewPart = { + type: 'tool', + id: 'tool-1', + name: 'bash', + messageID: 'message-1', + state: { + status: 'completed', + input: { command: 'echo done' }, + metadata: { shellID: 'sh-1', exit: 0 }, + content: [{ type: 'text', text: 'done' }], + }, + time: { created: 1_000, completed: 2_000 }, + } + renderBash(part, { input: 'echo done', output: 'done' }) + await screen.findByText('done') + await new Promise(resolve => setTimeout(resolve, 100)) + expect(getShellOutputMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/features/message/tools/renderers/BashRenderer.tsx b/src/features/message/tools/renderers/BashRenderer.tsx index eb062540b..92b3da992 100644 --- a/src/features/message/tools/renderers/BashRenderer.tsx +++ b/src/features/message/tools/renderers/BashRenderer.tsx @@ -8,13 +8,17 @@ * - exit code 内联在输出末尾 */ -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import { MaximizeIcon, MinimizeIcon } from '../../../../components/Icons' import { useFullscreen } from '../../../../contexts' +import { DirectoryContext } from '../../../../contexts/DirectoryContext.shared' +import { useInlineToolRequests } from '../../../chat/InlineToolRequestContext' import { useSyntaxHighlight } from '../../../../hooks/useSyntaxHighlight' import { useResponsiveMaxHeight } from '../../../../hooks/useResponsiveMaxHeight' import { parseAnsi, type AnsiSegment } from '../../../../utils/ansiUtils' +import { currentToolMetadata } from '../../../../types/api' +import { followShellOutput } from '../../shellOutput' import { copyTextToClipboard, clipboardErrorHandler } from '../../../../utils' import type { ToolRendererProps } from '../types' @@ -28,7 +32,30 @@ export function BashRenderer({ part, data, onFullscreenChange }: ToolRendererPro const isActive = state.status === 'running' || state.status === 'streaming' const hasError = !!data.error const command = data.input?.trim() - const output = data.output?.trim() + // 运行中 shell 的实时输出跟随(官方 session-ui shell 渲染器同款): + // v2 shell 工具一启动就 progress({ shellID }),事件流只在结束时给最终 + // output,存活期间靠 shell.output 游标轮询。目录上下文用可选读取—— + // 没有 DirectoryProvider 的环境(部分测试)不启用跟随,而不是炸掉。 + const shellID = (() => { + const metadata = currentToolMetadata(part) + return typeof metadata.shellID === 'string' ? metadata.shellID : undefined + })() + const directoryContext = useContext(DirectoryContext) + const currentDirectory = directoryContext?.currentDirectory + const { serverId } = useInlineToolRequests() + const [streamedOutput, setStreamedOutput] = useState('') + useEffect(() => { + if (!isActive || !shellID || !currentDirectory) return + return followShellOutput({ + id: shellID, + directory: currentDirectory, + serverId: serverId || undefined, + running: true, + onOutput: setStreamedOutput, + }) + }, [isActive, shellID, currentDirectory, serverId]) + // 存活期间以流式输出为准;结束后 content 里的最终 output 是权威 + const output = (isActive && shellID ? streamedOutput.trim() : '') || data.output?.trim() const cwd = data.cwd?.trim() const exitCode = data.exitCode const maxHeight = useResponsiveMaxHeight() From cd3a793c38b1511fa2c4e72b0e538dc45e37fc44 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 23:01:32 +0800 Subject: [PATCH 37/91] =?UTF-8?q?fix(message):=20followShellOutput=20UTF-8?= =?UTF-8?q?=20=E8=BE=B9=E7=95=8C=E8=87=AA=E6=84=88=EF=BC=8C=E4=BF=AE?= =?UTF-8?q?=E6=B5=81=E5=BC=8F=E8=BE=93=E5=87=BA=E7=9A=84=E4=B8=AD=E6=96=87?= =?UTF-8?q?=E4=B9=B1=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 服务端 shell.output 按字节区间独立 decode(core/shell.ts: buffer.subarray(...).toString('utf8')),多字节字符被区间边界 切开就永久变成 U+FFFD——逐字打印中文的命令(printf 逐字循环) 流式期间满屏 �,结束后又正常(最终 output 是完整 decode 的)。 官方客户端同款毛病,我们修掉: - 页尾出现 U+FFFD → 区间终点切在字符中间:剥掉替换符,游标按 每符 1 字节回退,下轮从(大概率)lead 字节干净续上 - 页头出现 U+FFFD → 上次回退字节数猜错了、游标落在字符中间: 回滚到追加前的存档点(一定是干净边界)整段重读 - 输出本身含 U+FFFD 的极端情况:同一位置只自愈一次,再失败原样 接受,不死循环(真实替换符恰好恢复一次) - 信息流 bash 卡、! 命令消息、后台 shell 弹窗三路共用此函数,一起修好 --- src/features/message/shellOutput.test.ts | 97 +++++++++++++++++++++++- src/features/message/shellOutput.ts | 38 +++++++++- 2 files changed, 131 insertions(+), 4 deletions(-) diff --git a/src/features/message/shellOutput.test.ts b/src/features/message/shellOutput.test.ts index 5d0bbae78..8c8dad99a 100644 --- a/src/features/message/shellOutput.test.ts +++ b/src/features/message/shellOutput.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { followShellOutput, SHELL_OUTPUT_TAIL_BYTES } from './shellOutput' const loadMock = vi.fn() @@ -93,3 +93,98 @@ describe('followShellOutput(官方 shell-output.ts 同款)', () => { expect(loadMock.mock.calls.at(-1)?.[1]).toBe(5) }) }) + +// ============================================ +// UTF-8 边界自愈 +// 服务端 shell.output 按字节区间独立 decode(core/shell.ts), +// 多字节字符跨区间会被切成 U+FFFD。这里按字节流精确模拟分页, +// 验证累计文本永远干净。 +// ============================================ + +// 'ab流cd' 的字节布局:a b [E4 B5 81] c d(流 = 3 字节) +function page(output: string, cursor: number, size: number) { + return { output, cursor, size, truncated: false } +} + +describe('followShellOutput UTF-8 边界自愈', () => { + beforeEach(() => { + loadMock.mockReset() + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('页尾切在字符第 1 字节后(r=1):剥离回退,下页从 lead 字节干净续上', async () => { + const outputs: string[] = [] + loadMock + // [0,3):'a','b',E4 → decode 'ab�',游标 3 + .mockResolvedValueOnce(page('ab�', 3, 3)) + // 自愈后游标 2:[2,7) 从 lead 字节开始 → '流cd' + .mockResolvedValueOnce(page('流cd', 7, 7)) + .mockResolvedValue(page('', 7, 7)) + + const dispose = followShellOutput({ id: 'sh-r1', running: true, onOutput: o => outputs.push(o) }) + await vi.advanceTimersByTimeAsync(0) + expect(outputs.at(-1)).toBe('ab') + expect(loadMock.mock.calls[0][1]).toBe(0) + + await vi.advanceTimersByTimeAsync(1000) + // 第二轮请求用的是剥离后的游标 2 + expect(loadMock.mock.calls[1][1]).toBe(2) + expect(outputs.at(-1)).toBe('ab流cd') + dispose() + }) + + it('页尾切在第 2 字节后(r=2,猜测回退过头):页头检查回滚存档点整段重读', async () => { + const outputs: string[] = [] + loadMock + // [0,4):'a','b',E4,B5 → decode 'ab�',游标 4;剥离 1 符 → 游标 3(落在字符中间) + .mockResolvedValueOnce(page('ab�', 4, 4)) + // [3,7):从 continuation 字节开始 → decode '�cd' → 页头检查失败,回滚到 0 + .mockResolvedValueOnce(page('�cd', 7, 7)) + // [0,7) 整段重读 → 干净 + .mockResolvedValueOnce(page('ab流cd', 7, 7)) + .mockResolvedValue(page('', 7, 7)) + + const dispose = followShellOutput({ id: 'sh-r2', running: true, onOutput: o => outputs.push(o) }) + await vi.advanceTimersByTimeAsync(0) + expect(outputs.at(-1)).toBe('ab') + + // 第二轮:游标 3 落在字符中间 → 页头检查 → 回滚到存档点 0 + await vi.advanceTimersByTimeAsync(1000) + expect(loadMock.mock.calls[1][1]).toBe(3) + + // 第三轮:从存档点 0 整段重读,文本自愈 + await vi.advanceTimersByTimeAsync(1000) + expect(loadMock.mock.calls[2][1]).toBe(0) + expect(outputs.at(-1)).toBe('ab流cd') + expect(outputs.at(-1)).not.toContain('�') + dispose() + }) + + it('输出本身含 U+FFFD:同一位置不重复自愈,原样接受避免死循环', async () => { + const outputs: string[] = [] + loadMock + // 文件里真的有 U+FFFD(3 字节 EF BF BD),页尾恰好切在它后面 + .mockResolvedValueOnce(page('ab�', 5, 5)) + // 剥离 1 符游标 4 → [4,...) 从真实 U+FFFD 的第 3 字节开始 → 页头又是 � + .mockResolvedValueOnce(page('�x', 7, 7)) + // 回滚到 0 重读:同样的页尾,同样剥离 → 游标又到 4 → 页头又失败 + .mockResolvedValueOnce(page('ab�', 5, 5)) + // 同一位置第二次 → 原样接受 + .mockResolvedValueOnce(page('�x', 7, 7)) + .mockResolvedValue(page('', 7, 7)) + + const dispose = followShellOutput({ id: 'sh-real', running: true, onOutput: o => outputs.push(o) }) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(1000) + await vi.advanceTimersByTimeAsync(1000) + await vi.advanceTimersByTimeAsync(1000) + + // 最终接受原样内容:真实 U+FFFD 恰好恢复一次(不多不少),且轮询没有卡死 + expect(outputs.at(-1)).toBe('ab�x') + dispose() + }) +}) diff --git a/src/features/message/shellOutput.ts b/src/features/message/shellOutput.ts index 3909ff23f..9ea9a5e23 100644 --- a/src/features/message/shellOutput.ts +++ b/src/features/message/shellOutput.ts @@ -46,6 +46,17 @@ export function followShellOutput(input: { let text = cached?.output ?? '' let loading = false let disposed = false + // ── UTF-8 边界自愈 ── + // 服务端按字节区间独立 decode(core/shell.ts: buffer.subarray(...).toString('utf8')), + // 多字节字符被区间边界切开就永久变成 U+FFFD(逐字打印中文的场景必现)。 + // 自愈规则: + // 1. 页头出现 U+FFFD → 上次「页尾剥离」猜错了回退字节数,游标落在字符中间。 + // 回滚到追加前的存档点,等字符写全后整段重读(存档点一定是干净边界) + // 2. 页尾出现 U+FFFD → 区间终点切在字符中间:剥掉替换符,游标按每符 1 字节 + // 回退(猜少了会被下一轮的规则 1 抓回来) + // 3. 输出本身含 U+FFFD 的极端情况:同一位置只自愈一次,再失败原样接受,不死循环 + let savepoint = { cursor, text } + let recoveredAt = -1 const read = async () => { if (loading) return loading = true @@ -62,9 +73,30 @@ export function followShellOutput(input: { break } if (!page) break - const advanced = page.cursor > cursor - cursor = Math.max(cursor, page.cursor) - text = (text + page.output).slice(-SHELL_OUTPUT_TAIL_BYTES) + + // 规则 1:页头替换符 → 游标在字符中间,回滚到存档点整段重读 + if (page.output.startsWith('�') && recoveredAt !== cursor) { + recoveredAt = cursor + cursor = savepoint.cursor + text = savepoint.text + remember(input.id, { cursor, output: text, state: 'partial' }) + break + } + + // 规则 2:页尾替换符 → 剥掉,游标按每符 1 字节回退 + let output = page.output + let pageCursor = page.cursor + const tail = output.match(/�+$/) + if (tail) { + output = output.slice(0, -tail[0].length) + pageCursor -= tail[0].length + } + + // 追加前存档(下一轮的页头检查若失败,回滚到这里) + savepoint = { cursor, text } + const advanced = pageCursor > cursor + cursor = Math.max(cursor, pageCursor) + text = (text + output).slice(-SHELL_OUTPUT_TAIL_BYTES) const complete = !input.running && cursor >= page.size remember(input.id, { cursor, output: text, state: complete ? 'complete' : 'partial' }) input.onOutput(text) From 1ed2b55fe770a78be8a96a7499d5637c964b80f8 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 23:22:08 +0800 Subject: [PATCH 38/91] =?UTF-8?q?feat(sessions):=20shell=20=E5=BA=93?= =?UTF-8?q?=E5=AD=98=E6=8E=A5=E5=85=A5=E5=85=A8=E5=B1=80=E4=BA=8B=E4=BB=B6?= =?UTF-8?q?=E7=9B=B4=E5=86=99=EF=BC=8C=E6=8C=82=E8=BD=BD/=E6=91=98?= =?UTF-8?q?=E4=B8=8B=E7=9A=84=E5=AE=9E=E6=97=B6=E6=80=A7=E5=AF=B9=E9=BD=90?= =?UTF-8?q?=E5=AE=98=E6=96=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前总觉得挂载比官方慢半拍,查了官方数据层(@opencode/client/solid) 找到根因:他们监听的是全局 shell.created/exited/deleted 事件—— created 带完整 ShellInfo 直接写进响应式 store,UI 即时更新; 我们只在 session.shell.started/ended 后防抖 500ms + HTTP 重取, 天然慢一拍还多一次往返。 - events.ts 路由 shell.created/exited/deleted(信封带 location 工作区引用) - shellInventoryStore 三个 applier:created 就地 upsert、exited 就地 更新状态/退出码(挂载行即时消失、弹窗状态即时翻转)、deleted 移除; 只写已登记目录,没目录信息退化为防抖重取兜底 - useGlobalEvents 接线,非活动服务器的事件忽略(库存只跟活动服务器) - listShells 首拉 + 15s 轮询保留,作事件丢失的对账层 - 已用 curl 实测服务端 SSE 确发这三个事件且带 location --- src/api/events.ts | 9 ++++ src/hooks/useGlobalEvents.ts | 18 ++++++++ src/store/shellInventoryStore.test.ts | 39 +++++++++++++++++ src/store/shellInventoryStore.ts | 60 +++++++++++++++++++++++++++ src/types/api/event.ts | 14 +++++++ 5 files changed, 140 insertions(+) diff --git a/src/api/events.ts b/src/api/events.ts index e42d73ec8..eb4807bb7 100644 --- a/src/api/events.ts +++ b/src/api/events.ts @@ -347,6 +347,15 @@ function dispatchEvent(callbacks: EventCallbacks, event: GlobalEvent): void { case 'session.shell.ended': callbacks.onShellEnded?.(event.data, facts) break + case 'shell.created': + callbacks.onShellInventoryCreated?.(event.data, event.location) + break + case 'shell.exited': + callbacks.onShellInventoryExited?.(event.data, event.location) + break + case 'shell.deleted': + callbacks.onShellInventoryDeleted?.(event.data, event.location) + break case 'session.skill.activated': callbacks.onSkillActivated?.(event.data, facts) break diff --git a/src/hooks/useGlobalEvents.ts b/src/hooks/useGlobalEvents.ts index 58c027b2f..b7d76e388 100644 --- a/src/hooks/useGlobalEvents.ts +++ b/src/hooks/useGlobalEvents.ts @@ -894,6 +894,24 @@ export function useGlobalEvents(directories?: string[]) { shellInventoryStore.requestRefresh() }, + // 全局 shell 库存事件:官方客户端数据层的实时来源——事件带完整 + // ShellInfo 直写库存,挂载行/活跃判定即时更新,不用等防抖重取。 + // 库存只跟活动服务器,其它服务器的事件忽略 + onShellInventoryCreated: (data, location) => { + if (serverId !== serverStore.getActiveServerId()) return + shellInventoryStore.applyShellCreated(location?.directory, data.info) + }, + + onShellInventoryExited: (data, location) => { + if (serverId !== serverStore.getActiveServerId()) return + shellInventoryStore.applyShellExited(location?.directory, data.id, data.status, data.exit) + }, + + onShellInventoryDeleted: (data, location) => { + if (serverId !== serverStore.getActiveServerId()) return + shellInventoryStore.applyShellDeleted(location?.directory, data.id) + }, + onSkillActivated: (data, facts) => { const scopedId = scope(data.sessionID) messageStore.handleSkillActivated({ ...data, sessionID: scopedId }, facts) diff --git a/src/store/shellInventoryStore.test.ts b/src/store/shellInventoryStore.test.ts index 40c323b5f..396f3be5a 100644 --- a/src/store/shellInventoryStore.test.ts +++ b/src/store/shellInventoryStore.test.ts @@ -155,4 +155,43 @@ describe('shellInventoryStore(按目录登记 + 事件驱动 + 兜底轮询) untrackB() unsubscribe() }) + + it('shell.created/exited/deleted 事件直写:即时生效不等重取(官方数据层同款)', async () => { + listShellsMock.mockResolvedValue([makeShell('sh-1', 's1')]) + const spy = vi.fn() + const unsubscribe = shellInventoryStore.subscribe(spy) + const untrack = shellInventoryStore.trackDirectory(DIR) + await vi.advanceTimersByTimeAsync(0) + const v0 = shellInventoryStore.getVersion() + spy.mockClear() + + // created:新 shell 立即 upsert(不发 listShells) + const callsBefore = listShellsMock.mock.calls.length + shellInventoryStore.applyShellCreated(DIR, makeShell('sh-2', 's1')) + expect(shellInventoryStore.getShellsForDir(DIR).map(s => s.id)).toEqual(['sh-1', 'sh-2']) + expect(shellInventoryStore.getVersion()).toBe(v0 + 1) + expect(spy).toHaveBeenCalled() + expect(listShellsMock.mock.calls.length).toBe(callsBefore) + + // exited:就地更新状态/退出码(running 过滤立即排除) + shellInventoryStore.applyShellExited(DIR, 'sh-2', 'exited', 0) + const shells = shellInventoryStore.getShellsForDir(DIR) + expect(shells.find(s => s.id === 'sh-2')?.status).toBe('exited') + expect(shells.find(s => s.id === 'sh-2')?.exit).toBe(0) + expect(runningShellsForSession(shells, 's1').map(s => s.id)).toEqual(['sh-1']) + + // deleted:移除 + shellInventoryStore.applyShellDeleted(DIR, 'sh-2') + expect(shellInventoryStore.getShellsForDir(DIR).map(s => s.id)).toEqual(['sh-1']) + + // 未登记目录的事件不维护(登记时会全量拉);无目录退化为防抖重取 + shellInventoryStore.applyShellCreated('/not-tracked', makeShell('sh-9', 's9')) + expect(shellInventoryStore.getShellsForDir('/not-tracked')).toEqual([]) + shellInventoryStore.applyShellCreated(undefined, makeShell('sh-9', 's9')) + await vi.advanceTimersByTimeAsync(600) + expect(listShellsMock.mock.calls.length).toBeGreaterThan(callsBefore) + + untrack() + unsubscribe() + }) }) diff --git a/src/store/shellInventoryStore.ts b/src/store/shellInventoryStore.ts index d22602ffe..42a3e152b 100644 --- a/src/store/shellInventoryStore.ts +++ b/src/store/shellInventoryStore.ts @@ -97,6 +97,66 @@ class ShellInventoryStore { }, REFRESH_DEBOUNCE_MS) } + /** + * shell.created 事件直写(官方客户端数据层同款实时来源): + * 完整 ShellInfo 就地 upsert,挂载行/活跃判定即时出现,不等重取。 + * 只维护已登记的目录(未登记的首次登记时会全量拉);没有目录信息时 + * 退化为防抖重取兜底 + */ + applyShellCreated = (directory: string | undefined, info: ShellInfo) => { + if (!directory) { + this.requestRefresh() + return + } + if (!this.dirRefs.has(directory)) return + const list = this.shellsByDir.get(directory) ?? [] + const idx = list.findIndex(shell => shell.id === info.id) + if (idx >= 0 && sameShellList([list[idx]], [info])) return + const next = idx >= 0 ? list.map((shell, i) => (i === idx ? info : shell)) : [...list, info] + this.shellsByDir.set(directory, next) + this.bump() + } + + /** shell.exited:状态/退出码就地更新——挂载行即时消失、弹窗状态即时翻转 */ + applyShellExited = (directory: string | undefined, id: string, status: ShellInfo['status'], exit?: number) => { + if (!directory) { + this.requestRefresh() + return + } + const list = this.shellsByDir.get(directory) + if (!list) return + const idx = list.findIndex(shell => shell.id === id) + if (idx < 0) return + const prev = list[idx] + if (prev.status === status && prev.exit === exit) return + const updated: ShellInfo = { + ...prev, + status, + ...(exit !== undefined ? { exit } : {}), + time: { ...prev.time, completed: prev.time.completed ?? Date.now() }, + } + this.shellsByDir.set( + directory, + list.map((shell, i) => (i === idx ? updated : shell)), + ) + this.bump() + } + + /** shell.deleted:从库存移除(服务端清理/被 remove) */ + applyShellDeleted = (directory: string | undefined, id: string) => { + if (!directory) { + this.requestRefresh() + return + } + const list = this.shellsByDir.get(directory) + if (!list || !list.some(shell => shell.id === id)) return + this.shellsByDir.set( + directory, + list.filter(shell => shell.id !== id), + ) + this.bump() + } + private bump() { this.version++ this.subscribers.forEach(fn => fn()) diff --git a/src/types/api/event.ts b/src/types/api/event.ts index 3a98d07a2..c68319f50 100644 --- a/src/types/api/event.ts +++ b/src/types/api/event.ts @@ -82,6 +82,9 @@ import type { SessionCompactionFailed, SessionShellStarted, SessionShellEnded, + ShellCreated, + ShellExited, + ShellDeleted, SessionSkillActivated, SessionInstructionsUpdated, V2Event, @@ -292,6 +295,9 @@ export type CompactionFailedPayload = SessionCompactionFailed['data'] // ---- shell / skill / instructions ---- export type ShellStartedPayload = SessionShellStarted['data'] +export type ShellCreatedPayload = ShellCreated['data'] +export type ShellExitedPayload = ShellExited['data'] +export type ShellDeletedPayload = ShellDeleted['data'] export type ShellEndedPayload = SessionShellEnded['data'] @@ -402,6 +408,14 @@ export interface EventCallbacks { /** shell 生命周期 */ onShellStarted?: (data: ShellStartedPayload, facts?: EventFacts) => void onShellEnded?: (data: ShellEndedPayload, facts?: EventFacts) => void + /** + * 全局 shell 库存事件(官方客户端数据层的实时来源): + * shell.created 带完整 ShellInfo 直写库存,挂载行即时出现; + * exited/deleted 就地更新/移除。location 是事件信封上的工作区引用 + */ + onShellInventoryCreated?: (data: ShellCreatedPayload, location?: LocationRef) => void + onShellInventoryExited?: (data: ShellExitedPayload, location?: LocationRef) => void + onShellInventoryDeleted?: (data: ShellDeletedPayload, location?: LocationRef) => void /** 激活 skill */ onSkillActivated?: (data: SkillActivatedPayload, facts?: EventFacts) => void /** 指令文件变更(插入 system 消息) */ From aae118ad1105ec4fb42a8f1567a4aca16e92bb3f Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 23:53:58 +0800 Subject: [PATCH 39/91] =?UTF-8?q?feat(settings):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E3=80=8C=E6=B8=B2=E6=9F=93=20HTML=20=E5=86=85=E5=AE=B9?= =?UTF-8?q?=E3=80=8D=E5=BC=80=E5=85=B3=EF=BC=8C=E5=8F=AF=E5=85=B3=E9=97=AD?= =?UTF-8?q?=20AI=20=E8=BE=93=E5=87=BA=E7=9A=84=20HTML=20=E6=B4=BB=E6=B8=B2?= =?UTF-8?q?=E6=9F=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AI 输出奇怪 HTML 时之前没法关掉渲染(artifact 沙箱预览 / 块级 island / html 代码块预览 / 内联裸标签全都默认活渲染)。 - themeStore 持久化 renderHtmlContent(默认开,保持现状) - 关闭后:HTML 文档/artifact/island 一律按源码代码块展示;html 代码块 退回普通代码块;正文内联裸 HTML 经 marked renderer.html 转义成文本 - 渲染器缓存按 reasoning×renderHtml 四变体隔离,htmlCache key 带标志位 - 设置入口在 聊天→对话体验,紧跟「用户消息 Markdown 渲染」; 登记进设置搜索目录 --- src/components/MarkdownRenderer.test.tsx | 54 ++++++++++++++++++- src/components/MarkdownRenderer.tsx | 50 +++++++++++++---- src/components/markdownHtmlRenderer.ts | 36 ++++++++----- .../settings/components/ChatSettings.tsx | 10 ++++ .../settings/settingsSearchCatalog.ts | 1 + src/hooks/useTheme.ts | 6 +++ src/locales/en/settings.json | 2 + src/locales/zh-CN/settings.json | 2 + src/store/themeStore.ts | 21 ++++++++ 9 files changed, 157 insertions(+), 25 deletions(-) diff --git a/src/components/MarkdownRenderer.test.tsx b/src/components/MarkdownRenderer.test.tsx index ab7573022..1407475e2 100644 --- a/src/components/MarkdownRenderer.test.tsx +++ b/src/components/MarkdownRenderer.test.tsx @@ -1,6 +1,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MarkdownRenderer } from './MarkdownRenderer' +import { themeStore } from '../store/themeStore' import { clearMermaidRenderCache } from './mermaidRenderCache' const mermaidMocks = vi.hoisted(() => ({ @@ -1512,3 +1513,54 @@ $$` expect(screen.queryByRole('link', { name: 'bad' })).not.toBeInTheDocument() }) }) + +describe('MarkdownRenderer HTML 渲染开关', () => { + beforeEach(() => { + themeStore.setRenderHtmlContent(false) + }) + afterEach(() => { + themeStore.setRenderHtmlContent(true) + }) + + it('关闭后完整 HTML 文档按源码代码块展示,不起沙箱预览', () => { + render( + \n

Document

'} + />, + ) + + expect(screen.queryByTitle('HTML preview')).not.toBeInTheDocument() + expect(screen.getByTestId('code-block')).toHaveTextContent('html:') + }) + + it('关闭后块级 HTML 不再渲染成活内容,直接展示源码', () => { + render(Rendered HTML
'} />) + + expect(screen.queryByText('Rendered HTML')).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'View HTML source' })).not.toBeInTheDocument() + expect(screen.getByTestId('code-block')).toHaveTextContent('html:
Rendered HTML
') + }) + + it('关闭后 html 代码块不再给预览,只按普通代码块展示', () => { + render(Run\n```'} />) + + expect(screen.queryByTitle('HTML preview')).not.toBeInTheDocument() + expect(screen.getByTestId('code-block')).toHaveTextContent('html:') + }) + + it('关闭后正文里混的内联 HTML 转义成文本源码', () => { + const { container } = render( + inline HTML after.'} />, + ) + + expect(container.querySelector('span[style]')).toBeNull() + expect(container.textContent).toContain('inline HTML') + }) + + it('重新开启后恢复活渲染', () => { + themeStore.setRenderHtmlContent(true) + render(Rendered HTML
'} />) + + expect(screen.getByText('Rendered HTML').tagName).toBe('STRONG') + }) +}) diff --git a/src/components/MarkdownRenderer.tsx b/src/components/MarkdownRenderer.tsx index a5bded441..7ed9b02b1 100644 --- a/src/components/MarkdownRenderer.tsx +++ b/src/components/MarkdownRenderer.tsx @@ -8,6 +8,7 @@ import { useMemo, useRef, useState, + useSyncExternalStore, } from 'react' import morphdom from 'morphdom' import { CodeBlock } from './CodeBlock' @@ -22,6 +23,12 @@ import type { Tokens } from 'marked' import { isMarkupPreviewLanguage, projectMarkdownStream, stripLeadingHtmlComments, type MarkdownStreamProjection } from './markdownStream' import { renderMarkdownToHtml, renderKatexHtml } from './markdownHtmlRenderer' import { getFootnoteId, scanTextSegments } from './markdownSegments' +import { themeStore } from '../store/themeStore' + +/** 只订阅 renderHtmlContent 布尔值(useTheme 全量订阅会让每条消息的 markdown 跟着任何设置变动重渲染) */ +function useRenderHtmlContent(): boolean { + return useSyncExternalStore(themeStore.subscribe, () => themeStore.renderHtmlContent) +} import type { MarkdownSegment } from './markdownSegments' import { buildHtmlSandboxThemeCss, @@ -71,11 +78,11 @@ const PREFIXED_BLOCK_HTML_SOURCE_PATTERN = /^\s*<(?:style|script)\b[\s\S]*<(?:ad const ARTIFACT_HTML_SOURCE_PATTERN = /(?:= HTML_CACHE_MAX) { const firstKey = htmlCache.keys().next().value if (firstKey !== undefined) htmlCache.delete(firstKey) @@ -1243,10 +1250,12 @@ const MarkdownDomBlock = memo(function MarkdownDomBlock({ src, isReasoning, isLive, + renderHtml, }: { src: string isReasoning: boolean isLive?: boolean + renderHtml: boolean }) { const rootRef = useRef(null) const appliedHtmlRef = useRef(null) @@ -1293,7 +1302,9 @@ const MarkdownDomBlock = memo(function MarkdownDomBlock({ } // live 中间态不进 htmlCache(避免 64 槽被流式碎片挤爆);稳定块才缓存 - const html = isLive ? renderMarkdownToHtml(renderSrc, isReasoning) : getCachedHtml(renderSrc, isReasoning) + const html = isLive + ? renderMarkdownToHtml(renderSrc, isReasoning, renderHtml) + : getCachedHtml(renderSrc, isReasoning, renderHtml) if (appliedHtmlRef.current === html) { appliedSrcRef.current = renderSrc return @@ -1301,7 +1312,7 @@ const MarkdownDomBlock = memo(function MarkdownDomBlock({ appliedHtmlRef.current = html appliedSrcRef.current = renderSrc applyMarkdownHtml(root, html) - }, [renderSrc, isReasoning, isLive]) + }, [renderSrc, isReasoning, isLive, renderHtml]) const handleClick = useCallback((event: React.MouseEvent) => { if (event.defaultPrevented) return @@ -1369,7 +1380,7 @@ function MarkdownHtmlIsland({ return ( setShowSource(true)}> - + ) } @@ -1383,6 +1394,7 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({ complete, isReasoning, isStreaming, + renderHtml, }: { src: string mode: 'full' | 'live' | 'code' | 'table' @@ -1390,6 +1402,7 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({ complete?: boolean isReasoning: boolean isStreaming: boolean + renderHtml: boolean }) { // 流式高亮/未完成态只对「未闭合 code」或 live 有意义;稳定 full 块 isStreaming 恒 false 以冻 memo const streamActive = isStreaming && (mode === 'live' || (mode === 'code' && !complete)) @@ -1412,7 +1425,7 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({
) } - if (isMarkupPreviewLanguage(language) && !isReasoning) { + if (renderHtml && isMarkupPreviewLanguage(language) && !isReasoning) { return (
@@ -1449,7 +1462,7 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({ const isHtmlArtifact = ARTIFACT_HTML_SOURCE_PATTERN.test(src) && (BLOCK_HTML_SOURCE_PATTERN.test(htmlSourceStart) || PREFIXED_BLOCK_HTML_SOURCE_PATTERN.test(htmlSourceStart)) - if (!isReasoning && (isHtmlDocument || isHtmlArtifact)) { + if (renderHtml && !isReasoning && (isHtmlDocument || isHtmlArtifact)) { return (
@@ -1459,7 +1472,7 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({ ) } - if (!isReasoning && BLOCK_HTML_SOURCE_PATTERN.test(htmlSourceStart)) { + if (renderHtml && !isReasoning && BLOCK_HTML_SOURCE_PATTERN.test(htmlSourceStart)) { return (
@@ -1467,9 +1480,22 @@ const MarkdownStreamBlock = memo(function MarkdownStreamBlock({ ) } + // 关闭 HTML 渲染:HTML 文档/artifact/island 一律按源码代码块展示 + if (!renderHtml && !isReasoning && (isHtmlDocument || isHtmlArtifact || BLOCK_HTML_SOURCE_PATTERN.test(htmlSourceStart))) { + return ( +
+
+
+ +
+
+
+ ) + } + return (
- +
) }) @@ -1525,7 +1551,8 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({ }: MarkdownRendererProps) { const isReasoning = variant === 'reasoning' const projectionKey = useId() - const renderHtmlImmediately = isStreaming && STREAMING_HTML_CONTENT_PATTERN.test(content) + const renderHtml = useRenderHtmlContent() + const renderHtmlImmediately = isStreaming && renderHtml && STREAMING_HTML_CONTENT_PATTERN.test(content) const smoothedContent = useSmoothMarkdownStream(content, isStreaming && !renderHtmlImmediately) const renderedContent = renderHtmlImmediately ? content : isStreaming ? smoothedContent : content const streamBlocks = useMemo(() => { @@ -1552,6 +1579,7 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({ language={block.language} complete={block.complete} isReasoning={isReasoning} + renderHtml={renderHtml} isStreaming={ isStreaming && (block.mode === 'live' || (block.mode === 'code' && !block.complete)) } diff --git a/src/components/markdownHtmlRenderer.ts b/src/components/markdownHtmlRenderer.ts index aa1e71d29..8ead22b59 100644 --- a/src/components/markdownHtmlRenderer.ts +++ b/src/components/markdownHtmlRenderer.ts @@ -273,9 +273,17 @@ const MARKDOWN_ALERTS = { }, } as const -function createMarkdownHtmlRenderer(isReasoning: boolean) { +function createMarkdownHtmlRenderer(isReasoning: boolean, renderHtml: boolean) { const renderer = new marked.Renderer() + // 关闭 HTML 渲染时:markdown 里的裸 HTML(块级+内联)一律转义成文本源码, + // 不再活渲染(artifact/island 在 MarkdownRenderer 块级已被分流成代码块) + if (!renderHtml) { + renderer.html = function ({ text }) { + return escapeHtml(text) + } + } + renderer.heading = function ({ tokens, depth }) { const text = this.parser.parseInline(tokens) const className = isReasoning @@ -408,10 +416,10 @@ function createMarkdownHtmlRenderer(isReasoning: boolean) { return renderer } -function renderFootnoteDefinitionsHtml(src: string, isReasoning: boolean): string | null { +function renderFootnoteDefinitionsHtml(src: string, isReasoning: boolean, renderHtml: boolean): string | null { const lines = src.trim().split(/\n+/) const items: string[] = [] - const renderer = getRenderer(isReasoning) + const renderer = getRenderer(isReasoning, renderHtml) for (const line of lines) { const match = /^\[\^([^\]]+)\]:\s+([\s\S]+)$/.exec(line.trim()) @@ -594,35 +602,37 @@ function sanitizeHtml(html: string): string { } // eslint-disable-next-line @typescript-eslint/no-explicit-any -let rendererCache: { default: any; reasoning: any } | null = null +let rendererCache: Record | null = null // eslint-disable-next-line @typescript-eslint/no-explicit-any -function getRenderer(isReasoning: boolean): any { +function getRenderer(isReasoning: boolean, renderHtml: boolean): any { if (!rendererCache) { rendererCache = { - default: createMarkdownHtmlRenderer(false), - reasoning: createMarkdownHtmlRenderer(true), + 'default:html': createMarkdownHtmlRenderer(false, true), + 'default:nohtml': createMarkdownHtmlRenderer(false, false), + 'reasoning:html': createMarkdownHtmlRenderer(true, true), + 'reasoning:nohtml': createMarkdownHtmlRenderer(true, false), } } - return isReasoning ? rendererCache.reasoning : rendererCache.default + return rendererCache[`${isReasoning ? 'reasoning' : 'default'}:${renderHtml ? 'html' : 'nohtml'}`] } -export function renderMarkdownToHtml(src: string, isReasoning: boolean): string { +export function renderMarkdownToHtml(src: string, isReasoning: boolean, renderHtml = true): string { const displayMath = getDisplayMathSource(src) if (displayMath != null) { const className = isReasoning ? 'my-2 overflow-x-auto text-text-400' : 'my-4 overflow-x-auto text-text-200' return `
${renderKatexHtml(displayMath, true)}
` } - const footnotes = renderFootnoteDefinitionsHtml(src, isReasoning) + const footnotes = renderFootnoteDefinitionsHtml(src, isReasoning, renderHtml) if (footnotes != null) return sanitizeHtml(footnotes) - const renderer = getRenderer(isReasoning) + const renderer = getRenderer(isReasoning, renderHtml) const html = marked.parse(src, { renderer, async: false }) as string return sanitizeHtml(html) } -export function renderMarkdownInlineToHtml(src: string, isReasoning: boolean): string { - const renderer = getRenderer(isReasoning) +export function renderMarkdownInlineToHtml(src: string, isReasoning: boolean, renderHtml = true): string { + const renderer = getRenderer(isReasoning, renderHtml) const html = marked.parseInline(src, { renderer }) as string return sanitizeHtml(html) } diff --git a/src/features/settings/components/ChatSettings.tsx b/src/features/settings/components/ChatSettings.tsx index d59ccfa7e..5f4ab6c42 100644 --- a/src/features/settings/components/ChatSettings.tsx +++ b/src/features/settings/components/ChatSettings.tsx @@ -32,6 +32,8 @@ export function ChatSettings() { setDesktopCollapsedInputDock, renderUserMarkdown, setRenderUserMarkdown, + renderHtmlContent, + setRenderHtmlContent, composerSelectorStyle, setComposerSelectorStyle, } = useTheme() @@ -109,6 +111,14 @@ export function ChatSettings() { setRenderUserMarkdown(!renderUserMarkdown)} /> + setRenderHtmlContent(!renderHtmlContent)} + > + setRenderHtmlContent(!renderHtmlContent)} /> + + { + themeStore.setRenderHtmlContent(enabled) + }, []) + // ---- Step Finish Display ---- const setStepFinishDisplay = useCallback((display: Partial) => { @@ -278,6 +282,8 @@ export function useTheme() { setCollapseUserMessages, renderUserMarkdown: state.renderUserMarkdown, setRenderUserMarkdown, + renderHtmlContent: state.renderHtmlContent, + setRenderHtmlContent, // step-finish 信息栏显示 stepFinishDisplay: state.stepFinishDisplay, diff --git a/src/locales/en/settings.json b/src/locales/en/settings.json index 424eb6589..bfc337735 100644 --- a/src/locales/en/settings.json +++ b/src/locales/en/settings.json @@ -188,6 +188,8 @@ "collapseLongMessagesDesc": "Auto-collapse lengthy user messages", "renderUserMarkdown": "Render User Markdown", "renderUserMarkdownDesc": "Render sent user messages as Markdown when enabled; keep plain text when disabled", + "renderHtmlContent": "Render HTML Content", + "renderHtmlContentDesc": "Render HTML in AI output as live preview; show HTML as source code when disabled", "outlineCurrentHighlight": "Highlight Current Position", "outlineCurrentHighlightDesc": "Mark the user prompt that owns the current viewport in the right-side history rail", "actionsOnLatestAssistantOnly": "Actions on latest reply only", diff --git a/src/locales/zh-CN/settings.json b/src/locales/zh-CN/settings.json index ea61937c1..0e2f44202 100644 --- a/src/locales/zh-CN/settings.json +++ b/src/locales/zh-CN/settings.json @@ -188,6 +188,8 @@ "collapseLongMessagesDesc": "自动折叠较长的用户消息", "renderUserMarkdown": "用户消息 Markdown 渲染", "renderUserMarkdownDesc": "开启后,用户发送的消息会按 Markdown 渲染;关闭时保持纯文本显示", + "renderHtmlContent": "渲染 HTML 内容", + "renderHtmlContentDesc": "开启时将 AI 输出中的 HTML 渲染为实时预览,关闭后一律按源码展示", "outlineCurrentHighlight": "高亮当前对话位置", "outlineCurrentHighlightDesc": "在右侧历史导航条中标出当前视口所属的用户提示词", "actionsOnLatestAssistantOnly": "仅末尾显示操作按钮", diff --git a/src/store/themeStore.ts b/src/store/themeStore.ts index 21365d198..e713eeb8a 100644 --- a/src/store/themeStore.ts +++ b/src/store/themeStore.ts @@ -147,6 +147,7 @@ const DEFAULT_COMPLETED_AT_FORMAT: CompletedAtFormat = 'time' const DEFAULT_REASONING_DISPLAY_MODE: ReasoningDisplayMode = 'markdown' const DEFAULT_RENDER_USER_MARKDOWN = false +const DEFAULT_RENDER_HTML_CONTENT = true const DEFAULT_DIFF_STYLE: DiffStyle = 'markers' const DEFAULT_DESCRIPTIVE_TOOL_STEPS = true const DEFAULT_INLINE_TOOL_REQUESTS = true @@ -192,6 +193,8 @@ export interface ThemeState { collapseUserMessages: boolean /** 是否将用户消息渲染为 Markdown */ renderUserMarkdown: boolean + /** 是否渲染 AI 输出中的 HTML(关闭后 HTML 一律按源码展示) */ + renderHtmlContent: boolean /** step-finish 信息栏显示开关 */ stepFinishDisplay: StepFinishDisplay /** 完成时刻显示格式 */ @@ -265,6 +268,7 @@ const STORAGE_KEY_CUSTOM_CSS_SNIPPETS = 'theme-custom-css-snippets' const STORAGE_KEY_ACTIVE_CUSTOM_CSS_SNIPPET_ID = 'theme-active-custom-css-snippet-id' const STORAGE_KEY_COLLAPSE_USER_MESSAGES = 'collapse-user-messages' const STORAGE_KEY_RENDER_USER_MARKDOWN = 'render-user-markdown' +const STORAGE_KEY_RENDER_HTML_CONTENT = 'render-html-content' const STORAGE_KEY_STEP_FINISH_DISPLAY = 'step-finish-display' const STORAGE_KEY_COMPLETED_AT_FORMAT = 'completed-at-format' const STORAGE_KEY_REASONING_DISPLAY_MODE = 'reasoning-display-mode' @@ -350,6 +354,10 @@ class ThemeStore { const savedRenderUserMarkdown = localStorage.getItem(STORAGE_KEY_RENDER_USER_MARKDOWN) const renderUserMarkdown = savedRenderUserMarkdown === null ? DEFAULT_RENDER_USER_MARKDOWN : savedRenderUserMarkdown === 'true' + + const savedRenderHtmlContent = localStorage.getItem(STORAGE_KEY_RENDER_HTML_CONTENT) + const renderHtmlContent = + savedRenderHtmlContent === null ? DEFAULT_RENDER_HTML_CONTENT : savedRenderHtmlContent === 'true' const savedReasoningDisplay = localStorage.getItem(STORAGE_KEY_REASONING_DISPLAY_MODE) const reasoningDisplayMode: ReasoningDisplayMode = savedReasoningDisplay === 'italic' || savedReasoningDisplay === 'markdown' @@ -485,6 +493,7 @@ class ThemeStore { activeCustomCSSSnippetId, collapseUserMessages, renderUserMarkdown, + renderHtmlContent, stepFinishDisplay, completedAtFormat, reasoningDisplayMode, @@ -544,6 +553,9 @@ class ThemeStore { get renderUserMarkdown() { return this.state.renderUserMarkdown } + get renderHtmlContent() { + return this.state.renderHtmlContent + } get stepFinishDisplay() { return this.state.stepFinishDisplay } @@ -803,6 +815,13 @@ class ThemeStore { this.emit() } + setRenderHtmlContent(enabled: boolean) { + if (this.state.renderHtmlContent === enabled) return + this.state = { ...this.state, renderHtmlContent: enabled } + localStorage.setItem(STORAGE_KEY_RENDER_HTML_CONTENT, String(enabled)) + this.emit() + } + setStepFinishDisplay(display: Partial) { const next = { ...this.state.stepFinishDisplay, ...display } this.state = { ...this.state, stepFinishDisplay: next } @@ -1240,6 +1259,8 @@ function normalizeThemeBackup(raw: unknown): ThemeBackup { collapseUserMessages: typeof parsed?.collapseUserMessages === 'boolean' ? parsed.collapseUserMessages : true, renderUserMarkdown: typeof parsed?.renderUserMarkdown === 'boolean' ? parsed.renderUserMarkdown : DEFAULT_RENDER_USER_MARKDOWN, + renderHtmlContent: + typeof parsed?.renderHtmlContent === 'boolean' ? parsed.renderHtmlContent : DEFAULT_RENDER_HTML_CONTENT, stepFinishDisplay: parsed?.stepFinishDisplay && typeof parsed.stepFinishDisplay === 'object' ? { ...DEFAULT_STEP_FINISH_DISPLAY, ...(parsed.stepFinishDisplay as Partial) } From 0fe075717637a8ac8180c31118172afea271c2b5 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 16 Oct 2026 23:54:16 +0800 Subject: [PATCH 40/91] =?UTF-8?q?feat(chat):=20=E8=BE=93=E5=85=A5=E6=A1=86?= =?UTF-8?q?=20=E2=86=91=E2=86=93=20=E4=BC=98=E5=85=88=E7=BF=BB=E9=98=85?= =?UTF-8?q?=E5=BD=93=E5=89=8D=E4=BC=9A=E8=AF=9D=E8=87=AA=E5=B7=B1=E7=9A=84?= =?UTF-8?q?=E5=8E=86=E5=8F=B2=E8=BE=93=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前在会话里按 ↑ 翻的是全局「最近输入」,会翻出别的会话发过的 内容,体感很奇怪。现在在会话里翻的是这个会话自己发过的用户输入: - messageStoreHooks 新增 useSessionPromptHistory:从当前 focused session 已加载的用户消息派生历史条目(最新在前),附件映射成与 全局历史相同的可序列化形状;自定义 equality,流式刷字不触发重渲染 - useInputHistory 加 sessionEntries 覆盖源;新会话/无消息时回退 全局持久化历史(保留「新会话回忆最近输入」) - shell 轨道无会话内来源(shell 命令是独立消息类型),保持全局轨道 - InputBox 接线:sessionId 与 focused 一致且非 shell 模式时启用 --- src/features/chat/InputBox.test.tsx | 2 + src/features/chat/InputBox.tsx | 10 ++- .../chat/InputBoxAttachments.test.tsx | 2 + .../chat/input/useInputHistory.test.ts | 68 +++++++++++++++++++ src/features/chat/input/useInputHistory.ts | 21 ++++-- src/store/messageStoreHooks.ts | 61 +++++++++++++++++ 6 files changed, 157 insertions(+), 7 deletions(-) diff --git a/src/features/chat/InputBox.test.tsx b/src/features/chat/InputBox.test.tsx index c27f8e043..c5a4d4361 100644 --- a/src/features/chat/InputBox.test.tsx +++ b/src/features/chat/InputBox.test.tsx @@ -90,6 +90,8 @@ vi.mock('../../hooks', () => ({ vi.mock('../../store/messageStoreHooks', () => ({ useMessages: () => messagesMock, + useCurrentSessionId: () => null, + useSessionPromptHistory: () => [], })) vi.mock('../../store/keybindingStore', () => ({ diff --git a/src/features/chat/InputBox.tsx b/src/features/chat/InputBox.tsx index 6ffda5ad0..6a827a6dd 100644 --- a/src/features/chat/InputBox.tsx +++ b/src/features/chat/InputBox.tsx @@ -20,6 +20,7 @@ import { useMobileCollapse } from './input/useMobileCollapse' import { useAttachmentRail } from './input/useAttachmentRail' import { useInputHistory } from './input/useInputHistory' import { promptHistoryStore } from '../../store/promptHistoryStore' +import { useCurrentSessionId, useSessionPromptHistory } from '../../store/messageStoreHooks' import { usePersistedDraft, draftStorageKey, clearPersistedDraft, readPersistedDraft } from './input/usePersistedDraft' import { TEXT_STYLE, @@ -309,16 +310,23 @@ function InputBoxComponent({ // ============================================ // 历史消息导航(类终端体验,逻辑在 useInputHistory hook 中) - // 数据源:全局持久化 prompt 历史(官方 composer/history 同款) + // 数据源:当前会话自己的历史用户输入(在该会话里翻这个会话发过的内容), + // 新会话/无消息时回退全局持久化 prompt 历史(官方 composer/history 同款) // + 当前会话/工作区的持久化草稿(空输入按 ↑ 先召回草稿) // ============================================ const draftKey = useMemo(() => draftStorageKey(sessionId, rootPath), [sessionId, rootPath]) const draftKeyRef = useRef(null) draftKeyRef.current = draftKey + const focusedSessionId = useCurrentSessionId() + const sessionPromptHistory = useSessionPromptHistory() + // shell 轨道没有会话内来源(shell 命令是独立消息类型),保持全局轨道 + const historyEntries = + !shellMode && sessionId && sessionId === focusedSessionId ? sessionPromptHistory : null const { handleHistoryKeyDown, handleHistoryChange, resetHistoryIndex } = useInputHistory({ textareaRef, mode: shellMode ? 'shell' : 'normal', recallDraft: useCallback(() => readPersistedDraft(draftKeyRef.current), []), + sessionEntries: historyEntries, }) // 草稿持久化(按会话/工作区作用域,官方 composer persistence 的存储维度; diff --git a/src/features/chat/InputBoxAttachments.test.tsx b/src/features/chat/InputBoxAttachments.test.tsx index 53b69e43e..641c8b795 100644 --- a/src/features/chat/InputBoxAttachments.test.tsx +++ b/src/features/chat/InputBoxAttachments.test.tsx @@ -59,6 +59,8 @@ vi.mock('../../hooks', () => ({ vi.mock('../../store/messageStoreHooks', () => ({ useMessages: () => [], + useCurrentSessionId: () => null, + useSessionPromptHistory: () => [], })) vi.mock('../../store/keybindingStore', () => ({ diff --git a/src/features/chat/input/useInputHistory.test.ts b/src/features/chat/input/useInputHistory.test.ts index 5f7e49043..a77435e29 100644 --- a/src/features/chat/input/useInputHistory.test.ts +++ b/src/features/chat/input/useInputHistory.test.ts @@ -111,3 +111,71 @@ describe('useInputHistory 草稿召回', () => { expect(again?.text).toBe('草稿行') }) }) + +describe('useInputHistory 会话内历史', () => { + beforeEach(() => { + localStorage.clear() + promptHistoryStore.reset() + }) + + function setupWithSessionEntries(sessionEntries: { text: string; attachments: [] }[] | null, globalHistory: string[] = []) { + localStorage.clear() + promptHistoryStore.reset() + for (const text of globalHistory) { + promptHistoryStore.add(text, [], 'normal') + } + const textarea = document.createElement('textarea') + const textareaRef = { current: textarea } + const { result } = renderHook(() => + useInputHistory({ + textareaRef, + mode: 'normal', + sessionEntries, + }), + ) + return { textarea, result } + } + + it('会话内历史非空时 ↑ 翻阅会话自己的输入,而不是全局最近输入', () => { + const { textarea, result } = setupWithSessionEntries( + [ + { text: '本会话最新一条', attachments: [] }, + { text: '本会话更早一条', attachments: [] }, + ], + ['别的会话的最近输入'], + ) + textarea.value = '' + textarea.setSelectionRange(0, 0) + + const first = result.current.handleHistoryKeyDown(keyEvent('ArrowUp'), '', []) + expect(first?.text).toBe('本会话最新一条') + + textarea.value = first!.text + textarea.setSelectionRange(0, 0) + const second = result.current.handleHistoryKeyDown(keyEvent('ArrowUp'), first!.text, []) + expect(second?.text).toBe('本会话更早一条') + }) + + it('会话内历史为空数组时回退全局持久化历史(新会话回忆最近输入)', () => { + const { textarea, result } = setupWithSessionEntries([], ['全局最近输入']) + textarea.value = '' + textarea.setSelectionRange(0, 0) + + const recalled = result.current.handleHistoryKeyDown(keyEvent('ArrowUp'), '', []) + expect(recalled?.text).toBe('全局最近输入') + }) + + it('会话内历史 ↓ 越过最新一条回到进入前的输入', () => { + const { textarea, result } = setupWithSessionEntries([{ text: '本会话消息', attachments: [] }]) + textarea.value = '' + textarea.setSelectionRange(0, 0) + + const up = result.current.handleHistoryKeyDown(keyEvent('ArrowUp'), '', []) + expect(up?.text).toBe('本会话消息') + + textarea.value = up!.text + textarea.setSelectionRange(textarea.value.length, textarea.value.length) + const down = result.current.handleHistoryKeyDown(keyEvent('ArrowDown'), up!.text, []) + expect(down).toEqual({ text: '', attachments: [], cursor: 'end' }) + }) +}) diff --git a/src/features/chat/input/useInputHistory.ts b/src/features/chat/input/useInputHistory.ts index 3feacc489..fad17dbd6 100644 --- a/src/features/chat/input/useInputHistory.ts +++ b/src/features/chat/input/useInputHistory.ts @@ -1,13 +1,15 @@ import { useRef, useCallback, useEffect } from 'react' -import { usePromptHistory, fromHistoryEntry } from '../../../store/promptHistoryStore' +import { usePromptHistory, fromHistoryEntry, type PromptHistoryEntry } from '../../../store/promptHistoryStore' import type { Attachment } from '../../attachment' // ============================================ // useInputHistory // 类终端的历史消息导航(↑↓ 翻阅已发送消息) // -// 数据源是**全局持久化**的 prompt 历史(官方 composer/history 同款: +// 默认数据源是**全局持久化**的 prompt 历史(官方 composer/history 同款: // 跨会话跨重启保留,normal/shell 分轨,发送即记账、失败移除)。 +// 传入 sessionEntries(当前会话自己的历史用户输入)时优先使用—— +// 在某个会话里翻的是这个会话发过的内容,而不是其它会话的最近输入。 // ============================================ interface HistoryEntry { @@ -25,6 +27,11 @@ interface UseInputHistoryOptions { * ↓ 越过最新一条历史时回到草稿。 */ recallDraft?: () => HistoryEntry | null + /** + * 会话内历史(当前会话已发送的用户输入,最新在前)。 + * 非空时替代全局历史;空数组/不传时回退全局持久化历史。 + */ + sessionEntries?: PromptHistoryEntry[] | null } interface UseInputHistoryReturn { @@ -45,13 +52,15 @@ interface UseInputHistoryReturn { resetHistoryIndex: () => void } -export function useInputHistory({ textareaRef, mode, recallDraft }: UseInputHistoryOptions): UseInputHistoryReturn { +export function useInputHistory({ textareaRef, mode, recallDraft, sessionEntries }: UseInputHistoryOptions): UseInputHistoryReturn { // store 条目最新在前;导航时下标 0 = 最新一条 const storeEntries = usePromptHistory(mode) - const historyRef = useRef(storeEntries) + // 会话内历史优先(该会话发过的输入);没有时回退全局「最近输入」 + const effectiveEntries = sessionEntries && sessionEntries.length > 0 ? sessionEntries : storeEntries + const historyRef = useRef(effectiveEntries) useEffect(() => { - historyRef.current = storeEntries - }, [storeEntries]) + historyRef.current = effectiveEntries + }, [effectiveEntries]) const recallDraftRef = useRef(recallDraft) useEffect(() => { diff --git a/src/store/messageStoreHooks.ts b/src/store/messageStoreHooks.ts index 08d849ff9..16491a7fd 100644 --- a/src/store/messageStoreHooks.ts +++ b/src/store/messageStoreHooks.ts @@ -9,6 +9,8 @@ import { useSyncExternalStore, useRef, useCallback } from 'react' import { messageStore } from './messageStore' import { paneLayoutStore } from './paneLayoutStore' import type { MessageStoreSnapshot, SessionMessageInfo, SessionStateSnapshot } from './messageStoreTypes' +import { isUserMessage, userMessageText, type UserMessage } from '../types/api/message' +import type { HistoryAttachment, PromptHistoryEntry } from './promptHistoryStore' // ============================================ // Snapshot Cache (避免 useSyncExternalStore 无限循环) @@ -243,6 +245,65 @@ export function useMessages(): SessionMessageInfo[] { return useMessageStoreSelector(selectMessages, sameMessageArray) } +// ============================================ +// 会话内输入历史(输入框 ↑↓ 翻阅) +// ============================================ +// +// 在某个 session 里时,↑↓ 应该翻阅**这个会话自己的**历史用户输入, +// 而不是全局「最近输入」。数据直接来自该会话已加载的用户消息, +// 映射成与全局 promptHistoryStore 相同的条目形态(附件只保留可序列化子集)。 +// ============================================ + +/** 用户消息 → 历史条目(附件只映射可序列化子集,与全局历史同一形状) */ +function userMessageToHistoryEntry(message: UserMessage): PromptHistoryEntry { + const attachments: HistoryAttachment[] = [] + for (const file of message.files ?? []) { + attachments.push({ + type: 'file', + displayName: file.name ?? file.mention?.text ?? 'file', + mime: file.mime, + ...(file.source.type === 'uri' ? { url: file.source.uri } : {}), + }) + } + for (const agent of message.agents ?? []) { + attachments.push({ type: 'agent', displayName: agent.name, agentName: agent.name }) + } + for (const skill of message.skills ?? []) { + attachments.push({ type: 'skill', displayName: skill.name, skillId: skill.id }) + } + return { text: userMessageText(message), attachments } +} + +/** 当前 focused session 的用户输入历史(最新在前);无用户消息时为空数组 */ +const selectSessionPromptHistory = (state: MessageStoreSnapshot): PromptHistoryEntry[] => { + const entries: PromptHistoryEntry[] = [] + for (let i = state.messages.length - 1; i >= 0; i--) { + const message = state.messages[i] + if (isUserMessage(message)) entries.push(userMessageToHistoryEntry(message)) + } + return entries +} + +function samePromptHistory(a: PromptHistoryEntry[], b: PromptHistoryEntry[]): boolean { + if (a === b) return true + if (a.length !== b.length) return false + return a.every((entry, i) => { + const other = b[i] + return ( + entry.text === other.text && + entry.attachments.length === other.attachments.length && + entry.attachments.every( + (attachment, j) => + attachment.type === other.attachments[j].type && attachment.displayName === other.attachments[j].displayName, + ) + ) + }) +} + +export function useSessionPromptHistory(): PromptHistoryEntry[] { + return useMessageStoreSelector(selectSessionPromptHistory, samePromptHistory) +} + /** 当前 focused session 是否已有消息(length 级,流式加字不触发) */ export function useHasMessages(): boolean { return useMessageStoreSelector(selectHasMessages) From 8e86eee6c50d118d3b660aadcb602a1efccd1840 Mon Sep 17 00:00:00 2001 From: lehhair Date: Sat, 17 Oct 2026 00:32:38 +0800 Subject: [PATCH 41/91] =?UTF-8?q?fix(ui):=20=E8=BE=B9=E7=BC=98=E6=B8=90?= =?UTF-8?q?=E9=9A=90=E6=94=B9=E7=94=A8=20mask=EF=BC=8C=E9=81=BF=E5=BC=80?= =?UTF-8?q?=20Tailwind=20v4=20=E6=B8=90=E5=8F=98=E5=9C=A8=20oklab=20?= =?UTF-8?q?=E4=B8=8B=E7=9A=84=E8=89=B2=E5=B8=A6=E5=88=86=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/features/chat/Header.tsx | 8 +++++++- src/features/chat/InputBox.tsx | 4 ++-- src/features/chat/PaneHeader.tsx | 6 +++++- src/features/message/CollapsibleUserText.tsx | 10 +++++----- 4 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/features/chat/Header.tsx b/src/features/chat/Header.tsx index 1d3daf77e..974d7a102 100644 --- a/src/features/chat/Header.tsx +++ b/src/features/chat/Header.tsx @@ -284,7 +284,13 @@ export function Header({ setShareDialogOpen(false)} /> -
+ {/* 用纯色块 + mask 渐隐,而不是 bg-gradient:渐变类在 Tailwind v4 里默认走 oklab, + 从 bg-bg-100 插值到 transparent(透明黑)中间会带出灰,和内容叠起来就是分层。 + mask 只动 alpha,不插值颜色,任何主题下都干净。 */} +
) } diff --git a/src/features/chat/InputBox.tsx b/src/features/chat/InputBox.tsx index 6a827a6dd..0a7dc7878 100644 --- a/src/features/chat/InputBox.tsx +++ b/src/features/chat/InputBox.tsx @@ -1563,11 +1563,11 @@ function InputBoxComponent({
{attachmentsOverflowing && showAttachmentLeftFade && ( -
+
)} {attachmentsOverflowing && showAttachmentRightFade && ( -
+
)}
diff --git a/src/features/chat/PaneHeader.tsx b/src/features/chat/PaneHeader.tsx index 8a7261a97..6f6c5a141 100644 --- a/src/features/chat/PaneHeader.tsx +++ b/src/features/chat/PaneHeader.tsx @@ -315,7 +315,11 @@ export function PaneHeader({ )}
-
+ {/* 同 Header:纯色块 + mask 渐隐,避开 Tailwind v4 渐变类的 oklab 插值分层 */} +
) } diff --git a/src/features/message/CollapsibleUserText.tsx b/src/features/message/CollapsibleUserText.tsx index 370dde11d..696209858 100644 --- a/src/features/message/CollapsibleUserText.tsx +++ b/src/features/message/CollapsibleUserText.tsx @@ -3,7 +3,7 @@ // // 原本私有于 MessageRenderer,抽出来给队列气泡(QueueBubbles)复用: // 正文/折叠/遮罩/展开按钮逻辑共享,气泡外壳(className)、正文颜色 -// (textClassName)、渐变遮罩色(maskClassName)按场景配。 +// (textClassName)、渐变遮罩底色(maskClassName)按场景配。 // ============================================ import { memo, useLayoutEffect, useRef, useState } from 'react' @@ -32,9 +32,9 @@ export interface CollapsibleUserTextProps { className?: string /** 正文颜色等;默认 text-text-100 */ textClassName?: string - /** 底部渐变遮罩的 from 色 token;默认 from-bg-300(与默认外壳底色一致) */ + /** 底部渐变遮罩的底色类;默认 bg-bg-300(与默认外壳底色一致) */ maskClassName?: string - /** 是否显示底部渐变遮罩(半透明底色的气泡没有能严丝合缝的 from 色,可关掉) */ + /** 是否显示底部渐变遮罩(半透明底色的气泡没有能严丝合缝的底色,可关掉) */ showMask?: boolean } @@ -45,7 +45,7 @@ export const CollapsibleUserText = memo(function CollapsibleUserText({ messageId, className = 'px-4 py-2.5 bg-bg-300 rounded-2xl max-w-full', textClassName = 'text-text-100', - maskClassName = 'from-bg-300', + maskClassName = 'bg-bg-300', showMask = true, }: CollapsibleUserTextProps) { const { t } = useTranslation('message') @@ -110,7 +110,7 @@ export const CollapsibleUserText = memo(function CollapsibleUserText({ {/* 底部渐变遮罩 */} {showMask && showCollapse && isCollapsed && (
)}
From be027569201a86d5e48bdffcc91fc108ba35e60c Mon Sep 17 00:00:00 2001 From: lehhair Date: Sat, 17 Oct 2026 00:50:00 +0800 Subject: [PATCH 42/91] =?UTF-8?q?fix(sessions):=20=E5=B7=B2=E5=9B=9E?= =?UTF-8?q?=E5=A4=8D=E7=9A=84=E6=9D=83=E9=99=90/=E6=8F=90=E9=97=AE?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E8=A2=AB=E5=BF=AB=E7=85=A7=E9=87=8D=E6=94=BE?= =?UTF-8?q?=E5=A4=8D=E6=B4=BB=EF=BC=8C=E6=B8=85=E6=8E=89=E4=BE=A7=E8=BE=B9?= =?UTF-8?q?=E6=A0=8F=E6=AE=8B=E7=95=99=E5=BE=BD=E6=A0=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hooks/useGlobalEvents.ts | 6 +++- src/store/activeSessionStore.test.ts | 49 ++++++++++++++++++++++++++-- src/store/activeSessionStore.ts | 39 ++++++++++++++++++++++ 3 files changed, 91 insertions(+), 3 deletions(-) diff --git a/src/hooks/useGlobalEvents.ts b/src/hooks/useGlobalEvents.ts index b7d76e388..ab492c6a8 100644 --- a/src/hooks/useGlobalEvents.ts +++ b/src/hooks/useGlobalEvents.ts @@ -488,7 +488,10 @@ export function useGlobalEvents(directories?: string[]) { } const currentDirectories = directoriesRef.current const currentScopeKey = getScopeKey(directoriesRef.current) - for (const pending of latePendingRequests.values()) { + // 重放后立即消费掉:latePendingRequests 的语义是「本次拉取窗口内迟到的 + // 事件」,补进 store 一次就该交给服务端快照接管。留着不删的话,下一次 + // fetch 会把它再重放一遍——已经回复过的请求就是这么在侧边栏复活的。 + for (const [requestId, pending] of latePendingRequests) { // 只处理属于该 server 的 pending(复合 key 前缀) if (!pending.sessionId.startsWith(`${serverId}::`)) continue const matchesScope = pending.directory @@ -501,6 +504,7 @@ export function useGlobalEvents(directories?: string[]) { pending.type, pending.description, ) + latePendingRequests.delete(requestId) } }) .catch(() => { diff --git a/src/store/activeSessionStore.test.ts b/src/store/activeSessionStore.test.ts index bd3972c7d..cb44fdea9 100644 --- a/src/store/activeSessionStore.test.ts +++ b/src/store/activeSessionStore.test.ts @@ -3,8 +3,7 @@ import { activeSessionStore } from './activeSessionStore' describe('activeSessionStore scoped refresh handling', () => { beforeEach(() => { - activeSessionStore.initialize({}) - activeSessionStore.initializePendingRequests([], []) + activeSessionStore.reset() }) it('drops same-server sessions missing from the snapshot (snapshot is absolute per server)', () => { @@ -139,4 +138,50 @@ describe('activeSessionStore scoped refresh handling', () => { next: 1000, }) }) + + it('drops a replayed pending request after it has been replied', () => { + // 症状:本地乐观回复清掉了 store,但 useGlobalEvents 闭包里的 + // latePendingRequests 没清;下一次 fetch 重放就把已回复的请求补回来, + // 侧边栏徽标卡住不消失。settled 记录必须把它挡住。 + activeSessionStore.addPendingRequest('req-1', 'local::root', 'permission', 'bash: rm -rf') + expect(activeSessionStore.getBusySessions()[0]?.pendingAction).toEqual({ + type: 'permission', + description: 'bash: rm -rf', + }) + + activeSessionStore.resolvePendingRequest('req-1') + + // 模拟下一次 fetch 快照里的迟到事件重放 + activeSessionStore.addPendingRequest('req-1', 'local::root', 'permission', 'bash: rm -rf') + + expect(activeSessionStore.getBusySessions()).toEqual([]) + }) + + it('still accepts a fresh request id after another one settled', () => { + activeSessionStore.addPendingRequest('req-1', 'local::root', 'question', 'first') + activeSessionStore.resolvePendingRequest('req-1') + activeSessionStore.addPendingRequest('req-2', 'local::root', 'question', 'second') + + expect(activeSessionStore.getBusySessions()[0]?.pendingAction).toEqual({ + type: 'question', + description: 'second', + }) + }) + + it('lets a server snapshot revive a request the local side had settled', () => { + // 服务端快照是权威:它说还 pending 就要显示(本地乐观回复可能没真正生效), + // 所以 settled 只拦 addPendingRequest,不拦 applyPendingSnapshot。 + activeSessionStore.addPendingRequest('req-1', 'local::root', 'permission', 'x') + activeSessionStore.resolvePendingRequest('req-1') + + activeSessionStore.initializePendingRequests( + [{ id: 'req-1', sessionID: 'local::root', action: 'bash', resources: ['x'] }], + [], + ) + + expect(activeSessionStore.getBusySessions()[0]?.pendingAction).toEqual({ + type: 'permission', + description: 'bash: x', + }) + }) }) diff --git a/src/store/activeSessionStore.ts b/src/store/activeSessionStore.ts index 123e5f3e7..d0198e633 100644 --- a/src/store/activeSessionStore.ts +++ b/src/store/activeSessionStore.ts @@ -90,6 +90,15 @@ class ActiveSessionStore { // 未回复的 permission/question 请求 — requestId → PendingRequest private pendingRequests = new Map() + // 已回复/取消的 requestId(FIFO,取最近 512 条)。 + // 存在的意义:useGlobalEvents 会把拉取窗口内迟到的 asked 事件记在闭包里的 + // latePendingRequests,fetch 回来后再补进 store。本地乐观回复只清得掉 store + // 里的 pendingRequests,够不着那个闭包——于是已回复的请求会被下一次 fetch + // 重放回来,侧边栏徽标就这么卡住(不刷新页面永远不消失)。 + // 只要 requestId 记在这里,addPendingRequest 一律不认。 + private settledRequestIds = new Map() + private static readonly SETTLED_LIMIT = 512 + // 服务端已报告 idle,但因有未回复请求而暂缓移出的 session private deferredIdleSessions = new Set() @@ -145,6 +154,14 @@ class ActiveSessionStore { return false } + private markSettled(requestId: string) { + this.settledRequestIds.set(requestId, true) + if (this.settledRequestIds.size > ActiveSessionStore.SETTLED_LIMIT) { + const oldest = this.settledRequestIds.keys().next().value + if (oldest !== undefined) this.settledRequestIds.delete(oldest) + } + } + getSnapshot = (): ActiveSessionState => this.state getBusySessionsSnapshot = (): ActiveSessionEntry[] => this.cachedBusySessions getBusyCountSnapshot = (): number => this.cachedBusyCount @@ -308,6 +325,8 @@ class ActiveSessionStore { // ============================================ addPendingRequest(requestId: string, sessionId: string, type: 'permission' | 'question', description?: string) { + // 已回复/取消过的请求:fetch 快照重放、乱序事件再推回来都不认 + if (this.settledRequestIds.has(requestId)) return this.pendingRequests.set(requestId, { requestId, sessionId, type, description }) // 确保 session 在 busy 列表 if (!this.state.statusMap[sessionId] || this.state.statusMap[sessionId].type === 'idle') { @@ -323,6 +342,10 @@ class ActiveSessionStore { // ============================================ resolvePendingRequest(requestId: string) { + // 无论这条当前还在不在 pending 里都先记下:SSE replied 和本地乐观回复都会 + // 走到这里,先到的把 id 记牢,后到的(含 fetch 重放)就被 addPendingRequest 挡掉。 + this.markSettled(requestId) + const req = this.pendingRequests.get(requestId) if (!req) return this.pendingRequests.delete(requestId) @@ -420,6 +443,22 @@ class ActiveSessionStore { get busyCount(): number { return this.cachedBusyCount } + + // ============================================ + // 全量重置(测试隔离 / 会话上下文彻底切换) + // ============================================ + + reset() { + this.state = { statusMap: {}, initialized: false } + this.pendingRequests = new Map() + this.settledRequestIds = new Map() + this.deferredIdleSessions = new Set() + this.sessionMeta = new Map() + this.statusSnapshotFlights = new Map() + this.cachedBusySessions = [] + this.cachedBusyCount = 0 + this.notify() + } } // ============================================ From f4a7d7c4f3cc71470cb000510f29204a4beae8da Mon Sep 17 00:00:00 2001 From: lehhair Date: Sat, 17 Oct 2026 01:04:05 +0800 Subject: [PATCH 43/91] =?UTF-8?q?feat(chat):=20=E4=BC=9A=E8=AF=9D=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E6=94=B6=E8=BF=9B=E6=A0=87=E9=A2=98=E8=8F=9C=E5=8D=95?= =?UTF-8?q?=EF=BC=8C=E5=8E=BB=E6=8E=89=E5=BC=B9=E7=AA=97=E5=A4=B4=E9=83=A8?= =?UTF-8?q?=E6=A8=AA=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/ui/Dialog.tsx | 2 +- src/features/chat/Header.tsx | 153 ++++++++++++++---- src/features/chat/SessionMoveDialog.tsx | 189 ++++++++++++++++++++++ src/features/chat/SessionMoveMenu.tsx | 204 ------------------------ src/locales/en/chat.json | 2 + src/locales/zh-CN/chat.json | 2 + 6 files changed, 320 insertions(+), 232 deletions(-) create mode 100644 src/features/chat/SessionMoveDialog.tsx delete mode 100644 src/features/chat/SessionMoveMenu.tsx diff --git a/src/components/ui/Dialog.tsx b/src/components/ui/Dialog.tsx index fa32900e6..1f9cf566d 100644 --- a/src/components/ui/Dialog.tsx +++ b/src/components/ui/Dialog.tsx @@ -354,7 +354,7 @@ export function Dialog({ <> {/* Header */} {(title || showCloseButton) && ( -
+
{title}
diff --git a/src/features/chat/Header.tsx b/src/features/chat/Header.tsx index 974d7a102..e60b7e0cd 100644 --- a/src/features/chat/Header.tsx +++ b/src/features/chat/Header.tsx @@ -8,11 +8,16 @@ import { SplitHorizontalIcon, MaximizeIcon, MinimizeIcon, + DownloadIcon, + GitWorktreeIcon, } from '../../components/Icons' -import { IconButton } from '../../components/ui' +import { DropdownMenu, IconButton, MenuItem } from '../../components/ui' import { ModelSelector, type ModelSelectorHandle } from './ModelSelector' -import { SessionMoveMenu } from './SessionMoveMenu' +import { SessionMoveDialog } from './SessionMoveDialog' import { ShareDialog } from './ShareDialog' +import { useSessionActiveEntry } from '../../store/activeSessionStore' +import { serverStore } from '../../store/serverStore' +import { makeSessionKey } from '../../utils/sessionKey' import { messageStore, useHeaderSessionMeta } from '../../store' import { useLayoutStore, layoutStore } from '../../store/layoutStore' import { useSessionContext } from '../../contexts/useSessionContext' @@ -48,8 +53,15 @@ interface SessionTitleControlProps { handleRename: () => void handleStartEdit: () => void onShare: () => void + onMove: () => void + /** 会话运行中:菜单里的「移动」置灰(官方 blocked while running) */ + moveDisabled: boolean clickToRenameTitle: string - shareTitle: string + moreActionsTitle: string + exportTitle: string + exportDesc: string + moveTitle: string + moveRunningTitle: string } function SessionTitleControl({ @@ -63,9 +75,44 @@ function SessionTitleControl({ handleRename, handleStartEdit, onShare, + onMove, + moveDisabled, clickToRenameTitle, - shareTitle, + moreActionsTitle, + exportTitle, + exportDesc, + moveTitle, + moveRunningTitle, }: SessionTitleControlProps) { + // 标题右侧的 chevron 是「会话操作」入口:导出 / 移动都收进这个菜单, + // 不再单独占一个按钮。 + const [menuOpen, setMenuOpen] = useState(false) + const triggerRef = useRef(null) + const menuRef = useRef(null) + + useEffect(() => { + if (!menuOpen) return + const onPointerDown = (event: MouseEvent) => { + const target = event.target as Node + if (triggerRef.current?.contains(target) || menuRef.current?.contains(target)) return + setMenuOpen(false) + } + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== 'Escape') return + setMenuOpen(false) + triggerRef.current?.focus() + } + document.addEventListener('mousedown', onPointerDown) + document.addEventListener('keydown', onKeyDown) + return () => { + document.removeEventListener('mousedown', onPointerDown) + document.removeEventListener('keydown', onKeyDown) + } + }, [menuOpen]) + + // 注意:进入重命名时菜单会自动收起——点击标题按钮属于「外部点击」, + // 上面的 mousedown 监听会先关掉菜单,无需额外 effect。 + const inputClass = compact ? 'px-2 py-1.5 text-[length:var(--fs-base)] font-medium text-text-100 bg-transparent border-none outline-none w-[160px] h-full' : 'px-3 py-1.5 text-[length:var(--fs-base)] font-medium text-text-100 bg-transparent border-none outline-none w-[200px] lg:w-[300px] h-full text-center' @@ -75,10 +122,15 @@ function SessionTitleControl({ const dividerClass = compact ? 'w-[1.5px] h-3 bg-border-200/50 mx-0.5 shrink-0' : 'w-[1.5px] h-3 bg-border-200/50 mx-0.5 shrink-0 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 [@media(any-pointer:coarse)]:opacity-100 transition-opacity' - const shareButtonClass = compact + const menuButtonClass = compact ? 'p-1 text-text-400 hover:text-text-100 transition-colors rounded-md hover:bg-bg-300/50 shrink-0' : 'p-1 text-text-400 hover:text-text-100 transition-colors rounded-md hover:bg-bg-300/50 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 [@media(any-pointer:coarse)]:opacity-100 shrink-0' + const pick = (action: () => void) => { + setMenuOpen(false) + action() + } + return (
-
- + +
+ } + onClick={() => pick(onShare)} + /> + } + disabled={moveDisabled} + onClick={() => pick(onMove)} + /> +
+
)}
@@ -137,6 +221,7 @@ export function Header({ const { composerSelectorStyle } = useTheme() const [shareDialogOpen, setShareDialogOpen] = useState(false) + const [moveDialogOpen, setMoveDialogOpen] = useState(false) const [isEditingTitle, setIsEditingTitle] = useState(false) const [editTitle, setEditTitle] = useState('') const titleInputRef = useRef(null) @@ -144,6 +229,11 @@ export function Header({ const sessionTitle = currentSessionTitle || t('header.newChat') const isCompact = presentation.isCompact + // 会话运行中禁止移动(官方 blocked while running)——用活跃状态判断 + const activeSessionKey = sessionId ? makeSessionKey(serverStore.getActiveServerId(), sessionId) : '' + const activeEntry = useSessionActiveEntry(activeSessionKey) + const sessionRunning = activeEntry?.status?.type === 'busy' || activeEntry?.status?.type === 'retry' + useEffect(() => { document.title = currentSessionTitle ? `${currentSessionTitle} - OpenCode` : 'OpenCode' return () => { @@ -185,26 +275,26 @@ export function Header({ } const titleControl = ( - <> - setShareDialogOpen(true)} - clickToRenameTitle={t('header.clickToRename')} - shareTitle={t('header.shareSession')} - /> - {/* 会话移动到其他目录 / worktree(v2 session.move,官方 session-workspace-menu) */} - {sessionId && !isEditingTitle && ( - - )} - + setShareDialogOpen(true)} + onMove={() => setMoveDialogOpen(true)} + moveDisabled={sessionRunning} + clickToRenameTitle={t('header.clickToRename')} + moreActionsTitle={t('header.moreActions')} + exportTitle={t('header.shareSession')} + exportDesc={t('header.exportSessionDesc')} + moveTitle={t('sessionMove.title')} + moveRunningTitle={t('sessionMove.runningTitle')} + /> ) return ( @@ -284,6 +374,15 @@ export function Header({ setShareDialogOpen(false)} /> + {sessionId && ( + setMoveDialogOpen(false)} + sessionId={sessionId} + directory={sessionDirectory || currentDirectory || ''} + /> + )} + {/* 用纯色块 + mask 渐隐,而不是 bg-gradient:渐变类在 Tailwind v4 里默认走 oklab, 从 bg-bg-100 插值到 transparent(透明黑)中间会带出灰,和内容叠起来就是分层。 mask 只动 alpha,不插值颜色,任何主题下都干净。 */} diff --git a/src/features/chat/SessionMoveDialog.tsx b/src/features/chat/SessionMoveDialog.tsx new file mode 100644 index 000000000..ec255e81f --- /dev/null +++ b/src/features/chat/SessionMoveDialog.tsx @@ -0,0 +1,189 @@ +// ============================================ +// SessionMoveDialog — 把会话移动到其他目录 / worktree +// +// 对应官方 session/timeline/session-workspace-menu.tsx: +// - 目标列表 = 项目根(本地)+ 现有 worktree +// - 会话运行中禁止移动(blocked while running),由入口是否可点判定 +// - 成功后服务端发 session.moved,各列表据此增删 +// +// 入口在 Header 的会话标题菜单里;这里只负责弹窗本体。 +// ============================================ + +import { useCallback, useEffect, useState } from 'react' +import { useTranslation } from 'react-i18next' +import { FolderIcon, GitWorktreeIcon, SpinnerIcon } from '../../components/Icons' +import { Button, Dialog } from '../../components/ui' +import { getCurrentProject, moveSession } from '../../api/client' +import { listWorktreeEntries, createWorktree } from '../../api/worktree' +import { isSameDirectory, normalizeToForwardSlash, uiErrorHandler } from '../../utils' + +interface SessionMoveDialogProps { + isOpen: boolean + onClose: () => void + /** 会话 id(可为 scoped key) */ + sessionId: string + /** 会话当前所在目录 */ + directory: string +} + +interface MoveTarget { + directory: string + label: string + kind: 'local' | 'worktree' +} + +export function SessionMoveDialog({ isOpen, onClose, sessionId, directory }: SessionMoveDialogProps) { + const { t } = useTranslation(['chat', 'common']) + const [loading, setLoading] = useState(false) + /** 正在移入的目标目录(行内 spinner,同时禁用其它行) */ + const [movingTo, setMovingTo] = useState(null) + const [targets, setTargets] = useState([]) + const [projectID, setProjectID] = useState(null) + const [newName, setNewName] = useState('') + const [creating, setCreating] = useState(false) + + const loadTargets = useCallback(async () => { + setLoading(true) + try { + const project = await getCurrentProject(directory || undefined) + if (!project) { + setTargets([]) + setProjectID(null) + return + } + setProjectID(project.id) + const root = normalizeToForwardSlash(project.canonical) + const current = normalizeToForwardSlash(directory) + const entries = await listWorktreeEntries(project.id) + const list: MoveTarget[] = [] + // 本地(项目根):当前不在根时才列出(官方同款) + if (!isSameDirectory(root, current)) { + list.push({ directory: root, label: t('chat:sessionMove.local'), kind: 'local' }) + } + for (const entry of entries) { + const dir = normalizeToForwardSlash(entry.directory) + if (isSameDirectory(dir, current) || isSameDirectory(dir, root)) continue + list.push({ directory: dir, label: dir.split('/').filter(Boolean).pop() ?? dir, kind: 'worktree' }) + } + setTargets(list) + } catch { + setTargets([]) + setProjectID(null) + } finally { + setLoading(false) + } + }, [directory, t]) + + // 打开时拉一次目标列表;关闭时清掉残留的在途状态 + useEffect(() => { + if (!isOpen) { + setMovingTo(null) + setCreating(false) + setNewName('') + return + } + void loadTargets() + }, [isOpen, loadTargets]) + + const handleMove = async (destination: string) => { + if (movingTo) return + setMovingTo(destination) + try { + await moveSession(sessionId, destination) + onClose() + // 列表增删由 session.moved 事件驱动(useSessions) + } catch (e) { + uiErrorHandler('move session', e) + } finally { + setMovingTo(null) + } + } + + const handleCreateAndMove = async () => { + const name = newName.trim() + if (!name || !projectID || creating) return + setCreating(true) + try { + const wt = await createWorktree({ projectID, name }) + setNewName('') + await handleMove(normalizeToForwardSlash(wt.directory)) + } catch (e) { + uiErrorHandler('create worktree', e) + } finally { + setCreating(false) + } + } + + return ( + +
+ {/* 目标列表:项目根 + 现有 worktree */} +
+ {loading ? ( +
+ +
+ ) : targets.length === 0 ? ( +
+ {t('chat:sessionMove.empty')} +
+ ) : ( + targets.map(target => ( + + )) + )} +
+ + {/* 新建 worktree 并移入(官方菜单的 "create" 项) */} + {projectID && ( +
+
{t('chat:sessionMove.newWorktreeSection')}
+
+ setNewName(e.target.value)} + onKeyDown={e => { + if (e.key === 'Enter') { + e.preventDefault() + void handleCreateAndMove() + } + }} + placeholder={t('chat:sessionMove.newWorktreePlaceholder')} + disabled={creating || movingTo !== null} + className="flex-1 min-w-0 bg-bg-000 border border-border-200 rounded-lg px-3 py-2 text-[length:var(--fs-base)] text-text-100 placeholder:text-text-400/60 focus:outline-none focus:border-accent-main-100/50" + /> + +
+
+ )} +
+
+ ) +} diff --git a/src/features/chat/SessionMoveMenu.tsx b/src/features/chat/SessionMoveMenu.tsx deleted file mode 100644 index 48055d3cd..000000000 --- a/src/features/chat/SessionMoveMenu.tsx +++ /dev/null @@ -1,204 +0,0 @@ -// ============================================ -// SessionMoveMenu — 把会话移动到其他目录 / worktree -// -// 对应官方 session/timeline/session-workspace-menu.tsx: -// - 目标列表 = 项目根(本地)+ 新建 worktree + 现有 worktree -// - 会话运行中禁止移动(blocked while running) -// - 成功后服务端发 session.moved,各列表据此增删 -// -// 交互是 Dialog(ui/Dialog):头部触发按钮不变, -// 点开是居中的目标选择弹窗,底部是新建 worktree 区。 -// ============================================ - -import { useCallback, useState } from 'react' -import { useTranslation } from 'react-i18next' -import { FolderIcon, GitWorktreeIcon, SpinnerIcon } from '../../components/Icons' -import { Button, Dialog } from '../../components/ui' -import { getCurrentProject, moveSession } from '../../api/client' -import { listWorktreeEntries, createWorktree } from '../../api/worktree' -import { useSessionActiveEntry } from '../../store/activeSessionStore' -import { serverStore } from '../../store/serverStore' -import { makeSessionKey } from '../../utils/sessionKey' -import { isSameDirectory, normalizeToForwardSlash } from '../../utils' -import { uiErrorHandler } from '../../utils' - -interface SessionMoveMenuProps { - /** 会话 id(可为 scoped key) */ - sessionId: string - /** 会话当前所在目录 */ - directory: string -} - -interface MoveTarget { - directory: string - label: string - kind: 'local' | 'worktree' -} - -export function SessionMoveMenu({ sessionId, directory }: SessionMoveMenuProps) { - const { t } = useTranslation(['chat', 'common']) - const [open, setOpen] = useState(false) - const [loading, setLoading] = useState(false) - /** 正在移入的目标目录(行内 spinner,同时禁用其它行) */ - const [movingTo, setMovingTo] = useState(null) - const [targets, setTargets] = useState([]) - const [projectID, setProjectID] = useState(null) - const [newName, setNewName] = useState('') - const [creating, setCreating] = useState(false) - - // 官方 blocked():会话运行中禁止移动 - const activeKey = makeSessionKey(serverStore.getActiveServerId(), sessionId) - const activeEntry = useSessionActiveEntry(activeKey) - const running = activeEntry?.status.type === 'busy' || activeEntry?.status.type === 'retry' - - const loadTargets = useCallback(async () => { - setLoading(true) - try { - const project = await getCurrentProject(directory || undefined) - if (!project) { - setTargets([]) - setProjectID(null) - return - } - setProjectID(project.id) - const root = normalizeToForwardSlash(project.canonical) - const current = normalizeToForwardSlash(directory) - const entries = await listWorktreeEntries(project.id) - const list: MoveTarget[] = [] - // 本地(项目根):当前不在根时才列出(官方同款) - if (!isSameDirectory(root, current)) { - list.push({ directory: root, label: t('chat:sessionMove.local'), kind: 'local' }) - } - for (const entry of entries) { - const dir = normalizeToForwardSlash(entry.directory) - if (isSameDirectory(dir, current) || isSameDirectory(dir, root)) continue - list.push({ directory: dir, label: dir.split('/').filter(Boolean).pop() ?? dir, kind: 'worktree' }) - } - setTargets(list) - } catch { - setTargets([]) - setProjectID(null) - } finally { - setLoading(false) - } - }, [directory, t]) - - const handleMove = async (destination: string) => { - if (movingTo) return - setMovingTo(destination) - try { - await moveSession(sessionId, destination) - setOpen(false) - // 列表增删由 session.moved 事件驱动(useSessions) - } catch (e) { - uiErrorHandler('move session', e) - } finally { - setMovingTo(null) - } - } - - const handleCreateAndMove = async () => { - const name = newName.trim() - if (!name || !projectID || creating) return - setCreating(true) - try { - const wt = await createWorktree({ projectID, name }) - setNewName('') - await handleMove(normalizeToForwardSlash(wt.directory)) - } catch (e) { - uiErrorHandler('create worktree', e) - } finally { - setCreating(false) - } - } - - return ( - <> - - - setOpen(false)} title={t('chat:sessionMove.title')} width={480}> -
- {/* 目标列表:项目根 + 现有 worktree */} -
- {loading ? ( -
- -
- ) : targets.length === 0 ? ( -
- {t('chat:sessionMove.empty')} -
- ) : ( - targets.map(target => ( - - )) - )} -
- - {/* 新建 worktree 并移入(官方菜单的 "create" 项) */} - {projectID && ( -
-
{t('chat:sessionMove.newWorktreeSection')}
-
- setNewName(e.target.value)} - onKeyDown={e => { - if (e.key === 'Enter') { - e.preventDefault() - void handleCreateAndMove() - } - }} - placeholder={t('chat:sessionMove.newWorktreePlaceholder')} - disabled={creating || movingTo !== null} - className="flex-1 min-w-0 bg-bg-000 border border-border-200 rounded-lg px-3 py-2 text-[length:var(--fs-base)] text-text-100 placeholder:text-text-400/60 focus:outline-none focus:border-accent-main-100/50" - /> - -
-
- )} -
-
- - ) -} diff --git a/src/locales/en/chat.json b/src/locales/en/chat.json index 2d94c04b3..000df60b7 100644 --- a/src/locales/en/chat.json +++ b/src/locales/en/chat.json @@ -5,6 +5,8 @@ "openSidebar": "Open sidebar", "clickToRename": "Click to rename", "shareSession": "Export session", + "moreActions": "Session actions", + "exportSessionDesc": "Export as JSON, importable on another device", "closeBottomPanel": "Close bottom panel", "openBottomPanel": "Open bottom panel", "closePanel": "Close panel", diff --git a/src/locales/zh-CN/chat.json b/src/locales/zh-CN/chat.json index 204881367..392386b52 100644 --- a/src/locales/zh-CN/chat.json +++ b/src/locales/zh-CN/chat.json @@ -5,6 +5,8 @@ "openSidebar": "打开侧边栏", "clickToRename": "点击重命名", "shareSession": "导出会话", + "moreActions": "会话操作", + "exportSessionDesc": "导出为 JSON,可导入到其他设备", "closeBottomPanel": "关闭底部面板", "openBottomPanel": "打开底部面板", "closePanel": "关闭面板", From 9176a5145aecab6f7bac873a811d3af0dea00fde Mon Sep 17 00:00:00 2001 From: lehhair Date: Sat, 17 Oct 2026 01:09:29 +0800 Subject: [PATCH 44/91] =?UTF-8?q?fix(message):=20=E7=A7=BB=E5=8A=A8?= =?UTF-8?q?=E7=AB=AF=E4=B8=8D=E5=86=8D=E6=8A=8A=20agent=20=E5=BE=BD?= =?UTF-8?q?=E6=A0=87=E6=92=91=E9=AB=98=EF=BC=88=E5=86=85=E8=81=94=E7=B4=A7?= =?UTF-8?q?=E5=87=91=E6=8C=89=E9=92=AE=E9=80=80=E5=87=BA=2032px=20?= =?UTF-8?q?=E6=9C=80=E5=B0=8F=E7=82=B9=E5=87=BB=E5=8C=BA=E5=9F=9F=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/features/message/tools/renderers/TaskRenderer.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/src/features/message/tools/renderers/TaskRenderer.tsx b/src/features/message/tools/renderers/TaskRenderer.tsx index ddc5f6e29..d1c9bac0f 100644 --- a/src/features/message/tools/renderers/TaskRenderer.tsx +++ b/src/features/message/tools/renderers/TaskRenderer.tsx @@ -278,6 +278,7 @@ export const TaskHeader = memo(function TaskHeader({ {sessionId ? ( ))} @@ -1027,19 +1015,6 @@ const ToolGroup = memo(function ToolGroup({ ) : (
{toolParts}
)} - - {stepFinish && ( -
- -
- )}
) }) @@ -1048,17 +1023,6 @@ const ToolGroup = memo(function ToolGroup({ // Helpers // ============================================ -function formatTokens( - tokens: StepFinishInfo['tokens'], - t: (key: string, opts?: Record) => string, -): string { - const total = tokens.input + tokens.output + tokens.reasoning + tokens.cache.read + tokens.cache.write - if (total >= 1000) { - return t('tokensK', { count: (total / 1000).toFixed(1) }) - } - return `${total} ${t('tokens')}` -} - /** * 消息级「步骤完成」信息。 * @@ -1375,16 +1339,3 @@ function groupContentForRender(message: AssistantMessage): RenderItem[] { flushToolGroup() return result } - -/** - * 最后一个「会真正渲染出内容」的条目下标。 - * step 完成信息只挂在它上面(对齐旧行为:只挂在本消息最后一个 step-finish)。 - */ -function findLastRenderableIndex(items: RenderItem[]): number { - for (let i = items.length - 1; i >= 0; i--) { - const item = items[i] - if (item.type === 'tool-group') return i - if (hasVisibleText(item.content)) return i - } - return -1 -} diff --git a/src/features/message/messageSpacing.ts b/src/features/message/messageSpacing.ts index fc60a12da..3a995a928 100644 --- a/src/features/message/messageSpacing.ts +++ b/src/features/message/messageSpacing.ts @@ -4,7 +4,6 @@ * - item: 列表项之间只靠 top 间距(根节点不加 pb) * - body: header 下方展开内容 * - stack: 消息内 parts 纵向 gap(0.5rem) - * - finish: ToolGroup 内 tools → StepFinish(与 stack 等距,无 list gap 时用) * - processBody: 过程壳内多助手列表;gap 与 stack / 扁平连续助手 8px 同距 * - toolBodyInset: compact/timeline 工具 body 左右缩进 + body 顶距 * - inner: 工具 body 内权限/提问等子块 @@ -20,8 +19,6 @@ export const MSG_SPACING = { item: 'pt-1', body: 'pt-1', stack: STACK_GAP, - /** 与 stack 的 0.5rem 等距;ToolGroup 内无 list gap,用 top 补 */ - finish: 'pt-2', processBody: `flex flex-col ${STACK_GAP} pt-1`, toolBodyInset: 'pl-2 pr-2.5 pt-1', inner: 'pt-2', diff --git a/src/features/message/stepFinishPlacement.test.tsx b/src/features/message/stepFinishPlacement.test.tsx new file mode 100644 index 000000000..463b1fc3c --- /dev/null +++ b/src/features/message/stepFinishPlacement.test.tsx @@ -0,0 +1,178 @@ +import type { ReactNode } from 'react' +import { render, screen } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { MessageRenderer } from './MessageRenderer' +import type { AssistantContent, AssistantMessage } from '../../types/api/message' + +/** + * step 完成信息(tokens / cost / 耗时 / agent / model)的挂载位置。 + * + * v2 一个助手消息 = 一个 step,数据全在消息上,所以固定挂在本消息内容末尾。 + * 这里刻意**保留真的 StepFinishPartView**(其它 part 都是空实现), + * 旧代码把信息挂在「最后一个可见条目」上,末尾是正文时整块数据会跟着丢。 + */ + +vi.mock('motion/mini', () => ({ + animate: () => Promise.resolve(), +})) + +vi.mock('../../hooks', async importOriginal => ({ + ...(await importOriginal()), + useDelayedRender: (show: boolean) => show, + useDisclosureScrollLock: () => ({ + rootRef: () => undefined, + headerRef: () => undefined, + withScrollLock: (action: () => void) => action(), + }), +})) + +vi.mock('../../hooks/useInputCapabilities', () => ({ + useInputCapabilities: () => ({ preferTouchUi: false, canHover: true, hasCoarsePointer: false, hasTouch: false }), +})) + +vi.mock('../../hooks/useTheme', () => ({ + useTheme: () => ({ + collapseUserMessages: false, + renderUserMarkdown: false, + stepFinishDisplay: { + latestOnly: true, + turnDuration: true, + tokens: true, + cache: true, + cost: true, + duration: true, + agent: false, + model: false, + completedAt: false, + }, + completedAtFormat: 'time', + actionsOnLatestAssistantOnly: true, + descriptiveToolSteps: false, + inlineToolRequests: false, + immersiveMode: false, + processCollapseEnabled: false, + }), +})) + +vi.mock('../../components/MarkdownRenderer', () => ({ + MarkdownRenderer: ({ content }: { content: string }) =>
{content}
, +})) + +vi.mock('../../components/ui', () => ({ + CopyButton: ({ text }: { text: string }) => , + SmoothHeight: ({ children }: { children: ReactNode }) => <>{children}, +})) + +vi.mock('./parts', async () => { + const { StepFinishPartView } = await import('./parts/StepFinishPartView') + return { + TextPartView: ({ part }: { part: { text: string } }) =>
{part.text}
, + ReasoningPartView: () => null, + ToolPartView: () => null, + StepFinishPartView, + RetryPartView: () => null, + MessageErrorView: () => null, + CompactionPartView: () => null, + } +}) + +/** 133228 tokens → 展示成 133.2k;缓存命中 132480 → 132.5k */ +const USAGE = { input: 477, output: 195, reasoning: 66, cache: { read: 132480, write: 10 } } + +function assistant(content: AssistantContent[], usage = true): AssistantMessage { + return { + type: 'assistant', + id: 'assistant-1', + agent: 'build', + model: { id: 'model-1', providerID: 'provider-1' }, + content, + time: { created: 1000, streamed: 9000, completed: 12000 }, + ...(usage ? { tokens: USAGE, cost: 0.0123 } : { tokens: undefined, cost: undefined }), + } as AssistantMessage +} + +const text = (value: string): AssistantContent => ({ type: 'text', text: value }) +const reasoning = (value: string): AssistantContent => ({ type: 'reasoning', text: value }) +const tool = (name: string): AssistantContent => ({ + type: 'tool', + id: `tool-${name}`, + name, + state: { + status: 'completed', + input: { command: 'pwd' }, + content: [{ type: 'text', text: 'ok' }], + metadata: { title: 'pwd' }, + }, + time: { created: 1, completed: 2 }, +}) + +describe('step 完成信息挂载位置', () => { + it('消息末尾是正文时照样渲染(旧代码会整块丢掉)', () => { + render() + + expect(screen.getByText('答案')).toBeInTheDocument() + expect(screen.getByText(/133\.2k/)).toBeInTheDocument() + expect(screen.getByText(/11\.0s total/)).toBeInTheDocument() + }) + + it('只有正文、末尾没有工具组时也渲染', () => { + render() + + expect(screen.getByText(/133\.2k/)).toBeInTheDocument() + }) + + it('消息末尾是工具组时渲染', () => { + render() + + expect(screen.getByText(/133\.2k/)).toBeInTheDocument() + }) + + it('工具组在前、正文在末时渲染,且只渲染一次', () => { + render() + + expect(screen.getAllByText(/133\.2k/)).toHaveLength(1) + }) + + it('壳内那截且壳外还有一份时(stepFinishVisible=false)不渲染,避免重复', () => { + const { container } = render( + , + ) + + expect(container.textContent).not.toContain('133.2k') + }) + + it('壳内那截没有壳外副本时照常渲染', () => { + render( + , + ) + + expect(screen.getByText(/133\.2k/)).toBeInTheDocument() + }) + + it("壳外 final 正文渲染", () => { + render( + , + ) + + expect(screen.getByText(/133\.2k/)).toBeInTheDocument() + }) + + it('latestOnly 开启且不是整轮最后一条时不渲染', () => { + const { container } = render() + + expect(container.textContent).not.toContain('133.2k') + }) + + it('没有 tokens/cost 时回落到回合耗时一行', () => { + render() + + expect(screen.getByText('中断了')).toBeInTheDocument() + expect(screen.getByText(/11\.0s total/)).toBeInTheDocument() + }) +}) From 6596015fcf62eadf48320e4a1f476f8c176de909 Mon Sep 17 00:00:00 2001 From: lehhair Date: Sat, 17 Oct 2026 03:19:08 +0800 Subject: [PATCH 48/91] =?UTF-8?q?fix(chat):=20=E4=BC=9A=E8=AF=9D=E8=BF=98?= =?UTF-8?q?=20busy=20=E6=97=B6=E8=BF=87=E7=A8=8B=E5=A3=B3=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E6=8F=90=E5=89=8D=E6=94=B6=E6=88=90=E3=80=8C=E5=B7=B2?= =?UTF-8?q?=E5=A4=84=E7=90=86=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 多步 agent 里上一步 completed、下一步还没到时,会话(session.status busy/retry) 其实还在跑,但时间线只看「所有助手消息都 completed」就判成 Worked: 壳先收起显示「已处理 29m 30s」,下一步内容一到又展开,看着像提前收工。 buildProcessTimeline 现在多看一眼 sessionIsStreaming:最后一个用户回合 在全 completed 但会话仍 busy 时保持 Working,等 idle 摘掉 busy、或下一轮 user 接手(index 不再是最后一个)才收壳。传进来的 sessionIsStreaming 就是 useChatSession 的 isSessionBusy(服务端 status busy/retry),所以可靠。 发送瞬间的旧守卫仍然成立:busy 已开但新 user 已入列时, 上一轮 index 不再是最后一个 → 立刻 Worked,不会闪回 Working。 --- src/features/chat/ChatArea.test.ts | 49 +++++++++++++++++++++++++----- src/features/chat/chatPageModel.ts | 9 ++++-- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/src/features/chat/ChatArea.test.ts b/src/features/chat/ChatArea.test.ts index 96e38b619..84897a061 100644 --- a/src/features/chat/ChatArea.test.ts +++ b/src/features/chat/ChatArea.test.ts @@ -819,25 +819,60 @@ describe('buildProcessTimeline', () => { expect(shells[1]).toMatchObject({ userMessageId: 'user-2', isActive: true }) }) - it('does not reopen a completed turn when session becomes busy before the next user lands', () => { - // 发送瞬间:streaming 已 true,新 user 还没进列表 → 已 Worked 的回合不能闪回 Working - const settled = createAssistantMessage( + it('keeps the last turn Working while the session is still busy (multi-step gap)', () => { + // 上一步已 completed、下一步还没到,但 session.status 仍是 busy —— 这是多步 agent 的常态。 + // 不能在这一刻判成 Worked 收壳,否则下一步内容到达时又要展开,看着像「提前收工」。 + const stepped = createAssistantMessage( 'assistant-1', - [createToolPart('tool-1', 'assistant-1'), { type: 'text', text: 'done' }], + [createToolPart('tool-1', 'assistant-1'), { type: 'text', text: '看一眼' }], 1001, 1500, ) - const messages = [createUserMessage('user-1', 1000), settled] - const timeline = buildProcessTimeline(messages, { + const messages = [createUserMessage('user-1', 1000), stepped] + + const busy = buildProcessTimeline(messages, { turnDurationMap: new Map([['assistant-1', 500]]), sessionIsStreaming: true, messageHasProcess: hasProcess, messageHasFinal: hasFinal, }) - expect(timeline.find(item => item.kind === 'process-shell')).toMatchObject({ + expect(busy.find(item => item.kind === 'process-shell')).toMatchObject({ + kind: 'process-shell', + isActive: true, + }) + + // busy 摘掉(idle)→ 收壳,并显示总耗时 + const settled = buildProcessTimeline(messages, { + turnDurationMap: new Map([['assistant-1', 500]]), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + expect(settled.find(item => item.kind === 'process-shell')).toMatchObject({ kind: 'process-shell', isActive: false, + durationMs: 500, + }) + }) + + it('settles the previous turn once the next user turn lands, even while busy', () => { + // 发送瞬间:busy 已 true、新 user 已入列 → 上一轮立刻 Worked,不能闪回 Working + const settled = createAssistantMessage( + 'assistant-1', + [createToolPart('tool-1', 'assistant-1'), { type: 'text', text: 'done' }], + 1001, + 1500, + ) + const messages = [createUserMessage('user-1', 1000), settled, createUserMessage('user-2', 2000)] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map([['assistant-1', 500]]), + sessionIsStreaming: true, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, }) + + const shells = timeline.filter(item => item.kind === 'process-shell') + expect(shells[0]).toMatchObject({ userMessageId: 'user-1', isActive: false }) }) it('settles shell with process inside and final answer outside', () => { diff --git a/src/features/chat/chatPageModel.ts b/src/features/chat/chatPageModel.ts index 2ad28cd27..d99dcef25 100644 --- a/src/features/chat/chatPageModel.ts +++ b/src/features/chat/chatPageModel.ts @@ -971,9 +971,12 @@ export function buildProcessTimeline( // 空回合:idle 结束;或后面已有 assistant(被跳过) return !sessionIsStreaming || laterHasAssistant(index) } - // 全 completed 且无 live → 锁定 Worked。 - // 不要再用 sessionIsStreaming 重开:发送时 busy 常早于新 user 入列,会闪一下。 - // 工具循环间隙若下一助手还没到,会短暂 Worked;下一助手 live 后自然回到 Working。 + // 全 completed 但会话还 busy(服务端 session.status busy/retry)且这是最后一个用户回合: + // 只是同一回合「上一步已收尾、下一步还没到」的间隙(多步 agent 的常态), + // 不能判成 Worked —— 否则壳会先收起、等下一步内容到了再展开。 + // 等 idle 把 busy 摘掉,或下一轮 user 接手(index 不再是最后一个)才收。 + if (sessionIsStreaming && index === userTurns.length - 1) return false + // 确实收工(busy 已清 / 后面已有新一轮) return assistants.every(m => m.time.completed != null) } From df48d76f80f55cb48a53ceecd91a6c87640ea359 Mon Sep 17 00:00:00 2001 From: lehhair Date: Sat, 17 Oct 2026 03:24:48 +0800 Subject: [PATCH 49/91] chore: bump version to 0.7.17 --- CHANGELOG.md | 20 ++++++++++++++++++++ package-lock.json | 4 ++-- package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 6 files changed, 26 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e5a07e7a..2a1aeed14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## [v0.7.17] - 2026-10-16 + +- fix(chat): 会话还 busy 时过程壳不再提前收成「已处理」 (6596015f) +- fix(message): step 完成信息改为消息级末尾一行,不再因末尾是正文而整块丢失 (42cdac7b) +- fix(chat): 进入会话时可靠对齐输入框模型 (5cb5c39c) +- fix(markdown): 修正 CJK 强调闭合、货币 $、脚注与任务列表解析 (19daea72) +- fix(message): 移动端不再把 agent 徽标撑高(内联紧凑按钮退出 32px 最小点击区域) (9176a514) +- feat(chat): 会话操作收进标题菜单,去掉弹窗头部横线 (f4a7d7c4) +- fix(sessions): 已回复的权限/提问不再被快照重放复活,清掉侧边栏残留徽标 (be027569) +- fix(ui): 边缘渐隐改用 mask,避开 Tailwind v4 渐变在 oklab 下的色带分层 (8e86eee6) +- feat(chat): 输入框 ↑↓ 优先翻阅当前会话自己的历史输入 (0fe07571) +- feat(settings): 新增「渲染 HTML 内容」开关,可关闭 AI 输出的 HTML 活渲染 (aae118ad) +- feat(sessions): shell 库存接入全局事件直写,挂载/摘下的实时性对齐官方 (1ed2b55f) +- fix(message): followShellOutput UTF-8 边界自愈,修流式输出的中文乱码 (cd3a793c) +- feat(message): bash/shell 工具卡运行中实时输出跟随 (31cb107a) +- feat(sessions): shell 输出弹窗复用信息流沉浸模式工具卡 (146db2a3) +- feat(sessions): 后台 shell 在跑的 idle 会话也算活跃,进活跃 tab (70db9fa8) +- fix(sessions): shell 库存按工作区目录取数,挂载覆盖文件夹/活跃列表 (2f204f26) +- feat(sessions): 后台 shell 挂到侧边栏父会话下,活着就算会话活跃 (aff816d5) + ## [v0.7.16] - 2026-10-16 - fix(chat): 队列操作行插队按钮挪到行首 (80cb042f) diff --git a/package-lock.json b/package-lock.json index bab506e86..e8460e4eb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "opencodeui", - "version": "0.7.16", + "version": "0.7.17", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opencodeui", - "version": "0.7.16", + "version": "0.7.17", "hasInstallScript": true, "license": "GPL-3.0-only", "dependencies": { diff --git a/package.json b/package.json index fe49e2649..132240dd4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencodeui", - "version": "0.7.16", + "version": "0.7.17", "description": "A third-party web frontend for OpenCode", "license": "GPL-3.0-only", "type": "module", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index e2780af1e..c481e1c58 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2725,7 +2725,7 @@ dependencies = [ [[package]] name = "opencodeui" -version = "0.7.16" +version = "0.7.17" dependencies = [ "futures-util", "log", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 4d0b83c82..c987feb5e 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodeui" -version = "0.7.16" +version = "0.7.17" description = "OpenCode UI - Tauri Mobile App" authors = ["lehhair"] license = "GPL-3.0-only" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 934d359b2..4fc936b74 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "OpenCode", - "version": "0.7.16", + "version": "0.7.17", "identifier": "com.opencodeui.app", "build": { "frontendDist": "../dist", From 7ae730d87e095df6765298f747548e3a468f591a Mon Sep 17 00:00:00 2001 From: lehhair Date: Sat, 17 Oct 2026 12:09:33 +0800 Subject: [PATCH 50/91] =?UTF-8?q?feat(settings):=20=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E7=BC=96=E8=BE=91=E5=99=A8=E6=94=B9=E4=B8=BA=20OpenCode=20v2?= =?UTF-8?q?=20=E9=85=8D=E7=BD=AE=20schema?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原来的编辑器按 v1 键名读写(provider / agent / command / plugin / attachment / autoupdate / autoshare / snapshot / reference / tools / permission / server / compatibility),但 v2 的 config.get() 返回的是 归一化后的 v2 形态,两代键名混着用就会写出被迁移或直接丢弃的字段。 现在以 packages/schema 的 v2 config.ts 为准,编辑器只读写 v2 原生键: - 顶层分区收敛为 14 个:general / commands / skills / plugins / providers / agents / mcp / permissions / formatters / lsp / media / runtime / experimental / advanced,删掉 server 与 compatibility - 键改名:agent+mode→agents、command→commands、plugin→plugins、 provider→providers(npm→package、api→settings.baseURL)、 attachment→media、autoupdate→update、autoshare→share、 snapshot→snapshots、reference→references、skill→skills、 tools+permission→permissions 有序规则集 - agent 字段:prompt→system、disable→disabled、maxSteps→steps、 采样参数进 request.body、variant 进 model 的 #variant - mcp:mcp[name]→mcp.servers[name],enabled→disabled, OAuth 字段改 snake_case,timeout 变 { startup, catalog, execution } - compaction:preserve_recent_tokens→keep.tokens、reserved→buffer - 删除 v2 已不存在的 small_model / logLevel / 顶层 subagent_depth、 provider 的 id/whitelist/blacklist、model 的 status/release_date/ attachment/reasoning/temperature/experimental 保存语义:v2 的 config.update 只接受 { shell },没有字段级写接口, 所以改为把合并后的全局配置整文件写回全局文档,写入目标与官方 Config.update 一致(全局目录里存在的最后一个 opencode.json / opencode.jsonc,都不存在时新建 jsonc)。代价是纯 JSON 重写,注释 与排版会丢,界面上有提示;旧提示里「官方 merge API 不能删除 key」 的说法是错的,已经去掉,删除键现在是可行的。 新增 src/features/settings/components/configEditorShape.test.ts: 用真实的 setRoot/setNested 搭一份覆盖全部 14 分区的夹具,钉住 「顶层只能是 v2 键」和「产出必须过本地 v2 校验」两件事;另有一条 联网用例默认跳过,设 VITE_OCUI_OFFICIAL_SCHEMA=1 时拿线上官方 schema 再复验一遍。 --- src/api/config.ts | 84 ++- .../components/ConfigSettings.search.test.tsx | 20 +- .../settings/components/ConfigSettings.tsx | 60 +- .../components/configEditorAgentFields.tsx | 101 ++- .../components/configEditorAgents.tsx | 3 +- .../components/configEditorControls.tsx | 29 +- .../components/configEditorDrill.test.tsx | 13 +- .../components/configEditorIntegrations.tsx | 117 ++-- .../settings/components/configEditorMeta.ts | 135 ++-- .../components/configEditorPermissions.tsx | 331 +++------- .../components/configEditorProviders.tsx | 557 +++++++++------- .../components/configEditorSearch.test.ts | 53 +- .../settings/components/configEditorSearch.ts | 194 +++--- .../components/configEditorSections.tsx | 485 ++++++-------- .../components/configEditorShape.test.ts | 307 +++++++++ .../settings/components/configEditorTypes.ts | 4 +- .../settings/components/configEditorUtils.ts | 31 + .../components/configEditorValidation.test.ts | 27 +- .../components/configEditorValidation.ts | 623 +++++++++--------- src/locales/en/settings.json | 7 +- src/locales/zh-CN/settings.json | 7 +- 21 files changed, 1760 insertions(+), 1428 deletions(-) create mode 100644 src/features/settings/components/configEditorShape.test.ts diff --git a/src/api/config.ts b/src/api/config.ts index bc5f69a9d..16659ff3e 100644 --- a/src/api/config.ts +++ b/src/api/config.ts @@ -26,7 +26,7 @@ import { getSDKClient } from './sdk' import { locationParam } from './location' -import type { ConfigSource, ConfigInfo, ConfigShellsResponse } from './types' +import type { ConfigDocument, ConfigSource, ConfigInfo, ConfigShellsResponse } from './types' /** * 获取配置来源清单。 @@ -49,19 +49,41 @@ export async function getConfig(directory?: string, serverId?: string): Promise< return mergeConfigInfo(sources) } +/** 官方探测的可写文档名,按优先级从低到高(写存在的最后一个)。 */ +const CONFIG_DOCUMENT_NAMES = ['opencode.json', 'opencode.jsonc'] + +function isDocument(source: ConfigSource): source is ConfigDocument { + return source.type === 'document' +} + /** - * 获取全局(无 location)配置。 + * 取全局来源(第一个 `type: 'directory'` 标记之前)。 * * 不带 location 的 `config.get()` 也会返回默认 location 的项目级来源, - * 「全局配置」只是第一个 `type: 'directory'` 标记**之前**的条目 - * (与官方 app 的 general settings 控制器一致),否则项目级配置会 - * 混进全局视图,保存时还可能写错文件。 + * 项目来源从那个 directory 条目开始(与官方 core 的 `Config.load` 一致)。 + */ +function globalSources(sources: ConfigSource[]): ConfigSource[] { + const boundary = sources.findIndex(source => source.type === 'directory') + return boundary === -1 ? sources : sources.slice(0, boundary) +} + +/** 拼一个配置文档路径,兼顾 Windows 与 POSIX 分隔符。 */ +function joinDocumentPath(directory: string, name: string): string { + const trimmed = directory.replace(/[\\/]+$/, '') + const separator = trimmed.includes('\\') ? '\\' : '/' + return `${trimmed}${separator}${name}` +} + +/** + * 获取全局(无 location)配置。 + * + * 只合并**有 `path` 的全局文档**:wellknown 远程文档没有 `path`, + * 把它们的值当成可编辑基线会让用户不小心写进本地文件。 */ export async function getGlobalConfig(serverId?: string): Promise { const sdk = getSDKClient(serverId) const sources = await sdk.config.get() - const boundary = sources.findIndex(source => source.type === 'directory') - return mergeConfigInfo(boundary === -1 ? sources : sources.slice(0, boundary)) + return mergeConfigInfo(globalSources(sources).filter(source => isDocument(source) && Boolean(source.path))) } /** @@ -92,47 +114,43 @@ export async function updateShell(shell: string | null, serverId?: string): Prom } /** - * 定位可写的配置文档。 + * 定位全局可写配置文档。 * - * v2 把可写配置收敛了:`config.update` 只接受 `{ shell }`, - * 任意字段的保存没有 API。但 `config.get()` 会返回文档及其 `path`, - * 因此「写配置」在 v2 里的原生做法是直接写那个文件。 + * 官方 `Config.update` 的写入目标是**全局配置目录**里的 + * `opencode.json` → `opencode.jsonc`,取其中存在的最后一个; + * 都不存在时新建 `opencode.jsonc`(见 core 的 `ConfigDiscovery.names` 与 `Config.update`)。 + * 这里与官方保持一致——不写项目级文档,避免编辑器把全局设置落到项目里。 * - * @returns 文档路径;找不到文档时为 undefined + * @returns 待写路径 */ -export async function findConfigDocumentPath( - directory?: string, - serverId?: string, -): Promise { - const sources = await getConfigSources(directory, serverId) - const documents = sources.filter( - (source): source is Extract => source.type === 'document', - ) - // 取最后一个文档:合并顺序里它优先级最高,写入它才不会被别的来源覆盖 - return documents[documents.length - 1]?.path +export async function findGlobalConfigDocumentPath(serverId?: string): Promise { + const sdk = getSDKClient(serverId) + const sources = await sdk.config.get() + const global = globalSources(sources) + // 优先级顺序里最后一个存在的文档,写入它才不会被更低的来源覆盖 + const target = global.filter(isDocument).filter(source => source.path).at(-1) + if (target?.path) return target.path + + const directory = global.find(source => source.type === 'directory') + if (directory) return joinDocumentPath(directory.path, CONFIG_DOCUMENT_NAMES[CONFIG_DOCUMENT_NAMES.length - 1]) + + throw new Error('No global config directory found') } /** - * 把配置对象写回其文档文件。 + * 把配置对象写回**全局**配置文档。 * * ⚠️ 这是整文件写入:会以标准 JSON 覆盖原文件,**JSONC 注释与原始排版会丢失**。 * v2 没有字段级写入接口,这是唯一能真正持久化配置的途径。 * * @returns 写入的路径 */ -export async function writeConfigDocument( - config: ConfigInfo, - directory?: string, - serverId?: string, -): Promise { - const path = await findConfigDocumentPath(directory, serverId) - if (!path) { - throw new Error('No writable config document found') - } +export async function writeGlobalConfigDocument(config: ConfigInfo, serverId?: string): Promise { + const path = await findGlobalConfigDocumentPath(serverId) const sdk = getSDKClient(serverId) const payload = new TextEncoder().encode(`${JSON.stringify(config, null, 2)}\n`) - await sdk.file.write({ path, payload, location: locationParam(directory, serverId) }) + await sdk.file.write({ path, payload }) return path } diff --git a/src/features/settings/components/ConfigSettings.search.test.tsx b/src/features/settings/components/ConfigSettings.search.test.tsx index 1d905e4a0..d23e58b0e 100644 --- a/src/features/settings/components/ConfigSettings.search.test.tsx +++ b/src/features/settings/components/ConfigSettings.search.test.tsx @@ -6,9 +6,10 @@ import { ConfigSettings } from './ConfigSettings' const api = vi.hoisted(() => ({ getGlobalConfig: vi.fn(), getConfig: vi.fn(), - // v2:config.providers() 被 model.list() 取代;写配置改走文档写入 + // v2:config.providers() 被 model.list() / provider.list() 取代;写配置改走全局文档写入 getActiveModels: vi.fn(), - writeConfigDocument: vi.fn(), + getProviders: vi.fn(), + writeGlobalConfigDocument: vi.fn(), listAvailableShells: vi.fn(), })) @@ -25,22 +26,19 @@ describe('ConfigSettings search', () => { // v2 的配置顶层键是 providers(复数) providers: { openai: { - options: { baseURL: 'https://gateway.example.com' }, + name: 'Gateway OpenAI', }, }, }) api.getConfig.mockResolvedValue({}) api.getActiveModels.mockResolvedValue([]) - api.writeConfigDocument.mockResolvedValue('/repo/opencode.json') + api.getProviders.mockResolvedValue([{ id: 'openai', name: 'OpenAI' }]) + api.writeGlobalConfigDocument.mockResolvedValue('/repo/opencode.jsonc') api.listAvailableShells.mockResolvedValue([]) Element.prototype.scrollIntoView = vi.fn() Element.prototype.scrollTo = vi.fn() }) - // 阻塞:与 configEditorDrill 的 provider 用例同因——v2 的配置顶层键是 - // `providers`(复数),而配置编辑器(ProvidersSection / configEditorValidation / - // 搜索索引)仍按 v1 的 `provider` 读取,因此搜不到 providers 下的字段。 - // 待把该组顶层键改成 `providers` 后再启用(夹具已改为复数)。 it('searches a raw JSON value and opens its nested field', async () => { render() fireEvent.click(screen.getByRole('button', { name: 'Open Config Editor' })) @@ -48,12 +46,12 @@ describe('ConfigSettings search', () => { const input = screen.getByRole('combobox', { name: 'Search config fields...' }) fireEvent.focus(input) - fireEvent.change(input, { target: { value: 'gateway.example.com' } }) - const result = await screen.findByRole('option', { name: /providers\.openai\.options\.baseURL/ }) + fireEvent.change(input, { target: { value: 'Gateway OpenAI' } }) + const result = await screen.findByRole('option', { name: /providers\.openai\.name/ }) fireEvent.click(result) await waitFor(() => expect(screen.getByRole('tab', { name: 'Providers & Models' })).toHaveAttribute('aria-selected', 'true')) - const field = await screen.findByDisplayValue('https://gateway.example.com') + const field = await screen.findByDisplayValue('Gateway OpenAI') await waitFor(() => expect(field.closest('[data-config-field]')).toHaveClass('settings-search-highlight')) expect(field).toHaveFocus() // 单跑 0.5s 就过;但本文件要挂载完整 ConfigSettings + 配置编辑器弹窗(jsdom 冷启动最重的路径之一), diff --git a/src/features/settings/components/ConfigSettings.tsx b/src/features/settings/components/ConfigSettings.tsx index 2104bc388..cb238e282 100644 --- a/src/features/settings/components/ConfigSettings.tsx +++ b/src/features/settings/components/ConfigSettings.tsx @@ -12,7 +12,12 @@ import { KeyboardIcon, LayersIcon, PlugIcon, - SunIcon, + CodeIcon, + ImageIcon, + TerminalIcon, + LightbulbIcon, + ShieldIcon, + PencilIcon, QuestionIcon, CogIcon, } from '../../../components/Icons' @@ -22,8 +27,9 @@ import { getConfig, getGlobalConfig, getActiveModels, + getProviders, listAvailableShells, - writeConfigDocument, + writeGlobalConfigDocument, } from '../../../api' import type { Config } from '../../../types/api/config' import { useCurrentDirectory, useIsMobile } from '../../../hooks' @@ -39,28 +45,26 @@ import { clone, getObject, sameValue, tx } from './configEditorUtils' const CONFIG_TAB_ICONS: Record = { general: , - server: , - providers: , - agents: , commands: , skills: , plugins: , - mcp: , - permissions: , - formatters: , - lsp: , - attachments: , - runtime: , - experimental: , - compatibility: , - advanced: , + providers: , + agents: , + mcp: , + permissions: , + formatters: , + lsp: , + media: , + runtime: , + experimental: , + advanced: , } const CONFIG_SECTION_GROUPS: { en: string; zh: string; sections: SectionID[] }[] = [ - { en: 'Core', zh: '核心', sections: ['general', 'server'] }, + { en: 'Core', zh: '核心', sections: ['general'] }, { en: 'Extensions', zh: '扩展', sections: ['commands', 'skills', 'plugins', 'providers', 'agents', 'mcp'] }, { en: 'Tools', zh: '工具', sections: ['permissions', 'formatters', 'lsp'] }, - { en: 'Advanced', zh: '高级', sections: ['attachments', 'runtime', 'experimental', 'compatibility', 'advanced'] }, + { en: 'Advanced', zh: '高级', sections: ['media', 'runtime', 'experimental', 'advanced'] }, ] function ConfigEditorDialog({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) { @@ -170,12 +174,14 @@ function ConfigEditorDialog({ isOpen, onClose }: { isOpen: boolean; onClose: () setValidationErrors([]) setValidationDrillTarget(null) try { - const [global, nextEffective, shellList, providerModels] = await Promise.all([ + const [global, nextEffective, shellList, providerModels, providers] = await Promise.all([ getGlobalConfig(), getConfig(directory), listAvailableShells(directory).catch(() => []), // v2 删除了 config.providers(),模型清单改由 model.list() 提供 getActiveModels(directory).catch(() => []), + // provider 元信息(显示名)来自 provider.list() + getProviders(directory).catch(() => []), ]) const modelChoices: Choice[] = providerModels.map(model => ({ @@ -183,14 +189,18 @@ function ConfigEditorDialog({ isOpen, onClose }: { isOpen: boolean; onClose: () label: `${model.providerID}/${model.id}`, })) + const catalog: JsonRecord = {} + for (const provider of providers) { + catalog[provider.id] = { name: provider.name } + } + if (request !== loadRequestRef.current) return setOriginal(clone(global)) setConfig(clone(global)) setJsonDraftErrors(new Set()) setDraftErrors(new Set()) setEffective(nextEffective) - // v2 没有 provider 目录接口,这里留空(仅供 provider 元信息展示的旧路径) - setProviderCatalog({}) + setProviderCatalog(catalog) setShells([ { value: '', label: t('config.shellAuto') }, ...shellList.map((shell: { path: string; name: string; acceptable: boolean }) => ({ @@ -275,16 +285,16 @@ function ConfigEditorDialog({ isOpen, onClose }: { isOpen: boolean; onClose: () setSaving(true) try { // v2 的 config.update 只接受 { shell },任意字段的保存没有 API。 - // 原生做法是直接把合并结果写回配置文档文件(见 api/config 的说明)。 - const savedPath = await writeConfigDocument(snapshot, directory) + // 原生做法是直接把合并结果写回**全局**配置文档(见 api/config 的说明)。 + const savedPath = await writeGlobalConfigDocument(snapshot) if (request !== saveRequestRef.current) return const saved = await getGlobalConfig().catch(() => snapshot) setOriginal(clone(saved)) setConfig(current => (sameValue(current, snapshot) ? clone(saved) : current)) setSchemaWarning( tx( - `Saved to ${savedPath}. Note: v2 has no field-level config API, so the file is rewritten as plain JSON — comments and original formatting are lost.`, - `已保存到 ${savedPath}。注意:v2 没有字段级配置接口,此操作会以纯 JSON 重写文件,注释与原始排版会丢失。`, + `Saved to ${savedPath}. Note: v2 has no field-level config API, so the global document is rewritten as plain JSON — comments and original formatting are lost.`, + `已保存到 ${savedPath}。注意:v2 没有字段级配置接口,此操作会以纯 JSON 重写全局配置文档,注释与原始排版会丢失。`, lang, ), ) @@ -311,8 +321,8 @@ function ConfigEditorDialog({ isOpen, onClose }: { isOpen: boolean; onClose: () 'plan', 'general', 'explore', - ...Object.keys(getObject(config, 'agent')), - ...Object.keys(getObject(effective, 'agent')), + ...Object.keys(getObject(config, 'agents')), + ...Object.keys(getObject(effective, 'agents')), ]) return Array.from(names) .sort() diff --git a/src/features/settings/components/configEditorAgentFields.tsx b/src/features/settings/components/configEditorAgentFields.tsx index 94c79b103..db804c553 100644 --- a/src/features/settings/components/configEditorAgentFields.tsx +++ b/src/features/settings/components/configEditorAgentFields.tsx @@ -1,36 +1,95 @@ -import { BoolField, KeyValueField, NumberField, PositiveIntegerField, Select, TextArea, TextField } from './configEditorControls' -import type { FieldDef } from './configEditorFields' -import { PermissionEditor, ToolToggleMap } from './configEditorPermissions' +import { BoolField, KeyValueField, PositiveIntegerField, Select, StringMapField, TextArea, TextField } from './configEditorControls' +import { DrillFields, type FieldDef } from './configEditorFields' +import { PermissionEditor } from './configEditorPermissions' import { enumChoices } from './configEditorSectionTypes' import type { Choice, JsonRecord, Lang } from './configEditorTypes' -import { previewValue, tx } from './configEditorUtils' +import { isRecord, modelSelectionText, previewValue, tx } from './configEditorUtils' +/** + * v2 的 agent 字段(对应 `ConfigAgent.Info`)。 + * + * 相比 v1:`prompt`→`system`、`disable`→`disabled`、`maxSteps`→`steps`, + * `temperature`/`top_p` 等采样参数进 `request.body`,`tools` 与 + * `permission` 合并成有序规则集 `permissions`,`variant` 并入 `model` 选择。 + */ export function buildAgentConfigFields({ value, - setField, + onChange, lang, models, }: { value: JsonRecord - setField: (key: string, value: unknown) => void + onChange: (next: JsonRecord) => void lang: Lang models: Choice[] }): FieldDef[] { + const set = (key: string, v: unknown) => onChange({ ...value, [key]: v }) + const unset = (key: string) => { + const next = { ...value } + delete next[key] + onChange(next) + } return [ - { key: 'description', label: 'description', desc: tx('Description of when to use the agent.', '何时使用该 agent 的说明。', lang), control: setField('description', v)} /> }, - { key: 'mode', label: 'mode', desc: tx("Agent mode: 'primary', 'subagent' or 'all'.", "agent 模式:primary、subagent 或 all。", lang), control: setField('model', v)} /> }, - { key: 'variant', label: 'variant', desc: tx("Default model variant (only with the agent's configured model).", '默认模型 variant(仅对该 agent 配置的模型生效)。', lang), control: setField('variant', v)} /> }, - { key: 'prompt', label: 'prompt', block: true, desc: tx('System prompt override for this agent.', '该 agent 的系统提示词覆盖。', lang), control: