Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(desktop): 减少任务切换重算并恢复历史阅读位置 (#4643)
Dash2e660c3bebcb
diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.tsindex 0c475c007d..e7a075882a 100644--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts@@ -858,7 +858,7 @@ describe('automation-generated sessions', () => {expect(source).toContain('toggleCollapsed()');// 切折叠必须复位轴 2:showAll 被收起告警列表和展开历史列表共用。复位挂在// collapsed 变化上,覆盖 chevron 与父层「收起所有分组」,不只一条点击路径。- expect(source).toContain('useLayoutEffect(() => {\n setShowAll(false);\n }, [collapsed]);');+ expect(source).toMatch(/useLayoutEffect\(\(\) => \{\s+setShowAll\(false\);\s+\}, \[collapsed\]\);/);expect(source).toContain('const ToggleIcon = collapsed ? ChevronRight : ChevronDown');expect(source).toContain('aria-expanded={!collapsed}');// 轴 1 收起时只留组头 + 被提上来的未处理告警行,取舍统一由 childView 决定diff --git a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.tsindex 918a800170..ff7fd0b625 100644--- a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts+++ b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts@@ -52,7 +52,13 @@ describe('Mixed main list (sidebar-redesign D 期)', () => {it('renders dialogues through the mixed ProjectsSection instead of a fixed DialogueSection', () => {expect(sidebarSource).toContain('dialogues={visibleDialogues}');expect(sidebarSource).not.toContain('<DialogueSection');- expect(projectsSectionSource).toContain('buildMainListEntries');+ expect(projectsSectionSource).toContain('useMainListEntries(');+ const entriesHook = readFileSync(+ resolve(__dirname, '..', 'features', 'cc-agent', 'hooks', 'useMainListEntries.ts'),+ 'utf8',+ );+ expect(entriesHook).toContain('buildMainListEntries({');+ expect(entriesHook).toContain('projects, dialogues, bots, unclassified');});it('drops the removed date-grouped section entirely', () => {diff --git a/apps/desktop/src/renderer/__tests__/generatedFilesProjection.test.ts b/apps/desktop/src/renderer/__tests__/generatedFilesProjection.test.tsnew file mode 100644index 0000000000..e0b43a3863--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/generatedFilesProjection.test.ts@@ -0,0 +1,29 @@+import { expect, it } from 'vitest';+import { collectCachedGeneratedFiles } from '@/components/chat/generatedFilesProjection';+import { collectGeneratedFiles } from '@/lib/generatedFiles';++it('reuses a reassembled turn after visiting another task and updates results, pagination and directory', () => {+ const user = { role: 'user', content: 'create report' };+ const tool = {+ role: 'tool_use',+ toolName: 'Write',+ toolUseId: 'write',+ toolInput: { file_path: 'report.md', content: 'report' },+ };+ const rows = [user, tool];+ const first = collectCachedGeneratedFiles(rows, '/one');+ expect(first).toMatchObject([{ path: '/one/report.md', ready: false }]);+ collectCachedGeneratedFiles([{ role: 'user', content: 'another task' }], '/one');+ expect(collectCachedGeneratedFiles([...rows], '/one')).toBe(first);+ const complete = [...rows, { role: 'tool_result', toolUseId: 'write', content: '{"ok":true}' }];+ expect(collectCachedGeneratedFiles(complete, '/one')).toEqual(+ collectGeneratedFiles(complete, '/one'),+ );+ expect(collectCachedGeneratedFiles(complete, '/one')[0].ready).toBeUndefined();+ const failed = [...rows, { role: 'tool_result', toolUseId: 'write', content: '{"ok":false}' }];+ expect(collectCachedGeneratedFiles(failed, '/one')).toEqual([]);+ expect(collectCachedGeneratedFiles(complete, '/two')).toMatchObject([{ path: '/two/report.md' }]);+ const edited = [user, { ...tool, toolInput: { file_path: 'edited.md' } }, complete[2]];+ expect(collectCachedGeneratedFiles(edited, '/two')).toMatchObject([{ path: '/two/edited.md' }]);+ expect(collectCachedGeneratedFiles([user], '/two')).toEqual([]);+});diff --git a/apps/desktop/src/renderer/__tests__/historyViewportCompensation.test.ts b/apps/desktop/src/renderer/__tests__/historyViewportCompensation.test.tsindex be209fa8f1..e27aef2c86 100644--- a/apps/desktop/src/renderer/__tests__/historyViewportCompensation.test.ts+++ b/apps/desktop/src/renderer/__tests__/historyViewportCompensation.test.ts@@ -3,7 +3,7 @@ import { resolve } from 'node:path';import ts from 'typescript';import { describe, expect, it, vi } from 'vitest';import { toRenderItemViewportSnapshot } from '../components/chat/MessageStream';-import { viewportAnchorCorrection } from '../components/chat/messageViewportCompensation';+import { findRenderItemElement, viewportAnchorCorrection } from '../components/chat/messageViewportCompensation';import { detectScrollAnchoringApplied } from '../components/chat/scrollAnchoringDetect';const source = readFileSync(resolve(__dirname, '../components/chat/MessageStream.tsx'), 'utf8')@@ -39,7 +39,7 @@ function run({ targetTop = 42, missing = false, loading = false, exact = false }},getBoundingClientRect: () => ({ top: 0 }),};- const target = { getBoundingClientRect: () => ({ top: 1058 + targetTop - top, height: 100 }) };+ const target = { getAttribute: () => 'anchor', getBoundingClientRect: () => ({ top: 1058 + targetTop - top, height: 100 }) };const items = [{ key: 'anchor' }];const previousHeight = { current: 38313 };const bindings = {@@ -64,6 +64,7 @@ function run({ targetTop = 42, missing = false, loading = false, exact = false }toRenderItemViewportSnapshot,detectScrollAnchoringApplied,viewportAnchorCorrection,+ findRenderItemElement,beginProgrammaticScroll: vi.fn(() => 1),finishProgrammaticScroll: vi.fn(),requestAnimationFrame: vi.fn(),diff --git a/apps/desktop/src/renderer/__tests__/mainListModel.test.ts b/apps/desktop/src/renderer/__tests__/mainListModel.test.tsindex 5742088270..2c5d13f5e7 100644--- a/apps/desktop/src/renderer/__tests__/mainListModel.test.ts+++ b/apps/desktop/src/renderer/__tests__/mainListModel.test.ts@@ -16,6 +16,7 @@ import {holdViewedPriorityRank,sessionPriorityRecencyMs,sessionPriorityRank,+ sortSessionsForMainList,splitEntriesByDevice,type MainListEntry,} from '../features/cc-agent/lib/mainListModel';@@ -1043,3 +1044,28 @@ it('keeps manual project order while creation-time tasks stay stable inside eachexpect(labels(activityOrder)).toEqual(['p:beta', 'p:alpha']);expect(getMainListEntrySessions(activityOrder[1]).map((s) => s.id)).toEqual(['old', 'recent']);});+++describe('per-sort numeric keys', () => {+ it('reads each activity key a bounded number of times and observes later in-place updates', () => {+ let reads = 0;+ const rows = Array.from({ length: 100 }, (_, i) => {+ const row = session({ id: String(i), updatedAt: new Date(i * 1000).toISOString() });+ let value = row.updatedAt;+ Object.defineProperty(row, 'updatedAt', { get: () => { reads++; return value; }, set: (v) => { value = v; } });+ return row;+ });+ expect(sortSessionsForMainList(rows, 'recency')[0].id).toBe('99');+ expect(reads).toBe(100);+ rows[0].updatedAt = '2030-01-01T00:00:00Z';+ expect(sortSessionsForMainList(rows, 'recency')[0].id).toBe('0');+ });+ it('preserves stable ties, created-id ties and invalid userSendAt semantics', () => {+ const a = session({ id: 'z', updatedAt: '2026-01-01T00:00:00Z' });+ const b = session({ id: 'a', updatedAt: a.updatedAt });+ const invalid = session({ id: 'invalid', updatedAt: '2030-01-01T00:00:00Z', userSendAt: 'invalid' });+ expect(sortSessionsForMainList([a, b, invalid], 'recency').map(x => x.id)).toEqual(['z', 'a', 'invalid']);+ expect(sortSessionsForMainList([a, b], 'created').map(x => x.id)).toEqual(['a', 'z']);+ expect(sortSessionsForMainList([a, b], 'priority').map(x => x.id)).toEqual(['z', 'a']);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.tsindex 0a2b513a86..a11ffcacb8 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts@@ -51,6 +51,8 @@ import * as sessionService from '@/lib/sessionService';import {markSessionAutomaticHistoryLoadCompleted,restoreSessionAutomaticHistoryLoadAttempts,+ saveSessionScroll,+ clearSessionScroll,} from '@/lib/sessionScrollStore';const BASE_TIME = new Date('2026-05-20T00:00:00.000Z');@@ -170,12 +172,86 @@ describe('makerChatStore active view tracking', () => {afterEach(() => {for (const dispose of [...disposers].reverse()) dispose();- for (const sessionId of sessionIds) makerChatStore.purgeSession(sessionId);+ for (const sessionId of sessionIds) {+ makerChatStore.purgeSession(sessionId);+ clearSessionScroll(sessionId);+ }makerChatStore.__teardownGlobalListeners();vi.unstubAllGlobals();vi.useRealTimers();});+ async function readingWindow(label: string, count = 350, contentSize = 1) {+ const id = sid(label);+ const leave = enter(id);+ vi.mocked(messageService.list).mockResolvedValueOnce(Array.from({ length: count }, (_, i) =>+ dbMessage(id, `${i}`, 'x'.repeat(contentSize), new Date(BASE_TIME.getTime() + i * 1000).toISOString()),+ ));+ makerChatStore.ensureInitialMessages(id);+ await flushPromises();+ saveSessionScroll(id, { windowAnchorKey: null, viewportTopKey: 'msg-client-0',+ messageClientId: 'client-0', offset: 0, isNearBottom: false });+ return { id, leave, messages: makerChatStore.getSnapshot(id).messages };+ }++ it('keeps a bounded old reading window on a hot return without another history read', async () => {+ const view = await readingWindow('reading');+ view.leave();+ expect(makerChatStore.getSnapshot(view.id).messages).toBe(view.messages);+ enter(view.id);+ makerChatStore.ensureInitialMessages(view.id);+ await flushPromises();+ expect(makerChatStore.getSnapshot(view.id).messages).toBe(view.messages);+ expect(messageService.list).toHaveBeenCalledTimes(1);+ });++ it('cannot resurrect a retained reading window after purge and same-id reopen', async () => {+ const view = await readingWindow('purged-reading');+ view.leave();+ makerChatStore.purgeSession(view.id);+ vi.mocked(messageService.list).mockResolvedValueOnce([+ dbMessage(view.id, 'fresh', 'new history', BASE_TIME.toISOString()),+ ]);+ enter(view.id);+ makerChatStore.ensureInitialMessages(view.id);+ await flushPromises();+ expect(makerChatStore.getSnapshot(view.id).messages.map((message) => message.clientId))+ .toEqual(['client-fresh']);+ });++ it('trims the displaced third reading window immediately and respects final-view ownership', async () => {+ const a = await readingWindow('reading-a');+ const extra = enter(a.id);+ a.leave();+ expect(makerChatStore.getSnapshot(a.id).messages).toBe(a.messages);+ extra();+ const b = await readingWindow('reading-b'); b.leave();+ const c = await readingWindow('reading-c'); c.leave();+ expect(makerChatStore.getSnapshot(a.id).messages).toHaveLength(200);+ expect(makerChatStore.getSnapshot(b.id).messages).toBe(b.messages);+ expect(makerChatStore.getSnapshot(c.id).messages).toBe(c.messages);+ });++ it('does not reserve tail views, oversized row counts or oversized text windows', async () => {+ const tail = await readingWindow('tail');+ saveSessionScroll(tail.id, { windowAnchorKey: null, viewportTopKey: 'msg-client-0', offset: 0, isNearBottom: true });+ tail.leave();+ expect(makerChatStore.getSnapshot(tail.id).messages).toHaveLength(200);+ const many = await readingWindow('many', 1001); many.leave();+ expect(makerChatStore.getSnapshot(many.id).messages).toHaveLength(200);+ const large = await readingWindow('large', 350, 100_000); large.leave();+ expect(makerChatStore.getSnapshot(large.id).messages).toHaveLength(200);+ });++ it('bounds the combined text budget and still demotes retained histories after five minutes', async () => {+ const a = await readingWindow('budget-a', 350, 50_000); a.leave();+ const b = await readingWindow('budget-b', 350, 50_000); b.leave();+ expect(makerChatStore.getSnapshot(a.id).messages).toHaveLength(200);+ expect(makerChatStore.getSnapshot(b.id).messages).toBe(b.messages);+ vi.advanceTimersByTime(5 * 60_000);+ expect(makerChatStore.getSnapshot(b.id).messages).toHaveLength(0);+ });+it('enterView marks a session active and clears lastViewedAt', () => {const sessionId = sid('enter');const dispose = enter(sessionId);diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.tsindex 23298348e0..c292c40fb2 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts@@ -897,6 +897,24 @@ describe('同一次中断事件的多次重连折叠成一行', () => {} as Message['agentMeta'],});+ it('keeps separate resume groups with substantive boundaries and trailing normal rows', async () => {+ vi.mocked(messageService.list).mockResolvedValueOnce([+ resumeRow('r1', 1), resumeRow('r2', 2),+ serverMessage({ clientId: 'boundary', role: 'assistant', content: 'visible', createdAt: '2026-06-12T00:00:05.000Z' }),+ resumeRow('r3', 1, undefined, '2026-06-12T00:00:1'),+ resumeRow('r4', 2, undefined, '2026-06-12T00:00:1'),+ serverMessage({ clientId: 'tail', role: 'assistant', content: 'done', createdAt: '2026-06-12T00:00:20.000Z' }),+ ]);+ makerChatStore.ensureInitialMessages(SID);+ await flush();+ await flush();+ expect(makerChatStore.getSnapshot(SID).messages.filter((m) => m.systemCardType === 'auto-resume')+ .map((m) => m.clientId)).toEqual(['r2', 'r4']);+ const messages = makerChatStore.getSnapshot(SID).messages;+ inputProjectionCb!(projection());+ expect(makerChatStore.getSnapshot(SID).messages).toBe(messages);+ });+it('连续三次重连只渲染最后一条(带最新计数),前两条退回隐藏占位', async () => {vi.mocked(messageService.list).mockResolvedValueOnce([resumeRow('r1', 1, 'failed'),diff --git a/apps/desktop/src/renderer/__tests__/messageItemHeightCacheIntegration.test.ts b/apps/desktop/src/renderer/__tests__/messageItemHeightCacheIntegration.test.tsindex e6a05eb572..635097d50c 100644--- a/apps/desktop/src/renderer/__tests__/messageItemHeightCacheIntegration.test.ts+++ b/apps/desktop/src/renderer/__tests__/messageItemHeightCacheIntegration.test.ts@@ -3,10 +3,10 @@ import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import ts from 'typescript';import { afterEach, describe, expect, it, vi } from 'vitest';-import { rememberedItemIntrinsicSize } from '../components/chat/messageViewportCompensation';+import { findRenderItemElement, rememberedItemIntrinsicSize } from '../components/chat/messageViewportCompensation';// Run the production capture callback and restore layout effect, including their-// DOM/index matching. A missing card must never borrow its neighbour's height.+// stable-key DOM matching. A missing card must never borrow its neighbour's height.const source = ts.createSourceFile('MessageStream.tsx', readFileSync(resolve(__dirname, '../components/chat/MessageStream.tsx'), 'utf8',), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);@@ -33,6 +33,7 @@ function setup(keys: string[], mountedKeys: string[], cached = { before: 100, caconst elements = new Map<string, HTMLElement>();for (const [index, key] of mountedKeys.entries()) {const row = items.appendChild(document.createElement('div'));+ row.dataset.renderItemKey = key;row.style.cssText = 'padding-top: 7px; padding-bottom: 9px; border-top: 1px solid; border-bottom: 3px solid';row.style.containIntrinsicBlockSize = 'auto 999px';row.getBoundingClientRect = () => ({ height: 120 + index * 200 }) as DOMRect;@@ -49,6 +50,9 @@ function setup(keys: string[], mountedKeys: string[], cached = { before: 100, cavisibleRenderItems: keys.map((key) => ({ key })),visibleRenderItemsRef: { current: keys.map((key) => ({ key })) },rememberedItemIntrinsicSize,+ findRenderItemElement,+ restoreLoadRef: { current: 'settled' },+ restoreClientIdForItem: () => undefined,refreshViewportAnchor: () => ({ viewportTopKey: 'after', offset: 12 }),saveSessionScroll: save,sessionId: 'height-cache-fixture',@@ -84,13 +88,18 @@ describe('message item height cache DOM alignment', () => {view.capture(true);expect(view.save).toHaveBeenCalledOnce();expect(view.save.mock.calls[0][1]).toMatchObject({ viewportTopKey: 'after', offset: 12 });- expect(view.save.mock.calls[0][1].itemHeights).toBeUndefined();+ const byKey = view.save.mock.calls[0][1].itemHeights.byKey;+ expect(byKey).not.toHaveProperty(missing);+ expect(byKey).toEqual(Object.fromEntries(+ ['before', 'card', 'after'].filter(key => key !== missing).map((key, index) => [key, 100 + index * 200]),+ ));});- it('clears estimates instead of applying the absent card height to the next row', () => {+ it('restores each present key without borrowing an absent card height', () => {const view = setup(['before', 'card', 'after'], ['before', 'after']);view.restore();- for (const row of view.elements.values()) expect(row.style.containIntrinsicBlockSize).toBe('');+ expect(view.elements.get('before')!.style.containIntrinsicBlockSize).toBe('auto 100px');+ expect(view.elements.get('after')!.style.containIntrinsicBlockSize).toBe('auto 600px');});it('captures content-box heights and restores matching rows', () => {diff --git a/apps/desktop/src/renderer/__tests__/messageProjectionCache.test.ts b/apps/desktop/src/renderer/__tests__/messageProjectionCache.test.tsnew file mode 100644index 0000000000..fdfbe7c457--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/messageProjectionCache.test.ts@@ -0,0 +1,33 @@+import { expect, it, vi } from 'vitest';+import { createMessageProjectionCache } from '@/components/chat/messageProjectionCache';++it('reuses history when switching away and back, but invalidates each changed projection input', () => {+ const project = createMessageProjectionCache<object[], object>();+ const a = [{}];+ const b = [{}];+ const compute = vi.fn(() => ({}));+ const dependencies: unknown[] = [new Map(), {}, false, [], '/work', undefined];+ const first = project(a, dependencies, compute);+ project(b, dependencies, compute);+ expect(project(a, [...dependencies], compute)).toBe(first);+ expect(compute).toHaveBeenCalledTimes(2);+ for (let index = 0; index < dependencies.length; index++) {+ dependencies[index] = {};+ expect(project(a, [...dependencies], compute)).not.toBe(first);+ expect(compute).toHaveBeenCalledTimes(index + 3);+ }+ const beforeNewMessages = compute.mock.calls.length;+ project([...a], dependencies, compute);+ expect(compute).toHaveBeenCalledTimes(beforeNewMessages + 1);+});++it('does not publish a failed projection', () => {+ const project = createMessageProjectionCache<object, string>();+ const snapshot = {};+ expect(() =>+ project(snapshot, [], () => {+ throw new Error('failed');+ }),+ ).toThrow('failed');+ expect(project(snapshot, [], () => 'ready')).toBe('ready');+});diff --git a/apps/desktop/src/renderer/__tests__/messageRenderItemDom.test.ts b/apps/desktop/src/renderer/__tests__/messageRenderItemDom.test.tsnew file mode 100644index 0000000000..d44a4005d0--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/messageRenderItemDom.test.ts@@ -0,0 +1,49 @@+// @vitest-environment jsdom+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { describe, expect, it } from 'vitest';+import { findRenderItemElement } from '../components/chat/messageViewportCompensation';+import { pickIntersectingChildAnchor, readViewportChildAnchorClientId } from '../components/chat/MessageStream';++describe('render item identity across asynchronous cards', () => {+ it('keeps the same message when an earlier card mounts or disappears', () => {+ const container = document.createElement('div');+ const message = document.createElement('div');+ message.setAttribute('data-render-item-key', 'msg-target');+ container.append(message);+ expect(findRenderItemElement(container, 'genfiles-earlier')).toBeUndefined();+ expect(findRenderItemElement(container, 'msg-target')).toBe(message);++ const card = document.createElement('div');+ card.setAttribute('data-render-item-key', 'genfiles-earlier');+ container.prepend(card);+ expect(findRenderItemElement(container, 'msg-target')).toBe(message);+ expect(findRenderItemElement(container, 'genfiles-earlier')).toBe(card);+ card.remove();+ expect(findRenderItemElement(container, 'msg-target')).toBe(message);+ expect(findRenderItemElement(container, 'missing')).toBeUndefined();+ });+});++// Exercise the actual capture callback, including absent/zero-height rows and gaps.+it('captures a visible row after empty rows and retains its signed viewport gap', () => {+ const source = readFileSync(resolve(__dirname, '../components/chat/MessageStream.tsx'), 'utf8');+ const start = source.indexOf(' const measureViewportTop = useCallback');+ const end = source.indexOf(' const refreshViewportAnchor = useCallback', start);+ const code = ts.transpileModule(source.slice(start, end) + '\nreturn measureViewportTop();', {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+ const container = document.createElement('div');+ container.getBoundingClientRect = () => ({ top: 40 }) as DOMRect;+ const items = document.createElement('div');+ for (const [key, top, height] of [['empty', 42, 0], ['visible', 54, 80]] as const) {+ const row = items.appendChild(document.createElement('div'));+ row.dataset.renderItemKey = key;+ row.getBoundingClientRect = () => ({ top, bottom: top + height, height }) as DOMRect;+ }+ const result = new Function('useCallback', 'scrollRef', 'itemsRef', 'pickIntersectingChildAnchor', 'readViewportChildAnchorClientId', code)(+ (callback: unknown) => callback, { current: container }, { current: items }, pickIntersectingChildAnchor, readViewportChildAnchorClientId,+ );+ expect(result).toEqual({ viewportTopKey: 'visible', offset: -14 });+});diff --git a/apps/desktop/src/renderer/__tests__/messageStreamRenderWindowIntegration.test.ts b/apps/desktop/src/renderer/__tests__/messageStreamRenderWindowIntegration.test.tsindex 10b68c3395..cd38dfae83 100644--- a/apps/desktop/src/renderer/__tests__/messageStreamRenderWindowIntegration.test.ts+++ b/apps/desktop/src/renderer/__tests__/messageStreamRenderWindowIntegration.test.ts@@ -31,7 +31,11 @@ import {buildRenderItems,groupWorkRuns,snapRenderWindowStartIdx,- isViewportAnchorWithinDefaultTail,+ resolveSavedViewportKey,+ resolveRestoredRenderWindow,+ restoreClientIdFromKey,+ restoreClientIdForItem,+ viewportRestoreNeedsMoreContent,resolveAnchoredWindowItemCount,resolveDefaultWindowStartIdx,shouldBoostDefaultWindow,@@ -602,22 +606,68 @@ describe('first-paint content budget (clampTailWindowStartByBudget)', () => {});});-describe('restored default-tail window bound', () => {+describe('restored reading position', () => {+ it('grows a short restored window when overflow still cannot accommodate the saved offset', () => {+ // Regression: 98 px of overflow existed, but restoring needed 330 px.+ expect(viewportRestoreNeedsMoreContent(330, 1242, 1144, false)).toBe(true);+ expect(viewportRestoreNeedsMoreContent(330, 1600, 1144, false)).toBe(false);+ expect(viewportRestoreNeedsMoreContent(330, 1242, 1144, true)).toBe(false);+ expect(viewportRestoreNeedsMoreContent(0, 900, 1144, false)).toBe(false);+ });++ it('retains real source identifiers for synthetic cards and compound keys', () => {+ expect(restoreClientIdFromKey('genfiles-user-with-dashes')).toBe('user-with-dashes');+ expect(restoreClientIdFromKey('work-summary-tool-with-dashes')).toBe('tool-with-dashes');+ expect(restoreClientIdFromKey('subagent-media-tool-with-dashes')).toBe('tool-with-dashes');+ expect(restoreClientIdFromKey('ghostcard-tool-with-dashes')).toBe('tool-with-dashes');+ expect(restoreClientIdFromKey('fork-origin-session')).toBeUndefined();+ expect(restoreClientIdForItem({ type: 'agent_plan', key: 'plan-changing', todos: [], sourceClientIds: ['plan-source'] }))+ .toBe('plan-source');+ expect(restoreClientIdForItem({ type: 'generated_files', key: 'genfiles-user', files: [], turnStartMs: null, turnEndMs: null }))+ .toBe('user');+ });+const items = Array.from({ length: RENDER_WINDOW_INITIAL_ITEMS + 40 }, (_, i) => ({key: `message-m-${i}`,type: 'message' as const,message: mkAssistant(`m-${i}`),}));- it('accepts an anchor still inside the current default tail', () => {- expect(- isViewportAnchorWithinDefaultTail(items, items[items.length - RENDER_WINDOW_INITIAL_ITEMS].key),- ).toBe(true);- expect(isViewportAnchorWithinDefaultTail(items, items.at(-1)!.key)).toBe(true);+ it('restores an old anchor outside the tail using a bounded window', () => {+ const snapshot = { windowAnchorKey: null, viewportTopKey: items[0].key, offset: 18, isNearBottom: false };+ expect(resolveSavedViewportKey(items, snapshot)).toBe(items[0].key);+ expect(resolveAnchoredWindowItemCount(0, 0, RENDER_WINDOW_FIRST_PAINT_ITEMS))+ .toBe(RENDER_WINDOW_FIRST_PAINT_ITEMS);+ expect(resolveSavedViewportKey(items.slice(1), snapshot)).toBeNull();+ });++ it('remounts around the viewport instead of the entire previously expanded history', () => {+ const snapshot = { windowAnchorKey: items[0].key, viewportTopKey: items[70].key,+ anchoredForwardCount: 120, offset: 18, isNearBottom: false };+ const window = resolveRestoredRenderWindow(snapshot);+ const anchorIndex = items.findIndex(item => item.key === window.anchor);+ const start = snapRenderWindowStartIdx(items, anchorIndex);+ const visible = items.slice(start, start + resolveAnchoredWindowItemCount(start, anchorIndex, window.forwardItems));+ expect(window.forwardItems).toBe(RENDER_WINDOW_FIRST_PAINT_ITEMS);+ expect(visible).toContain(items[70]);+ expect(visible).not.toContain(items[0]);+ expect(visible.length).toBeLessThan(snapshot.anchoredForwardCount);+ });++ it('retains legacy window fallback and resets near-bottom snapshots to the tail', () => {+ const legacy = { windowAnchorKey: items[0].key, viewportTopKey: '',+ anchoredForwardCount: 120, offset: 18, isNearBottom: false };+ expect(resolveRestoredRenderWindow(legacy)).toEqual({ anchor: items[0].key, forwardItems: 120 });+ expect(resolveRestoredRenderWindow({ ...legacy, isNearBottom: true }))+ .toEqual({ anchor: null, forwardItems: RENDER_WINDOW_FIRST_PAINT_ITEMS });});- it('rejects an anchor pushed out of the tail by background appends', () => {- expect(isViewportAnchorWithinDefaultTail(items, items[0].key)).toBe(false);- expect(isViewportAnchorWithinDefaultTail(items, 'message-m-missing')).toBe(false);+ it('prefers a saved generated-files card over its earlier source user row', () => {+ const source = { type: 'message' as const, key: 'msg-user', message: mkUser('user') };+ const card = { type: 'generated_files' as const, key: 'genfiles-user', files: [], turnStartMs: null, turnEndMs: null };+ const snapshot = { windowAnchorKey: null, viewportTopKey: card.key, restoreClientId: 'user', offset: 12, isNearBottom: false };+ expect(resolveSavedViewportKey([source, card], snapshot)).toBe(card.key);+ expect(resolveSavedViewportKey([source], snapshot)).toBe(source.key);+ expect(resolveSavedViewportKey([], snapshot)).toBeNull();});});diff --git a/apps/desktop/src/renderer/__tests__/messageViewportDeletionIntegration.test.ts b/apps/desktop/src/renderer/__tests__/messageViewportDeletionIntegration.test.tsindex 5ca2850e55..b282587017 100644--- a/apps/desktop/src/renderer/__tests__/messageViewportDeletionIntegration.test.ts+++ b/apps/desktop/src/renderer/__tests__/messageViewportDeletionIntegration.test.ts@@ -16,6 +16,7 @@ import {toRenderItemViewportSnapshot,} from '../components/chat/MessageStream';import {+ findRenderItemElement,canCompensateMessageHeight,viewportAnchorCorrection,} from '../components/chat/messageViewportCompensation';@@ -100,6 +101,7 @@ function setup({ deleted = true, hidden = false, nativeShift = 0 } = {}) {const elements = new Map<string, HTMLElement>();for (const item of after) {const row = items.appendChild(document.createElement('div'));+ row.dataset.renderItemKey = item.key;const rowTop = item.key === afterGroup.key ? 200 : item.type === 'message' && item.message.role === 'user' ? 0 : 1800;row.getBoundingClientRect = () => rect(containerTop + rowTop - root.scrollTop, 1000);for (const id of collectDeleteAnchorClientIds([item])) {@@ -128,6 +130,7 @@ function setup({ deleted = true, hidden = false, nativeShift = 0 } = {}) {requestAnimationFrame: (callback: FrameRequestCallback) => frames.push(callback),beginProgrammaticScroll: () => { programmaticScrollRef.current = true; return 1; },finishProgrammaticScroll: () => { programmaticScrollRef.current = false; },+ findRenderItemElement,canCompensateMessageHeight,viewportAnchorCorrection,renderItemContainsClientId,diff --git a/apps/desktop/src/renderer/__tests__/messageViewportRestoreDom.test.ts b/apps/desktop/src/renderer/__tests__/messageViewportRestoreDom.test.tsnew file mode 100644index 0000000000..b401ff9def--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/messageViewportRestoreDom.test.ts@@ -0,0 +1,166 @@+// @vitest-environment jsdom+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { createElement, useLayoutEffect, useState } from 'react';+import { createRoot } from 'react-dom/client';+import { flushSync } from 'react-dom';+import { describe, expect, it } from 'vitest';+import { findRestorableViewportItemIdx, pickIntersectingChildAnchor, readViewportChildAnchorClientId, viewportRestoreNeedsMoreContent } from '../components/chat/MessageStream';+import { findRenderItemElement, viewportAnchorCorrection } from '../components/chat/messageViewportCompensation';++// Run the actual capture and positioning callbacks with a deterministic layout.+// jsdom cannot lay out, so rectangles model a message moving into a work group.+const source = ts.createSourceFile('MessageStream.tsx', readFileSync(+ resolve(__dirname, '../components/chat/MessageStream.tsx'), 'utf8',+), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const component = source.statements.find((node): node is ts.FunctionDeclaration =>+ ts.isFunctionDeclaration(node) && node.name?.text === 'MessageStream')!;+const names = ['measureViewportTop', 'scrollMessageToViewportTop'];+const statements = component.body!.statements.filter(node => ts.isVariableStatement(node) &&+ node.declarationList.declarations.some(d => names.includes(d.name.getText(source))));+if (statements.length !== names.length) throw new Error('Viewport callbacks not found');+const query = source.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === 'queryMessageElement')!;+const code = ts.transpileModule([query, ...statements].map(node => node.getText(source)).join('\n') ++ '\nreturn {capture:measureViewportTop,restore:scrollMessageToViewportTop};', {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+}).outputText;++function setup() {+ const container = document.createElement('div');+ const items = container.appendChild(document.createElement('div'));+ container.scrollTop = 100;+ container.getBoundingClientRect = () => ({ top: 40 }) as DOMRect;+ const row = items.appendChild(document.createElement('div'));+ row.dataset.renderItemKey = 'msg-target';+ row.dataset.messageClientId = 'target';+ const measure = (element: HTMLElement, y: number, height = 300) => {+ element.getBoundingClientRect = () => ({ top: y - container.scrollTop,+ bottom: y - container.scrollTop + height, height }) as DOMRect;+ };+ measure(row, 120);+ const bindings = {+ useCallback: (callback: unknown) => callback,+ scrollRef: { current: container }, itemsRef: { current: items },+ pickIntersectingChildAnchor, readViewportChildAnchorClientId, viewportAnchorCorrection,+ CSS: { escape: (id: string) => id }, isLoadingMore: false,+ prevScrollHeightRef: { current: 0 }, prevScrollTopAtLoadRef: { current: 0 },+ beginProgrammaticScroll: () => 1, finishProgrammaticScroll: () => false,+ requestAnimationFrame: (callback: () => void) => { callback(); return 1; },+ };+ const callbacks = new Function(...Object.keys(bindings), code)(...Object.values(bindings));+ return { container, row, measure, ...callbacks };+}++describe('message viewport capture and restore across remount', () => {+ it('captures an exact message on the render-item root and restores after a 40px group prefix', () => {+ const view = setup();+ const saved = view.capture();+ expect(saved).toEqual({ viewportTopKey: 'msg-target', offset: 20,+ messageClientId: 'target', messageOffset: 20 });+ delete view.row.dataset.messageClientId;+ view.row.dataset.renderItemKey = 'work-target';+ const message = view.row.appendChild(document.createElement('div'));+ message.dataset.messageClientId = 'target';+ view.measure(message, 160, 260);+ expect(view.restore(saved.messageClientId, saved.messageOffset)).toBe(true);+ expect(message.getBoundingClientRect().top).toBe(20);+ expect(view.container.scrollTop).toBe(140);+ });++ it('still prefers the innermost visible exact message and excludes hidden children', () => {+ const view = setup();+ const child = view.row.appendChild(document.createElement('div'));+ child.dataset.messageClientId = 'inner';+ view.measure(child, 130, 100);+ const hidden = child.appendChild(document.createElement('div'));+ hidden.dataset.messageClientId = 'hidden';+ view.measure(hidden, 135, 0);+ expect(view.capture()).toMatchObject({ messageClientId: 'inner', messageOffset: 10 });+ child.remove();+ expect(view.capture()).toMatchObject({ messageClientId: 'target', messageOffset: 20 });+ });++ it('preserves the signed gap when the first message starts below the viewport', () => {+ const view = setup();+ view.measure(view.row, 152);+ const saved = view.capture();+ expect(saved).toMatchObject({ messageClientId: 'target', messageOffset: -12 });+ view.measure(view.row, 192);+ expect(view.restore(saved.messageClientId, saved.messageOffset)).toBe(true);+ expect(view.row.getBoundingClientRect().top).toBe(52);+ });+});++it('finishes a required forward-window expansion in the layout commit before paint', () => {+ const restoration = component.body!.statements.find(node => ts.isExpressionStatement(node) &&+ node.getText(source).includes('const restoredKey = resolveSavedViewportKey'))!;+ const effect = ts.transpileModule(restoration.getText(source), {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+ const allRenderItems = Array.from({ length: 30 }, (_, i) => ({ key: `row-${i}` }));+ const restoreLoadRef = { current: 'idle' };+ const restoringRef = { current: true };+ const restoreSnapshotRef = { current: { viewportTopKey: 'row-0' } };+ const commits: number[] = [];+ function Fixture() {+ const [count, setCount] = useState(15);+ useLayoutEffect(() => { commits.push(count); });+ const bindings = {+ useLayoutEffect, restoringRef, restoreLoadRef, restoreSnapshotRef,+ historyLoaded: true, firstMountDeferred: false, historyCleared: false,+ restoreCancelledRef: { current: false }, sessionId: 'reading', restoreRevision: 0,+ allRenderItems, visibleRenderItems: allRenderItems.slice(0, count),+ restoreClientIdFromKey: () => 'source', resolveSavedViewportKey: () => 'row-0',+ setFirstVisibleItemKey: () => { throw new Error('Anchor was already mounted'); },+ setAnchoredForwardItems: setCount,+ applyRestoreRef: { current: () => {+ if (count < 30) { setCount(count + 40); return false; }+ return true;+ } },+ };+ new Function(...Object.keys(bindings), effect)(...Object.values(bindings));+ return null;+ }+ const root = createRoot(document.createElement('div'));+ try {+ flushSync(() => root.render(createElement(Fixture)));+ expect(commits).toEqual([15, 55]);+ expect(restoreLoadRef.current).toBe('settled');+ } finally {+ flushSync(() => root.unmount());+ }+});++it('bounds synchronous expansion rounds through thousands of non-rendering rows', () => {+ const statement = component.body!.statements.find(node => ts.isVariableStatement(node) &&+ node.declarationList.declarations.some(d => d.name.getText(source) === 'applyRestore'))!;+ const effect = ts.transpileModule(statement.getText(source) + '\nreturn applyRestore;', {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+ const container = { scrollTop: 0, scrollHeight: 800, clientHeight: 800,+ getBoundingClientRect: () => ({ top: 0 }) };+ const row = { getAttribute: () => 'anchor', getBoundingClientRect: () => ({ top: 100, height: 100 }) };+ const count = { current: 15 };+ const coversEnd = { current: false };+ const bindings = {+ useCallback: (callback: unknown) => callback,+ restoreSnapshotRef: { current: { viewportTopKey: 'anchor', offset: 0 } },+ scrollRef: { current: container }, itemsRef: { current: { children: [row] } },+ visibleRenderItemsRef: { current: [{ key: 'anchor' }] },+ findRestorableViewportItemIdx, findRenderItemElement, viewportAnchorCorrection,+ viewportRestoreNeedsMoreContent, windowCoversEndRef: coversEnd,+ restoreLoadRef: { current: 'idle' }, anchoredForwardItemsRef: count,+ RENDER_WINDOW_GROWTH_ITEMS: 80,+ setAnchoredForwardItems: (update: (previous: number) => number) => { count.current = update(count.current); },+ beginProgrammaticScroll: () => 1, finishProgrammaticScroll: () => false,+ refreshViewportAnchor: () => null, scrollMessageToViewportTop: () => false,+ requestAnimationFrame: (callback: () => void) => { callback(); return 1; },+ };+ const restore = new Function(...Object.keys(bindings), effect)(...Object.values(bindings));+ let rounds = 0;+ while (count.current < 5000 && rounds < 50) { expect(restore()).toBe(false); rounds++; }+ expect(rounds).toBeLessThan(10);+ coversEnd.current = true;+ expect(restore()).toBe(true);+});diff --git a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.tsindex c519261e2e..90fa9d31d7 100644--- a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts+++ b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts@@ -83,10 +83,11 @@ describe('pinned project sidebar integration', () => {'const filter = useSidebarFilter(hiddenProjectKeys, sidebarSettingsSnapshot);',);expect(sidebarSource).toContain('collectRestorableProjectKeys({');+ expect(sidebarSource).toContain('collectRestorableProjectKeysRef.current = () =>');expect(sidebarSource).toContain('sessions: scopedSidebarSessions,');expect(sidebarSource).toContain('const restored = await restoreHiddenProjectIfPresent({');expect(sidebarSource).toContain(- 'getCurrentProjectKeys: () => restorableProjectKeysRef.current,',+ 'getCurrentProjectKeys: () => collectRestorableProjectKeysRef.current(),',);expect(sidebarSource).toContain('ensureProjectIncluded: filter.ensureProjectIncluded,');expect(sidebarSource).toContain('localPlatform,');diff --git a/apps/desktop/src/renderer/__tests__/projectGroupsSelector.test.ts b/apps/desktop/src/renderer/__tests__/projectGroupsSelector.test.tsindex 5634e4f543..6e4e3bc321 100644--- a/apps/desktop/src/renderer/__tests__/projectGroupsSelector.test.ts+++ b/apps/desktop/src/renderer/__tests__/projectGroupsSelector.test.ts@@ -125,3 +125,135 @@ describe('project grouping structural reuse', () => {expect(after.projects.filter((p, i) => p === before.projects[i]).length).toBeGreaterThan(20);});});++function session(id: string, patch: Partial<Session> = {}): Session {+ return {+ id,+ title: id,+ workingDir: `/workspace/${id}`,+ workspaceKind: 'project',+ status: 'active',+ pinnedAt: null,+ userSendAt: '2026-08-01T00:00:00Z',+ createdAt: '2026-08-01T00:00:00Z',+ updatedAt: '2026-08-01T00:00:00Z',+ _count: { messages: 1 },+ ...patch,+ } as Session;+}++describe('project grouping projection', () => {+ it('publishes row patches in every bucket without invalidating unrelated projects', () => {+ const rows = [session('a', { pinnedAt: '2026-08-01T00:00:00Z' }), session('b')];+ const options = { includePinnedInProjects: true };+ const select = createProjectGroupsSelector();+ const before = select(rows, options);+ const changed = {+ ...rows[0],+ title: 'new title',+ totalCostUsd: 12,+ updatedAt: '2026-08-02T00:00:00Z',+ _count: { messages: 20 },+ };+ const after = select([changed, rows[1]], options);+ expect(after).toEqual(groupSessions([changed, rows[1]], options));+ expect(after.pinned[0]).toBe(changed);+ expect(after.projects.find((p) => p.workingDir.endsWith('/a'))?.sessions[0]).toBe(changed);+ expect(after.projects.find((p) => p.workingDir.endsWith('/b'))).toBe(+ before.projects.find((p) => p.workingDir.endsWith('/b')),+ );+ expect(after.dialogues).toBe(before.dialogues);+ expect(select([changed, rows[1]], options)).toBe(after);+ });++ it.each([+ { workingDir: '/other/repo' },+ { pinnedAt: '2026-09-01T00:00:00Z' },+ { status: 'archived' },+ { workspaceKind: 'dialogue' },+ { userSendAt: '2026-09-01T00:00:00Z' },+ { createdAt: '2020-01-01T00:00:00Z' },+ { remoteHostId: 'ssh-host' },+ { deviceLinkDeviceId: 'device', deviceLinkDeviceName: 'Mac' },+ { deviceLinkConnectionStatus: 'disconnected' },+ { source: 'scheduler' },+ { orcaRole: 'lead' },+ { agentKind: 'pi' },+ ] as Partial<Session>[])(+ 'matches canonical regrouping when structural fields change: %j',+ (patch) => {+ const rows = [session('a'), session('b', { workingDir: '/other/a' })];+ const select = createProjectGroupsSelector();+ select(rows);+ const changed = [{ ...rows[0], ...patch }, rows[1]];+ expect(select(changed)).toEqual(groupSessions(changed));+ },+ );++ it('invalidates first-message classification and the fallback draft clock', () => {+ const draft = session('draft', { userSendAt: null, _count: { messages: 0 } });+ const select = createProjectGroupsSelector();+ expect(select([draft]).unclassified).toHaveLength(1);+ const firstReply = { ...draft, _count: { messages: 1 } };+ expect(select([firstReply])).toEqual(groupSessions([firstReply]));+ expect(select([firstReply]).projects).toHaveLength(1);+ const later = { ...firstReply, updatedAt: '2026-09-01T00:00:00Z' };+ expect(select([later]).projects[0].latestActivityAt).toBe(later.updatedAt);+ });++ it('preserves stable-sort input order and resets on removal or empty data', () => {+ const rows = [session('a', { workingDir: '/same' }), session('b', { workingDir: '/same' })];+ const select = createProjectGroupsSelector();+ select(rows);+ for (const next of [[rows[1], rows[0]], [rows[1]], [], rows]) {+ expect(select(next)).toEqual(groupSessions(next));+ }+ });++ it('invalidates aliases, platform, pinned/draft policy, persistent projects and bot ownership', () => {+ const rows = [session('a')];+ const select = createProjectGroupsSelector();+ const policies: GroupSessionsOptions[] = [+ {},+ { projectAliases: new Map([['local:/workspace/a', 'Alias']]) },+ { localPlatform: 'win32' },+ { includePinnedInProjects: true },+ { includeDraftsInProjects: true },+ {+ persistentLocalProjects: [+ { workingDir: '/empty', lastUsedAt: '2026-09-01T00:00:00Z', knownAgentKinds: ['pi'] },+ ],+ },+ {+ botOwnerBySessionId: new Map([+ ['a', { botId: 'bot', displayName: 'Bot', avatar: 'star', avatarColor: 'blue' }],+ ]),+ },+ ];+ for (const options of policies)+ expect(select(rows, options)).toEqual(groupSessions(rows, options));+ const options = policies.at(-1)!;+ const updated = [{ ...rows[0], title: 'bot row update' }];+ expect(select(updated, options)).toEqual(groupSessions(updated, options));+ expect(select(updated, options).bots[0].sessions[0]).toBe(updated[0]);+ });++ it('reuses equal persistent catalogues but refreshes changed project metadata', () => {+ const rows = [session('a')];+ const projects = [+ { workingDir: '/empty', lastUsedAt: '2026-09-01T00:00:00Z', knownAgentKinds: ['pi'] },+ ];+ const select = createProjectGroupsSelector();+ const first = select(rows, { persistentLocalProjects: projects });+ expect(+ select(rows, {+ persistentLocalProjects: projects.map((p) => ({+ ...p,+ knownAgentKinds: [...p.knownAgentKinds],+ })),+ }),+ ).toBe(first);+ const changed = { persistentLocalProjects: [{ ...projects[0], knownAgentKinds: ['cc'] }] };+ expect(select(rows, changed)).toEqual(groupSessions(rows, changed));+ });+});diff --git a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.tsindex 43357668ff..0dd4231cc4 100644--- a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts+++ b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts@@ -129,7 +129,7 @@ describe('Projects sidebar section', () => {expect(projectsSectionSource).toContain('return splitEntriesByDevice(mixedEntries, [...(remoteDeviceIndex?.keys() ?? [])], {',);- expect(projectsSectionSource).toContain('unclassified: deviceGroupingActive && !unclassifiedHidden ? unclassified : []');+ expect(projectsSectionSource).toContain('unclassified: deviceGroupingActive && !unclassifiedHidden ? unclassified : undefined');// 每段独立折叠视图 + 段内作用域的「显示全部」(复核 P2:共用一个标志会让// 点任一段全段展开)。expect(projectsSectionSource).toMatch(diff --git a/apps/desktop/src/renderer/__tests__/restoreComposerDocument.test.ts b/apps/desktop/src/renderer/__tests__/restoreComposerDocument.test.tsnew file mode 100644index 0000000000..bfb2ba3b6a--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/restoreComposerDocument.test.ts@@ -0,0 +1,71 @@+// @vitest-environment jsdom+import { Editor, Mark } from '@tiptap/core';+import Document from '@tiptap/extension-document';+import Paragraph from '@tiptap/extension-paragraph';+import Text from '@tiptap/extension-text';+import History from '@tiptap/extension-history';+import { undoDepth, redoDepth } from '@tiptap/pm/history';+import { AllSelection } from '@tiptap/pm/state';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { restoreComposerDocument } from '../components/new-chat/restoreComposerDocument';++const TestMark = Mark.create({ name: 'testMark', renderHTML: () => ['strong', 0] });+const editors: Editor[] = [];+afterEach(() => { for (const editor of editors.splice(0)) editor.destroy(); });+function create(content = '<p></p>') {+ const editor = new Editor({ extensions: [Document, Paragraph, Text, History, TestMark], content, parseOptions: { preserveWhitespace: 'full' } });+ editors.push(editor);+ return editor;+}+describe('empty composer task switch', () => {+ it.each([undefined, { type: 'doc', content: [{ type: 'paragraph' }] }])('skips untouched empty replacement %j', (draft) => {+ const editor = create();+ const transaction = vi.fn(); editor.on('transaction', transaction);+ for (let i = 0; i < 6; i++) restoreComposerDocument(editor, draft);+ expect(transaction).not.toHaveBeenCalled();+ expect(undoDepth(editor.state)).toBe(0);+ });+ it.each(['<p>text</p>', '<p> </p>', '<p></p><p></p>'])('resets noncanonical content %s', (content) => {+ const editor = create(content);+ const transaction = vi.fn(); editor.on('transaction', transaction);+ restoreComposerDocument(editor);+ expect(transaction).toHaveBeenCalled();+ expect(editor.state.doc.eq(editor.schema.topNodeType.createAndFill()!)).toBe(true);+ });+ it.each(['undo', 'redo'] as const)('retains the reset when %s history exists', (kind) => {+ const editor = create();+ editor.commands.insertContent('text');+ if (kind === 'redo') editor.commands.undo();+ else editor.commands.clearContent();+ expect((kind === 'undo' ? undoDepth : redoDepth)(editor.state)).toBeGreaterThan(0);+ expect(editor.state.doc.textContent).toBe('');+ const transaction = vi.fn(); editor.on('transaction', transaction);+ restoreComposerDocument(editor);+ expect(transaction).toHaveBeenCalled();+ });+ it.each(['selection', 'marks', 'composing'])('retains the reset for %s state', (kind) => {+ const editor = create();+ if (kind === 'selection') editor.view.dispatch(editor.state.tr.setSelection(new AllSelection(editor.state.doc)));+ if (kind === 'marks') editor.view.dispatch(editor.state.tr.addStoredMark(editor.schema.marks.testMark.create()));+ if (kind === 'composing') vi.spyOn(editor.view, 'composing', 'get').mockReturnValue(true);+ const transaction = vi.fn(); editor.on('transaction', transaction);+ restoreComposerDocument(editor);+ expect(transaction).toHaveBeenCalled();+ });+ it('restores nonempty and noncanonical target drafts', () => {+ for (const content of [+ { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'draft' }] }] },+ { type: 'doc', content: [{ type: 'paragraph' }, { type: 'paragraph' }] },+ ]) {+ const editor = create();+ restoreComposerDocument(editor, content);+ expect(editor.state.doc.eq(editor.schema.nodeFromJSON(content))).toBe(true);+ }+ });+ it('retains the reset for voice and other explicit transition state', () => {+ const editor = create();+ const transaction = vi.fn(); editor.on('transaction', transaction);+ restoreComposerDocument(editor, undefined, true);+ expect(transaction).toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/__tests__/sidebarNavigation.test.tsx b/apps/desktop/src/renderer/__tests__/sidebarNavigation.test.tsxnew file mode 100644index 0000000000..c6491e8da3--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/sidebarNavigation.test.tsx@@ -0,0 +1,47 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, expect, it, vi } from 'vitest';+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';+import {+ withSidebarNavigation,+ useSidebarNavigate,+ type SidebarNavigationProps,+} from '@/features/cc-agent/sidebar/sidebarNavigation';++afterEach(cleanup);++it('does not render an unchanged row on task navigation and still navigates from the latest route', () => {+ const rendered = vi.fn();+ const Row = withSidebarNavigation<{ label: string }>(function Row({+ label,+ navigate,+ }: { label: string } & SidebarNavigationProps) {+ rendered();+ return <button onClick={() => navigate('scheduled', { relative: 'path' })}>{label}</button>;+ });+ function Harness() {+ const navigate = useSidebarNavigate();+ const location = useLocation();+ return (+ <>+ <button onClick={() => navigate('/cc-agent/b')}>switch</button>+ <Row label="schedule" />+ <output>{location.pathname}</output>+ </>+ );+ }+ render(+ <MemoryRouter initialEntries={['/cc-agent/a']}>+ <Routes>+ <Route path="/cc-agent/:id/*" element={<Harness />} />+ </Routes>+ </MemoryRouter>,+ );+ expect(rendered).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByText('switch'));+ expect(screen.getByText('/cc-agent/b')).toBeTruthy();+ expect(rendered).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByText('schedule'));+ expect(screen.getByText('/cc-agent/b/scheduled')).toBeTruthy();+ expect(rendered).toHaveBeenCalledTimes(1);+});diff --git a/apps/desktop/src/renderer/__tests__/taskSwitchProjectionCache.test.ts b/apps/desktop/src/renderer/__tests__/taskSwitchProjectionCache.test.tsnew file mode 100644index 0000000000..cd4d0463b5--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/taskSwitchProjectionCache.test.ts@@ -0,0 +1,111 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { buildCachedRenderItems, buildRenderItems } from '@/components/chat/MessageStream';+import { extractAnchorCardId, extractGhostCardId, extractToolResultMedia } from '@/components/chat/AgentActionRow';+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';+import type { ChatMessage } from '@/lib/makerChatStore';+import type { GhostCardSnapshot, GhostCardEntry } from '@/cindy-brain/ghostCardStore';++beforeEach(() => setDataOwnerGeneration('cache-test'));+afterEach(() => vi.restoreAllMocks());++describe('tool result metadata reuse', () => {+ it('parses once across media/card/anchor consumers and refreshes changed content', () => {+ const content = JSON.stringify({ xdt_card_id: 'one', xdt_anchor_card_id: 'anchor', xdt_image_url: 'cindy-media://one.png' });+ const parse = vi.spyOn(JSON, 'parse');+ expect(extractGhostCardId(content)).toBe('one');+ expect(extractAnchorCardId(content)).toBe('anchor');+ const media = extractToolResultMedia(content);+ expect(media).toHaveLength(1);+ media.pop();+ expect(extractToolResultMedia(content)).toHaveLength(1);+ expect(parse.mock.calls.filter(([text]) => text === content)).toHaveLength(1);+ expect(extractGhostCardId(content.replace('one', 'two'))).toBe('two');+ });++ it('caches malformed negative results and expires on owner changes', () => {+ const content = '{ invalid xdt_card_id';+ const parse = vi.spyOn(JSON, 'parse');+ expect(extractGhostCardId(content)).toBeNull();+ expect(extractToolResultMedia(content)).toEqual([]);+ expect(parse.mock.calls.filter(([text]) => text === content)).toHaveLength(1);+ setDataOwnerGeneration('another-owner');+ expect(extractGhostCardId(content)).toBeNull();+ expect(parse.mock.calls.filter(([text]) => text === content)).toHaveLength(2);+ });++ it('evicts old entries by count and total retained text', () => {+ const oldest = '{"xdt_card_id":"old"}';+ const parse = vi.spyOn(JSON, 'parse');+ extractGhostCardId(oldest);+ for (let i = 0; i < 512; i++) extractGhostCardId(`{"xdt_card_id":"${i}"}`);+ extractGhostCardId(oldest);+ expect(parse.mock.calls.filter(([text]) => text === oldest)).toHaveLength(2);+ for (let i = 0; i < 3; i++) extractGhostCardId(String(i) + ' '.repeat(12 * 1024 * 1024));+ extractGhostCardId(oldest);+ expect(parse.mock.calls.filter(([text]) => text === oldest)).toHaveLength(3);+ });++ it('does not retain oversized results and preserves literal-token compatibility', () => {+ const content = JSON.stringify({ xdt_card_id: 'large', text: ' '.repeat(32 * 1024 * 1024) });+ const parse = vi.spyOn(JSON, 'parse');+ expect(extractGhostCardId(content)).toBe('large');+ expect(extractGhostCardId(content)).toBe('large');+ expect(parse.mock.calls.filter(([text]) => text === content)).toHaveLength(2);+ expect(extractGhostCardId('{"xdt_\\u0063ard_id":"escaped","xdt_image_url":"cindy-media://one.png"}')).toBeNull();+ });+});++const rows = (id: string): ChatMessage[] => [{ clientId: id, role: 'assistant', content: id }];++describe('history projection across message-view mounts', () => {+ it('reuses recent projections, evicts the least recent and clears on owner change', () => {+ const a = rows('a'), b = rows('b'), c = rows('c'), d = rows('d');+ const first = buildCachedRenderItems(a);+ const second = buildCachedRenderItems(b);+ buildCachedRenderItems(c);+ expect(buildCachedRenderItems(a)).toBe(first);+ buildCachedRenderItems(d);+ expect(buildCachedRenderItems(a)).toBe(first);+ expect(buildCachedRenderItems(b)).not.toBe(second);+ setDataOwnerGeneration('another-owner');+ expect(buildCachedRenderItems(a)).not.toBe(first);+ });++ it('invalidates every semantic builder input but not a per-mount parser cache', () => {+ const messages = rows('a');+ const tasks = new Map();+ const ghost: GhostCardSnapshot = { version: 0, byCallId: new Map(), liveCards: [] };+ const options = { historyWindowIncomplete: false, workingDir: '/a', botSessionId: 'a', turnChangeSets: [] };+ const first = buildCachedRenderItems(messages, tasks, ghost, options);+ expect(buildCachedRenderItems(messages, tasks, ghost, { ...options, markdownImageTargetCache: new Map() })).toBe(first);+ for (const changed of [+ { ...options, historyWindowIncomplete: true }, { ...options, workingDir: '/b' },+ { ...options, botSessionId: 'b' }, { ...options, turnChangeSets: [] },+ ]) {+ const base = buildCachedRenderItems(messages, tasks, ghost, options);+ expect(buildCachedRenderItems(messages, tasks, ghost, changed)).not.toBe(base);+ }+ const base = buildCachedRenderItems(messages, tasks, ghost, options);+ expect(buildCachedRenderItems(messages, new Map(), ghost, options)).not.toBe(base);+ expect(buildCachedRenderItems([...messages], tasks, ghost, options)).not.toBe(base);+ expect(buildCachedRenderItems([{ ...messages[0], isStreaming: true }], tasks, ghost, options)).not.toBe(base);+ });++ it('updates card fallback when a new snapshot shares the mutated card Map', () => {+ const messages: ChatMessage[] = [+ { clientId: 'call', role: 'tool_use', content: '', toolUseId: 't', toolName: 'mcp__cindy__ghost_call', toolInput: { ghost_id: 'art' } },+ { clientId: 'result', role: 'tool_result', toolUseId: 't', content: '{"xdt_card_id":"card","xdt_image_url":"cindy-media://one.png"}' },+ ];+ const byCallId = new Map<string, GhostCardEntry>([['card', { status: 'missing' }]]);+ const snapshot: GhostCardSnapshot = { version: 0, byCallId, liveCards: [] };+ const first = buildCachedRenderItems(messages, undefined, snapshot);+ expect(first.items.some((item) => item.type === 'tool_media')).toBe(true);+ byCallId.set('card', { status: 'ready', ghostId: 'art', html: '<p>ready</p>', height: 100 });+ const nextSnapshot = { ...snapshot, version: 1 };+ const next = buildCachedRenderItems(messages, undefined, nextSnapshot);+ expect(next).not.toBe(first);+ expect(next).toEqual(buildRenderItems(messages, undefined, nextSnapshot));+ expect(next.items.some((item) => item.type === 'ghost_card')).toBe(true);+ expect(next.items.some((item) => item.type === 'tool_media')).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/useMainListEntries.test.tsx b/apps/desktop/src/renderer/__tests__/useMainListEntries.test.tsxnew file mode 100644index 0000000000..dc4323cce9--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/useMainListEntries.test.tsx@@ -0,0 +1,36 @@+// @vitest-environment jsdom+import { renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';+import type { Session } from '@/lib/ccAgent.types';+import { useMainListEntries } from '../features/cc-agent/hooks/useMainListEntries';+import type { BuildMainListEntriesInput } from '../features/cc-agent/lib/mainListModel';++const a = { id: 'a', updatedAt: '2026-01-01', createdAt: '2026-01-01' } as Session;+const b = { id: 'b', updatedAt: '2026-01-02', createdAt: '2026-01-02' } as Session;+const context = (id: string) => ({ runningSessionIds: new Set([id]), attentionSessionIds: new Set<string>() });+const ids = (entries: ReturnType<typeof useMainListEntries>) => entries.map(e => e.kind === 'session' ? e.session.id : e.kind);+function input(sortBy: BuildMainListEntriesInput['sortBy']): BuildMainListEntriesInput {+ return { projects: [], dialogues: [a, b], groupBy: 'flat', groupDialogue: false,+ sortBy, manualProjectOrder: [], priorityContext: context('a') };+}+describe('sidebar sorting invalidation', () => {+ it.each(['recency', 'created'] as const)('reuses %s ordering when only viewed priority changes', (sortBy) => {+ const initial = input(sortBy);+ const { result, rerender } = renderHook(useMainListEntries, { initialProps: initial });+ const first = result.current;+ rerender({ ...initial, priorityContext: context('b') });+ expect(result.current).toBe(first);+ expect(ids(result.current)).toEqual(['b', 'a']);+ rerender({ ...initial, dialogues: [{ ...a, updatedAt: '2030-01-01', createdAt: '2030-01-01' }, b] });+ expect(ids(result.current)).toEqual(['a', 'b']);+ });+ it('reorders priority when running state changes and keeps time ordering when switching modes', () => {+ const initial = input('priority');+ const { result, rerender } = renderHook(useMainListEntries, { initialProps: initial });+ expect(ids(result.current)).toEqual(['a', 'b']);+ rerender({ ...initial, priorityContext: context('b') });+ expect(ids(result.current)).toEqual(['b', 'a']);+ rerender({ ...initial, sortBy: 'recency' });+ expect(ids(result.current)).toEqual(['b', 'a']);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/useProjectGroups.test.tsx b/apps/desktop/src/renderer/__tests__/useProjectGroups.test.tsxnew file mode 100644index 0000000000..690eb4c102--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/useProjectGroups.test.tsx@@ -0,0 +1,69 @@+// @vitest-environment jsdom+import { cleanup, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { Session } from '@/lib/ccAgent.types';+import { useProjectGroups } from '@/features/cc-agent/hooks/useProjectGroups';++const registry = vi.hoisted(() => ({ hosts: [] as RemoteHostSnapshot[], bots: [] }));+vi.mock('@/hooks/useRemoteSshHosts', () => ({ useRemoteSshHosts: () => registry.hosts }));+vi.mock('@/features/bots/botStore', () => ({ useBotProfiles: () => registry.bots }));+beforeEach(() => {+ registry.hosts = [];+});+afterEach(cleanup);++function task(id: string, patch: Partial<Session> = {}): Session {+ return {+ id,+ title: id,+ workingDir: `/workspace/${id}`,+ workspaceKind: 'project',+ status: 'active',+ pinnedAt: null,+ userSendAt: '2026-08-01T00:00:00Z',+ createdAt: '2026-08-01T00:00:00Z',+ updatedAt: '2026-08-01T00:00:00Z',+ _count: { messages: 1 },+ ...patch,+ } as Session;+}++it('preserves untouched enriched project nodes through row-only updates', () => {+ const rows = [task('a'), task('b')];+ const { result, rerender } = renderHook(({ rows }) => useProjectGroups(rows), {+ initialProps: { rows },+ });+ const before = result.current.projects;+ const updated = { ...rows[0], title: 'latest' };+ rerender({ rows: [updated, rows[1]] });+ expect(result.current.projects[0].sessions[0]).toBe(updated);+ expect(result.current.projects[1]).toBe(before[1]);+});++it('refreshes SSH labels when only the registry changes', () => {+ const rows = [task('a', { remoteHostId: 'remote' })];+ const { result, rerender } = renderHook(() => useProjectGroups(rows));+ expect(result.current.projects[0].remoteMachineIdentity?.label).toBe('remote');+ registry.hosts = [+ { config: { id: 'remote', displayName: 'Build Mac', user: 'u', hostname: 'host', port: 22 } },+ ] as RemoteHostSnapshot[];+ rerender();+ expect(result.current.projects[0].remoteMachineIdentity?.displayLabel).toBe(+ 'Build Mac (remote) · u@host',+ );+});++it('updates collision labels when another device starts or stops sharing the name', () => {+ const rows = [+ task('a', { deviceLinkDeviceId: 'one', deviceLinkDeviceName: 'Mac' }),+ task('b', { deviceLinkDeviceId: 'two', deviceLinkDeviceName: 'Other' }),+ ];+ const { result, rerender } = renderHook(({ rows }) => useProjectGroups(rows), {+ initialProps: { rows },+ });+ expect(result.current.projects[0].remoteMachineIdentity?.detail).toBeNull();+ rerender({ rows: [rows[0], { ...rows[1], deviceLinkDeviceName: 'Mac' }] });+ expect(result.current.projects[0].remoteMachineIdentity?.detail).toBe('one');+ rerender({ rows });+ expect(result.current.projects[0].remoteMachineIdentity?.detail).toBeNull();+});diff --git a/apps/desktop/src/renderer/__tests__/useStableTranslation.test.tsx b/apps/desktop/src/renderer/__tests__/useStableTranslation.test.tsxnew file mode 100644index 0000000000..22e23f23af--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/useStableTranslation.test.tsx@@ -0,0 +1,43 @@+// @vitest-environment jsdom+import { act, render } from '@testing-library/react';+import { createInstance } from 'i18next';+import { I18nextProvider, initReactI18next, useTranslation } from 'react-i18next';+import { describe, expect, it, vi } from 'vitest';+import { useStableTranslation } from '../hooks/useStableTranslation';++async function instance() {+ const i18n = createInstance();+ await i18n.use(initReactI18next).init({ lng: 'en', fallbackLng: 'en',+ resources: { en: { translation: { greeting: 'Hello' } }, zh: { translation: { greeting: '你好' } } },+ react: { useSuspense: false },+ });+ return i18n;+}++describe('stable translation subscriptions', () => {+ it.each([false, true])('preserves language updates with stable=%s', async (stable) => {+ const i18n = await instance();+ const on = vi.spyOn(i18n, 'on');+ const off = vi.spyOn(i18n, 'off');+ const hook = stable ? useStableTranslation : useTranslation;+ function Probe({ revision }: { revision: number }) {+ const { t } = hook();+ return <div data-revision={revision}>{t('greeting')}</div>;+ }+ const tree = (revision: number) => <I18nextProvider i18n={i18n}><Probe revision={revision} /></I18nextProvider>;+ const view = render(tree(0));+ const subscriptions = () => on.mock.calls.filter(([event]) => event === 'languageChanged').length;+ const initial = subscriptions();+ expect(initial).toBeGreaterThan(0);+ for (let revision = 1; revision <= 4; revision++) view.rerender(tree(revision));+ if (stable) { expect(subscriptions()).toBe(initial); expect(off).not.toHaveBeenCalled(); }+ else expect(subscriptions()).toBeGreaterThan(initial);+ await act(async () => { await i18n.changeLanguage('zh'); });+ expect(view.getByText('你好')).toBeTruthy();+ const beforeUnmount = off.mock.calls.length;+ view.unmount();+ expect(off.mock.calls.length).toBeGreaterThan(beforeUnmount);+ expect(off.mock.calls.some(([event, listener]) => event === 'languageChanged' &&+ on.mock.calls.some(([e, fn]) => e === event && fn === listener))).toBe(true);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/workActivityProjection.test.ts b/apps/desktop/src/renderer/__tests__/workActivityProjection.test.tsindex da9d1fde2b..5f71c0c2c0 100644--- a/apps/desktop/src/renderer/__tests__/workActivityProjection.test.ts+++ b/apps/desktop/src/renderer/__tests__/workActivityProjection.test.ts@@ -25,6 +25,23 @@ function segment(key: string, toolCalls: ChatMessage[]) {}describe('projectWorkActivities', () => {+ it('reuses rebuilt history groups but observes result, status and message changes', () => {+ const message = tool('cache-tool', 'Read', { file_path: '/repo/a.ts' });+ const first = projectWorkActivities([segment('cache', [message])], true);+ expect(projectWorkActivities([segment('cache', [message])], true)).toBe(first);+ const completed = segment('cache', [message]);+ completed.settledIds.add(message.clientId);+ const settled = projectWorkActivities([completed], true);+ expect(settled).not.toBe(first);+ expect(settled.activities[0]).toMatchObject({ status: 'done' });+ completed.resultMap.set(message.clientId, 'file contents');+ const withResult = projectWorkActivities([completed], true);+ expect(withResult.activities[0]).toMatchObject({ toolResult: 'file contents' });+ expect(projectWorkActivities([segment('cache', [{ ...message, toolInput: { file_path: '/repo/b.ts' } }])], true))+ .not.toBe(withResult);+ expect(projectWorkActivities([completed], false)).not.toBe(withResult);+ });+it('splits a complete Codex commandActions list into ordered display rows', () => {const command = tool('exec-1', 'exec', {command: 'cat src/a.ts && rg TODO src',diff --git a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsxindex 6154982867..339026558b 100644--- a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx+++ b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx@@ -57,6 +57,7 @@ import {} from '@cindy/maker-shared';import { cn, basename } from '@/lib/utils';+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';import { Spinner } from '@/components/ui/spinner';import type { ChatMessage } from '@/lib/makerChatStore';import {@@ -296,16 +297,7 @@ function isToolAudioUrl(url: string): boolean {* renderer 据此从 ghostCardStore 取卡渲染;取不到令牌 = 走今日 generic 路径。*/export function extractGhostCardId(toolResult: string): string | null {- if (!toolResult || typeof toolResult !== 'string') return null;- if (!toolResult.includes('xdt_card_id')) return null;- try {- const parsed = JSON.parse(toolResult) as { xdt_card_id?: unknown };- return typeof parsed.xdt_card_id === 'string' && parsed.xdt_card_id.length > 0- ? parsed.xdt_card_id- : null;- } catch {- return null;- }+ return getToolResultMetadata(toolResult).cardId;}/**@@ -316,19 +308,73 @@ export function extractGhostCardId(toolResult: string): string | null {* 采纳,锚不上回退本调用位置渲染(老意识/坏锚零影响)。*/export function extractAnchorCardId(toolResult: string): string | null {- if (!toolResult || typeof toolResult !== 'string') return null;- if (!toolResult.includes('xdt_anchor_card_id')) return null;- try {- const parsed = JSON.parse(toolResult) as { xdt_anchor_card_id?: unknown };- return typeof parsed.xdt_anchor_card_id === 'string' && parsed.xdt_anchor_card_id.length > 0- ? parsed.xdt_anchor_card_id- : null;- } catch {- return null;- }+ return getToolResultMetadata(toolResult).anchorId;}export function extractToolResultMedia(toolResult: string): ToolMediaItem[] {+ // Callers may filter/append their own list; never lend out the cached array.+ return getToolResultMetadata(toolResult).media.slice();+}++interface ToolResultMetadata {+ cardId: string | null;+ anchorId: string | null;+ media: ToolMediaItem[];+}++const EMPTY_TOOL_METADATA: ToolResultMetadata = { cardId: null, anchorId: null, media: [] };+// Bound both count and retained text. Large historical tool outputs must not turn+// a small entry-count cache into unbounded retention. Parsed JSON is never kept.+const TOOL_METADATA_MAX_ENTRIES = 512;+const TOOL_METADATA_MAX_CHARACTERS = 32 * 1024 * 1024;+const toolMetadataCache = new Map<string, ToolResultMetadata>();+let toolMetadataCharacters = 0;+let toolMetadataOwner = getDataOwnerGeneration();++function getToolResultMetadata(toolResult: string): ToolResultMetadata {+ const owner = getDataOwnerGeneration();+ if (owner !== toolMetadataOwner) {+ toolMetadataCache.clear();+ toolMetadataCharacters = 0;+ toolMetadataOwner = owner;+ }+ if (!toolResult || typeof toolResult !== 'string') return EMPTY_TOOL_METADATA;+ const cached = toolMetadataCache.get(toolResult);+ if (cached) {+ toolMetadataCache.delete(toolResult);+ toolMetadataCache.set(toolResult, cached);+ return cached;+ }+ let metadata = EMPTY_TOOL_METADATA;+ if (/xdt_(?:card_id|anchor_card_id|image_url|video_url|audio_url)/.test(toolResult)) {+ try {+ const parsed = JSON.parse(toolResult) as Record<string, unknown> | null;+ if (parsed && typeof parsed === 'object') {+ metadata = {+ cardId: toolResult.includes('xdt_card_id') && typeof parsed.xdt_card_id === 'string' && parsed.xdt_card_id.length > 0+ ? parsed.xdt_card_id : null,+ anchorId: toolResult.includes('xdt_anchor_card_id') && typeof parsed.xdt_anchor_card_id === 'string' && parsed.xdt_anchor_card_id.length > 0+ ? parsed.xdt_anchor_card_id : null,+ media: extractParsedToolResultMedia(toolResult, parsed),+ };+ }+ } catch {+ // Malformed and ordinary text results have no media/card metadata.+ }+ }+ if (toolResult.length <= TOOL_METADATA_MAX_CHARACTERS) {+ toolMetadataCache.set(toolResult, metadata);+ toolMetadataCharacters += toolResult.length;+ while (toolMetadataCache.size > TOOL_METADATA_MAX_ENTRIES || toolMetadataCharacters > TOOL_METADATA_MAX_CHARACTERS) {+ const oldest = toolMetadataCache.keys().next().value!;+ toolMetadataCache.delete(oldest);+ toolMetadataCharacters -= oldest.length;+ }+ }+ return metadata;+}++function extractParsedToolResultMedia(toolResult: string, parsed: Record<string, unknown>): ToolMediaItem[] {if (!toolResult || typeof toolResult !== 'string') return [];// 快速否定:不含任何 xdt_*_url 字面量直接 short-circuit。if (@@ -339,19 +385,6 @@ export function extractToolResultMedia(toolResult: string): ToolMediaItem[] {return [];}try {- const parsed = JSON.parse(toolResult) as {- xdt_image_url?: unknown;- xdt_image_urls?: unknown;- xdt_video_url?: unknown;- xdt_video_urls?: unknown;- xdt_audio_urls?: unknown;- xdt_audio_tracks?: unknown;- xdt_audio_in_card?: unknown;- xdt_images_in_card?: unknown;- _xdt_render_image?: unknown;- _xdt_model_files?: unknown;- _xdt_audio_tracks?: unknown;- };if (parsed._xdt_render_image === false) return [];const modelFiles = parseModelFiles(parsed._xdt_model_files);// Track which image index we're at across xdt_image_url + xdt_image_urlsdiff --git a/apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx b/apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsxindex 2477544e9e..81ffbaad13 100644--- a/apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx+++ b/apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx@@ -44,6 +44,7 @@ import { useExpandedBlockMemory } from '@/hooks/useExpandedBlockMemory';import { AgentActionRow } from './AgentActionRow';export interface AgentActionsBlockProps {+ renderItemKey?: string;toolCalls: ChatMessage[];/** clientId of tool_use → string content of its tool_result. */resultMap: Map<string, string>;@@ -61,6 +62,7 @@ export interface AgentActionsBlockProps {}export function AgentActionsBlock({+ renderItemKey,toolCalls,resultMap,settledIds,@@ -105,6 +107,7 @@ export function AgentActionsBlock({// 任务卡)查不到时,MessageStream 的 focus 用 ~= 属性选择器落到本块容器。// 视口删除补偿不读这个聚合列表,避免把隐藏工具 id 当成活锚点。<div+ data-render-item-key={renderItemKey}className="flex w-full justify-start"data-message-client-ids={toolCalls.map((c) => c.clientId).join(' ')}>diff --git a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsxindex 529e069db8..73c3ec41f9 100644--- a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx+++ b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx@@ -46,6 +46,7 @@ import {const EFFORT_BADGE_LEVELS = new Set<string>(['minimal', ...CODEX_SUBAGENT_EFFORTS]);interface AgentTaskCardProps {+ renderItemKey?: string;toolCall?: ChatMessage;update?: AgentTaskUpdate;result?: string;@@ -151,6 +152,7 @@ function readHistoryFileStatus(}export function AgentTaskCard({+ renderItemKey,toolCall,update,result,@@ -408,6 +410,7 @@ export function AgentTaskCard({// 搜索跳转)靠该锚点滚动定位 —— 普通消息行有,任务卡也必须有,否则面板点// Agent/Bash 行会静默无反应。<div+ data-render-item-key={renderItemKey}className="flex w-full justify-start"{...(toolCall?.clientId ? { 'data-message-client-id': toolCall.clientId } : {})}>diff --git a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsxindex 3f5f9a42bc..d0bde7c6fa 100644--- a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx+++ b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx@@ -659,6 +659,7 @@ const MAX_VISIBLE_BOT_ARTIFACTS = 4;function generatedFilesCardPropsEqual(prev: {+ renderItemKey?: string;files: readonly GeneratedFileRef[];turnStartMs: number | null;turnEndMs: number | null;@@ -667,6 +668,7 @@ function generatedFilesCardPropsEqual(onVisibilityChange?: (checkKey: string, visible: boolean) => void;},next: {+ renderItemKey?: string;files: readonly GeneratedFileRef[];turnStartMs: number | null;turnEndMs: number | null;@@ -676,6 +678,7 @@ function generatedFilesCardPropsEqual(},): boolean {return (+ prev.renderItemKey === next.renderItemKey &&prev.botArtifacts === next.botArtifacts &&prev.onVisibilityChange === next.onVisibilityChange &&generatedFilesCheckKey(prev.files, prev.turnStartMs, prev.turnEndMs, prev.turnSealed) ===@@ -684,6 +687,7 @@ function generatedFilesCardPropsEqual(}export const GeneratedFilesCard = memo(function GeneratedFilesCard({+ renderItemKey,files,turnStartMs,turnEndMs,@@ -691,6 +695,7 @@ export const GeneratedFilesCard = memo(function GeneratedFilesCard({botArtifacts = false,onVisibilityChange,}: {+ renderItemKey?: string;files: readonly GeneratedFileRef[];turnStartMs: number | null;turnEndMs: number | null;@@ -841,7 +846,7 @@ export const GeneratedFilesCard = memo(function GeneratedFilesCard({const hiddenPrimaryCount = primary.length - visiblePrimary.length;return (- <div className="my-1 flex max-w-[680px] flex-col gap-2" data-testid="bot-generated-artifacts">+ <div data-render-item-key={renderItemKey} className="my-1 flex max-w-[680px] flex-col gap-2" data-testid="bot-generated-artifacts">{primary.length > 0 ? (<><span className="text-12 font-medium text-[var(--text-secondary)]">@@ -911,7 +916,7 @@ export const GeneratedFilesCard = memo(function GeneratedFilesCard({const hasOnlyArtifacts = existing.every((file) => file.artifact);return (- <div className="my-1 flex flex-col gap-2">+ <div data-render-item-key={renderItemKey} className="my-1 flex flex-col gap-2">{!hasOnlyArtifacts && (<span className="text-12 font-medium text-[var(--text-secondary)]">{t('chat.generatedFiles.title')}diff --git a/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx b/apps/desktop/src/renderer/components/chat/MessageActionBar.tsxindex ab07e3bfa3..916b4e70a2 100644--- a/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx@@ -41,7 +41,7 @@ import {Trash2,Undo2,} from 'lucide-react';-import { useTranslation } from 'react-i18next';+import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';import { cn } from '@/lib/utils';import { CHAT_COLOR_TRANSITION_CLASS, CHAT_ICON_BUTTON_CLASS } from './chatChrome';import { Spinner } from '@/components/ui/spinner';diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex b70c8301b9..02ce90b8fe 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -31,8 +31,18 @@ import {type CSSProperties,type ReactNode,} from 'react';-import { HistoryViewHandoff, renderHistoryView, historyPrefetchThreshold, historyViewLeaves } from '@cindy/maker-shared/message-window';-import { getRemoteHistoryView, type HistoryChatMessage } from '@/lib/makerChatStore';+import {+ HistoryViewHandoff,+ renderHistoryView,+ historyPrefetchThreshold,+ historyViewLeaves,+} from '@cindy/maker-shared/message-window';+import {+ getRemoteHistoryView,+ makerChatStore,+ type HistoryChatMessage,+} from '@/lib/makerChatStore';+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';import { createPortal } from 'react-dom';import { GitFork } from 'lucide-react';import { SelectionQuoteButton } from './SelectionQuoteButton';@@ -78,10 +88,12 @@ import { useMessageNavRailPreference } from '@/hooks/useMessageNavRailPreferenceimport { HISTORY_GAP_SPLIT_MS } from '@/lib/historyGap';import { projectRemoteUsers } from '@/lib/remoteUserHandoff';import { resolveToolFilePath, type KnownLocalFileRef } from '@/lib/localPathResolver';-import { collectGeneratedFiles, type GeneratedFileRef } from '@/lib/generatedFiles';+import type { GeneratedFileRef } from '@/lib/generatedFiles';+import { collectCachedGeneratedFiles } from './generatedFilesProjection';import { useTurnChangeSets } from './useTurnChangeSets';import {canCompensateMessageHeight,+ findRenderItemElement,rememberedItemIntrinsicSize,viewportAnchorCorrection,} from './messageViewportCompensation';@@ -631,10 +643,16 @@ export function snapRenderWindowStartIdx(return clamped;}-function ForkOriginMarker({ onClick }: { onClick?: () => void }) {+function ForkOriginMarker({+ onClick,+ renderItemKey,+}: {+ onClick?: () => void;+ renderItemKey?: string;+}) {const { t } = useTranslation();return (- <div className="flex items-center gap-4 py-3">+ <div data-render-item-key={renderItemKey} className="flex items-center gap-4 py-3"><div className="h-px flex-1 bg-[var(--border-default)]" /><buttontype="button"@@ -954,9 +972,9 @@ function deferredWorkContainsClientId(clientId: string,): boolean {return (- item.deferred?.key?.split('|').some(- (key) => key === `work-${clientId}` || key === `work-summary-${clientId}`,- ) ?? false+ item.deferred?.key+ ?.split('|')+ .some((key) => key === `work-${clientId}` || key === `work-summary-${clientId}`) ?? false);}@@ -981,6 +999,40 @@ function deferredWorkContainsClientId(* 走同样的 recover。每次扫描 O(n × m) 其中 m 是平均 toolCalls/segment,典型 n=200* 时几毫秒,可接受。*/+export function restoreClientIdFromKey(key: string): string | undefined {+ // Synthetic cards are anchored to a real source row, including generated files.+ const prefix = [+ 'work-summary-',+ 'subagent-media-',+ 'genfiles-',+ 'msg-',+ 'seg-',+ 'work-',+ 'media-',+ 'ghostcard-',+ ].find((prefix) => key.startsWith(prefix));+ return prefix ? key.slice(prefix.length) || undefined : undefined;+}++export function restoreClientIdForItem(item: RenderItem): string | undefined {+ if (item.type === 'fork_origin') return undefined;+ if (item.type === 'agent_plan') return item.sourceClientIds[0];+ if (item.type === 'turn_changes') return item.changeSet.anchorClientId ?? undefined;+ if (item.type === 'ghost_card') return item.toolCall.clientId;+ if (item.type === 'work_group')+ return restoreClientIdFromKey(item.key) ?? collectDeleteAnchorClientIds([item])[0];+ return collectDeleteAnchorClientIds([item])[0] ?? restoreClientIdFromKey(item.key);+}++export function viewportRestoreNeedsMoreContent(+ desiredScrollTop: number,+ scrollHeight: number,+ viewportHeight: number,+ coversEnd: boolean,+): boolean {+ return !coversEnd && desiredScrollTop > Math.max(0, scrollHeight - viewportHeight) + 1;+}+function recoverLostAnchorIdx(items: RenderItem[], lostKey: string): number {const dashIdx = lostKey.indexOf('-');if (dashIdx < 0) return -1;@@ -1017,7 +1069,8 @@ function recoverLostAnchorIdx(items: RenderItem[], lostKey: string): number {it.key === `work-${lostCid}` ||it.key === `work-summary-${lostCid}` ||deferredWorkContainsClientId(it, lostCid)- ) return i;+ )+ return i;// Remote deferred groups retain their key before their children are loaded.if (recoverLostAnchorIdx(it.children, lostKey) >= 0) return i;} else if (it.type !== 'fork_origin') {@@ -1210,18 +1263,39 @@ function hasVisibleExactChildAnchor(itemElement: HTMLElement): boolean {return false;}-/**- * Whether a restored viewport anchor still belongs to the bounded default tail.- * This is intentionally limited to the restore path; user-created anchored- * windows remain unbounded until the separate bidirectional-window change.- */-export function isViewportAnchorWithinDefaultTail(+/** Prefer the saved card itself before falling back to its source message. */+export function resolveSavedViewportKey(items: RenderItem[],- viewportTopKey: string,- windowSize = RENDER_WINDOW_INITIAL_ITEMS,-): boolean {- const idx = findRestorableViewportItemIdx(items, viewportTopKey);- return idx >= Math.max(0, items.length - windowSize);+ snapshot: SessionScrollSnapshot,+): string | null {+ const index = findRestorableViewportItemIdx(items, snapshot.viewportTopKey);+ if (index >= 0) return items[index].key;+ const clientId =+ snapshot.restoreClientId ??+ snapshot.messageClientId ??+ restoreClientIdFromKey(snapshot.viewportTopKey);+ return clientId ? renderItemKeyForClientId(items, clientId) : null;+}++/** Restore the reading viewport, not all the offscreen rows expanded before leaving. */+export function resolveRestoredRenderWindow(snapshot: SessionScrollSnapshot | undefined): {+ anchor: string | null;+ forwardItems: number;+} {+ if (!snapshot || snapshot.isNearBottom) {+ return { anchor: null, forwardItems: RENDER_WINDOW_FIRST_PAINT_ITEMS };+ }+ if (snapshot.viewportTopKey) {+ return { anchor: snapshot.viewportTopKey, forwardItems: RENDER_WINDOW_FIRST_PAINT_ITEMS };+ }+ // Legacy snapshots without an exact viewport still need their original window.+ return {+ anchor: snapshot.windowAnchorKey,+ forwardItems:+ snapshot.anchoredForwardCount && snapshot.anchoredForwardCount > 0+ ? snapshot.anchoredForwardCount+ : RENDER_WINDOW_FIRST_PAINT_ITEMS,+ };}/**@@ -1439,7 +1513,8 @@ export function buildRenderItems(if (isSubagentInternalMessage(message)) return 'other';if (message.systemCardType === 'bot-session-task') return 'task';return message.role === 'assistant' && !message.systemCardType && message.content.trim()- ? 'prose' : 'other';+ ? 'prose'+ : 'other';});}// ── Pass -1: 剔除子代理内部消息 ──@@ -1771,7 +1846,7 @@ export function buildRenderItems(}const workingDir = opts?.workingDir ?? '';if (workingDir) {- for (const file of collectGeneratedFiles(slice, workingDir)) {+ for (const file of collectCachedGeneratedFiles(slice, workingDir)) {const normalized = pathKey(file.path);if (exactPaths.has(normalized) && changeSets.length > 0) continue;generatedByPath.set(normalized, file);@@ -2192,6 +2267,65 @@ export function buildRenderItems(return { items, singleResultMap };}+type RenderProjection = ReturnType<typeof buildRenderItems>;+const recentRenderProjections: {+ dependencies: readonly unknown[];+ projection: RenderProjection;+ characters: number;+}[] = [];+let renderProjectionOwner = getDataOwnerGeneration();++/**+ * Reuse pure history projection across keyed MessageStream mounts. Retain at+ * most three inputs and 32M source characters; no DOM, hooks or subscriptions.+ * Dependencies mirror every semantic input to buildRenderItems. In particular+ * ghost snapshots (not their mutable byCallId Map) invalidate card decisions.+ */+export function buildCachedRenderItems(+ ...args: Parameters<typeof buildRenderItems>+): RenderProjection {+ const [messages, taskUpdates, ghostCards, opts] = args;+ const owner = getDataOwnerGeneration();+ if (owner !== renderProjectionOwner) {+ recentRenderProjections.length = 0;+ renderProjectionOwner = owner;+ }+ const dependencies = [+ messages,+ taskUpdates,+ ghostCards,+ ghostCards?.version,+ opts?.historyWindowIncomplete,+ opts?.turnChangeSets,+ opts?.workingDir,+ opts?.botSessionId,+ ];+ const index = recentRenderProjections.findIndex((entry) =>+ entry.dependencies.every((value, i) => Object.is(value, dependencies[i])),+ );+ if (index >= 0) {+ const [entry] = recentRenderProjections.splice(index, 1);+ recentRenderProjections.push(entry);+ return entry.projection;+ }+ const projection = buildRenderItems(...args);+ const characters = messages.reduce((sum, message) => sum + message.content.length, 0);+ const maxCharacters = 32 * 1024 * 1024;+ if (characters <= maxCharacters) {+ // Keep only the latest dependencies for a given source array.+ const old = recentRenderProjections.findIndex((entry) => entry.dependencies[0] === messages);+ if (old >= 0) recentRenderProjections.splice(old, 1);+ recentRenderProjections.push({ dependencies, projection, characters });+ while (+ recentRenderProjections.length > 3 ||+ recentRenderProjections.reduce((sum, entry) => sum + entry.characters, 0) > maxCharacters+ ) {+ recentRenderProjections.shift();+ }+ }+ return projection;+}+type GeneratedFilesRenderItemRef = Extract<RenderItem, { type: 'generated_files' }>;/**@@ -2472,24 +2606,37 @@ export function MessageStream({);const displayMessages = useMemo(() => {if (!historySnapshot) return messages;- const historyIds = new Set(historyViewLeaves(historySnapshot.items).flatMap((item) =>- item.type === 'messages' ? item.messages.map((row) => row.clientId) : []));+ const historyIds = new Set(+ historyViewLeaves(historySnapshot.items).flatMap((item) =>+ item.type === 'messages' ? item.messages.map((row) => row.clientId) : [],+ ),+ );for (const detail of historySnapshot.details.values()) {for (const row of detail.messages) historyIds.add(row.clientId);}return projectRemoteUsers(messages, historyIds);}, [historySnapshot, messages]);- const historyHandoff = useMemo(() => new HistoryViewHandoff<HistoryChatMessage>(- (row) => row.isStreaming === true,- ), [historyView]);+ const historyHandoff = useMemo(+ () => new HistoryViewHandoff<HistoryChatMessage>((row) => row.isStreaming === true),+ [historyView],+ );// Observe live rows before the first history page too: a stream can finish// while that page is in flight. Local tasks retain their existing path.- const historyLiveMessages = useMemo(() => historyView ? displayMessages.map((row) => ({- ...row, id: row.id ?? row.clientId, createdAt: row.createdAt ?? '',- })) : [], [historyView, displayMessages]);- const handoff = useMemo(() => historySnapshot- ? historyHandoff.reconcile(historySnapshot, historyLiveMessages) : null,- [historyHandoff, historySnapshot, historyLiveMessages]);+ const historyLiveMessages = useMemo(+ () =>+ historyView+ ? displayMessages.map((row) => ({+ ...row,+ id: row.id ?? row.clientId,+ createdAt: row.createdAt ?? '',+ }))+ : [],+ [historyView, displayMessages],+ );+ const handoff = useMemo(+ () => (historySnapshot ? historyHandoff.reconcile(historySnapshot, historyLiveMessages) : null),+ [historyHandoff, historySnapshot, historyLiveMessages],+ );// 右上角 chip 栈插槽 —— PrevMessageJumpChip 通过 portal 挂到这里,// 与 DiffPanelToggle 在同一栈中各占一行。Provider 不存在时返回 null,// 渲染处会兜底跳过(典型场景:其他视图直接用 MessageStream 但不需要栈)。@@ -2509,8 +2656,7 @@ export function MessageStream({// 的全局 querySelector 找锚点用。const scrollRef = useRef<HTMLDivElement>(null);const contentRef = useRef<HTMLDivElement>(null);- /** 渲染 item 的内层 flex 容器 —— 其 children 与 visibleRenderItems 按索引一一对应,- * 「按条目相对定位」的还原逻辑靠它反查视口顶端那条 item 的 DOM 节点。 */+ /** 渲染 item 的内层 flex 容器;按 data-render-item-key 定位,异步卡片可不占 DOM。 */const itemsRef = useRef<HTMLDivElement>(null);// ── 切会话恢复浏览位置(默认常开) ──@@ -2525,6 +2671,20 @@ export function MessageStream({const restoringRef = useRef<boolean>(restoreSnapshotRef.current ? restoreSnapshotRef.current.isNearBottom === false : false,);+ const restoreLoadRef = useRef<'idle' | 'pending' | 'loaded' | 'failed' | 'settled'>('idle');+ const restoreMountedRef = useRef(false);+ const [restoreRevision, setRestoreRevision] = useState(0);+ const restoreCancelledRef = useRef(false);+ const initialHistoryClearedRef = useRef(historyCleared);+ if (historyCleared !== initialHistoryClearedRef.current || focusMessageClientId) {+ restoreCancelledRef.current = true;+ }+ useLayoutEffect(() => {+ restoreMountedRef.current = true;+ return () => {+ restoreMountedRef.current = false;+ };+ }, []);/** Whether we should keep pinning the viewport to the bottom. */const isNearBottomRef = useRef(!restoringRef.current);/** Set while we programmatically change scrollTop, so the scroll handler@@ -2574,29 +2734,12 @@ export function MessageStream({// 具体的 RenderItem.key,从那个 item 开始 slice 到末尾。expand 时把锚点往前挪// RENDER_WINDOW_GROWTH_ITEMS 个 item。//- // 还原快照是"默认窗口 + 非贴底"(windowAnchorKey=null 且 isNearBottom=false)- // 时,直接把窗口锚定到 viewportTopKey(视口顶端那条 item):applyRestore 需要- // 的锚点必然在窗口内(就是第一条),位置恢复不漂;窗口 = 视口位置 → 末尾,- // 必然有界(该快照态意味着用户仍在末尾 INITIAL 窗口内,≤80 条、典型只有一半)。- // 此前(codex review P2)这种快照走"全量 INITIAL 默认窗口"保锚点命中,几万字- // 会话切回要全量渲染 73+ 条、首帧 ~400ms(2026-08-09 沙盒 perf 日志实测),- // 锚定后回落到与贴底切换同阶。viewportTopKey 缺失(老快照)才退回全量窗口。+ // 非贴底恢复从 viewportTopKey 附近重建,不重挂之前扩出来的全部离屏条目。+ // 边界吸附保留上文,applyRestore 补齐定位所需的下方空间;用户继续滚动时+ // 沿既有双向扩窗路径补齐。缺少视口锚点的旧快照仍恢复原窗口。const [firstVisibleItemKey, setFirstVisibleItemKey] = useState<string | null>(() => {- if (!restoringRef.current) return null;- const snap = restoreSnapshotRef.current;- if (!snap) return null;- if (snap.windowAnchorKey !== null) return snap.windowAnchorKey;- if (!snap.isNearBottom && snap.viewportTopKey) return snap.viewportTopKey;- return null;+ return resolveRestoredRenderWindow(restoreSnapshotRef.current).anchor;});- const restoreDefaultViewportRef = useRef(- Boolean(- restoringRef.current &&- restoreSnapshotRef.current?.windowAnchorKey === null &&- restoreSnapshotRef.current?.isNearBottom === false &&- restoreSnapshotRef.current?.viewportTopKey,- ),- );// 两段式默认窗口的当前尺寸(FIRST_PAINT → 空闲期扩到 INITIAL)。只影响// firstVisibleItemKey === null 的"默认窗口"分支;锚点窗口不看它。// "默认窗口 + 非贴底"快照已在上面转为锚点窗口,不再进本分支;仅@@ -2612,15 +2755,10 @@ export function MessageStream({* 锚点窗口向后的 item 上界(render-window-bidirectional 要点 1)。* 仅 firstVisibleItemKey !== null 时生效;null(默认窗口)时不参与 slice。* 锚点变化时重置为 FIRST_PAINT,expandWindow / 向下扩窗时增长。- * 初始化时从滚动快照恢复(P1 fix:否则扩窗后切走的浏览位置会丢失)。+ * 重挂载从视口锚点附近开始;applyRestore 会补齐定位所需的下方空间。*/const [anchoredForwardItems, setAnchoredForwardItems] = useState(() => {- if (!restoringRef.current) return RENDER_WINDOW_FIRST_PAINT_ITEMS;- const snap = restoreSnapshotRef.current;- if (snap?.anchoredForwardCount && snap.anchoredForwardCount > 0) {- return snap.anchoredForwardCount;- }- return RENDER_WINDOW_FIRST_PAINT_ITEMS;+ return resolveRestoredRenderWindow(restoreSnapshotRef.current).forwardItems;});const [highlightMessageClientId, setHighlightMessageClientId] = useState<string | null>(null);const lastAppliedFocusRef = useRef<string | null>(null);@@ -2667,7 +2805,7 @@ export function MessageStream({}, [sessionId]);useEffect(() => {for (const m of messages) {- if (m.role === 'tool_result' && m.content.includes('xdt_card_id')) {+ if (m.role === 'tool_result') {const cardId = extractGhostCardId(m.content);if (cardId) ensureCard(cardId);}@@ -2695,7 +2833,7 @@ export function MessageStream({// parsed image targets without retaining state beyond the session mount.const markdownImageTargetCacheRef = useRef<MarkdownImageTargetCache>(new Map());const { items: ungroupedRenderItems, singleResultMap } = useMemo(() => {- const built = buildRenderItems(displayMessages, taskUpdates, ghostCardSnapshot, {+ const built = buildCachedRenderItems(displayMessages, taskUpdates, ghostCardSnapshot, {historyWindowIncomplete: !historyLoaded || Boolean(hasMoreMessages) || historyWindowHasIsland,turnChangeSets,workingDir,@@ -2705,13 +2843,22 @@ export function MessageStream({if (historyView && historySnapshot?.ready) {const results = new Map(built.singleResultMap);const items = renderHistoryView<HistoryChatMessage, RenderItem>({- view: historyView, snapshot: historySnapshot, liveMessages: historyLiveMessages, streaming: isSessionStreaming,+ view: historyView,+ snapshot: historySnapshot,+ liveMessages: historyLiveMessages,+ streaming: isSessionStreaming,isLive: (row) => row.isStreaming === true,pendingHandoff: handoff?.pending,- isLocalUser: (row) => row.role === 'user' && (row.isPendingPersist === true || !!row.blockedByGhost || !!row.localSendPrecedingClientIds),+ isLocalUser: (row) =>+ row.role === 'user' &&+ (row.isPendingPersist === true ||+ !!row.blockedByGhost ||+ !!row.localSendPrecedingClientIds),build: (rows) => {+ // History chunks are freshly assembled arrays, not reusable source snapshots.const chunk = buildRenderItems([...rows], taskUpdates, ghostCardSnapshot, {- historyWindowIncomplete: true, workingDir,+ historyWindowIncomplete: true,+ workingDir,botSessionId: simplifiedBotConversation ? sessionId : undefined,markdownImageTargetCache: markdownImageTargetCacheRef.current,});@@ -2719,23 +2866,41 @@ export function MessageStream({return groupWorkRuns(chunk.items, isSessionStreaming);},structure: {- placeholder: (summary) => ({ id: summary.firstMessageId,+ placeholder: (summary) => ({+ id: summary.firstMessageId,clientId: summary.anchorClientId ?? summary.key.slice('work-'.length),- role: 'thinking', content: '', createdAt: new Date(summary.startedAtMs).toISOString(),+ role: 'thinking',+ content: '',+ createdAt: new Date(summary.startedAtMs).toISOString(),thinkingDurationMs: Math.max(0, summary.endedAtMs - summary.startedAtMs),- thinkingRedacted: true, isStreaming: summary.isStreaming,+ thinkingRedacted: true,+ isStreaming: summary.isStreaming,}),- children: (item) => item.type === 'work_group' ? item.children : undefined,- sourceIds: (item) => item.type === 'message' ? [item.message.clientId]- : item.type === 'tool_segment' ? item.toolCalls.map((tool) => tool.clientId)- : item.type === 'agent_task' && item.toolCall ? [item.toolCall.clientId] : [],- rebuild: (item, children, deferred) => item.type === 'work_group'- ? { ...item, children: children as WorkGroupChildItem[], deferred } : item,+ children: (item) => (item.type === 'work_group' ? item.children : undefined),+ sourceIds: (item) =>+ item.type === 'message'+ ? [item.message.clientId]+ : item.type === 'tool_segment'+ ? item.toolCalls.map((tool) => tool.clientId)+ : item.type === 'agent_task' && item.toolCall+ ? [item.toolCall.clientId]+ : [],+ rebuild: (item, children, deferred) =>+ item.type === 'work_group'+ ? { ...item, children: children as WorkGroupChildItem[], deferred }+ : item,},});const keys = new Set<string>();- const unique = items.filter((item) => { if (keys.has(item.key)) return false; keys.add(item.key); return true; });- return { items: reuseGeneratedFilesRenderItems(unique, generatedFilesItemCacheRef.current), singleResultMap: results };+ const unique = items.filter((item) => {+ if (keys.has(item.key)) return false;+ keys.add(item.key);+ return true;+ });+ return {+ items: reuseGeneratedFilesRenderItems(unique, generatedFilesItemCacheRef.current),+ singleResultMap: results,+ };}return {items: reuseGeneratedFilesRenderItems(built.items, generatedFilesItemCacheRef.current),@@ -2774,18 +2939,26 @@ export function MessageStream({// work-group pass:把最终回答前的工作过程折叠成 work_group,无最终回答时// 继续走旧的 tool_segment + thinking 折叠兼容路径。// isSessionStreaming 翻转(每 turn 一次)与 items 变化时重算,O(n) 单扫描。- const { visibleGeneratedFileKeys, onGeneratedFilesVisibilityChange } = useBotGeneratedFileDeliveries(- ungroupedRenderItems, sessionFileValue,- );+ const { visibleGeneratedFileKeys, onGeneratedFilesVisibilityChange } =+ useBotGeneratedFileDeliveries(ungroupedRenderItems, sessionFileValue);const allRenderItems = useMemo(() => {const grouped = insertForkOriginItem(- historySnapshot?.ready ? ungroupedRenderItems : groupWorkRuns(ungroupedRenderItems, isSessionStreaming),+ historySnapshot?.ready+ ? ungroupedRenderItems+ : groupWorkRuns(ungroupedRenderItems, isSessionStreaming),forkOrigin,- );+ );return simplifiedBotConversation? simplifyBotRenderItems(grouped, isSessionStreaming, visibleGeneratedFileKeys): grouped;- }, [ungroupedRenderItems, isSessionStreaming, forkOrigin, simplifiedBotConversation, historySnapshot?.ready, visibleGeneratedFileKeys]);+ }, [+ ungroupedRenderItems,+ isSessionStreaming,+ forkOrigin,+ simplifiedBotConversation,+ historySnapshot?.ready,+ visibleGeneratedFileKeys,+ ]);const botMessageTimeGroups = useMemo(() => {if (!simplifiedBotConversation) return new Map<string, number>();return collectBotMessageTimeGroups(@@ -2855,12 +3028,14 @@ export function MessageStream({// Desktop 的加载体感)。挂载后的滚动定位不受影响:pin-to-bottom 与 applyRestore// 都由 ResizeObserver 在内容真正挂载时驱动,首帧空内容它们自然 no-op。// 各 auto-fill effect 均有 `visibleRenderItems.length === 0` 早退守卫,空帧不误触发。- const [firstMountDeferred, setFirstMountDeferred] = useState(true);+ // Warm history already has a bounded first-paint window. An empty shell adds+ // another render and frame to every switch without doing any useful loading.+ const [firstMountDeferred, setFirstMountDeferred] = useState(() => !historyLoaded);useEffect(() => {- // rAF 保证外壳那一帧真正上屏后才挂消息树;卸载时取消,防 setState-after-unmount。+ if (!firstMountDeferred) return;const raf = requestAnimationFrame(() => setFirstMountDeferred(false));return () => cancelAnimationFrame(raf);- }, []);+ }, [firstMountDeferred]);const { items: visibleRenderItems, startIdx: visibleStartIdx } = useMemo(() => {if (firstMountDeferred) return { items: EMPTY_RENDER_ITEMS, startIdx: 0 };@@ -2898,23 +3073,6 @@ export function MessageStream({}}- // A default-tail snapshot can become stale while the session is in the- // background. If enough messages arrive, the saved viewport anchor is no- // longer in the bounded tail; prefer a bounded tail first paint over- // mounting the entire anchor-to-end range. The layout effect below clears- // the stale anchor state before the next paint.- if (- restoreDefaultViewportRef.current &&- restoringRef.current &&- idx < Math.max(0, allRenderItems.length - RENDER_WINDOW_INITIAL_ITEMS)- ) {- const defaultStartIdx = snapRenderWindowStartIdx(- allRenderItems,- Math.max(0, allRenderItems.length - RENDER_WINDOW_INITIAL_ITEMS),- );- return { items: allRenderItems.slice(defaultStartIdx), startIdx: defaultStartIdx };- }-const startIdx = snapRenderWindowStartIdx(allRenderItems, idx);const windowItemCount = resolveAnchoredWindowItemCount(startIdx, idx, anchoredForwardItems);return {@@ -2929,29 +3087,6 @@ export function MessageStream({firstMountDeferred,]);- // If a restored default-tail anchor fell out of the tail while this session- // was backgrounded, permanently fall back to the bounded default window for- // this mount. This also prevents expandWindow from treating the stale key as- // a user-created anchored window.- useLayoutEffect(() => {- if (!restoreDefaultViewportRef.current || !restoringRef.current || firstVisibleItemKey === null)- return;- const snap = restoreSnapshotRef.current;- if (!snap?.viewportTopKey) return;- if (allRenderItems.length === 0) return;- const anchorIdx = findRestorableViewportItemIdx(allRenderItems, snap.viewportTopKey);- // History hydration can temporarily omit the anchor; retain restore mode- // until a later render can locate it instead of treating it as deleted.- if (anchorIdx < 0) return;- if (isViewportAnchorWithinDefaultTail(allRenderItems, snap.viewportTopKey)) return;- restoreDefaultViewportRef.current = false;- restoringRef.current = false;- isNearBottomRef.current = false;- setIsNearBottom(false);- setFirstVisibleItemKey(null);- setDefaultWindowItems(RENDER_WINDOW_INITIAL_ITEMS);- }, [allRenderItems, firstVisibleItemKey]);-// 两段式默认窗口第二段:首帧(非空)提交后,空闲期把默认窗口扩回 INITIAL。// 只在仍钉底时扩(prepend 在视口上方,pin-to-bottom layout effect 同帧重钉,// 无跳动);已向上滚离底部 / 已切到锚点窗口的,交给既有 expandWindow 路径。@@ -2995,23 +3130,22 @@ export function MessageStream({const container = scrollRef.current;const items = itemsRef.current;if (!container || !items) return null;- const vis = visibleRenderItemsRef.current;const cTop = container.getBoundingClientRect().top;const children = items.children;for (let i = 0; i < children.length; i++) {const rect = (children[i] as HTMLElement).getBoundingClientRect();// 第一条「底边还在容器顶边下方」的 item = 正好跨过视口顶边的那条。- if (rect.bottom - cTop > 0) {- const key = vis[i]?.key;+ if (rect.height > 0 && rect.bottom - cTop > 0) {+ const key = children[i].getAttribute('data-render-item-key');if (!key) return null;const snapshot: ViewportTopSnapshot = {viewportTopKey: key,- offset: Math.max(0, cTop - rect.top),+ offset: cTop - rect.top,};const itemElement = children[i] as HTMLElement;const childAnchor = pickIntersectingChildAnchor(Array.from(- itemElement.querySelectorAll<HTMLElement>('[data-message-client-id]'),+ [itemElement, ...itemElement.querySelectorAll<HTMLElement>('[data-message-client-id]')],(element) => {const clientId = readViewportChildAnchorClientId(element);if (!clientId) return null;@@ -3025,6 +3159,14 @@ export function MessageStream({if (childAnchor) {snapshot.messageClientId = childAnchor.clientId;snapshot.messageOffset = childAnchor.offset;+ } else {+ // A root message can start just below the viewport, in the inter-row+ // gap. Keep its exact identity and signed gap through regrouping too.+ const rootClientId = readViewportChildAnchorClientId(itemElement);+ if (rootClientId) {+ snapshot.messageClientId = rootClientId;+ snapshot.messageOffset = snapshot.offset;+ }}return snapshot;}@@ -3092,10 +3234,7 @@ export function MessageStream({refreshViewportAnchor();return;}- const vis = visibleRenderItemsRef.current;- const idx = snapshot ? vis.findIndex((item) => item.key === snapshot.viewportTopKey) : -1;- const itemElement =- idx >= 0 ? (itemsRef.current?.children[idx] as HTMLElement | undefined) : undefined;+ const itemElement = findRenderItemElement(itemsRef.current, snapshot?.viewportTopKey);if (!shouldRefreshExpandedChildViewportAnchor({snapshotMessageClientId: clientId,@@ -3113,9 +3252,7 @@ export function MessageStream({const scrollKeyToViewportTop = useCallback((key: string, offset: number) => {const container = scrollRef.current;- const idx = visibleRenderItemsRef.current.findIndex((item) => item.key === key);- const child =- idx >= 0 ? (itemsRef.current?.children[idx] as HTMLElement | undefined) : undefined;+ const child = findRenderItemElement(itemsRef.current, key);if (!container || !child) return false;const delta = viewportAnchorCorrection(container.getBoundingClientRect().top,@@ -3145,7 +3282,11 @@ export function MessageStream({if (!container || !target) return false;const rect = target.getBoundingClientRect();if (rect.height <= 0) return false;- const delta = viewportAnchorCorrection(container.getBoundingClientRect().top, rect.top, offset);+ const delta = viewportAnchorCorrection(+ container.getBoundingClientRect().top,+ rect.top,+ offset,+ );if (!isLoadingMore) {prevScrollHeightRef.current = 0;prevScrollTopAtLoadRef.current = 0;@@ -3557,7 +3698,7 @@ export function MessageStream({// 锚定窗向下扩到真正盖住尾部,且用户已经贴在当前窗口底 → 切回默认尾窗并// 恢复跟随。扩窗发生在本次 scroll 之后,同一帧的 handleScroll 还看不到// windowCoversEnd=true,没有下一次滚动时会永远停在「已到底、但不跟」。- if (!wasCovering && windowCoversEnd && firstVisibleItemKey !== null) {+ if (!restoringRef.current && !wasCovering && windowCoversEnd && firstVisibleItemKey !== null) {const el = scrollRef.current;if (!el) return;const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;@@ -3580,20 +3721,14 @@ export function MessageStream({const items = itemsRef.current;const sizes = restoreSnapshotRef.current?.itemHeights;if (!items || !sizes) return;- // Some cards render null. Without one DOM row per item, index-based- // estimates would be applied to a neighbouring message instead.- if (items.children.length !== visibleRenderItems.length) {- for (const element of Array.from(items.children)) {- (element as HTMLElement).style.containIntrinsicBlockSize = '';- }- return;- }const width = items.getBoundingClientRect().width;- visibleRenderItems.forEach((item, index) => {- const element = items.children[index] as HTMLElement | undefined;- const size = rememberedItemIntrinsicSize(sizes.byKey[item.key], sizes.width, width);- if (element) element.style.containIntrinsicBlockSize = size ?? '';- });+ for (const child of Array.from(items.children)) {+ const element = child as HTMLElement;+ const key = element.getAttribute('data-render-item-key');+ element.style.containIntrinsicBlockSize = key+ ? (rememberedItemIntrinsicSize(sizes.byKey[key], sizes.width, width) ?? '')+ : '';+ }}, [visibleRenderItems]);// 把视口滚回快照记录的「锚点 item + 偏移」。按条目相对定位,所以即使上方图片 /@@ -3603,33 +3738,71 @@ export function MessageStream({const snap = restoreSnapshotRef.current;const container = scrollRef.current;const items = itemsRef.current;- if (!snap || !container || !items) return;+ if (!snap || !container || !items) return false;const idx = findRestorableViewportItemIdx(visibleRenderItemsRef.current, snap.viewportTopKey);- if (idx < 0) return; // 锚点 item 不在当前窗口(消息被删 / clear)→ 放弃还原,停在默认位置- const child = items.children[idx] as HTMLElement | undefined;- if (!child) return;+ if (idx < 0) return false; // 锚点 item 不在当前窗口(消息被删 / clear)→ 放弃还原,停在默认位置+ const child = findRenderItemElement(items, visibleRenderItemsRef.current[idx]?.key);+ if (!child) return false;+ const messageTarget = snap.messageClientId+ ? queryMessageElement(container, snap.messageClientId)+ : null;+ const useMessageTarget = messageTarget && messageTarget.getBoundingClientRect().height > 0;+ const target = useMessageTarget ? messageTarget : child;+ const offset = useMessageTarget ? (snap.messageOffset ?? 0) : snap.offset;+ const desiredScrollTop =+ container.scrollTop ++ viewportAnchorCorrection(+ container.getBoundingClientRect().top,+ target.getBoundingClientRect().top,+ offset,+ );+ // A bounded restored window may have some overflow, yet still lack enough+ // content below the anchor to place it at its saved offset. Grow forward+ // before scrolling so the browser cannot clamp the restored position.+ if (+ viewportRestoreNeedsMoreContent(+ desiredScrollTop,+ container.scrollHeight,+ container.clientHeight,+ windowCoversEndRef.current,+ )+ ) {+ restoreLoadRef.current = 'loaded';+ // Sparse/null-rendering cards must not require one synchronous commit per+ // fixed batch all the way through a long history. Grow geometrically.+ const nextCount = Math.max(+ anchoredForwardItemsRef.current + RENDER_WINDOW_GROWTH_ITEMS,+ anchoredForwardItemsRef.current * 2,+ );+ setAnchoredForwardItems((count) => Math.max(count, nextCount));+ return false;+ }// A work group can remount collapsed or settle internally after its outer// row was positioned. Prefer the same visible child when it still exists.if (snap.messageClientId &&scrollMessageToViewportTop(snap.messageClientId, snap.messageOffset ?? 0)) {+ restoreLoadRef.current = 'settled';refreshViewportAnchor();- return;+ return true;}const cTop = container.getBoundingClientRect().top;const rect = child.getBoundingClientRect();// 期望 child 顶端落在 (容器顶边 - offset) 处;向下滚 delta 会让 rect.top 上移 delta。const delta = rect.top - (cTop - snap.offset);if (Math.abs(delta) < 1) {+ restoreLoadRef.current = 'settled';refreshViewportAnchor();- return;+ return true;}const generation = beginProgrammaticScroll();container.scrollTop += delta;+ restoreLoadRef.current = 'settled';requestAnimationFrame(() => {if (finishProgrammaticScroll(generation) === false) refreshViewportAnchor();});+ return true;}, [beginProgrammaticScroll,finishProgrammaticScroll,@@ -3641,48 +3814,117 @@ export function MessageStream({const applyRestoreRef = useRef(applyRestore);applyRestoreRef.current = applyRestore;+ // An explicit saved reading position is independent of automatic tail fill.+ // Run after intrinsic-size seeding, before paint, so a bounded remount does+ // not first display the clamped position and then expand on a later frame.+ // Reuse the store's bounded, epoch-guarded local/remote history lookup.+ useLayoutEffect(() => {+ if (!restoringRef.current || !historyLoaded || firstMountDeferred) return;+ if (restoreCancelledRef.current) {+ restoringRef.current = false;+ return;+ }+ const snap = restoreSnapshotRef.current;+ if (!snap || !sessionId) return;+ const clientId =+ snap.restoreClientId ?? snap.messageClientId ?? restoreClientIdFromKey(snap.viewportTopKey);+ const restoredKey = resolveSavedViewportKey(allRenderItems, snap);+ if (restoredKey) {+ restoreSnapshotRef.current = { ...snap, viewportTopKey: restoredKey };+ if (!visibleRenderItems.some((item) => item.key === restoredKey)) {+ restoreLoadRef.current = 'loaded';+ setFirstVisibleItemKey(restoredKey);+ setAnchoredForwardItems(RENDER_WINDOW_FIRST_PAINT_ITEMS);+ } else {+ restoreLoadRef.current = applyRestoreRef.current() ? 'settled' : 'loaded';+ }+ return;+ }+ if (restoreLoadRef.current === 'pending') return;+ if (restoreLoadRef.current === 'idle' && clientId) {+ restoreLoadRef.current = 'pending';+ const finish = (found: boolean) => {+ if (!restoreMountedRef.current || !restoringRef.current || restoreCancelledRef.current)+ return;+ restoreLoadRef.current = found ? 'loaded' : 'failed';+ setRestoreRevision((value) => value + 1);+ };+ void makerChatStore.loadAroundMessageClientId(sessionId, clientId, { radius: 60 }).then(+ (row) => finish(row !== null),+ () => finish(false),+ );+ return;+ }+ // A deleted/non-displayable anchor must not leave the view stuck restoring.+ restoreLoadRef.current = 'settled';+ restoringRef.current = false;+ isNearBottomRef.current = true;+ setIsNearBottom(true);+ setFirstVisibleItemKey(null);+ }, [+ allRenderItems,+ visibleRenderItems,+ historyLoaded,+ historyCleared,+ firstMountDeferred,+ sessionId,+ restoreRevision,+ ]);+// 保存当前浏览位置到 sessionScrollStore,并同步刷新删除前快照(单次量测)。用户// 滚动时持续调用(DOM 一定存活),unmount cleanup 兜底最后一帧;量测失败则跳过。const saveRafRef = useRef<number | null>(null);- const saveScrollSnapshot = useCallback((includeHeights = false) => {- const measured = refreshViewportAnchor();- if (!sessionId || !measured) return;- const items = itemsRef.current;- let itemHeights: SessionScrollSnapshot['itemHeights'];- const visible = visibleRenderItemsRef.current;- // Only capture sizes on leave, and bound them to the last mounted tail.- // A missing ghost/generated-files card shifts every following DOM index.- // Omit this optional cache rather than persisting heights under wrong keys.- if (includeHeights && items && items.children.length === visible.length) {- const byKey: Record<string, number> = {};- for (- let index = Math.max(0, visible.length - RENDER_WINDOW_INITIAL_ITEMS);- index < visible.length;- index++- ) {- const element = items.children[index] as HTMLElement | undefined;- if (!element) continue;- const style = getComputedStyle(element);- // contain-intrinsic-size describes the content box, excluding padding/borders.- byKey[visible[index].key] =- element.getBoundingClientRect().height -- (parseFloat(style.paddingTop) || 0) - (parseFloat(style.paddingBottom) || 0) -- (parseFloat(style.borderTopWidth) || 0) - (parseFloat(style.borderBottomWidth) || 0);+ const saveScrollSnapshot = useCallback(+ (includeHeights = false) => {+ // Do not overwrite the reading position with the temporary tail while loading it.+ if (restoringRef.current && restoreLoadRef.current !== 'settled') return;+ const measured = refreshViewportAnchor();+ if (!sessionId || !measured) return;+ const items = itemsRef.current;+ let itemHeights: SessionScrollSnapshot['itemHeights'];+ const visible = visibleRenderItemsRef.current;+ // Only capture sizes on leave, bounded to the last mounted window. Match+ // keys because async cards can disappear without occupying a DOM row.+ if (includeHeights && !isNearBottomRef.current && items) {+ const byKey: Record<string, number> = {};+ for (+ let index = Math.max(0, visible.length - RENDER_WINDOW_INITIAL_ITEMS);+ index < visible.length;+ index+++ ) {+ const element = findRenderItemElement(items, visible[index].key);+ if (!element) continue;+ const style = getComputedStyle(element);+ // contain-intrinsic-size describes the content box, excluding padding/borders.+ byKey[visible[index].key] =+ element.getBoundingClientRect().height -+ (parseFloat(style.paddingTop) || 0) -+ (parseFloat(style.paddingBottom) || 0) -+ (parseFloat(style.borderTopWidth) || 0) -+ (parseFloat(style.borderBottomWidth) || 0);+ }+ itemHeights = { width: items.getBoundingClientRect().width, byKey };}- itemHeights = { width: items.getBoundingClientRect().width, byKey };- }- saveSessionScroll(sessionId, {- windowAnchorKey: firstVisibleItemKeyRef.current,- viewportTopKey: measured.viewportTopKey,- offset: measured.offset,- messageClientId: measured.messageClientId,- messageOffset: measured.messageOffset,- itemHeights,- isNearBottom: isNearBottomRef.current,- anchoredForwardCount:- firstVisibleItemKeyRef.current !== null ? anchoredForwardItemsRef.current : undefined,- });- }, [sessionId, refreshViewportAnchor]);+ saveSessionScroll(sessionId, {+ windowAnchorKey: firstVisibleItemKeyRef.current,+ viewportTopKey: measured.viewportTopKey,+ offset: measured.offset,+ messageClientId: measured.messageClientId,+ restoreClientId:+ measured.messageClientId ??+ (() => {+ const item = visible.find((item) => item.key === measured.viewportTopKey);+ return item ? restoreClientIdForItem(item) : undefined;+ })(),+ messageOffset: measured.messageOffset,+ itemHeights,+ isNearBottom: isNearBottomRef.current,+ anchoredForwardCount:+ firstVisibleItemKeyRef.current !== null ? anchoredForwardItemsRef.current : undefined,+ });+ },+ [sessionId, refreshViewportAnchor],+ );// perf-baseline (见 perfLog 注释):// 父组件用 key={sessionId} 包了本组件,所以每次切 session 都是全新 mount,@@ -4111,7 +4353,9 @@ export function MessageStream({userIntentLoadInFlightRef.current = true;prevScrollHeightRef.current = el.scrollHeight;prevScrollTopAtLoadRef.current = el.scrollTop;- const release = () => { userIntentLoadInFlightRef.current = false; };+ const release = () => {+ userIntentLoadInFlightRef.current = false;+ };void onLoadMore().then(release, release);return;}@@ -4583,7 +4827,8 @@ export function MessageStream({dragging: scrollbarDragStartTopRef.current !== null,expanding: performance.now() < suppressHeightCompensationUntilRef.current,})- ) return;+ )+ return;const snapshot = lastViewportTopRef.current;if (!snapshot) {refreshViewportAnchor();@@ -4598,10 +4843,9 @@ export function MessageStream({const messageClientId = snapshot.messageClientId;if (messageClientId !== undefined &&- !allRenderItemsRef.current.some((item) =>- renderItemContainsClientId(item, messageClientId),- )- ) return;+ !allRenderItemsRef.current.some((item) => renderItemContainsClientId(item, messageClientId))+ )+ return;restoreViewportSnapshot(snapshot);}, [isLoadingMore, refreshViewportAnchor, restoreViewportSnapshot]);@@ -4633,25 +4877,24 @@ export function MessageStream({const onCardExpandToggle = (event: Event, preserveHeader = true) => {suppressHeightCompensationUntilRef.current = performance.now() + CARD_EXPAND_PIN_SUPPRESS_MS;restoringRef.current = false;- const header = preserveHeader && event.target instanceof Element- ? event.target.closest('button')- : null;+ const header =+ preserveHeader && event.target instanceof Element ? event.target.closest('button') : null;const container = scrollRef.current;- disclosureAnchorRef.current = header && container- ? {- element: header,- offset: container.getBoundingClientRect().top - header.getBoundingClientRect().top,- }- : null;+ disclosureAnchorRef.current =+ header && container+ ? {+ element: header,+ offset: container.getBoundingClientRect().top - header.getBoundingClientRect().top,+ }+ : null;refreshViewportAnchor();};// All disclosures suppress auto-follow, but only opted-in headers stay fixed.// A long-message footer moves down as text appears above it; following that// button would scroll past the text the user just chose to read.const onDisclosureClick = (event: MouseEvent) => {- const button = event.target instanceof Element- ? event.target.closest('button[aria-expanded]')- : null;+ const button =+ event.target instanceof Element ? event.target.closest('button[aria-expanded]') : null;if (button) {onCardExpandToggle(event, button.hasAttribute('data-scroll-disclosure-header'));}@@ -4777,7 +5020,13 @@ export function MessageStream({prevScrollHeightRef.current = 0;prevScrollTopAtLoadRef.current = 0;}- }, [visibleRenderItems, isLoadingMore, beginProgrammaticScroll, finishProgrammaticScroll, restoreViewportSnapshot]);+ }, [+ visibleRenderItems,+ isLoadingMore,+ beginProgrammaticScroll,+ finishProgrammaticScroll,+ restoreViewportSnapshot,+ ]);// ── 删除靠前 message 后的视口保位(#2289)──// 快照来自滚动/跳转落定;删除提交后再量会使 delta 恒为 0。贴底交给 pin-to-bottom。@@ -4862,6 +5111,7 @@ export function MessageStream({}let anchor = snapshot;if (restoringRef.current) {+ if (restoreLoadRef.current !== 'settled') return;const snap = restoreSnapshotRef.current;if (!snap?.viewportTopKey ||@@ -5051,8 +5301,9 @@ export function MessageStream({prevScrollTopRef.current = el.scrollTop;return;}- const draggingUp = draggingScrollbar- && currentScrollTop < prevScrollTopRef.current - SCROLL_DIRECTION_DEAD_ZONE_PX;+ const draggingUp =+ draggingScrollbar &&+ currentScrollTop < prevScrollTopRef.current - SCROLL_DIRECTION_DEAD_ZONE_PX;if (!programmaticScrollRef.current || draggingScrollbar) {// 用户手动滚动 = 接管浏览,退出「还原中」,后续恢复正常 auto-follow 判定。restoringRef.current = false;@@ -5668,12 +5919,22 @@ export function MessageStream({>{visibleRenderItems.map((item) => {if (item.type === 'fork_origin') {- return <ForkOriginMarker key={item.key} onClick={onOpenForkOrigin} />;+ return (+ <ForkOriginMarker+ renderItemKey={item.key}+ key={item.key}+ onClick={onOpenForkOrigin}+ />+ );}if (item.type === 'agent_plan') {return (- <div key={item.key} data-inline-plan-key={item.key}>+ <div+ key={item.key}+ data-render-item-key={item.key}+ data-inline-plan-key={item.key}+ ><InlinePlanCardtodos={item.todos}animated={@@ -5691,6 +5952,7 @@ export function MessageStream({return (<TurnChangesCardkey={item.key}+ renderItemKey={item.key}sessionId={sessionId}changeSet={item.changeSet}/>@@ -5701,12 +5963,15 @@ export function MessageStream({return (<GeneratedFilesCardkey={item.key}+ renderItemKey={item.key}files={item.files}turnStartMs={item.turnStartMs}turnEndMs={item.turnEndMs}turnSealed={item.turnSealed === true}botArtifacts={simplifiedBotConversation}- onVisibilityChange={simplifiedBotConversation ? onGeneratedFilesVisibilityChange : undefined}+ onVisibilityChange={+ simplifiedBotConversation ? onGeneratedFilesVisibilityChange : undefined+ }/>);}@@ -5715,6 +5980,7 @@ export function MessageStream({return (<AgentActionsBlockkey={item.key}+ renderItemKey={item.key}toolCalls={item.toolCalls}resultMap={item.resultMap}settledIds={item.settledIds}@@ -5727,6 +5993,7 @@ export function MessageStream({return (<AgentTaskCardkey={item.key}+ renderItemKey={item.key}toolCall={item.toolCall}update={item.update}result={item.result}@@ -5803,6 +6070,7 @@ export function MessageStream({// 视口子锚点不读这个聚合列表,只认已渲染的 data-message-client-id。<divkey={item.key}+ data-render-item-key={item.key}className="scroll-mt-20"data-message-client-ids={collectWorkGroupClientIds(item.children).join(' ',@@ -5833,7 +6101,11 @@ export function MessageStream({// 常态包一层 div(结构稳定,回锚媒体到达时卡片 iframe 不重挂);// 回锚媒体(如 mivo 视频)挂卡正下方,与 tool_media 同款间距。return (- <div key={item.key} className="flex flex-col gap-2">+ <div+ key={item.key}+ data-render-item-key={item.key}+ className="flex flex-col gap-2"+ ><GhostToolCardcallId={item.callId}ghostId={item.ghostId}@@ -5856,7 +6128,11 @@ export function MessageStream({// tool-result-media: 跳出 tool_segment 折叠卡片,渲染体在// ToolMediaList(与 ghost_card 回锚媒体共用单一来源)。return (- <div key={item.key} className="flex flex-col gap-2">+ <div+ key={item.key}+ data-render-item-key={item.key}+ className="flex flex-col gap-2"+ ><ToolMediaList items={item.items} sessionId={sessionId} /></div>);@@ -5872,6 +6148,7 @@ export function MessageStream({return (<ThinkingCardkey={item.key}+ renderItemKey={item.key}blockKey={msg.clientId}content={msg.content}isStreaming={msg.isStreaming}@@ -5888,34 +6165,34 @@ export function MessageStream({const shareable =Boolean(sessionId) && Boolean(msg.clientId) && isShareableMessage(msg);const messageNode = (- <MessageItem- message={msg}- toolResult={singleResultMap.get(msg.clientId)}- workingDir={workingDir}- sessionId={sessionId}- sessionTitle={sessionTitle}- agentKind={agentKind}- remoteHostId={remoteHostId}- sessionRunning={isSessionStreaming}- assistantForkBlocked={shouldBlockAssistantFork(- isSessionStreaming,- msg,- assistantsWithFollowingUserBoundary,- )}- assistantIsTurnFinal={turnFinalAssistantClientIds.has(msg.clientId)}- userTurnUsageDetails={userTurnUsageDetailsByAssistantId.get(msg.clientId)}- isFirstUserMessage={msg.clientId === firstUserMessageClientId}- isLastUserMessage={msg.clientId === lastUserMessageClientId}- isLastUserInput={msg.clientId === lastUserInputClientId}- isContinuationTurnOwner={msg.clientId === continuationTurnClientId}- continuationInFlightProjectionCapability={- continuationInFlightProjectionCapability- }- isLastMessage={msg.clientId === lastMessageClientId}- localFileRefs={localFileRefs}- assistantAvatar={assistantAvatar}- simplifiedBotConversation={simplifiedBotConversation}- />+ <MessageItem+ message={msg}+ toolResult={singleResultMap.get(msg.clientId)}+ workingDir={workingDir}+ sessionId={sessionId}+ sessionTitle={sessionTitle}+ agentKind={agentKind}+ remoteHostId={remoteHostId}+ sessionRunning={isSessionStreaming}+ assistantForkBlocked={shouldBlockAssistantFork(+ isSessionStreaming,+ msg,+ assistantsWithFollowingUserBoundary,+ )}+ assistantIsTurnFinal={turnFinalAssistantClientIds.has(msg.clientId)}+ userTurnUsageDetails={userTurnUsageDetailsByAssistantId.get(msg.clientId)}+ isFirstUserMessage={msg.clientId === firstUserMessageClientId}+ isLastUserMessage={msg.clientId === lastUserMessageClientId}+ isLastUserInput={msg.clientId === lastUserInputClientId}+ isContinuationTurnOwner={msg.clientId === continuationTurnClientId}+ continuationInFlightProjectionCapability={+ continuationInFlightProjectionCapability+ }+ isLastMessage={msg.clientId === lastMessageClientId}+ localFileRefs={localFileRefs}+ assistantAvatar={assistantAvatar}+ simplifiedBotConversation={simplifiedBotConversation}+ />);const highlightClass =highlightMessageClientId === msg.clientId@@ -5933,6 +6210,7 @@ export function MessageStream({return (<divkey={item.key}+ data-render-item-key={item.key}data-message-client-id={msg.clientId}className={cn('scroll-mt-20 transition-colors', highlightClass)}>@@ -5973,6 +6251,7 @@ export function MessageStream({return (<divkey={item.key}+ data-render-item-key={item.key}data-message-client-id={msg.clientId}{...shareAttributes}className={cn(@@ -6213,7 +6492,14 @@ const MessageItem = memo(function MessageItem({/>);return simplifiedBotConversation && message.systemCardType === 'bot-session-task'- ? withAssistantAvatar(assistantAvatar ? <span aria-hidden="true" className="invisible">{assistantAvatar}</span> : undefined, card)+ ? withAssistantAvatar(+ assistantAvatar ? (+ <span aria-hidden="true" className="invisible">+ {assistantAvatar}+ </span>+ ) : undefined,+ card,+ ): card;}return withAssistantAvatar(diff --git a/apps/desktop/src/renderer/components/chat/ThinkingCard.tsx b/apps/desktop/src/renderer/components/chat/ThinkingCard.tsxindex cc34a17741..a696b54887 100644--- a/apps/desktop/src/renderer/components/chat/ThinkingCard.tsx+++ b/apps/desktop/src/renderer/components/chat/ThinkingCard.tsx@@ -43,6 +43,7 @@ import { useExpandedBlockMemory } from '@/hooks/useExpandedBlockMemory';import { ThinkingText } from './ThinkingText';interface ThinkingCardProps {+ renderItemKey?: string;/** Thinking content with lightweight inline emphasis. Empty for redacted blocks. */content: string;/** True while the model is still streaming this block (delta still@@ -90,6 +91,7 @@ function BodyRail({ children }: { children: React.ReactNode }) {}export function ThinkingCard({+ renderItemKey,content,isStreaming,startedAt,@@ -127,7 +129,7 @@ export function ThinkingCard({// ── Redacted variant ─────────────────────────────────────────────────if (isRedacted) {return (- <div className="flex w-full justify-start">+ <div data-render-item-key={renderItemKey} className="flex w-full justify-start"><div className="w-full">{/* select-none:另两个变体的 header 是 <button> 天然禁选,redacted 分支是纯 div,需显式对齐,避免状态短语可被划选 */}@@ -157,7 +159,7 @@ export function ThinkingCard({// dots + live duration. Body only renders when the user expands.if (isStreaming) {return (- <div className="flex w-full justify-start">+ <div data-render-item-key={renderItemKey} className="flex w-full justify-start"><div className="w-full"><buttontype="button"@@ -225,7 +227,7 @@ export function ThinkingCard({? `Thought for ${formatDuration(durationMs ?? 0)} (aborted)`: `Thought for ${formatDuration(durationMs ?? 0)}`;return (- <div className="flex w-full justify-start">+ <div data-render-item-key={renderItemKey} className="flex w-full justify-start"><div className="w-full"><buttontype="button"diff --git a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsxindex c5ad9e920b..3bc2f714c5 100644--- a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx+++ b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx@@ -92,9 +92,11 @@ function TurnChangeFileRow({}export function TurnChangesCard({+ renderItemKey,sessionId,changeSet,}: {+ renderItemKey?: string;sessionId: string;changeSet: TurnChangeSetSummary;}) {@@ -176,7 +178,7 @@ export function TurnChangesCard({};return (- <section className="my-1 overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]">+ <section data-render-item-key={renderItemKey} className="my-1 overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)]"><div className="flex min-h-16 items-center gap-3 px-4 py-3"><div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-[var(--surface-chip)] text-[var(--text-secondary)]"><FileDiff size={18} />diff --git a/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx b/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsxindex e85637b10b..8854d96c9e 100644--- a/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx+++ b/apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx@@ -31,7 +31,7 @@ import {type ReactNode,} from 'react';import { ChevronRight, Layers, Sparkles } from 'lucide-react';-import { useTranslation } from 'react-i18next';+import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';import { cn } from '@/lib/utils';import type { ChatMessage } from '@/lib/makerChatStore';@@ -85,15 +85,11 @@ export type LiveWorkActivity = ProjectedWorkActivity;export const MAX_LIVE_WORK_ACTIVITIES = 5;/** 把一段可见 thinking 投影成单行动作;empty / redacted 不生成内容行。 */-function thinkingActivityForMessage(- message: ChatMessage,-): ProjectedThinkingActivity | null {+function thinkingActivityForMessage(message: ChatMessage): ProjectedThinkingActivity | null {if (message.thinkingRedacted) return null;const rawContent = message.content.trim();const content = rawContent.replace(/\s+/g, ' ');- return content- ? { kind: 'thinking', key: message.clientId, rawContent, content }- : null;+ return content ? { kind: 'thinking', key: message.clientId, rawContent, content } : null;}/** 把完整 work_group 历史投影成轻量 live preview。rendered assistant 文本@@ -136,11 +132,7 @@ function ToolActivityRow({ activity }: { activity: ProjectedToolActivity }) {);}-function ThinkingActivityRow({- activity,-}: {- activity: ProjectedThinkingActivity;-}) {+function ThinkingActivityRow({ activity }: { activity: ProjectedThinkingActivity }) {const rawContent = activity.rawContent;const hasExplicitLineBreak = /[\r\n]/.test(rawContent);const textRef = useRef<HTMLSpanElement>(null);@@ -155,9 +147,7 @@ function ThinkingActivityRow({const textElement = textRef.current;if (!textElement) return;const updateOverflow = () => {- setCanExpand(- hasExplicitLineBreak || textElement.scrollWidth > textElement.clientWidth + 1,- );+ setCanExpand(hasExplicitLineBreak || textElement.scrollWidth > textElement.clientWidth + 1);};updateOverflow();if (typeof ResizeObserver === 'undefined') return;@@ -209,10 +199,7 @@ function ThinkingActivityRow({{canExpand ? (<ChevronRightsize={13}- className={cn(- CHAT_CHEVRON_TRANSITION_CLASS,- expanded && 'rotate-90',- )}+ className={cn(CHAT_CHEVRON_TRANSITION_CLASS, expanded && 'rotate-90')}/>) : null}</span>@@ -228,11 +215,7 @@ function ExpandedThinkingRow({ message }: { message: ChatMessage }) {if (!message.thinkingRedacted) return null;return (<div data-message-client-id={message.clientId}>- <ThinkingCard- blockKey={message.clientId}- content={message.content}- isRedacted- />+ <ThinkingCard blockKey={message.clientId} content={message.content} isRedacted /></div>);}@@ -289,7 +272,9 @@ export function WorkGroupBlock({}: WorkGroupBlockProps) {const { t } = useTranslation();const { expanded: rememberedExpanded, setExpanded } = useExpandedBlockMemory(blockId);- const expanded = deferred?.setVisible ? rememberedExpanded : deferred?.expanded ?? rememberedExpanded;+ const expanded = deferred?.setVisible+ ? rememberedExpanded+ : (deferred?.expanded ?? rememberedExpanded);const deferredRef = useRef(deferred);deferredRef.current = deferred;useEffect(() => {@@ -310,7 +295,10 @@ export function WorkGroupBlock({// 多取一条即可判断展开是否能露出更多活动,显示仍只取最近 5 条。const recentActivities = useMemo(- () => compact ? [] : projectRecentWorkActivities(childItems, isStreaming, MAX_LIVE_WORK_ACTIVITIES + 1),+ () =>+ !compact && isStreaming+ ? projectRecentWorkActivities(childItems, true, MAX_LIVE_WORK_ACTIVITIES + 1)+ : [],[childItems, isStreaming, compact],);const liveActivities = useMemo(@@ -323,17 +311,19 @@ export function WorkGroupBlock({() =>childItems.some((child) =>- child.kind === 'group'- || child.kind === 'rendered'- || (child.kind === 'thinking' && child.message.thinkingRedacted === true),+ child.kind === 'group' ||+ child.kind === 'rendered' ||+ (child.kind === 'thinking' && child.message.thinkingRedacted === true),),[childItems],);// 运行中预览已经等于全部内容时,折叠/展开是视觉空操作 — 组头不提供交互。const canToggle =- compact || (!!deferred && !deferred.previewComplete) || !isStreaming- || hasBeyondPreviewChild- || recentActivities.length > MAX_LIVE_WORK_ACTIVITIES;+ compact ||+ (!!deferred && !deferred.previewComplete) ||+ !isStreaming ||+ hasBeyondPreviewChild ||+ recentActivities.length > MAX_LIVE_WORK_ACTIVITIES;const effectiveExpanded = expanded && canToggle;const isLivePreviewVisible =!compact && isStreaming && !effectiveExpanded && liveActivities.length > 0;@@ -350,7 +340,10 @@ export function WorkGroupBlock({// 外层完成态组展开成文字 + 内层动作组;内层动作组与运行态组复用本组件,// 展开后直接渲染 thinking /工具行,不再多套一层子卡摘要。const onToggle = useCallback(() => {- if (deferred && !deferred.setVisible) { deferred.toggle(); return; }+ if (deferred && !deferred.setVisible) {+ deferred.toggle();+ return;+ }setExpanded((v) => !v);}, [deferred, setExpanded]);@@ -361,29 +354,32 @@ export function WorkGroupBlock({const baseSummaryText = compact? t('chat.workGroup.workDetails'): isStreaming- ? t('chat.workGroup.working')- : durationMs !== undefined- ? t('chat.workGroup.worked', { duration: formatDuration(durationMs) })- : t('chat.workGroup.workDetails');- const explorationSummary = !compact && activityProjection?.isPureExploration- ? [- activityProjection.explorationCounts.read > 0- ? t('chat.workGroup.exploration.read', {- count: activityProjection.explorationCounts.read,- })- : null,- activityProjection.explorationCounts.search > 0- ? t('chat.workGroup.exploration.search', {- count: activityProjection.explorationCounts.search,- })- : null,- activityProjection.explorationCounts.list > 0- ? t('chat.workGroup.exploration.list', {- count: activityProjection.explorationCounts.list,- })- : null,- ].filter((part): part is string => part !== null).join(' · ')- : '';+ ? t('chat.workGroup.working')+ : durationMs !== undefined+ ? t('chat.workGroup.worked', { duration: formatDuration(durationMs) })+ : t('chat.workGroup.workDetails');+ const explorationSummary =+ !compact && activityProjection?.isPureExploration+ ? [+ activityProjection.explorationCounts.read > 0+ ? t('chat.workGroup.exploration.read', {+ count: activityProjection.explorationCounts.read,+ })+ : null,+ activityProjection.explorationCounts.search > 0+ ? t('chat.workGroup.exploration.search', {+ count: activityProjection.explorationCounts.search,+ })+ : null,+ activityProjection.explorationCounts.list > 0+ ? t('chat.workGroup.exploration.list', {+ count: activityProjection.explorationCounts.list,+ })+ : null,+ ]+ .filter((part): part is string => part !== null)+ .join(' · ')+ : '';const summaryText = explorationSummary? `${baseSummaryText} · ${explorationSummary}`: baseSummaryText;@@ -404,9 +400,7 @@ export function WorkGroupBlock({canToggle && 'cursor-pointer hover:opacity-80 transition-opacity',!canToggle && 'cursor-default',)}- aria-expanded={- canToggle ? effectiveExpanded || isLivePreviewVisible : undefined- }+ aria-expanded={canToggle ? effectiveExpanded || isLivePreviewVisible : undefined}><span className="inline-flex h-[1lh] items-center shrink-0">{isStreaming ? (@@ -462,19 +456,20 @@ export function WorkGroupBlock({'flex flex-col gap-2',)}>- {childItems.map((child) => (- <Fragment key={child.key}>- <ExpandedWorkGroupChild- child={child}- compact={compact}- toolActivities={- child.kind === 'tools'- ? activityProjection?.toolActivitiesByChildKey.get(child.key)- : undefined- }- />- </Fragment>- ))}+ {effectiveExpanded &&+ childItems.map((child) => (+ <Fragment key={child.key}>+ <ExpandedWorkGroupChild+ child={child}+ compact={compact}+ toolActivities={+ child.kind === 'tools'+ ? activityProjection?.toolActivitiesByChildKey.get(child.key)+ : undefined+ }+ />+ </Fragment>+ ))}{deferred?.loading && <Spinner size={14} />}{deferred?.failed && (<Button variant="secondary" disabled={deferred.loading} onClick={deferred.retry}>diff --git a/apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts b/apps/desktop/src/renderer/components/chat/generatedFilesProjection.tsnew file mode 100644index 0000000000..94b7c5441c--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts@@ -0,0 +1,18 @@+import { collectGeneratedFiles, type GeneratedFileRef } from '@/lib/generatedFiles';+import { createMessageProjectionCache } from './messageProjectionCache';++type Messages = Parameters<typeof collectGeneratedFiles>[0];+const project = createMessageProjectionCache<Messages[number], GeneratedFileRef[]>();++/**+ * History snapshots use immutable message objects, but turn slices are fresh arrays.+ * Reuse expensive tool/result parsing across slices and view mounts. A changed row,+ * its order, or working directory invalidates the projection; file existence and+ * permissions are still checked by the card against the current host.+ */+export function collectCachedGeneratedFiles(messages: Messages, workingDir: string) {+ if (messages.length === 0) return [];+ return project(messages[0], [workingDir, messages.length, ...messages], () =>+ collectGeneratedFiles(messages, workingDir),+ );+}diff --git a/apps/desktop/src/renderer/components/chat/messageProjectionCache.ts b/apps/desktop/src/renderer/components/chat/messageProjectionCache.tsnew file mode 100644index 0000000000..b23e35688b--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/messageProjectionCache.ts@@ -0,0 +1,21 @@+/**+ * Reuse pure projections of immutable history snapshots across view mounts.+ * One result per snapshot; weak keys let the history store's own eviction release it.+ * Every non-message input must be included in dependencies, as with useMemo.+ */+export function createMessageProjectionCache<K extends object, V>() {+ const snapshots = new WeakMap<K, { dependencies: readonly unknown[]; value: V }>();+ return (snapshot: K, dependencies: readonly unknown[], compute: () => V): V => {+ const previous = snapshots.get(snapshot);+ if (+ previous &&+ previous.dependencies.length === dependencies.length &&+ dependencies.every((value, index) => Object.is(value, previous.dependencies[index]))+ ) {+ return previous.value;+ }+ const value = compute();+ snapshots.set(snapshot, { dependencies: [...dependencies], value });+ return value;+ };+}diff --git a/apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts b/apps/desktop/src/renderer/components/chat/messageViewportCompensation.tsindex 5370fff7a3..0dcccfee15 100644--- a/apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts+++ b/apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts@@ -43,3 +43,14 @@ export function rememberedItemIntrinsicSize(return undefined;return `auto ${height}px`;}++/** Null-rendering cards do not occupy a DOM index. Match the stable render key. */+export function findRenderItemElement(+ container: HTMLElement | null | undefined,+ key: string | undefined,+): HTMLElement | undefined {+ if (!container || !key) return undefined;+ return Array.from(container.children).find(+ (element) => element.getAttribute('data-render-item-key') === key,+ ) as HTMLElement | undefined;+}diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 14abf8ddb3..0e6711a6f9 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -15,7 +15,7 @@ import { createPortal } from 'react-dom';import { useNavigate } from 'react-router-dom';import { buildLocalSkillPathRoute } from '@/features/skillhub/lib/localRoutes';import { Folder, MessageSquarePlus, Mic, Pen, TriangleAlert, X } from 'lucide-react';-import { useTranslation } from 'react-i18next';+import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';import { requiresFullAccessConfirmation } from '@cindy/maker-shared/permission-mode';import { ImageLightbox } from '@/components/chat/ImageLightbox';@@ -47,6 +47,7 @@ import {} from './ComposerListNodes';import { WindowsSelectionReplacement } from './WindowsSelectionReplacement';import { EmptyDocSelectionGuard } from './EmptyDocSelectionGuard';+import { restoreComposerDocument } from './restoreComposerDocument';import {hasFocusMovedToInteractiveElement,useComposerSendFocusRestore,@@ -3697,11 +3698,11 @@ export function ChatInput({isRestoringRef.current = true;try {const draft = storageKey !== undefined ? getComposerDraft(storageKey) : undefined;- if (draft?.text) {- editor.commands.setContent(normalizeRestoredComposerDraft(draft.text));- } else {- editor.commands.clearContent();- }+ restoreComposerDocument(+ editor,+ draft?.text ? normalizeRestoredComposerDraft(draft.text) : undefined,+ voiceInputBusyRef.current || voiceDraftTextRef.current.length > 0,+ );} finally {isRestoringRef.current = false;}diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/useComposerSendFocusRestore.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/useComposerSendFocusRestore.test.tsxindex 9cc8012199..1f21e4c1aa 100644--- a/apps/desktop/src/renderer/components/new-chat/__tests__/useComposerSendFocusRestore.test.tsx+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/useComposerSendFocusRestore.test.tsx@@ -31,6 +31,13 @@ function createEditor(): Editor {}describe('useComposerSendFocusRestore', () => {+ it('tolerates a retained editor whose view was unmounted', () => {+ const editor = createEditor();+ editor.unmount();+ expect(editor.isDestroyed).toBe(true);+ expect(() => renderHook(() => useComposerSendFocusRestore(editor, false))).not.toThrow();+ });+let nextFrameId = 1;let frames = new Map<number, FrameRequestCallback>();diff --git a/apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts b/apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.tsnew file mode 100644index 0000000000..7e0c336277--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts@@ -0,0 +1,25 @@+import type { Editor, JSONContent } from '@tiptap/core';+import { undoDepth, redoDepth } from '@tiptap/pm/history';+import { Selection } from '@tiptap/pm/state';++/** Skip only an untouched standard-empty to standard-empty replacement. */+export function restoreComposerDocument(+ editor: Editor,+ content?: JSONContent | null,+ forceReset = false,+): void {+ const { state } = editor;+ const empty = state.schema.topNodeType.createAndFill();+ if (!forceReset && !editor.view.composing && empty && state.doc.eq(empty) &&+ state.selection.eq(Selection.atStart(state.doc)) && !state.storedMarks?.length &&+ undoDepth(state) === 0 && redoDepth(state) === 0) {+ if (!content) return;+ try {+ if (state.schema.nodeFromJSON(content).eq(empty)) return;+ } catch {+ // Leave malformed/legacy content handling to the existing Tiptap command.+ }+ }+ if (content) editor.commands.setContent(content);+ else editor.commands.clearContent();+}diff --git a/apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts b/apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.tsindex 9a6660245a..055067b6ab 100644--- a/apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts+++ b/apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts@@ -47,7 +47,9 @@ export function useComposerSendFocusRestore(const pendingRestoreRef = useRef<PendingComposerFocusRestore | null>(null);useEffect(() => {- if (!editor) return;+ // Retained sidebar panels can reconnect effects after their editor view+ // has been unmounted. Tiptap's view.dom getter throws in that state.+ if (!editor || editor.isDestroyed) return;const editorDom = editor.view.dom;const ownerDocument = editorDom.ownerDocument;const cancelRestoreForOutsidePointer = (event: PointerEvent) => {diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.tsindex 2243b5108f..7af0bc52e9 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts@@ -53,7 +53,7 @@ describe('消息流的头像挂载', () => {// space invisibly. User messages and internal tool/work cards still bypass it.expect(messageStream.match(/withAssistantAvatar\(/g)?.length).toBe(3);expect(messageStream).toContain("simplifiedBotConversation && message.systemCardType === 'bot-session-task'");- expect(messageStream).toContain('<span aria-hidden="true" className="invisible">{assistantAvatar}</span>');+ expect(messageStream).toMatch(/<span aria-hidden="true" className="invisible">\s*\{assistantAvatar\}\s*<\/span>/);});});diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 60b22e0791..aa8262df8d 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -28,7 +28,7 @@ import {import type { CSSProperties, ReactNode } from 'react';import { useLocation, useNavigate, useOutletContext, useParams } from 'react-router-dom';import { dbToMakerAgentKind, normalizeDbAgentKind } from '../../../shared/agentKindConversion';-import { useTranslation } from 'react-i18next';+import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';import {isCodexResumeNotReadyProjectionError,type AgentInputReference,diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex 19b6b5f35a..3424b56bbb 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -43,6 +43,7 @@ import {X,} from 'lucide-react';import { useNavigate, useMatch, useLocation } from 'react-router-dom';+import { useSidebarNavigate } from './sidebar/sidebarNavigation';import { useTranslation } from 'react-i18next';import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';@@ -505,7 +506,7 @@ export function CCAgentSidebarUpper() {}return next;}, [scheduleSessionIndex, remoteScheduleIndex]);- const navigate = useNavigate();+ const navigate = useSidebarNavigate();// Workdir-browse mode (skillhub Market sidebar pattern). When the user// clicked the file-text button on a Project, we swap sidebar contents to@@ -1571,27 +1572,18 @@ function ExpandedView({[pinnedProjectKeys, localPlatform],);- const restorableProjectKeys = useMemo(- () =>- collectRestorableProjectKeys({- sessions: scopedSidebarSessions,- persistentLocalProjects: visiblePersistentLocalProjects,- lastActivityCutoff: cutoffForLastActivity(filter.lastActivity),- pinnedProjectKeys,- vendorPredicate,- localPlatform,- }),- [- filter.lastActivity,- localPlatform,+ // Only the directory-picker restore path needs this catalogue. Read the+ // latest inputs after its await instead of grouping twice on every patch.+ const collectRestorableProjectKeysRef = useRef<() => ReadonlySet<string>>(() => new Set());+ collectRestorableProjectKeysRef.current = () =>+ collectRestorableProjectKeys({+ sessions: scopedSidebarSessions,+ persistentLocalProjects: visiblePersistentLocalProjects,+ lastActivityCutoff: cutoffForLastActivity(filter.lastActivity),pinnedProjectKeys,- scopedSidebarSessions,vendorPredicate,- visiblePersistentLocalProjects,- ],- );- const restorableProjectKeysRef = useRef(restorableProjectKeys);- restorableProjectKeysRef.current = restorableProjectKeys;+ localPlatform,+ });const hiddenProjectComparisonKeys = useMemo(() => buildProjectKeyComparisonSet(hiddenProjectKeys, localPlatform),[hiddenProjectKeys, localPlatform],@@ -1843,9 +1835,10 @@ function ExpandedView({!(selectedMachineId !== MACHINE_ALL && selectedMachineId.length === 1);const [selectedSessionIds, setSelectedSessionIds] = useState<Set<string>>(() => new Set());- const [selectionAnchorSessionId, setSelectionAnchorSessionId] = useState<string | null>(null);+ // The range-selection anchor is interaction bookkeeping, never rendered.+ const selectionAnchorSessionIdRef = useRef<string | null>(null);// 这几个值 handleSessionClick 只在「点击那一刻」读一次。留在它的 deps 里会让- // 每次点击(:setSelectionAnchorSessionId 必触发)和每次切换都重建 handler,+ // 每次切换都重建 handler,// 行的 onClick 跟着换引用 → 整表 memo 失效重画一遍(SessionItem.tsx 不变量 #3)。// 经 ref 读还顺带避开闭包陈旧:拿到的是最新值而非渲染时快照。// attention / running / 未读集合更是:点进去会先清通知,若留在 deps 里,刚点的@@ -1865,8 +1858,6 @@ function ExpandedView({viewedSessionIdRef.current = viewedSessionId;const selectedSessionIdsRef = useRef(selectedSessionIds);selectedSessionIdsRef.current = selectedSessionIds;- const selectionAnchorSessionIdRef = useRef(selectionAnchorSessionId);- selectionAnchorSessionIdRef.current = selectionAnchorSessionId;const [bulkActionPending, setBulkActionPending] = useState<BulkSessionAction | null>(null);const sidebarScrollRef = useRef<HTMLDivElement>(null);/**@@ -2065,7 +2056,12 @@ function ExpandedView({const next = new Set([...prev].filter((id) => renderedSessionIds.has(id)));return sameStringSet(prev, next) ? prev : next;});- setSelectionAnchorSessionId((prev) => (prev && renderedSessionIds.has(prev) ? prev : null));+ if (+ selectionAnchorSessionIdRef.current &&+ !renderedSessionIds.has(selectionAnchorSessionIdRef.current)+ ) {+ selectionAnchorSessionIdRef.current = null;+ }}, []);// 只在真有多选集合时才盯 DOM。单击也会写下 selectionAnchorSessionId 当@@ -2084,7 +2080,7 @@ function ExpandedView({const handleClearSelection = useCallback(() => {setSelectedSessionIds((prev) => (prev.size === 0 ? prev : new Set()));- setSelectionAnchorSessionId((prev) => (prev === null ? prev : null));+ selectionAnchorSessionIdRef.current = null;}, []);useEffect(() => {@@ -2179,7 +2175,7 @@ function ExpandedView({}return next;});- setSelectionAnchorSessionId((prev) => prev ?? id);+ selectionAnchorSessionIdRef.current ??= id;return;}@@ -2192,14 +2188,14 @@ function ExpandedView({}return next;});- setSelectionAnchorSessionId(id);+ selectionAnchorSessionIdRef.current = id;return;}if (selectedSessionIdsRef.current.size > 0) {setSelectedSessionIds(new Set());}- setSelectionAnchorSessionId(id);+ selectionAnchorSessionIdRef.current = id;// 清点会先于路由更新抹掉 attention。必须先按当前档位钉住,否则// ProjectsSection 首次 hold 只能读到 rest,刚打开的完成未读仍会立刻沉底。const waiting = new Set(urgentSetRef.current);@@ -2225,7 +2221,9 @@ function ExpandedView({clearSystemSessionAttention(id);if (id === activeSessionIdRef.current) return; // No duplicate navigate.if (import.meta.env.DEV) perfLog.debug(`sidebar:click sid=${id}`); // 纯诊断,生产剔除- navigate(await resolveSessionRoute(id, target));+ // Known ordinary tasks can navigate in the current click batch.+ if (target && !isOrcaWorkerSession(target)) navigate(`/cc-agent/${id}`);+ else navigate(await resolveSessionRoute(id, target));},[navigate, clearNotification, markAutomationSessionRunsRead],);@@ -2428,7 +2426,7 @@ function ExpandedView({localPlatform,),setProjectHidden,- getCurrentProjectKeys: () => restorableProjectKeysRef.current,+ getCurrentProjectKeys: () => collectRestorableProjectKeysRef.current(),ensureProjectIncluded: filter.ensureProjectIncluded,localPlatform,});@@ -2554,6 +2552,7 @@ function ExpandedView({};// 优先用 active session(若属于这个 project)。+ const activeSessionId = activeSessionIdRef.current;if (activeSessionId) {const active = sessions.find((s) => s.id === activeSessionId);if (active && inProject(active)) {@@ -2569,7 +2568,7 @@ function ExpandedView({}toast.warning(t('ccAgent.sidebar.browseEmpty'));},- [activeSessionId, sessions, navigate, t],+ [sessions, navigate, t],);/* ---- Rename handler ---- */@@ -2611,7 +2610,7 @@ function ExpandedView({throw err;}},- [projectAliases, t],+ [projectAliases.updateAlias, t],);const handleRemoveProjectFromSidebar = useCallback(@@ -2699,7 +2698,7 @@ function ExpandedView({toast.error(t('ccAgent.sidebar.pinFailed'));}},- [filter, t],+ [filter.removePin, filter.promotePin, t],);// Event-only state: metadata updates recreate the collapsed Set even when@@ -3012,7 +3011,12 @@ function ExpandedView({for (const id of succeededIds) next.delete(id);return next;});- setSelectionAnchorSessionId((prev) => (prev && succeededIds.has(prev) ? null : prev));+ if (+ selectionAnchorSessionIdRef.current &&+ succeededIds.has(selectionAnchorSessionIdRef.current)+ ) {+ selectionAnchorSessionIdRef.current = null;+ }if (failed.length === 0) {toast.success(t('ccAgent.sidebar.bulkSelection.deleted', { count: succeededIds.size }));@@ -3148,7 +3152,12 @@ function ExpandedView({for (const id of succeededIds) next.delete(id);return next;});- setSelectionAnchorSessionId((prev) => (prev && succeededIds.has(prev) ? null : prev));+ if (+ selectionAnchorSessionIdRef.current &&+ succeededIds.has(selectionAnchorSessionIdRef.current)+ ) {+ selectionAnchorSessionIdRef.current = null;+ }if (failed.length === 0) {toast.success(t('ccAgent.sidebar.bulkSelection.archived', { count: succeededIds.size }));@@ -3323,7 +3332,8 @@ function ExpandedView({// 当前注视中的 session 被归档了 → 走 /cc-agent 让 CCAgentIndexRedirect// 做 Orca-aware 的「选下一条 / 空则跳 new」决策(见 runSessionAction 同位置注释)。- if (viewedSessionId && succeededIds.has(viewedSessionId)) {+ const currentlyViewedSessionId = viewedSessionIdRef.current;+ if (currentlyViewedSessionId && succeededIds.has(currentlyViewedSessionId)) {navigate('/cc-agent');}@@ -3343,7 +3353,6 @@ function ExpandedView({runningSessionIds,confirmDialog,refreshSessions,- viewedSessionId,navigate,patchLocal,filter.status,diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useMainListEntries.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useMainListEntries.tsnew file mode 100644index 0000000000..d3b8d21553--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useMainListEntries.ts@@ -0,0 +1,14 @@+import { useMemo } from 'react';+import { buildMainListEntries, type BuildMainListEntriesInput } from '../lib/mainListModel';++/** Browsing priority changes cannot invalidate time-based sorting. */+export function useMainListEntries(input: BuildMainListEntriesInput) {+ const { projects, dialogues, bots, unclassified, groupBy, groupDialogue, sortBy,+ projectOrder, manualProjectOrder, notifications, scheduleSessionIndex } = input;+ const priorityContext = sortBy === 'priority' ? input.priorityContext : undefined;+ return useMemo(() => buildMainListEntries({+ projects, dialogues, bots, unclassified, groupBy, groupDialogue, sortBy,+ projectOrder, manualProjectOrder, notifications, scheduleSessionIndex, priorityContext,+ }), [projects, dialogues, bots, unclassified, groupBy, groupDialogue, sortBy,+ projectOrder, manualProjectOrder, notifications, scheduleSessionIndex, priorityContext]);+}diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.tsindex cdea9127fd..e5cb1bc8e4 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts@@ -3,7 +3,7 @@* ---------------------------------------------------------------------------* 包 `groupSessions` 纯函数并用 useMemo 锁结果,避免 render 时重复计算。*- * Row-only changes reuse grouping and replace just the affected session references.+ * Row-only patches reuse membership and ordering, keeping unrelated nodes stable.*/import { useMemo } from 'react';@@ -29,7 +29,7 @@ export function useProjectGroups(includePinnedInProjects: boolean = false,persistentLocalProjects?: readonly PersistentLocalProject[],localPlatform: string = '',- /** Result from an earlier call with identical inputs (e.g. no activity filter). */+ /** Reuse an earlier call when the activity filter did not change its inputs. */equivalentResult?: ProjectGroupsResult,): ProjectGroupsResult {const sshHosts = useRemoteSshHosts();@@ -43,14 +43,13 @@ export function useProjectGroups(const groups = useMemo(() => {if (equivalentResult) return equivalentResult;- const groups = selectGroups(sessions, {+ return selectGroups(sessions, {projectAliases,includePinnedInProjects,botOwnerBySessionId,persistentLocalProjects,localPlatform,});- return groups;}, [equivalentResult,selectGroups,@@ -59,7 +58,6 @@ export function useProjectGroups(includePinnedInProjects,persistentLocalProjects,localPlatform,- sshHosts,botOwnerBySessionId,]);const ambiguousDeviceNames = useMemo(@@ -67,8 +65,8 @@ export function useProjectGroups([groups.projects],);const ambiguityKey = JSON.stringify([...ambiguousDeviceNames].sort());- // Preserve untouched project props as well as session props. Weak keys do not- // retain old grouping generations; machine-directory changes invalidate all.+ // Weak keys keep only live grouping nodes. Registry/collision changes must+ // re-enrich even unchanged nodes so remote labels never retain stale names.const enrichedProjects = useMemo(() => new WeakMap<ProjectNode, ProjectNode>(),[sshHosts, ambiguityKey],diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.tsindex 273efddbce..2dbe21ea38 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts@@ -22,7 +22,7 @@import { useCallback } from 'react';import { flushSync } from 'react-dom';-import { useNavigate } from 'react-router-dom';+import { useSidebarNavigate } from '../sidebar/sidebarNavigation';import { useTranslation } from 'react-i18next';import { toast } from '@/lib/toast';@@ -49,7 +49,7 @@ export interface RunSessionActionOptions {}export function useSessionLifecycleActions(options?: { includeArchived?: ListStatusFilter }) {- const navigate = useNavigate();+ const navigate = useSidebarNavigate();const { t } = useTranslation();// patchLocal / refreshSessions 转发到 sessionsStore 模块级单例,// 与调用方组件里的 useCCSessions 实例共享同一份 cache。diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts b/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.tsindex 1fe6ec00dc..e2830ee853 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts@@ -233,21 +233,15 @@ export function sortSessionsForMainList(sortBy: FilterSortBy,ctx: MainListPriorityContext = EMPTY_PRIORITY_CONTEXT,): Session[] {- if (sortBy === 'priority') {- return sessions- .slice()- .sort(- (a, b) =>- sessionPriorityRank(a, ctx) - sessionPriorityRank(b, ctx) ||- sessionPriorityRecencyMs(b, ctx) - sessionPriorityRecencyMs(a, ctx),- );- }- if (sortBy === 'created') {- return sessions.slice().sort((a, b) =>- sessionCreatedMs(b) - sessionCreatedMs(a) || a.id.localeCompare(b.id),- );- }- return sessions.slice().sort((a, b) => sessionActivityMs(b) - sessionActivityMs(a));+ // Compute numeric keys once per call, never retain them across session updates.+ return sessions.map((session) => ({+ session,+ rank: sortBy === 'priority' ? sessionPriorityRank(session, ctx) : 0,+ time: sortBy === 'priority' ? sessionPriorityRecencyMs(session, ctx)+ : sortBy === 'created' ? sessionCreatedMs(session) : sessionActivityMs(session),+ })).sort((a, b) => a.rank - b.rank || b.time - a.time ||+ (sortBy === 'created' ? a.session.id.localeCompare(b.session.id) : 0))+ .map(({ session }) => session);}export interface BuildMainListEntriesInput {@@ -372,24 +366,6 @@ export function buildMainListEntries({return sortMainListEntries(entries, sortBy, projectOrder, manualProjectOrder, ctx);}-function compareEntriesBySortBy(- a: MainListEntry,- b: MainListEntry,- sortBy: FilterSortBy,- ctx: MainListPriorityContext,-): number {- if (sortBy === 'priority') {- return (- entryPriorityRank(a, ctx) - entryPriorityRank(b, ctx) ||- entryPriorityRecencyMs(b, ctx) - entryPriorityRecencyMs(a, ctx)- );- }- const timeDifference = entryTimeMs(b, sortBy) - entryTimeMs(a, sortBy);- if (timeDifference !== 0 || sortBy !== 'created') return timeDifference;- return (getMainListEntrySessions(a)[0]?.id ?? '').localeCompare(- getMainListEntrySessions(b)[0]?.id ?? '',- );-}function sortMainListEntries(entries: readonly MainListEntry[],@@ -398,6 +374,17 @@ function sortMainListEntries(manualProjectOrder: readonly string[],ctx: MainListPriorityContext,): MainListEntry[] {+ const keys = new Map(entries.map((entry) => [entry, {+ rank: sortBy === 'priority' ? entryPriorityRank(entry, ctx) : 0,+ time: sortBy === 'priority' ? entryPriorityRecencyMs(entry, ctx) : entryTimeMs(entry, sortBy),+ id: sortBy === 'created' ? getMainListEntrySessions(entry)[0]?.id ?? '' : '',+ }]));+ const compare = (a: MainListEntry, b: MainListEntry) => {+ const left = keys.get(a)!;+ const right = keys.get(b)!;+ return left.rank - right.rank || right.time - left.time ||+ (sortBy === 'created' ? left.id.localeCompare(right.id) : 0);+ };if (projectOrder === 'custom') {// 自定义项目序:项目行按 manualProjectOrder;不在序的新项目由 normalize// 追加到已排序列之后。非项目条目排在项目之后,仍按当前任务排序。@@ -420,11 +407,11 @@ function sortMainListEntries(Number.MAX_SAFE_INTEGER));}- return compareEntriesBySortBy(a, b, sortBy, ctx);+ return compare(a, b);});}- return entries.slice().sort((a, b) => compareEntriesBySortBy(a, b, sortBy, ctx));+ return entries.slice().sort((a, b) => compare(a, b));}/* ============================== 设备分组(E 期) ============================== */diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/projectGroupsSelector.ts b/apps/desktop/src/renderer/features/cc-agent/lib/projectGroupsSelector.tsindex 58adb5981e..4df76e6121 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/projectGroupsSelector.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/projectGroupsSelector.ts@@ -18,10 +18,13 @@ const ROW_ONLY_FIELDS = new Set(['contextTokens','contextWindow','updatedAt',+ '_count',]);function sameGroupingInput(a: Session, b: Session): boolean {if ((a.userSendAt ?? a.updatedAt) !== (b.userSendAt ?? b.updatedAt)) return false;+ // Only crossing the draft boundary changes grouping.+ if (((a._count?.messages ?? 0) === 0) !== ((b._count?.messages ?? 0) === 0)) return false;const keys = new Set([...Object.keys(a), ...Object.keys(b)]);for (const key of keys) {if (!ROW_ONLY_FIELDS.has(key) && a[key as keyof Session] !== b[key as keyof Session]) {@@ -77,7 +80,10 @@ export function createProjectGroupsSelector() {}| undefined;- return (sessions: readonly Session[], options: GroupSessionsOptions): ProjectGroupsResult => {+ return (+ sessions: readonly Session[],+ options: GroupSessionsOptions = {},+ ): ProjectGroupsResult => {let result: ProjectGroupsResult | undefined;if (previous &&diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsxindex ec69f2d2e2..dc617fe8a8 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx@@ -1,7 +1,8 @@-import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { MountedMenuContent } from './MountedMenuContent';+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { ChevronDown, ChevronRight, EllipsisVertical, Play } from 'lucide-react';-import { useNavigate } from 'react-router-dom';-import { useTranslation } from 'react-i18next';+import { withSidebarNavigation, type SidebarNavigationProps } from './sidebarNavigation';+import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';import { cn } from '@/lib/utils';import { Spinner } from '@/components/ui/spinner';@@ -34,7 +35,10 @@ import {useSessionsAttentionUrgencyIdSet,} from '../contexts/SessionAttentionUrgencyContext';import { useSessionAttentionKind, useSessionsAttentionKindMap } from '@/lib/sessionAttentionStore';-import { useRemoteSessionActivity, useRemoteSessionsPhaseMap } from '@/features/device-link/remoteSessionActivityStore';+import {+ useRemoteSessionActivity,+ useRemoteSessionsPhaseMap,+} from '@/features/device-link/remoteSessionActivityStore';import { useAgentIslandActivity } from '@/state/agentIslandActivity';import {projectSidebarSessionActivity,@@ -96,753 +100,772 @@ function isAutomationGroupInlineAction(target: EventTarget | null): boolean {);}-export const AutomationSessionGroupItem = memo(function AutomationSessionGroupItem({- group,- activeSessionId,- runningSessionIds,- attachedSessionIds,- notifications,- selectedSessionIds,- onSessionClick,- onAction,- onRename,- onTogglePin,- onMoveSession,- projectOptions,- onScheduleAction,- collapsed: controlledCollapsed,- onCollapsedChange,- indented = false,- sourceLabelMap,- matchMap,- sessionVariant = 'text',-}: AutomationSessionGroupItemProps) {- const { t } = useTranslation();- const navigate = useNavigate();- // 轴 1:文件夹开/关,持久化、记忆上次展开(默认收起)。- const [storedCollapsed, toggleStoredCollapsed] = useAutomationGroupCollapsed(- group.id,- group.legacyId,- );- const collapsed = controlledCollapsed ?? storedCollapsed;- const toggleCollapsed = useCallback(() => {- if (onCollapsedChange) {- onCollapsedChange(!collapsed);- return;- }- toggleStoredCollapsed();- }, [collapsed, onCollapsedChange, toggleStoredCollapsed]);- // 轴 2:运行列表内部的「前 5 条 / 显示全部」临时态,离开自动收回。- // 收起告警列表和展开历史列表共用这一份状态,所以切折叠必须复位 —— 否则- // 收起态点过「显示全部」再展开会一次摊开整组历史(Codex #3184),对称地,- // 展开态点过「显示全部」再收起也会把整组历史带进告警列表。复位挂在- // collapsed 变化上,覆盖 chevron 与父层「收起所有分组」,不只一条点击路径。- const [showAll, setShowAll] = useState(false);- useLayoutEffect(() => {- setShowAll(false);- }, [collapsed]);- const [frozen, setFrozen] = useState<FrozenGroupState | null>(null);- const [menuOpen, setMenuOpen] = useState(false);- const [rowTooltipOpen, setRowTooltipOpen] = useState(false);- const [countdownNowMs, setCountdownNowMs] = useState(() => Date.now());- // 组头 = 组内「最新一条」运行的代理:状态、running/loading、点击打开目标都跟这条一致。- // 用 group.sessions 派生(仅活动时间排序,不掺 running/notifications),引用随组内成员- // 变化才变,天然稳定,无需再靠 frozen 快照固定"代表会话"。- const latestSession = useMemo(() => getAutomationGroupLatestSession(group), [group]);- const latestSessionId = latestSession?.id;- // ── 收起态的整组汇总 ────────────────────────────────────────────────────────- // 组头收起时代表的是**整组**,不能只反映最新一条:组内任意一条运行留下未处理告警- // (典型是被 App 重启打断、turn 从未收尾的运行)时,项目折叠头会按全部子任务汇总出- // 红点,而此前组头只看最新一条、收起态子行又整片不渲染 —— 于是「项目行有红点、- // 展开后哪一行都没有」。判据复用项目折叠头那一份(resolveCollapsedAttention),- // 红点与被提上来的告警行同源,两者不可能再打架。- // 三个 hook 都是"一组 id"的 primitive 快照订阅(组外会话变化、组内不改变本组结果的- // 变化都不唤醒本组件),不要退回整表 / 整集订阅 —— 每个项目下都有若干组头在挂载。- const groupSessionIds = useMemo(- () => group.sessions.map((session) => session.id),- [group.sessions],- );- const groupAttentionKinds = useSessionsAttentionKindMap(groupSessionIds);- const groupUrgentSessionIds = useSessionsAttentionUrgencyIdSet(groupSessionIds);- const groupRemotePhases = useRemoteSessionsPhaseMap(group.sessions);- const collapsedAttention = useMemo(- () =>- resolveCollapsedAttention({- sessions: group.sessions,- runningSessionIds,+export const AutomationSessionGroupItem = withSidebarNavigation<AutomationSessionGroupItemProps>(+ function AutomationSessionGroupItem({+ navigate,+ group,+ activeSessionId,+ runningSessionIds,+ attachedSessionIds,+ notifications,+ selectedSessionIds,+ onSessionClick,+ onAction,+ onRename,+ onTogglePin,+ onMoveSession,+ projectOptions,+ onScheduleAction,+ collapsed: controlledCollapsed,+ onCollapsedChange,+ indented = false,+ sourceLabelMap,+ matchMap,+ sessionVariant = 'text',+ }: AutomationSessionGroupItemProps & SidebarNavigationProps) {+ const { t } = useTranslation();+ // 轴 1:文件夹开/关,持久化、记忆上次展开(默认收起)。+ const [storedCollapsed, toggleStoredCollapsed] = useAutomationGroupCollapsed(+ group.id,+ group.legacyId,+ );+ const collapsed = controlledCollapsed ?? storedCollapsed;+ const toggleCollapsed = useCallback(() => {+ if (onCollapsedChange) {+ onCollapsedChange(!collapsed);+ return;+ }+ toggleStoredCollapsed();+ }, [collapsed, onCollapsedChange, toggleStoredCollapsed]);+ // 轴 2:运行列表内部的「前 5 条 / 显示全部」临时态,离开自动收回。+ // 收起告警列表和展开历史列表共用这一份状态,所以切折叠必须复位 —— 否则+ // 收起态点过「显示全部」再展开会一次摊开整组历史(Codex #3184),对称地,+ // 展开态点过「显示全部」再收起也会把整组历史带进告警列表。复位挂在+ // collapsed 变化上,覆盖 chevron 与父层「收起所有分组」,不只一条点击路径。+ const [showAll, setShowAll] = useState(false);+ useLayoutEffect(() => {+ setShowAll(false);+ }, [collapsed]);+ const [frozen, setFrozen] = useState<FrozenGroupState | null>(null);+ const [menuOpen, setMenuOpen] = useState(false);+ const [rowTooltipOpen, setRowTooltipOpen] = useState(false);+ const [countdownNowMs, setCountdownNowMs] = useState(() => Date.now());+ // 组头 = 组内「最新一条」运行的代理:状态、running/loading、点击打开目标都跟这条一致。+ // 用 group.sessions 派生(仅活动时间排序,不掺 running/notifications),引用随组内成员+ // 变化才变,天然稳定,无需再靠 frozen 快照固定"代表会话"。+ const latestSession = useMemo(() => getAutomationGroupLatestSession(group), [group]);+ const latestSessionId = latestSession?.id;+ // ── 收起态的整组汇总 ────────────────────────────────────────────────────────+ // 组头收起时代表的是**整组**,不能只反映最新一条:组内任意一条运行留下未处理告警+ // (典型是被 App 重启打断、turn 从未收尾的运行)时,项目折叠头会按全部子任务汇总出+ // 红点,而此前组头只看最新一条、收起态子行又整片不渲染 —— 于是「项目行有红点、+ // 展开后哪一行都没有」。判据复用项目折叠头那一份(resolveCollapsedAttention),+ // 红点与被提上来的告警行同源,两者不可能再打架。+ // 三个 hook 都是"一组 id"的 primitive 快照订阅(组外会话变化、组内不改变本组结果的+ // 变化都不唤醒本组件),不要退回整表 / 整集订阅 —— 每个项目下都有若干组头在挂载。+ const groupSessionIds = useMemo(+ () => group.sessions.map((session) => session.id),+ [group.sessions],+ );+ const groupAttentionKinds = useSessionsAttentionKindMap(groupSessionIds);+ const groupUrgentSessionIds = useSessionsAttentionUrgencyIdSet(groupSessionIds);+ const groupRemotePhases = useRemoteSessionsPhaseMap(group.sessions);+ const collapsedAttention = useMemo(+ () =>+ resolveCollapsedAttention({+ sessions: group.sessions,+ runningSessionIds,+ notifications,+ attentionKinds: groupAttentionKinds,+ urgentSessionIds: groupUrgentSessionIds,+ remotePhaseOf: (sessionId) => groupRemotePhases.get(sessionId),+ }),+ [+ group.sessions,+ groupAttentionKinds,+ groupRemotePhases,+ groupUrgentSessionIds,notifications,- attentionKinds: groupAttentionKinds,- urgentSessionIds: groupUrgentSessionIds,- remotePhaseOf: (sessionId) => groupRemotePhases.get(sessionId),- }),- [- group.sessions,- groupAttentionKinds,- groupRemotePhases,- groupUrgentSessionIds,+ runningSessionIds,+ ],+ );+ const alertSessionIds = useMemo(+ () => new Set(collapsedAttention.errorSessionIds),+ [collapsedAttention],+ );+ // 与组头红/绿未读点同源:没有未读就不提供「标为已读」,避免空操作占菜单。+ const canMarkRead = collapsedAttention.tone != null;+ // childView 的 24h 豁免依赖实时 now,必须每次渲染直接算,不能进 useMemo —— 否则依赖项+ // 不变时时间窗口会被冻结,跨过 24h 阈值的运行不会及时移出豁免。与普通对话列表+ // SessionEntryList 一致(它也是 render 内直接算 getSessionListCollapseView、不 memo);+ // 计算本身是 O(组内运行数) 的轻量过滤,无需 memo。+ const childView = getAutomationGroupChildView(group, {notifications,runningSessionIds,- ],- );- const alertSessionIds = useMemo(- () => new Set(collapsedAttention.errorSessionIds),- [collapsedAttention],- );- // 与组头红/绿未读点同源:没有未读就不提供「标为已读」,避免空操作占菜单。- const canMarkRead = collapsedAttention.tone != null;- // childView 的 24h 豁免依赖实时 now,必须每次渲染直接算,不能进 useMemo —— 否则依赖项- // 不变时时间窗口会被冻结,跨过 24h 阈值的运行不会及时移出豁免。与普通对话列表- // SessionEntryList 一致(它也是 render 内直接算 getSessionListCollapseView、不 memo);- // 计算本身是 O(组内运行数) 的轻量过滤,无需 memo。- const childView = getAutomationGroupChildView(group, {- notifications,- runningSessionIds,- showAll,- activeSessionId,- frozenVisibleSessionIds: frozen?.visibleSessionIds ?? null,- // 实时 now:启用「最近 24h 内有活动不折叠」豁免,和普通对话列表一致。- nowMs: Date.now(),- collapsed,- alertSessionIds,- });- // 轴 1 收起时只留组头 + 被提上来的告警行;展开时交给轴 2 的「前 5 / 显示全部」。- // 两种形态都由 getAutomationGroupChildView 一处决定(见该函数的 ⚠️)。- const visibleSessions = childView.visibleSessions;- // 组头右侧状态图标的**基线**来源(全端统一 5 档色表:error 红 > awaiting TapTap 蓝 >- // running spinner > 完成未读绿 > time),两路信号都只看「最新一条」运行:- // 1. SessionAttentionUrgencyContext:该 run 是失败 schedule run(attentionKind 缺失- // 但语义等同 error)→ 红- // 2. sessionAttentionStore kind:该 run 有 chat 侧 urgent attention- // (错误终止 → 红;pending ask-user / 权限 → 蓝)- // 组头是「最新一条运行的代理」:点击打开它,loading / vendor 呼吸与其一致。展开态右侧- // 状态就到此为止;**收起态**再叠一层整组汇总(上方 collapsedAttention +- // resolveCollapsedGroupRightStatus)—— 此时组头代表整组,组内任何一条的未处理告警都必须- // 露出来,否则会重演「项目折叠头有红点、展开却哪一行都没有」。- // 这两个 hook 仍按 latestSessionId 精准订阅(boolean / kind primitive 快照),整组那三个- // 也都是"一组 id"的 primitive 快照 —— 别退回整组对象 / 整张表订阅(性能不变量)。- const latestUrgentFromSchedule = useSessionAttentionUrgency(latestSessionId ?? '');- const latestChatKind = useSessionAttentionKind(latestSessionId ?? '');- const latestLocalActivity = useAgentIslandActivity(latestSessionId ?? '');- const latestRemoteActivity = useRemoteSessionActivity(- latestSessionId ?? '',- latestSession?.deviceLinkDeviceId,- );- const latestLiveActivity = latestSession?.deviceLinkDeviceId- ? latestRemoteActivity- : latestLocalActivity;- const scheduleId = group.scheduleId;- // 「已停止」= paused(用户主动暂停)+ expired(计划到期不再触发);两者对用户体验- // 而言都是「不会再自动跑」,视觉上都在 Timer chip 上叠 Pause 徽标,并在 tooltip- // 里显示「已停止」文案,避免用户误判为普通空闲态。- const isScheduleStopped = group.scheduleStatus === 'paused' || group.scheduleStatus === 'expired';- const hasVisibleChildren = visibleSessions.length > 0;- // running / loading 也只看最新那条:组头 vendor mark 呼吸 + Timer chip 呼吸 + 右侧- // spinner 都据此,与最新 session 子行一致(需求:「loading 状态和最新的 session 保持一致」)。- const isRunning = latestSessionId != null && latestSession?.deviceLinkDeviceId- ? latestRemoteActivity?.phase === 'running'- : latestSessionId != null && runningSessionIds.has(latestSessionId);- const primaryActivityIso = latestSession?.updatedAt;- const hasActiveHidden =- activeSessionId != null &&- group.sessions.some((session) => session.id === activeSessionId) &&- !visibleSessions.some((session) => session.id === activeSessionId);- const shouldTickCountdown =- group.scheduleStatus === 'active' &&- typeof group.nextFireAt === 'number' &&- Number.isFinite(group.nextFireAt) &&- group.nextFireAt > countdownNowMs;- const ToggleIcon = collapsed ? ChevronRight : ChevronDown;- // 组头右侧状态槽复用 SessionItem 的 5 档色表(error 红 / awaiting 蓝 / running spinner /- // done 绿 / time 文字):四个 input 全部取「最新一条」运行,送进同一 resolveSidebarRightStatus,- // 于是组头右侧状态与最新 session 子行像素级一致(色号 / 图标尺寸 / 判定完全同源)。- // 收起态在这个基线之上叠整组汇总,见下方 groupRightStatusKind —— 色表与图标不变,- // 只是档位改由整组决定。- const latestHasNotification = latestSessionId != null && notifications.has(latestSessionId);- const groupActivity = projectSidebarSessionActivity({- interruption: latestSession,- sessionId: latestSessionId ?? '',- title: latestSession?.title,- recordStatus: latestSession?.status,- liveActivity: latestLiveActivity,- attentionKind: latestChatKind,- isUrgentFromContext: latestUrgentFromSchedule,- isRunning,- hasAttentionNotification: latestHasNotification,- });- // 收起态按整组汇总补足组头(展开态仍严格只看最新一条),判据见- // resolveCollapsedGroupRightStatus。isRunning 与 vendor / Timer 呼吸不受影响,仍跟- // 最新一条 —— 保住「loading 与最新 session 一致」那条既有裁决。- const groupRightStatusKind: SidebarRightStatusKind = resolveCollapsedGroupRightStatus({- collapsed,- latestKind: resolveSidebarRightStatus(groupActivity),- tone: collapsedAttention.tone,- });- const showRightStatus = groupRightStatusKind !== 'time';- const actionButtonToneClassName = hasActiveHidden- ? 'text-sidebar-item-active-foreground hover:text-sidebar-item-active-foreground hover:bg-[color-mix(in_srgb,var(--sidebar-item-active-foreground)_14%,transparent)]'- : 'text-sidebar-action-icon hover:bg-sidebar-item-hover hover:text-foreground';-- const freezeCurrentLayout = (sessionId: string): void => {- setFrozen({- sessionId,- originActiveSessionId: activeSessionId ?? null,- hasBeenActive: false,- visibleSessionIds: visibleSessions.map((session) => session.id),+ showAll,+ activeSessionId,+ frozenVisibleSessionIds: frozen?.visibleSessionIds ?? null,+ // 实时 now:启用「最近 24h 内有活动不折叠」豁免,和普通对话列表一致。+ nowMs: Date.now(),+ collapsed,+ alertSessionIds,+ });+ // 轴 1 收起时只留组头 + 被提上来的告警行;展开时交给轴 2 的「前 5 / 显示全部」。+ // 两种形态都由 getAutomationGroupChildView 一处决定(见该函数的 ⚠️)。+ const visibleSessions = childView.visibleSessions;+ // 组头右侧状态图标的**基线**来源(全端统一 5 档色表:error 红 > awaiting TapTap 蓝 >+ // running spinner > 完成未读绿 > time),两路信号都只看「最新一条」运行:+ // 1. SessionAttentionUrgencyContext:该 run 是失败 schedule run(attentionKind 缺失+ // 但语义等同 error)→ 红+ // 2. sessionAttentionStore kind:该 run 有 chat 侧 urgent attention+ // (错误终止 → 红;pending ask-user / 权限 → 蓝)+ // 组头是「最新一条运行的代理」:点击打开它,loading / vendor 呼吸与其一致。展开态右侧+ // 状态就到此为止;**收起态**再叠一层整组汇总(上方 collapsedAttention ++ // resolveCollapsedGroupRightStatus)—— 此时组头代表整组,组内任何一条的未处理告警都必须+ // 露出来,否则会重演「项目折叠头有红点、展开却哪一行都没有」。+ // 这两个 hook 仍按 latestSessionId 精准订阅(boolean / kind primitive 快照),整组那三个+ // 也都是"一组 id"的 primitive 快照 —— 别退回整组对象 / 整张表订阅(性能不变量)。+ const latestUrgentFromSchedule = useSessionAttentionUrgency(latestSessionId ?? '');+ const latestChatKind = useSessionAttentionKind(latestSessionId ?? '');+ const latestLocalActivity = useAgentIslandActivity(latestSessionId ?? '');+ const latestRemoteActivity = useRemoteSessionActivity(+ latestSessionId ?? '',+ latestSession?.deviceLinkDeviceId,+ );+ const latestLiveActivity = latestSession?.deviceLinkDeviceId+ ? latestRemoteActivity+ : latestLocalActivity;+ const scheduleId = group.scheduleId;+ // 「已停止」= paused(用户主动暂停)+ expired(计划到期不再触发);两者对用户体验+ // 而言都是「不会再自动跑」,视觉上都在 Timer chip 上叠 Pause 徽标,并在 tooltip+ // 里显示「已停止」文案,避免用户误判为普通空闲态。+ const isScheduleStopped =+ group.scheduleStatus === 'paused' || group.scheduleStatus === 'expired';+ const hasVisibleChildren = visibleSessions.length > 0;+ // running / loading 也只看最新那条:组头 vendor mark 呼吸 + Timer chip 呼吸 + 右侧+ // spinner 都据此,与最新 session 子行一致(需求:「loading 状态和最新的 session 保持一致」)。+ const isRunning =+ latestSessionId != null && latestSession?.deviceLinkDeviceId+ ? latestRemoteActivity?.phase === 'running'+ : latestSessionId != null && runningSessionIds.has(latestSessionId);+ const primaryActivityIso = latestSession?.updatedAt;+ const hasActiveHidden =+ activeSessionId != null &&+ group.sessions.some((session) => session.id === activeSessionId) &&+ !visibleSessions.some((session) => session.id === activeSessionId);+ const shouldTickCountdown =+ group.scheduleStatus === 'active' &&+ typeof group.nextFireAt === 'number' &&+ Number.isFinite(group.nextFireAt) &&+ group.nextFireAt > countdownNowMs;+ const ToggleIcon = collapsed ? ChevronRight : ChevronDown;+ // 组头右侧状态槽复用 SessionItem 的 5 档色表(error 红 / awaiting 蓝 / running spinner /+ // done 绿 / time 文字):四个 input 全部取「最新一条」运行,送进同一 resolveSidebarRightStatus,+ // 于是组头右侧状态与最新 session 子行像素级一致(色号 / 图标尺寸 / 判定完全同源)。+ // 收起态在这个基线之上叠整组汇总,见下方 groupRightStatusKind —— 色表与图标不变,+ // 只是档位改由整组决定。+ const latestHasNotification = latestSessionId != null && notifications.has(latestSessionId);+ const groupActivity = projectSidebarSessionActivity({+ interruption: latestSession,+ sessionId: latestSessionId ?? '',+ title: latestSession?.title,+ recordStatus: latestSession?.status,+ liveActivity: latestLiveActivity,+ attentionKind: latestChatKind,+ isUrgentFromContext: latestUrgentFromSchedule,+ isRunning,+ hasAttentionNotification: latestHasNotification,+ });+ // 收起态按整组汇总补足组头(展开态仍严格只看最新一条),判据见+ // resolveCollapsedGroupRightStatus。isRunning 与 vendor / Timer 呼吸不受影响,仍跟+ // 最新一条 —— 保住「loading 与最新 session 一致」那条既有裁决。+ const groupRightStatusKind: SidebarRightStatusKind = resolveCollapsedGroupRightStatus({+ collapsed,+ latestKind: resolveSidebarRightStatus(groupActivity),+ tone: collapsedAttention.tone,});- };+ const showRightStatus = groupRightStatusKind !== 'time';+ const actionButtonToneClassName = hasActiveHidden+ ? 'text-sidebar-item-active-foreground hover:text-sidebar-item-active-foreground hover:bg-[color-mix(in_srgb,var(--sidebar-item-active-foreground)_14%,transparent)]'+ : 'text-sidebar-action-icon hover:bg-sidebar-item-hover hover:text-foreground';- // 子行 onClick 必须引用稳定,否则 SessionItem 的 memo 每次组头重渲染都被击穿。- // 但 freeze 需要读"点击瞬间"的最新布局(activeSessionId / visibleSessions 等),- // 依赖全塞进 useCallback 会让引用照样天天变 —— 用 latest-ref 模式:render 时同步- // 刷 ref,handler 本体只依赖 onSessionClick(上游 useCallback,稳定)。- const freezeCurrentLayoutRef = useRef(freezeCurrentLayout);- freezeCurrentLayoutRef.current = freezeCurrentLayout;- const showAllRef = useRef(showAll);- showAllRef.current = showAll;- // 收起态点告警行不冻结:冻结快照会把"当时可见的行"锁成布局,而收起态可见的只有- // 告警行 —— 之后用户展开这个组会看到被锁住的两三条告警行而不是正常的前 5 条运行。- const collapsedRef = useRef(collapsed);- collapsedRef.current = collapsed;- const handleChildSessionClick = useCallback<SessionClickHandler>(- (id, modifiers) => {- if (!collapsedRef.current && !showAllRef.current && !hasSessionSelectionModifier(modifiers)) {- freezeCurrentLayoutRef.current(id);- }- onSessionClick(id, modifiers);- },- [onSessionClick],- );+ const freezeCurrentLayout = (sessionId: string): void => {+ setFrozen({+ sessionId,+ originActiveSessionId: activeSessionId ?? null,+ hasBeenActive: false,+ visibleSessionIds: visibleSessions.map((session) => session.id),+ });+ };- useEffect(() => {- if (!frozen) return;- const stillInGroup = group.sessions.some((session) => session.id === frozen.sessionId);- if (!stillInGroup) {- setFrozen(null);- return;- }- if (activeSessionId === frozen.sessionId) {- if (!frozen.hasBeenActive) {- setFrozen({ ...frozen, hasBeenActive: true });+ // 子行 onClick 必须引用稳定,否则 SessionItem 的 memo 每次组头重渲染都被击穿。+ // 但 freeze 需要读"点击瞬间"的最新布局(activeSessionId / visibleSessions 等),+ // 依赖全塞进 useCallback 会让引用照样天天变 —— 用 latest-ref 模式:render 时同步+ // 刷 ref,handler 本体只依赖 onSessionClick(上游 useCallback,稳定)。+ const freezeCurrentLayoutRef = useRef(freezeCurrentLayout);+ freezeCurrentLayoutRef.current = freezeCurrentLayout;+ const showAllRef = useRef(showAll);+ showAllRef.current = showAll;+ // 收起态点告警行不冻结:冻结快照会把"当时可见的行"锁成布局,而收起态可见的只有+ // 告警行 —— 之后用户展开这个组会看到被锁住的两三条告警行而不是正常的前 5 条运行。+ const collapsedRef = useRef(collapsed);+ collapsedRef.current = collapsed;+ const handleChildSessionClick = useCallback<SessionClickHandler>(+ (id, modifiers) => {+ if (+ !collapsedRef.current &&+ !showAllRef.current &&+ !hasSessionSelectionModifier(modifiers)+ ) {+ freezeCurrentLayoutRef.current(id);+ }+ onSessionClick(id, modifiers);+ },+ [onSessionClick],+ );++ useEffect(() => {+ if (!frozen) return;+ const stillInGroup = group.sessions.some((session) => session.id === frozen.sessionId);+ if (!stillInGroup) {+ setFrozen(null);+ return;+ }+ if (activeSessionId === frozen.sessionId) {+ if (!frozen.hasBeenActive) {+ setFrozen({ ...frozen, hasBeenActive: true });+ }+ return;+ }+ if (frozen.hasBeenActive || (activeSessionId ?? null) !== frozen.originActiveSessionId) {+ setFrozen(null);}- return;- }- if (frozen.hasBeenActive || (activeSessionId ?? null) !== frozen.originActiveSessionId) {- setFrozen(null);- }- }, [activeSessionId, frozen, group.sessions]);+ }, [activeSessionId, frozen, group.sessions]);- // 手动展开(showAll)后,焦点一旦离开本组就自动收回 —— 让自动化分组和普通对话一样- // 不会越用越长。沿用 frozen 的「曾锚定 → 离开」判定:展开瞬间记下当时的 active 会话,- // 之后 active 落到组内即视为锚定;锚定过(或 active 已不是展开时那个会话)再离开组时收回。- const prevShowAllRef = useRef(false);- const expandAnchorRef = useRef<{- originActiveSessionId: string | null;- hasFocusedGroup: boolean;- } | null>(null);- useEffect(() => {- if (showAll && !prevShowAllRef.current) {- expandAnchorRef.current = {- originActiveSessionId: activeSessionId ?? null,- hasFocusedGroup: false,- };- } else if (!showAll) {- expandAnchorRef.current = null;- }- prevShowAllRef.current = showAll;+ // 手动展开(showAll)后,焦点一旦离开本组就自动收回 —— 让自动化分组和普通对话一样+ // 不会越用越长。沿用 frozen 的「曾锚定 → 离开」判定:展开瞬间记下当时的 active 会话,+ // 之后 active 落到组内即视为锚定;锚定过(或 active 已不是展开时那个会话)再离开组时收回。+ const prevShowAllRef = useRef(false);+ const expandAnchorRef = useRef<{+ originActiveSessionId: string | null;+ hasFocusedGroup: boolean;+ } | null>(null);+ useEffect(() => {+ if (showAll && !prevShowAllRef.current) {+ expandAnchorRef.current = {+ originActiveSessionId: activeSessionId ?? null,+ hasFocusedGroup: false,+ };+ } else if (!showAll) {+ expandAnchorRef.current = null;+ }+ prevShowAllRef.current = showAll;- const anchor = expandAnchorRef.current;- if (!showAll || !anchor) return;- const activeInGroup =- activeSessionId != null && group.sessions.some((session) => session.id === activeSessionId);- if (activeInGroup) {- anchor.hasFocusedGroup = true;- return;- }- if (anchor.hasFocusedGroup || (activeSessionId ?? null) !== anchor.originActiveSessionId) {- setShowAll(false);- expandAnchorRef.current = null;- }- }, [activeSessionId, group.sessions, showAll]);+ const anchor = expandAnchorRef.current;+ if (!showAll || !anchor) return;+ const activeInGroup =+ activeSessionId != null && group.sessions.some((session) => session.id === activeSessionId);+ if (activeInGroup) {+ anchor.hasFocusedGroup = true;+ return;+ }+ if (anchor.hasFocusedGroup || (activeSessionId ?? null) !== anchor.originActiveSessionId) {+ setShowAll(false);+ expandAnchorRef.current = null;+ }+ }, [activeSessionId, group.sessions, showAll]);- useEffect(() => {- if (!shouldTickCountdown) return;- setCountdownNowMs(Date.now());- const timer = window.setInterval(() => {+ useEffect(() => {+ if (!shouldTickCountdown) return;setCountdownNowMs(Date.now());- }, 1000);- return () => window.clearInterval(timer);- }, [group.nextFireAt, shouldTickCountdown]);+ const timer = window.setInterval(() => {+ setCountdownNowMs(Date.now());+ }, 1000);+ return () => window.clearInterval(timer);+ }, [group.nextFireAt, shouldTickCountdown]);- // meta = 「time」分支才用的最近活动相对时间。error / awaiting / running / done 四档- // 状态改由右侧状态图标(showRightStatus)统一表达,不再走文字。仅当 groupRightStatusKind- // === 'time' 时 meta 才会被读到。- const meta = useMemo(() => {- const lastRunText = formatSidebarTime(primaryActivityIso, t);- if (lastRunText) return lastRunText;- return t('ccAgent.sidebar.automationGroup.runCount', { count: group.sessions.length });- }, [group.sessions.length, primaryActivityIso, t]);+ // meta = 「time」分支才用的最近活动相对时间。error / awaiting / running / done 四档+ // 状态改由右侧状态图标(showRightStatus)统一表达,不再走文字。仅当 groupRightStatusKind+ // === 'time' 时 meta 才会被读到。+ const meta = useMemo(() => {+ const lastRunText = formatSidebarTime(primaryActivityIso, t);+ if (lastRunText) return lastRunText;+ return t('ccAgent.sidebar.automationGroup.runCount', { count: group.sessions.length });+ }, [group.sessions.length, primaryActivityIso, t]);- // 行 hover tooltip 内容:active 状态下的下次运行倒计时(如「5分钟后」)/ paused|expired- // 时的「已停止」+ 累计运行次数(取 group.sessions.length,一次调度产生一条会话)。全为- // 空时返回 null,Tip 会在 text 为空时直接透传 children,不挂 tooltip。- // useMemo:countdownNowMs 每秒 tick,内联 JSX 会每秒重建 element ref,Radix Tooltip- // 可能因此重挂内容;memo 后仅在文案实际变化时才刷新。- const countdownText = shouldTickCountdown- ? formatSidebarFutureTime(group.nextFireAt, t, new Date(countdownNowMs))- : '';- const stoppedText = isScheduleStopped ? t('ccAgent.sidebar.automationGroup.stopped') : '';- const runCountText =- group.sessions.length > 0- ? t('ccAgent.sidebar.automationGroup.runCount', { count: group.sessions.length })+ // 行 hover tooltip 内容:active 状态下的下次运行倒计时(如「5分钟后」)/ paused|expired+ // 时的「已停止」+ 累计运行次数(取 group.sessions.length,一次调度产生一条会话)。全为+ // 空时返回 null,Tip 会在 text 为空时直接透传 children,不挂 tooltip。+ // useMemo:countdownNowMs 每秒 tick,内联 JSX 会每秒重建 element ref,Radix Tooltip+ // 可能因此重挂内容;memo 后仅在文案实际变化时才刷新。+ const countdownText = shouldTickCountdown+ ? formatSidebarFutureTime(group.nextFireAt, t, new Date(countdownNowMs)): '';- const scheduleBindingLabel = t('ccAgent.sidebar.scheduleBinding.viewTask');- const toggleGroupLabel = t(- collapsed- ? 'ccAgent.sidebar.automationGroup.expand'- : 'ccAgent.sidebar.automationGroup.collapse',- { title: group.title },- );- const rowTooltip = useMemo(- () =>- countdownText || stoppedText || runCountText ? (- <div className="flex flex-col gap-0.5">- {countdownText && <span>{countdownText}</span>}- {stoppedText && <span>{stoppedText}</span>}- {runCountText && <span>{runCountText}</span>}- </div>- ) : null,- [countdownText, runCountText, stoppedText],- );+ const stoppedText = isScheduleStopped ? t('ccAgent.sidebar.automationGroup.stopped') : '';+ const runCountText =+ group.sessions.length > 0+ ? t('ccAgent.sidebar.automationGroup.runCount', { count: group.sessions.length })+ : '';+ const scheduleBindingLabel = t('ccAgent.sidebar.scheduleBinding.viewTask');+ const toggleGroupLabel = t(+ collapsed+ ? 'ccAgent.sidebar.automationGroup.expand'+ : 'ccAgent.sidebar.automationGroup.collapse',+ { title: group.title },+ );+ const rowTooltip = useMemo(+ () =>+ countdownText || stoppedText || runCountText ? (+ <div className="flex flex-col gap-0.5">+ {countdownText && <span>{countdownText}</span>}+ {stoppedText && <span>{stoppedText}</span>}+ {runCountText && <span>{runCountText}</span>}+ </div>+ ) : null,+ [countdownText, runCountText, stoppedText],+ );- // 点击空白行区域 = 点击标题。展开态打开最新一条;收起且整组是红时打开- // 贡献红点的那条。行内控件各自 stopPropagation,不会误触发。- const openLatestSession = () => {- const targetId = resolveCollapsedGroupHeaderSessionId({- collapsed,- latestSessionId,- attention: collapsedAttention,- });- if (!targetId) return;- // 仅在展开 + 前 5 条态下冻结当前布局;收起态无子项可冻结。- if (!collapsed && !showAll) freezeCurrentLayout(targetId);- onSessionClick(targetId);- };+ // 点击空白行区域 = 点击标题。展开态打开最新一条;收起且整组是红时打开+ // 贡献红点的那条。行内控件各自 stopPropagation,不会误触发。+ const openLatestSession = () => {+ const targetId = resolveCollapsedGroupHeaderSessionId({+ collapsed,+ latestSessionId,+ attention: collapsedAttention,+ });+ if (!targetId) return;+ // 仅在展开 + 前 5 条态下冻结当前布局;收起态无子项可冻结。+ if (!collapsed && !showAll) freezeCurrentLayout(targetId);+ onSessionClick(targetId);+ };- return (- <div className="flex w-full flex-col gap-0.5">- {/* 行 hover 浮层视觉与 SessionTooltip(PR 引用)对齐:右侧 align=start 弹出、+ return (+ <div className="flex w-full flex-col gap-0.5">+ {/* 行 hover 浮层视觉与 SessionTooltip(PR 引用)对齐:右侧 align=start 弹出、浅色 surface(--surface-elevated + --border-default + shadow-sm)、立即出现,和侧栏其它 hover 卡片在同一套调色板下(规则 16)。行内动作有自己的 Tip,进入这些按钮时由受控 open 关闭行级浮层,避免两层提示重叠。 */}- <Tip- text={rowTooltip}- side="right"- delay={0}- controlledOpen={rowTooltipOpen}- contentClassName={cn(- 'bg-[var(--surface-elevated)] text-[var(--text-primary)]',- 'border-[var(--border-default)] dark:border-[var(--border-default)] shadow-sm',- )}- >- {/* 行 onClick 只承担鼠标点击空白 = 点击标题的转发;不加 role="button" / tabIndex /+ <Tip+ text={rowTooltip}+ side="right"+ delay={0}+ controlledOpen={rowTooltipOpen}+ contentClassName={cn(+ 'bg-[var(--surface-elevated)] text-[var(--text-primary)]',+ 'border-[var(--border-default)] dark:border-[var(--border-default)] shadow-sm',+ )}+ >+ {/* 行 onClick 只承担鼠标点击空白 = 点击标题的转发;不加 role="button" / tabIndex /onKeyDown —— ARIA 不允许 role=button widget 内嵌可交互 <button>,且键盘 keydown会冒泡穿过内部按钮的 stopPropagation(click 语义)造成双触发。键盘可达性由内部标题 <button>(Tab focus + Enter/Space)天然提供。 */}- <div- onClick={openLatestSession}- onContextMenu={(event) => {- // 整行右键 = 打开「更多操作」同一份菜单(不再另做一份隐形锚点菜单)。- event.preventDefault();- event.stopPropagation();- if (!scheduleId) return;- setRowTooltipOpen(false);- setMenuOpen(true);- }}- onPointerOver={(event) => {- setRowTooltipOpen(!isAutomationGroupInlineAction(event.target));- }}- onPointerLeave={() => setRowTooltipOpen(false)}- onFocusCapture={(event) => {- setRowTooltipOpen(!isAutomationGroupInlineAction(event.target));- }}- onBlurCapture={(event) => {- const nextTarget = event.relatedTarget;- setRowTooltipOpen(- nextTarget instanceof Node &&- event.currentTarget.contains(nextTarget) &&- !isAutomationGroupInlineAction(nextTarget),- );- }}- className={cn(- // list 组头与普通 SessionCard 共用 10px 内容边距;只有展开后的子任务- // 由下方 pl-3 容器额外缩进。text 模式继续沿用 SessionItem 的树形缩进。- 'group relative flex h-8 w-full items-center gap-1.5 rounded-full',- sessionVariant === 'list' ? 'px-2.5' : indented ? 'pl-[22px] pr-2' : 'pl-3 pr-2',- 'text-left text-sm font-medium',- hasActiveHidden- ? 'bg-sidebar-item-active text-[var(--sidebar-item-active-foreground)]'- : 'text-foreground hover:bg-sidebar-item-hover',- latestSession && 'cursor-pointer',- )}- >- <span className="flex min-w-0 items-center gap-1.5">- {/* list 复用 SessionCard 的 12px 状态槽,text 复用 SessionItem 的 15px 槽;+ <div+ onClick={openLatestSession}+ onContextMenu={(event) => {+ // 整行右键 = 打开「更多操作」同一份菜单(不再另做一份隐形锚点菜单)。+ event.preventDefault();+ event.stopPropagation();+ if (!scheduleId) return;+ setRowTooltipOpen(false);+ setMenuOpen(true);+ }}+ onPointerOver={(event) => {+ setRowTooltipOpen(!isAutomationGroupInlineAction(event.target));+ }}+ onPointerLeave={() => setRowTooltipOpen(false)}+ onFocusCapture={(event) => {+ setRowTooltipOpen(!isAutomationGroupInlineAction(event.target));+ }}+ onBlurCapture={(event) => {+ const nextTarget = event.relatedTarget;+ setRowTooltipOpen(+ nextTarget instanceof Node &&+ event.currentTarget.contains(nextTarget) &&+ !isAutomationGroupInlineAction(nextTarget),+ );+ }}+ className={cn(+ // list 组头与普通 SessionCard 共用 10px 内容边距;只有展开后的子任务+ // 由下方 pl-3 容器额外缩进。text 模式继续沿用 SessionItem 的树形缩进。+ 'group relative flex h-8 w-full items-center gap-1.5 rounded-full',+ sessionVariant === 'list' ? 'px-2.5' : indented ? 'pl-[22px] pr-2' : 'pl-3 pr-2',+ 'text-left text-sm font-medium',+ hasActiveHidden+ ? 'bg-sidebar-item-active text-[var(--sidebar-item-active-foreground)]'+ : 'text-foreground hover:bg-sidebar-item-hover',+ latestSession && 'cursor-pointer',+ )}+ >+ <span className="flex min-w-0 items-center gap-1.5">+ {/* list 复用 SessionCard 的 12px 状态槽,text 复用 SessionItem 的 15px 槽;这样首图标和标题都能落在各自模式的普通任务列上。分组 agentKind 取最新一条 run(同一 schedule 所有 run 走同一 agent),缺失时退化为'cc'。isRunning 只看最新那条,与其子行一致。 */}- <span- className={cn(- 'flex shrink-0 items-center justify-center',- sessionVariant === 'list' ? 'w-3' : 'w-[15px]',- )}- >- <VendorIcon- vendor={agentKindToVendor(latestSession?.agentKind)}- size={agentKindToVendor(latestSession?.agentKind) === 'cc' ? 13 : 12}- running={isRunning}- colorClassName={- hasActiveHidden ? 'text-[var(--sidebar-item-active-foreground)]' : undefined- }- />- </span>- {/* text 延续 vendor → Timer → 标题;list 把 Timer 排到标题右侧,避免它+ <span+ className={cn(+ 'flex shrink-0 items-center justify-center',+ sessionVariant === 'list' ? 'w-3' : 'w-[15px]',+ )}+ >+ <VendorIcon+ vendor={agentKindToVendor(latestSession?.agentKind)}+ size={agentKindToVendor(latestSession?.agentKind) === 'cc' ? 13 : 12}+ running={isRunning}+ colorClassName={+ hasActiveHidden ? 'text-[var(--sidebar-item-active-foreground)]' : undefined+ }+ />+ </span>+ {/* text 延续 vendor → Timer → 标题;list 把 Timer 排到标题右侧,避免它被误读成一层缩进,同时保留自动任务身份和点击入口。Timer 与标题是同级按钮,避免 role=button 嵌进 title button 后无法进入 Tab 顺序。 */}- <Tip text={scheduleBindingLabel} side="bottom">+ <Tip text={scheduleBindingLabel} side="bottom">+ <button+ type="button"+ data-automation-group-inline-action="true"+ aria-label={scheduleBindingLabel}+ onClick={(event) => {+ event.stopPropagation();+ navigate(+ group.scheduleId+ ? scheduleFocusPath(group.scheduleId)+ : '/cc-agent/scheduled',+ );+ }}+ onPointerDown={(event) => event.stopPropagation()}+ className={cn(+ 'relative inline-flex size-3 shrink-0 cursor-pointer items-center justify-center',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ sessionVariant === 'list' && 'order-2',+ )}+ >+ {/* Timer 始终占同一个 12px 槽;暂停/过期只叠状态角标,不替换主图标。 */}+ <AutomationTimerIcon+ size={10}+ paused={isScheduleStopped}+ activeForeground={hasActiveHidden}+ running={isRunning}+ />+ </button>+ </Tip>+ <button+ type="button"+ onClick={(event) => {+ event.stopPropagation();+ openLatestSession();+ }}+ disabled={!latestSession}+ className="min-w-0 truncate text-left disabled:cursor-default"+ >+ <span className="min-w-0 truncate">{group.title}</span>+ </button>+ </span>+ {/* 展开箭头挪到标题后,视觉上属于「标题右侧的次要控件」,和右侧 meta/操作+ 槽用 ml-auto 分开;shrink-0 保证长标题挤压时不会先把 chevron 挤没。 */}+ <Tip text={toggleGroupLabel} side="bottom"><buttontype="button"data-automation-group-inline-action="true"- aria-label={scheduleBindingLabel}onClick={(event) => {+ // 阻止冒泡到行级 onClick(否则一次点击既切展开又打开会话)。event.stopPropagation();- navigate(- group.scheduleId ? scheduleFocusPath(group.scheduleId) : '/cc-agent/scheduled',- );+ setFrozen(null);+ toggleCollapsed();}}- onPointerDown={(event) => event.stopPropagation()}+ aria-expanded={!collapsed}+ aria-label={toggleGroupLabel}className={cn(- 'relative inline-flex size-3 shrink-0 cursor-pointer items-center justify-center',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',- sessionVariant === 'list' && 'order-2',+ 'flex size-5 shrink-0 items-center justify-center rounded-md',+ hasActiveHidden+ ? 'hover:bg-[color-mix(in_srgb,var(--sidebar-item-active-foreground)_14%,transparent)]'+ : 'hover:bg-sidebar-item-hover',)}>- {/* Timer 始终占同一个 12px 槽;暂停/过期只叠状态角标,不替换主图标。 */}- <AutomationTimerIcon- size={10}- paused={isScheduleStopped}- activeForeground={hasActiveHidden}- running={isRunning}+ <ToggleIcon+ size={12}+ strokeWidth={2}+ className={+ hasActiveHidden+ ? 'text-[var(--sidebar-item-active-foreground)]'+ : 'text-[var(--cmd-palette-item-meta)]'+ }/></button></Tip>- <button- type="button"- onClick={(event) => {- event.stopPropagation();- openLatestSession();- }}- disabled={!latestSession}- className="min-w-0 truncate text-left disabled:cursor-default"- >- <span className="min-w-0 truncate">{group.title}</span>- </button>- </span>- {/* 展开箭头挪到标题后,视觉上属于「标题右侧的次要控件」,和右侧 meta/操作- 槽用 ml-auto 分开;shrink-0 保证长标题挤压时不会先把 chevron 挤没。 */}- <Tip text={toggleGroupLabel} side="bottom">- <button- type="button"- data-automation-group-inline-action="true"- onClick={(event) => {- // 阻止冒泡到行级 onClick(否则一次点击既切展开又打开会话)。- event.stopPropagation();- setFrozen(null);- toggleCollapsed();- }}- aria-expanded={!collapsed}- aria-label={toggleGroupLabel}- className={cn(- 'flex size-5 shrink-0 items-center justify-center rounded-md',- hasActiveHidden- ? 'hover:bg-[color-mix(in_srgb,var(--sidebar-item-active-foreground)_14%,transparent)]'- : 'hover:bg-sidebar-item-hover',- )}- >- <ToggleIcon- size={12}- strokeWidth={2}- className={- hasActiveHidden- ? 'text-[var(--sidebar-item-active-foreground)]'- : 'text-[var(--cmd-palette-item-meta)]'- }- />- </button>- </Tip>- {/* focus 隐藏条件用命名 group(/slot) 收窄到本槽位:行内 toggle/title+ {/* focus 隐藏条件用命名 group(/slot) 收窄到本槽位:行内 toggle/titlebutton 点击后焦点常驻行内,整行 group-focus-within 会让选中态(非 hover)的 meta 文本被永久隐藏,与 SessionItem 同款修法。 */}- <div className="group/slot relative ml-auto flex h-6 max-w-[96px] shrink-0 items-center justify-end">- <div className="grid h-6 max-w-[96px] grid-cols-[max-content] items-center justify-items-end">- {/* 右侧状态槽 —— 与 SessionItem 同款五档色表 / 图标尺寸(size-4 wrapper ++ <div className="group/slot relative ml-auto flex h-6 max-w-[96px] shrink-0 items-center justify-end">+ <div className="grid h-6 max-w-[96px] grid-cols-[max-content] items-center justify-items-end">+ {/* 右侧状态槽 —— 与 SessionItem 同款五档色表 / 图标尺寸(size-4 wrapper +size-2 dot / size-12 spinner),让分组头和普通任务行状态语义视觉可比。showRightStatus=true 时渲染状态图标(error/awaiting/done 圆点 + runningspinner),false 时回落到 meta 相对时间文字。scheduleId 存在时统一 hoverfade 出让位给 [Run][More] 按钮组。 */}- <div- className={cn(- // 字体 / 色号与普通任务行的信息槽(SessionInfoMeta)完全同款——含- // tabular-nums(C 期给普通行加的等宽数字,分组头当时漏跟),- // 让「9 分钟 / 4 小时」这类时间在两种行里对齐、粗细一致- // (2026-08-12 用户裁决)。- 'col-start-1 row-start-1 flex items-center gap-1 text-xs font-medium tabular-nums',- hasActiveHidden- ? 'text-[var(--sidebar-item-active-foreground)]'- : 'text-sidebar-action-icon',- scheduleId &&- !menuOpen &&- 'group-hover:opacity-0 group-focus-within/slot:opacity-0',- menuOpen && 'opacity-0',- )}- >- {showRightStatus ? (- groupRightStatusKind === 'error' ? (- <span- role="img"- className="inline-flex size-4 items-center justify-center"- aria-label={t('ccAgent.sidebar.status.error', 'Failed — click to view')}- title={t('ccAgent.sidebar.status.error', 'Failed — click to view')}- >+ <div+ className={cn(+ // 字体 / 色号与普通任务行的信息槽(SessionInfoMeta)完全同款——含+ // tabular-nums(C 期给普通行加的等宽数字,分组头当时漏跟),+ // 让「9 分钟 / 4 小时」这类时间在两种行里对齐、粗细一致+ // (2026-08-12 用户裁决)。+ 'col-start-1 row-start-1 flex items-center gap-1 text-xs font-medium tabular-nums',+ hasActiveHidden+ ? 'text-[var(--sidebar-item-active-foreground)]'+ : 'text-sidebar-action-icon',+ scheduleId &&+ !menuOpen &&+ 'group-hover:opacity-0 group-focus-within/slot:opacity-0',+ menuOpen && 'opacity-0',+ )}+ >+ {showRightStatus ? (+ groupRightStatusKind === 'error' ? (<span- className="size-2 rounded-full"- style={{- backgroundColor: hasActiveHidden- ? 'var(--sidebar-item-active-foreground)'- : 'var(--card-status-error)',- }}- aria-hidden- />- </span>- ) : groupRightStatusKind === 'awaiting' ? (- <span- role="img"- className="inline-flex size-4 items-center justify-center"- aria-label={t('ccAgent.sidebar.status.needsAttention', 'Awaiting your input')}- title={t('ccAgent.sidebar.status.needsAttention', 'Awaiting your input')}- >+ role="img"+ className="inline-flex size-4 items-center justify-center"+ aria-label={t('ccAgent.sidebar.status.error', 'Failed — click to view')}+ title={t('ccAgent.sidebar.status.error', 'Failed — click to view')}+ >+ <span+ className="size-2 rounded-full"+ style={{+ backgroundColor: hasActiveHidden+ ? 'var(--sidebar-item-active-foreground)'+ : 'var(--card-status-error)',+ }}+ aria-hidden+ />+ </span>+ ) : groupRightStatusKind === 'awaiting' ? (<span- className="size-2 rounded-full"- style={{- backgroundColor: hasActiveHidden- ? 'var(--sidebar-item-active-foreground)'- : 'var(--card-status-awaiting)',- }}- aria-hidden+ role="img"+ className="inline-flex size-4 items-center justify-center"+ aria-label={t(+ 'ccAgent.sidebar.status.needsAttention',+ 'Awaiting your input',+ )}+ title={t('ccAgent.sidebar.status.needsAttention', 'Awaiting your input')}+ >+ <span+ className="size-2 rounded-full"+ style={{+ backgroundColor: hasActiveHidden+ ? 'var(--sidebar-item-active-foreground)'+ : 'var(--card-status-awaiting)',+ }}+ aria-hidden+ />+ </span>+ ) : groupRightStatusKind === 'running' ? (+ <Spinner+ role="img"+ size={12}+ strokeWidth={2}+ className={cn(+ 'size-4',+ hasActiveHidden+ ? 'text-sidebar-item-active-foreground'+ : 'text-sidebar-action-icon',+ )}+ aria-label={t('ccAgent.sidebar.status.running', 'Running')}+ title={t('ccAgent.sidebar.status.running', 'Running')}/>- </span>- ) : groupRightStatusKind === 'running' ? (- <Spinner- role="img"- size={12}- strokeWidth={2}+ ) : (+ <span+ role="img"+ className="inline-flex size-4 items-center justify-center"+ aria-label={t('ccAgent.sidebar.status.done', 'Completed — click to view')}+ title={t('ccAgent.sidebar.status.done', 'Completed — click to view')}+ >+ <span+ className="size-2 rounded-full"+ style={{+ backgroundColor: hasActiveHidden+ ? 'var(--sidebar-item-active-foreground)'+ : 'var(--card-status-done)',+ }}+ aria-hidden+ />+ </span>+ )+ ) : (+ <span className="min-w-0 truncate text-right">{meta}</span>+ )}+ </div>+ {scheduleId && (+ <>+ <div+ aria-hiddenclassName={cn(- 'size-4',- hasActiveHidden- ? 'text-sidebar-item-active-foreground'- : 'text-sidebar-action-icon',+ 'invisible col-start-1 row-start-1 h-6 w-[42px]',+ !menuOpen && 'hidden group-hover:block group-focus-within/slot:block',)}- aria-label={t('ccAgent.sidebar.status.running', 'Running')}- title={t('ccAgent.sidebar.status.running', 'Running')}/>- ) : (- <span- role="img"- className="inline-flex size-4 items-center justify-center"- aria-label={t('ccAgent.sidebar.status.done', 'Completed — click to view')}- title={t('ccAgent.sidebar.status.done', 'Completed — click to view')}+ <div+ className={cn(+ 'absolute right-0 top-0 flex h-6 items-center gap-0.5',+ 'opacity-0 transition-opacity',+ menuOpen+ ? 'opacity-100'+ : 'group-hover:opacity-100 group-focus-within/slot:opacity-100',+ )}>- <span- className="size-2 rounded-full"- style={{- backgroundColor: hasActiveHidden- ? 'var(--sidebar-item-active-foreground)'- : 'var(--card-status-done)',- }}- aria-hidden- />- </span>- )- ) : (- <span className="min-w-0 truncate text-right">{meta}</span>- )}- </div>- {scheduleId && (- <>- <div- aria-hidden- className={cn(- 'invisible col-start-1 row-start-1 h-6 w-[42px]',- !menuOpen && 'hidden group-hover:block group-focus-within/slot:block',- )}- />- <div- className={cn(- 'absolute right-0 top-0 flex h-6 items-center gap-0.5',- 'opacity-0 transition-opacity',- menuOpen- ? 'opacity-100'- : 'group-hover:opacity-100 group-focus-within/slot:opacity-100',- )}- >- {/* 高频 Run 继续直点;Edit/Pause/Resume/Delete 收进 More 菜单,避免 Edit+ {/* 高频 Run 继续直点;Edit/Pause/Resume/Delete 收进 More 菜单,避免 Edit和左侧 Timer chip 形成重复入口,同时保留原来菜单里的低频操作空间。 */}- <Tip text={t('ccAgent.sidebar.automationGroup.menu.runNow')} side="bottom">- <button- type="button"- data-automation-group-inline-action="true"- onClick={(event) => {- event.stopPropagation();- // 点击后主动 blur:group/slot 的 focus-within 会让操作按钮- // 常驻可见 + meta 常隐,鼠标移开也不恢复;显式失焦让 hover 语义- // 重新接管。- event.currentTarget.blur();- onScheduleAction(group, 'run');- }}- aria-label={t('ccAgent.sidebar.automationGroup.menu.runNow')}- className={cn(- 'flex size-5 shrink-0 items-center justify-center rounded-md',- 'transition-colors',- actionButtonToneClassName,- )}- >- <Play size={14} strokeWidth={2} />- </button>- </Tip>- <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>- <DropdownMenuTrigger asChild>- <Tip text={t('ccAgent.sidebar.automationGroup.menu.more')} side="bottom">- <button- type="button"- data-automation-group-inline-action="true"- onClick={(event) => {- event.stopPropagation();- event.currentTarget.blur();- }}- onPointerDown={(event) => event.stopPropagation()}- aria-label={t('ccAgent.sidebar.automationGroup.menu.more')}- className={cn(- 'flex size-5 shrink-0 items-center justify-center rounded-md',- 'transition-colors',- actionButtonToneClassName,- )}- >- <EllipsisVertical size={14} strokeWidth={2} />- </button>- </Tip>- </DropdownMenuTrigger>- <DropdownMenuContent- align="end"- sideOffset={2}- onClick={(event) => event.stopPropagation()}- className={cn(MENU_CONTENT_CLASS, 'min-w-36 overflow-hidden')}- >- {canMarkRead && (- <DropdownMenuItem- onSelect={() => onScheduleAction(group, 'mark-read')}- className={MENU_ITEM_CLASS}- >- {t('ccAgent.sidebar.automationGroup.menu.markAllAsRead')}- </DropdownMenuItem>- )}- <DropdownMenuItem- onSelect={() => onScheduleAction(group, 'edit')}- className={MENU_ITEM_CLASS}+ <Tip text={t('ccAgent.sidebar.automationGroup.menu.runNow')} side="bottom">+ <button+ type="button"+ data-automation-group-inline-action="true"+ onClick={(event) => {+ event.stopPropagation();+ // 点击后主动 blur:group/slot 的 focus-within 会让操作按钮+ // 常驻可见 + meta 常隐,鼠标移开也不恢复;显式失焦让 hover 语义+ // 重新接管。+ event.currentTarget.blur();+ onScheduleAction(group, 'run');+ }}+ aria-label={t('ccAgent.sidebar.automationGroup.menu.runNow')}+ className={cn(+ 'flex size-5 shrink-0 items-center justify-center rounded-md',+ 'transition-colors',+ actionButtonToneClassName,+ )}>- {t('ccAgent.sidebar.automationGroup.menu.edit')}- </DropdownMenuItem>- {group.scheduleStatus !== 'expired' && (- <DropdownMenuItem- onSelect={() => onScheduleAction(group, 'toggle-pause')}- className={MENU_ITEM_CLASS}- >- {group.scheduleStatus === 'paused'- ? t('ccAgent.sidebar.automationGroup.menu.resume')- : t('ccAgent.sidebar.automationGroup.menu.pause')}- </DropdownMenuItem>- )}- <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />- <DropdownMenuItem- onSelect={() => onScheduleAction(group, 'delete')}- disabled={- group.scheduleSource === 'project' &&- (!group.workingDir || !group.projectConfigId)- }- className={cn(MENU_ITEM_CLASS, 'text-[hsl(var(--destructive))]')}+ <Play size={14} strokeWidth={2} />+ </button>+ </Tip>+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>+ <DropdownMenuTrigger asChild>+ <Tip text={t('ccAgent.sidebar.automationGroup.menu.more')} side="bottom">+ <button+ type="button"+ data-automation-group-inline-action="true"+ onClick={(event) => {+ event.stopPropagation();+ event.currentTarget.blur();+ }}+ onPointerDown={(event) => event.stopPropagation()}+ aria-label={t('ccAgent.sidebar.automationGroup.menu.more')}+ className={cn(+ 'flex size-5 shrink-0 items-center justify-center rounded-md',+ 'transition-colors',+ actionButtonToneClassName,+ )}+ >+ <EllipsisVertical size={14} strokeWidth={2} />+ </button>+ </Tip>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ sideOffset={2}+ onClick={(event) => event.stopPropagation()}+ className={cn(MENU_CONTENT_CLASS, 'min-w-36 overflow-hidden')}>- {t('ccAgent.sidebar.automationGroup.menu.delete')}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>- </>- )}+ <MountedMenuContent>+ {() => (+ <>+ {canMarkRead && (+ <DropdownMenuItem+ onSelect={() => onScheduleAction(group, 'mark-read')}+ className={MENU_ITEM_CLASS}+ >+ {t('ccAgent.sidebar.automationGroup.menu.markAllAsRead')}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ onSelect={() => onScheduleAction(group, 'edit')}+ className={MENU_ITEM_CLASS}+ >+ {t('ccAgent.sidebar.automationGroup.menu.edit')}+ </DropdownMenuItem>+ {group.scheduleStatus !== 'expired' && (+ <DropdownMenuItem+ onSelect={() => onScheduleAction(group, 'toggle-pause')}+ className={MENU_ITEM_CLASS}+ >+ {group.scheduleStatus === 'paused'+ ? t('ccAgent.sidebar.automationGroup.menu.resume')+ : t('ccAgent.sidebar.automationGroup.menu.pause')}+ </DropdownMenuItem>+ )}+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />+ <DropdownMenuItem+ onSelect={() => onScheduleAction(group, 'delete')}+ disabled={+ group.scheduleSource === 'project' &&+ (!group.workingDir || !group.projectConfigId)+ }+ className={cn(MENU_ITEM_CLASS, 'text-[hsl(var(--destructive))]')}+ >+ {t('ccAgent.sidebar.automationGroup.menu.delete')}+ </DropdownMenuItem>+ </>+ )}+ </MountedMenuContent>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </>+ )}+ </div></div></div>- </div>- </Tip>- {hasVisibleChildren && (- <div className="flex flex-col gap-0.5 pl-3">- {visibleSessions.map((session: Session, index) => {- const nextSession = visibleSessions[index + 1];- const nextHighlighted =- nextSession != null &&- (nextSession.id === activeSessionId ||- (selectedSessionIds?.has(nextSession.id) ?? false));- const commonProps = {- session,- isActive: session.id === activeSessionId,- isRunning: runningSessionIds.has(session.id),- isAttached: attachedSessionIds.has(session.id),- hasAttentionNotification: notifications.has(session.id),- isSelected: selectedSessionIds?.has(session.id) ?? false,- onClick: handleChildSessionClick,- onAction,- onRename,- onTogglePin,- onMoveSession,- projectOptions,- indented,- matchIndices: matchMap?.get(session.id),- sourceLabel: sourceLabelMap?.get(session.id),- };+ </Tip>+ {hasVisibleChildren && (+ <div className="flex flex-col gap-0.5 pl-3">+ {visibleSessions.map((session: Session, index) => {+ const nextSession = visibleSessions[index + 1];+ const nextHighlighted =+ nextSession != null &&+ (nextSession.id === activeSessionId ||+ (selectedSessionIds?.has(nextSession.id) ?? false));+ const commonProps = {+ session,+ isActive: session.id === activeSessionId,+ isRunning: runningSessionIds.has(session.id),+ isAttached: attachedSessionIds.has(session.id),+ hasAttentionNotification: notifications.has(session.id),+ isSelected: selectedSessionIds?.has(session.id) ?? false,+ onClick: handleChildSessionClick,+ onAction,+ onRename,+ onTogglePin,+ onMoveSession,+ projectOptions,+ indented,+ matchIndices: matchMap?.get(session.id),+ sourceLabel: sourceLabelMap?.get(session.id),+ };- return sessionVariant === 'list' ? (- <SessionCard- key={session.id}- {...commonProps}- variant="list"- isFirst={index === 0}- hideBottomDivider={nextHighlighted}- />- ) : (- <SessionItem key={session.id} {...commonProps} insideAutomationGroup />- );- })}- {!showAll && childView.isOverflowing && (- <button- type="button"- onClick={() => setShowAll(true)}- className={cn(- 'flex h-6 w-full items-center justify-center rounded-full px-2 text-xs font-normal',- 'text-[var(--cmd-palette-item-meta)] transition-colors hover:bg-sidebar-item-hover hover:text-foreground',- 'focus:outline-none focus-visible:ring-1 focus-visible:ring-[var(--focus-ring)]',- )}- >- {t('ccAgent.sidebar.showAllSessions', { count: childView.totalCount })}- </button>- )}- </div>- )}- </div>- );-});+ return sessionVariant === 'list' ? (+ <SessionCard+ key={session.id}+ {...commonProps}+ variant="list"+ isFirst={index === 0}+ hideBottomDivider={nextHighlighted}+ />+ ) : (+ <SessionItem key={session.id} {...commonProps} insideAutomationGroup />+ );+ })}+ {!showAll && childView.isOverflowing && (+ <button+ type="button"+ onClick={() => setShowAll(true)}+ className={cn(+ 'flex h-6 w-full items-center justify-center rounded-full px-2 text-xs font-normal',+ 'text-[var(--cmd-palette-item-meta)] transition-colors hover:bg-sidebar-item-hover hover:text-foreground',+ 'focus:outline-none focus-visible:ring-1 focus-visible:ring-[var(--focus-ring)]',+ )}+ >+ {t('ccAgent.sidebar.showAllSessions', { count: childView.totalCount })}+ </button>+ )}+ </div>+ )}+ </div>+ );+ },+);diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/MountedMenuContent.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/MountedMenuContent.tsxnew file mode 100644index 0000000000..702300a4c9--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/MountedMenuContent.tsx@@ -0,0 +1,6 @@+import type { ReactNode } from 'react';++/** Build menu rows only while Radix mounts content, including its exit animation. */+export function MountedMenuContent({ children }: { children: () => ReactNode }) {+ return children();+}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsxindex 13ddd4e7d8..1991a04579 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx@@ -21,7 +21,7 @@* DraggableCardColumns 错落瀑布(每列独立 SortableJS 实例 + 跨列 group,多列也可整卡拖拽)。*/-import { memo, useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';+import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';import type {DragEvent as ReactDragEvent,MouseEvent as ReactMouseEvent,@@ -30,6 +30,7 @@ import type {} from 'react';import { Archive, ChevronRight, EllipsisVertical, Undo } from 'lucide-react';import { useTranslation } from 'react-i18next';+import { withSidebarNavigation, type SidebarNavigationProps } from './sidebarNavigation';import { cn } from '@/lib/utils';import { SessionStatusIcon } from './SessionStatusIcon';@@ -135,7 +136,8 @@ export type SessionCardProps = SessionItemProps & {hideBottomDivider?: boolean;};-export const SessionCard = memo(function SessionCard({+export const SessionCard = withSidebarNavigation<SessionCardProps>(function SessionCard({+ navigate,session,isActive,isRunning,@@ -153,7 +155,7 @@ export const SessionCard = memo(function SessionCard({variant = 'card',isFirst = false,hideBottomDivider = false,-}: SessionCardProps) {+}: SessionCardProps & SidebarNavigationProps) {const { t } = useTranslation();const cindyMakePreparing = useCindyMakePreparing(session);// mod+1..9 序号徽标:模块 store 按 sessionId 精准订阅,非按住态恒为 null。diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsxindex e9d804d27c..b73e429f71 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsx@@ -1,5 +1,5 @@import { useMemo } from 'react';-import { useTranslation } from 'react-i18next';+import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';import { cn } from '@/lib/utils';import type { Session } from '@/lib/ccAgent.types';diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsxindex c087a7c999..f9ff51b6de 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx@@ -29,10 +29,11 @@* Agent → Timer 沿用原 Clock 的 gap-1.5(6px),Timer → 标题同为 6px。*/-import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';import type { DragEvent as ReactDragEvent, MouseEvent as ReactMouseEvent, ReactNode } from 'react';import { Archive, ChevronRight, EllipsisVertical, Play, Undo } from 'lucide-react';-import { useTranslation } from 'react-i18next';+import { withSidebarNavigation, type SidebarNavigationProps } from './sidebarNavigation';+import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';import { cn } from '@/lib/utils';import type { Session } from '@/lib/ccAgent.types';@@ -318,7 +319,8 @@ export function hasSessionSelectionModifier(modifiers?: SessionClickModifiers):* 背景:2026-07 切换会话卡顿,实测整栏重画单次 80-96ms、每次切换连跑 3 遍,* 根源就是行内全表订阅 + 无 memo。*/-export const SessionItem = memo(function SessionItem({+export const SessionItem = withSidebarNavigation<SessionItemProps>(function SessionItem({+ navigate,session,isActive,isRunning,@@ -335,7 +337,7 @@ export const SessionItem = memo(function SessionItem({matchIndices,sourceLabel,insideAutomationGroup = false,-}: SessionItemProps) {+}: SessionItemProps & SidebarNavigationProps) {const { t } = useTranslation();const cindyMakePreparing = useCindyMakePreparing(session);const prRefs = usePrRefsForSession(session.id);diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsxindex 052f5ef179..4ef1fabe76 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx@@ -16,6 +16,7 @@* --text-tertiary/--text-secondary,hover 时比邻居暗一档、视觉不齐。*/+import { MountedMenuContent } from './MountedMenuContent';import type { ReactNode } from 'react';import {AlignJustify,@@ -78,7 +79,6 @@ import {import type { ProjectNode as ProjectNodeData } from '../lib/projectGrouping';import { getRemoteProjectMachineIdentity } from '../lib/remoteProjectIdentity';import type {- FilterGroupBy,FilterLastActivity,FilterProjectOrder,FilterSortBy,@@ -607,275 +607,288 @@ export function SidebarFilterPopover({纵向滚动;禁止横向滚动,避免分隔线的负边距撑出底部滚动条占位。滚动容器放内层(与下方项目列表同款做法),不与 content 的overflow-hidden 抢同一属性。减 0.75rem 让出 content 的 p-1 与边框。 */}- <div className="max-h-[calc(var(--radix-dropdown-menu-content-available-height)-0.75rem)] overflow-x-hidden overflow-y-auto">- <MenuSubRow- label={t('ccAgent.sidebar.filterGroupByHeading')}- value={groupByValue}- Icon={SidebarGroupsIcon}- >- <CheckMenuItem- label={t('ccAgent.sidebar.filterGroupBy.project')}- checked={groupBy === 'project'}- onToggle={() => setGroupBy(groupBy === 'project' ? 'flat' : 'project')}- Icon={Folder}- />- <CheckMenuItem- label={t('ccAgent.sidebar.filterGroupBy.dialogue')}- checked={groupDialogue}- onToggle={() => setGroupDialogue(!groupDialogue)}- Icon={MessageSquare}- />- {hasRemoteDevices && (- <CheckMenuItem- label={t('ccAgent.sidebar.filterGroupBy.device')}- checked={groupDevice}- onToggle={() => setGroupDevice(!groupDevice)}- Icon={Monitor}- />- )}- </MenuSubRow>- <MenuSubRow- label={t('ccAgent.sidebar.filterTaskSortHeading')}- value={sortByValue}- Icon={ArrowDownWideNarrow}- >- {SORT_BY_OPTIONS.map((option) => (- <SelectMenuItem- key={option.value}- label={t(option.menuLabelKey ?? option.labelKey)}- selected={sortBy === option.value}- Icon={option.Icon}- onSelect={() => setSortBy(option.value)}- tip={option.tipKey ? t(option.tipKey) : undefined}- />- ))}- </MenuSubRow>- {groupBy === 'project' && (- <MenuSubRow- label={t('ccAgent.sidebar.filterProjectOrderHeading')}- value={optionLabel(PROJECT_ORDER_OPTIONS, scopedProjectOrder, t)}- Icon={ListOrdered}- >- {PROJECT_ORDER_OPTIONS.map((option) => (- <SelectMenuItem- key={option.value}- label={t(option.labelKey)}- selected={scopedProjectOrder === option.value}- Icon={option.Icon}- onSelect={() => setProjectOrder(option.value)}- tip={option.tipKey ? t(option.tipKey) : undefined}- />- ))}- </MenuSubRow>- )}- <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />- <MenuSubRow- label={t('ccAgent.sidebar.taskStatusHeading')}- value={statusValue}- Icon={ListChecks}- >- {STATUS_OPTIONS.map((option) => (- <SelectMenuItem- key={option.value}- label={t(option.labelKey)}- selected={status === option.value}- Icon={option.Icon}- onSelect={() => setStatus(option.value)}- />- ))}- </MenuSubRow>- <MenuSubRow- label={t('ccAgent.sidebar.filterHeading')}- value={filterSummary}- valueEmphasized={activeFilterCount > 0}- Icon={Filter}- >- <MenuSubRow- label={t('ccAgent.sidebar.filterProjectsHeading')}- value={projectValue}- Icon={Folder}- >- <DropdownMenuItem- onSelect={(event) => {- event.preventDefault();- setProjectsAll();- }}- className={MENU_ITEM_CLASS}+ <MountedMenuContent>+ {() => (+ <div className="max-h-[calc(var(--radix-dropdown-menu-content-available-height)-0.75rem)] overflow-x-hidden overflow-y-auto">+ <MenuSubRow+ label={t('ccAgent.sidebar.filterGroupByHeading')}+ value={groupByValue}+ Icon={SidebarGroupsIcon}>- <MenuItemIcon Icon={Folders} />- <span className="truncate">{t('ccAgent.sidebar.filterAllProjects')}</span>- {projects === 'all' && (- <Check size={15} className="ml-auto shrink-0 text-[var(--msg-assistant-text)]" />+ <CheckMenuItem+ label={t('ccAgent.sidebar.filterGroupBy.project')}+ checked={groupBy === 'project'}+ onToggle={() => setGroupBy(groupBy === 'project' ? 'flat' : 'project')}+ Icon={Folder}+ />+ <CheckMenuItem+ label={t('ccAgent.sidebar.filterGroupBy.dialogue')}+ checked={groupDialogue}+ onToggle={() => setGroupDialogue(!groupDialogue)}+ Icon={MessageSquare}+ />+ {hasRemoteDevices && (+ <CheckMenuItem+ label={t('ccAgent.sidebar.filterGroupBy.device')}+ checked={groupDevice}+ onToggle={() => setGroupDevice(!groupDevice)}+ Icon={Monitor}+ />)}- </DropdownMenuItem>+ </MenuSubRow>+ <MenuSubRow+ label={t('ccAgent.sidebar.filterTaskSortHeading')}+ value={sortByValue}+ Icon={ArrowDownWideNarrow}+ >+ {SORT_BY_OPTIONS.map((option) => (+ <SelectMenuItem+ key={option.value}+ label={t(option.menuLabelKey ?? option.labelKey)}+ selected={sortBy === option.value}+ Icon={option.Icon}+ onSelect={() => setSortBy(option.value)}+ tip={option.tipKey ? t(option.tipKey) : undefined}+ />+ ))}+ </MenuSubRow>+ {groupBy === 'project' && (+ <MenuSubRow+ label={t('ccAgent.sidebar.filterProjectOrderHeading')}+ value={optionLabel(PROJECT_ORDER_OPTIONS, scopedProjectOrder, t)}+ Icon={ListOrdered}+ >+ {PROJECT_ORDER_OPTIONS.map((option) => (+ <SelectMenuItem+ key={option.value}+ label={t(option.labelKey)}+ selected={scopedProjectOrder === option.value}+ Icon={option.Icon}+ onSelect={() => setProjectOrder(option.value)}+ tip={option.tipKey ? t(option.tipKey) : undefined}+ />+ ))}+ </MenuSubRow>+ )}<DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />- <div className="max-h-[256px] overflow-y-auto">- <DropdownMenuItem- onSelect={(event) => {- event.preventDefault();- toggleProject(DIALOGUE_FILTER_KEY);- }}- className={MENU_ITEM_CLASS}+ <MenuSubRow+ label={t('ccAgent.sidebar.taskStatusHeading')}+ value={statusValue}+ Icon={ListChecks}+ >+ {STATUS_OPTIONS.map((option) => (+ <SelectMenuItem+ key={option.value}+ label={t(option.labelKey)}+ selected={status === option.value}+ Icon={option.Icon}+ onSelect={() => setStatus(option.value)}+ />+ ))}+ </MenuSubRow>+ <MenuSubRow+ label={t('ccAgent.sidebar.filterHeading')}+ value={filterSummary}+ valueEmphasized={activeFilterCount > 0}+ Icon={Filter}+ >+ <MenuSubRow+ label={t('ccAgent.sidebar.filterProjectsHeading')}+ value={projectValue}+ Icon={Folder}>- <MenuItemIcon Icon={MessageSquare} />- <span className="min-w-0 flex-1">- <span className="block truncate">{t('ccAgent.sidebar.dialogues')}</span>- </span>- <span className="shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">- {dialogueCount}- </span>- {(projects === 'all' || (projectsAsSet?.has(DIALOGUE_FILTER_KEY) ?? false)) && (- <Check size={15} className="shrink-0 text-[var(--msg-assistant-text)]" />- )}- </DropdownMenuItem>- {allKnownProjects.map((project) => {- const selected =- projects === 'all' ||- (projectsAsSet != null &&- projectFilterIncludes(projectsAsSet, project.projectKey, localPlatform));- const remoteIdentity = getRemoteProjectMachineIdentity(project);- return (+ <DropdownMenuItem+ onSelect={(event) => {+ event.preventDefault();+ setProjectsAll();+ }}+ className={MENU_ITEM_CLASS}+ >+ <MenuItemIcon Icon={Folders} />+ <span className="truncate">{t('ccAgent.sidebar.filterAllProjects')}</span>+ {projects === 'all' && (+ <Check+ size={15}+ className="ml-auto shrink-0 text-[var(--msg-assistant-text)]"+ />+ )}+ </DropdownMenuItem>+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />+ <div className="max-h-[256px] overflow-y-auto"><DropdownMenuItem- key={project.projectKey}onSelect={(event) => {event.preventDefault();- toggleProject(project.projectKey);+ toggleProject(DIALOGUE_FILTER_KEY);}}className={MENU_ITEM_CLASS}>- {project.scope === 'remote' ? (- <Tip text={remoteIdentity?.displayLabel ?? project.remoteHostId ?? ''}>- <Globe- size={14}- strokeWidth={2}- className="shrink-0 text-[var(--folder-item-icon)]"- />- </Tip>- ) : (- <MenuItemIcon Icon={Folder} />- )}+ <MenuItemIcon Icon={MessageSquare} /><span className="min-w-0 flex-1">- <span className="block truncate">{project.displayName}</span>- {remoteIdentity ? (- <span className="block truncate text-xs text-[var(--cmd-palette-item-meta)]">- {remoteIdentity.displayLabel}- </span>- ) : null}+ <span className="block truncate">{t('ccAgent.sidebar.dialogues')}</span></span><span className="shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">- {project.sessions.length}+ {dialogueCount}</span>- {selected && (+ {(projects === 'all' ||+ (projectsAsSet?.has(DIALOGUE_FILTER_KEY) ?? false)) && (<Check size={15} className="shrink-0 text-[var(--msg-assistant-text)]" />)}</DropdownMenuItem>- );- })}- </div>- </MenuSubRow>+ {allKnownProjects.map((project) => {+ const selected =+ projects === 'all' ||+ (projectsAsSet != null &&+ projectFilterIncludes(projectsAsSet, project.projectKey, localPlatform));+ const remoteIdentity = getRemoteProjectMachineIdentity(project);+ return (+ <DropdownMenuItem+ key={project.projectKey}+ onSelect={(event) => {+ event.preventDefault();+ toggleProject(project.projectKey);+ }}+ className={MENU_ITEM_CLASS}+ >+ {project.scope === 'remote' ? (+ <Tip text={remoteIdentity?.displayLabel ?? project.remoteHostId ?? ''}>+ <Globe+ size={14}+ strokeWidth={2}+ className="shrink-0 text-[var(--folder-item-icon)]"+ />+ </Tip>+ ) : (+ <MenuItemIcon Icon={Folder} />+ )}+ <span className="min-w-0 flex-1">+ <span className="block truncate">{project.displayName}</span>+ {remoteIdentity ? (+ <span className="block truncate text-xs text-[var(--cmd-palette-item-meta)]">+ {remoteIdentity.displayLabel}+ </span>+ ) : null}+ </span>+ <span className="shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">+ {project.sessions.length}+ </span>+ {selected && (+ <Check+ size={15}+ className="shrink-0 text-[var(--msg-assistant-text)]"+ />+ )}+ </DropdownMenuItem>+ );+ })}+ </div>+ </MenuSubRow>- <MenuSubRow- label={t('ccAgent.sidebar.filterAgentHeading')}- value={vendorValue}- Icon={Bot}- >- {VENDOR_OPTIONS.map((option) => (- <SelectMenuItem- key={option.value}- label={t(option.labelKey)}- selected={vendor === option.value}- Icon={option.Icon}- onSelect={() => setVendor(option.value)}- />- ))}- </MenuSubRow>+ <MenuSubRow+ label={t('ccAgent.sidebar.filterAgentHeading')}+ value={vendorValue}+ Icon={Bot}+ >+ {VENDOR_OPTIONS.map((option) => (+ <SelectMenuItem+ key={option.value}+ label={t(option.labelKey)}+ selected={vendor === option.value}+ Icon={option.Icon}+ onSelect={() => setVendor(option.value)}+ />+ ))}+ </MenuSubRow>- <MenuSubRow- label={t('ccAgent.sidebar.filterLastActivityHeading')}- value={lastActivityValue}- Icon={CalendarClock}- >- {LAST_ACTIVITY_OPTIONS.map((option) => (- <SelectMenuItem- key={option.value}- label={t(option.labelKey)}- selected={lastActivity === option.value}- Icon={option.Icon}- onSelect={() => setLastActivity(option.value)}- />- ))}- </MenuSubRow>+ <MenuSubRow+ label={t('ccAgent.sidebar.filterLastActivityHeading')}+ value={lastActivityValue}+ Icon={CalendarClock}+ >+ {LAST_ACTIVITY_OPTIONS.map((option) => (+ <SelectMenuItem+ key={option.value}+ label={t(option.labelKey)}+ selected={lastActivity === option.value}+ Icon={option.Icon}+ onSelect={() => setLastActivity(option.value)}+ />+ ))}+ </MenuSubRow>- <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />- <DropdownMenuItem- onSelect={(event) => {- event.preventDefault();- resetContentFilters();- }}- disabled={activeFilterCount === 0}- className={MENU_ITEM_CLASS}- >- <MenuItemIcon Icon={RotateCcw} />- <span className="truncate text-[var(--text-secondary)]">- {t('ccAgent.sidebar.filterReset')}- </span>- </DropdownMenuItem>- </MenuSubRow>+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />+ <DropdownMenuItem+ onSelect={(event) => {+ event.preventDefault();+ resetContentFilters();+ }}+ disabled={activeFilterCount === 0}+ className={MENU_ITEM_CLASS}+ >+ <MenuItemIcon Icon={RotateCcw} />+ <span className="truncate text-[var(--text-secondary)]">+ {t('ccAgent.sidebar.filterReset')}+ </span>+ </DropdownMenuItem>+ </MenuSubRow>- <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />- <MenuSubRow- label={t('ccAgent.sidebar.displayHeading')}- value={mainViewValue}- Icon={MainViewIcon}- >- {MAIN_VIEW_OPTIONS.map((option) => (- <SelectMenuItem- key={option.value}- label={t(option.labelKey)}- selected={mainViewMode === option.value}- onSelect={() => setMainViewMode(option.value)}- Icon={option.Icon}- />- ))}- </MenuSubRow>- <MenuSubRow- label={t('ccAgent.sidebar.taskInfoHeading')}- value={taskInfoSummary}- Icon={Info}- valueNode={- taskInfoFields.length > 0 ? (- // 已选项用图标串表示,不再罗列短词。顺序 = 用户勾选顺序(遍历- // taskInfoFields 而非选项表),与列表行的渲染顺序一致。- <span className="flex items-center justify-end gap-1">- {taskInfoFields.map((field) => {- const Icon = TASK_INFO_OPTIONS.find((option) => option.value === field)?.Icon;- return Icon ? (- <Icon- key={field}- size={13}- strokeWidth={1.8}- className="shrink-0"- aria-hidden- />- ) : null;- })}- </span>- ) : undefined- }- valueEmphasized={!taskInfoIsDefault}- >- {TASK_INFO_OPTIONS.map((option) => (- <CheckMenuItem- key={option.value}- label={t(option.labelKey)}- checked={taskInfoFields.includes(option.value)}- onToggle={() => toggleTaskInfoField(option.value)}- Icon={option.Icon}- />- ))}- </MenuSubRow>- </div>+ <MenuSubRow+ label={t('ccAgent.sidebar.displayHeading')}+ value={mainViewValue}+ Icon={MainViewIcon}+ >+ {MAIN_VIEW_OPTIONS.map((option) => (+ <SelectMenuItem+ key={option.value}+ label={t(option.labelKey)}+ selected={mainViewMode === option.value}+ onSelect={() => setMainViewMode(option.value)}+ Icon={option.Icon}+ />+ ))}+ </MenuSubRow>+ <MenuSubRow+ label={t('ccAgent.sidebar.taskInfoHeading')}+ value={taskInfoSummary}+ Icon={Info}+ valueNode={+ taskInfoFields.length > 0 ? (+ // 已选项用图标串表示,不再罗列短词。顺序 = 用户勾选顺序(遍历+ // taskInfoFields 而非选项表),与列表行的渲染顺序一致。+ <span className="flex items-center justify-end gap-1">+ {taskInfoFields.map((field) => {+ const Icon = TASK_INFO_OPTIONS.find(+ (option) => option.value === field,+ )?.Icon;+ return Icon ? (+ <Icon+ key={field}+ size={13}+ strokeWidth={1.8}+ className="shrink-0"+ aria-hidden+ />+ ) : null;+ })}+ </span>+ ) : undefined+ }+ valueEmphasized={!taskInfoIsDefault}+ >+ {TASK_INFO_OPTIONS.map((option) => (+ <CheckMenuItem+ key={option.value}+ label={t(option.labelKey)}+ checked={taskInfoFields.includes(option.value)}+ onToggle={() => toggleTaskInfoField(option.value)}+ Icon={option.Icon}+ />+ ))}+ </MenuSubRow>+ </div>+ )}+ </MountedMenuContent></DropdownMenuContent></DropdownMenu>);diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsxindex 76c2aec5e0..659e81782a 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsx@@ -89,6 +89,26 @@ beforeEach(() => {afterEach(cleanup);describe('sidebar display settings menu', () => {+ it('does not enumerate project menu rows while closed, and uses fresh props on open', async () => {+ const projects = [] as NonNullable<+ React.ComponentProps<typeof SidebarFilterPopover>['allKnownProjects']+ >;+ const enumerate = vi.spyOn(projects, 'map');+ const filter = makeFilter();+ const { rerender } = render(+ <SidebarFilterPopover filter={filter} allKnownProjects={projects} open={false} />,+ );+ rerender(+ <SidebarFilterPopover filter={{ ...filter }} allKnownProjects={projects} open={false} />,+ );+ expect(enumerate).not.toHaveBeenCalled();+ rerender(<SidebarFilterPopover filter={filter} allKnownProjects={projects} open />);+ expect(enumerate).toHaveBeenCalled();+ const submenu = await openSubmenu(/^任务排序/);+ fireEvent.click(within(submenu).getByRole('menuitem', { name: '创建时间' }));+ expect(filter.setSortBy).toHaveBeenCalledWith('created');+ });+it('presents seven summarized parent rows with icons, and three direct task sorting choices', async () => {const filter = makeFilter();render(<Preview filter={filter} />);diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.tsindex cd246c2c5c..761b0df8b5 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.ts+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.ts@@ -566,9 +566,11 @@ describe('父层 — 行级 handler 的引用稳定性', () => {resolve(__dirname, '..', 'AutomationSessionGroupItem.tsx'),'utf8',);- expect(sessionCard).toMatch(/export const SessionCard = memo\(/);+ const navigationAdapter = readFileSync(resolve(__dirname, '..', 'sidebarNavigation.tsx'), 'utf8');+ expect(navigationAdapter).toMatch(/const Row = memo\(Component\)/);+ expect(sessionCard).toMatch(/export const SessionCard = withSidebarNavigation</);expect(projectNode).toMatch(/export const ProjectNode = memo\(/);- expect(automationGroup).toMatch(/export const AutomationSessionGroupItem = memo\(/);+ expect(automationGroup).toMatch(/export const AutomationSessionGroupItem = withSidebarNavigation</);});it('runningSessionIds 必须 memo 化(否则每渲染 new Set 打穿整表)', () => {diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsxindex b8e47789ec..110abe783a 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx@@ -1,3 +1,4 @@+import { MountedMenuContent } from '../MountedMenuContent';/*** ProjectNode — 单个 Project 节点(Header + 受控折叠的子 sessions)* ---------------------------------------------------------------------------@@ -157,6 +158,119 @@ export const ProjectNode = memo(function ProjectNode({onBrowseFiles,onArchiveAll,}: ProjectNodeProps) {+ return (+ // 两个 data 属性各自服务不同消费者:+ // - data-project-working-dir : Sortable drop-target 识别 (历史: ProjectsSection 手写拖拽热区,+ // 现已被 SortableList 接管,但保留供深度链接/测试 hook)+ // - data-project-workingdir : CCAgentSidebarUpper 深度链接 scrollIntoView+ // 名字差一个连字符是历史遗留,保留两个比贸然统一更稳。+ <div+ data-project-working-dir={project.projectKey}+ data-project-workingdir={project.projectKey}+ className={cn('relative flex flex-col w-full select-none')}+ >+ <ProjectHeader+ project={project}+ statusFilter={statusFilter}+ isCollapsed={isCollapsed}+ collapsedAttentionTone={collapsedAttentionTone}+ hideRemoteMachineLabel={hideRemoteMachineLabel}+ onToggle={onToggle}+ isProjectPinned={isProjectPinned}+ onToggleProjectPin={onToggleProjectPin}+ onRenameProject={onRenameProject}+ onRemoveFromSidebar={onRemoveFromSidebar}+ onCreateInProject={onCreateInProject}+ onOpenConversationSearch={onOpenConversationSearch}+ onOpenInExplorer={onOpenInExplorer}+ onLinkCodexProject={onLinkCodexProject}+ linkingCodexProject={linkingCodexProject}+ onBrowseFiles={onBrowseFiles}+ onArchiveAll={onArchiveAll}+ />++ {/* Project Sessions(容器只负责 gap + 顶部 padding;左缩进由 SessionItem 自身承担)+ 展开/收起走 SectionCollapse 高度动画;「显示全部」在收起动画结束后复位。+ data-no-drag: 拦截 SortableList 默认 filter,阻止"鼠标落在子 session 上按下"+ 被父层 ProjectsSection SortableList 当成"拖动整个 ProjectNode"的起点。+ SessionItem 的 root 是 role="button" 而非 <button> 标签,默认 filter 拦不下来。 */}+ <SectionCollapse collapsed={isCollapsed} data-no-drag>+ {/* pb-1.5:展开块与下一个项目标题之间的间距(4px 树 gap + 6px = 10px),+ 大于会话行间距(gap-0.5),让项目块之间有分组呼吸(参考 Codex,2026-07 定稿)。 */}+ <div+ className={cn(+ 'flex flex-col gap-0.5 pt-0.5 pb-1.5 pr-0',+ sessionVariant === 'list' ? 'pl-3' : 'pl-0',+ )}+ >+ <SessionEntryList+ sessions={displaySessions ?? project.sessions}+ activeSessionId={activeSessionId}+ runningSessionIds={runningSessionIds}+ attachedSessionIds={attachedSessionIds}+ notifications={notifications}+ scheduleSessionIndex={scheduleSessionIndex}+ selectedSessionIds={selectedSessionIds}+ collapsible+ collapseLimit={getProjectSessionCollapseLimit()}+ disableCollapse={disableSessionCollapse}+ sectionCollapsed={isCollapsed || parentSectionCollapsed}+ onSessionClick={onSessionClick}+ onAction={onAction}+ onRename={onRename}+ onTogglePin={onTogglePin}+ onMoveSession={onMoveSession}+ projectOptions={projectOptions}+ onScheduleAction={onScheduleAction}+ indented+ sessionVariant={sessionVariant}+ />+ </div>+ </SectionCollapse>+ </div>+ );+});++type ProjectHeaderProps = Pick<+ ProjectNodeProps,+ | 'project'+ | 'statusFilter'+ | 'isCollapsed'+ | 'collapsedAttentionTone'+ | 'hideRemoteMachineLabel'+ | 'onToggle'+ | 'isProjectPinned'+ | 'onToggleProjectPin'+ | 'onRenameProject'+ | 'onRemoveFromSidebar'+ | 'onCreateInProject'+ | 'onOpenConversationSearch'+ | 'onOpenInExplorer'+ | 'onLinkCodexProject'+ | 'linkingCodexProject'+ | 'onBrowseFiles'+ | 'onArchiveAll'+>;++const ProjectHeader = memo(function ProjectHeader({+ project,+ statusFilter,+ isCollapsed,+ collapsedAttentionTone = null,+ hideRemoteMachineLabel = false,+ onToggle,+ isProjectPinned,+ onToggleProjectPin,+ onRenameProject,+ onRemoveFromSidebar,+ onCreateInProject,+ onOpenConversationSearch,+ onOpenInExplorer,+ onLinkCodexProject,+ linkingCodexProject,+ onBrowseFiles,+ onArchiveAll,+}: ProjectHeaderProps) {const { t } = useTranslation();// remote 项目复用本地专属入口(在文件管理器打开 / 复制深链 / 同步 Codex)会按本机// 路径误操作或丢失 host 身份,故这些入口对 remote 一律隐藏;host-aware 版本后续单独迭代。@@ -244,16 +358,7 @@ export const ProjectNode = memo(function ProjectNode({}, [onRemoveFromSidebar, project]);return (- // 两个 data 属性各自服务不同消费者:- // - data-project-working-dir : Sortable drop-target 识别 (历史: ProjectsSection 手写拖拽热区,- // 现已被 SortableList 接管,但保留供深度链接/测试 hook)- // - data-project-workingdir : CCAgentSidebarUpper 深度链接 scrollIntoView- // 名字差一个连字符是历史遗留,保留两个比贸然统一更稳。- <div- data-project-working-dir={project.projectKey}- data-project-workingdir={project.projectKey}- className={cn('relative flex flex-col w-full select-none')}- >+ <>{/* Project Headergroup 用于 hover 显示右侧 More / + New 图标按钮。data-project-workingdir 挂在外层 wrapper 上 — 深度链接 scrollIntoView@@ -477,29 +582,32 @@ export const ProjectNode = memo(function ProjectNode({// 统一菜单 surface(menuStyles):与 SessionItem / Dialogue / 自动化 等同款className={cn(MENU_CONTENT_CLASS, 'min-w-[160px] overflow-hidden')}>- <DropdownMenuItem- onClick={() => {- beginRename();- }}- className={MENU_ITEM_CLASS}- >- {t('ccAgent.sidebar.projectAction.rename')}- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => {- setMenuPos(null);- onToggleProjectPin(project, isProjectPinned);- }}- className={MENU_ITEM_CLASS}- >- {t(- isProjectPinned- ? 'ccAgent.sidebar.projectAction.unpin'- : 'ccAgent.sidebar.projectAction.pin',- )}- </DropdownMenuItem>- <DropdownMenuSeparator className="my-1 h-px bg-[var(--cmd-palette-border)]" />- {/* 菜单 items 顺序:浏览 → 工具 → 危险+ <MountedMenuContent>+ {() => (+ <>+ <DropdownMenuItem+ onClick={() => {+ beginRename();+ }}+ className={MENU_ITEM_CLASS}+ >+ {t('ccAgent.sidebar.projectAction.rename')}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => {+ setMenuPos(null);+ onToggleProjectPin(project, isProjectPinned);+ }}+ className={MENU_ITEM_CLASS}+ >+ {t(+ isProjectPinned+ ? 'ccAgent.sidebar.projectAction.unpin'+ : 'ccAgent.sidebar.projectAction.pin',+ )}+ </DropdownMenuItem>+ <DropdownMenuSeparator className="my-1 h-px bg-[var(--cmd-palette-border)]" />+ {/* 菜单 items 顺序:浏览 → 工具 → 危险[搜索, 查看文件, 在文件管理器中打开] - [复制深度链接, 同步 Codex] - [全部归档]与 SessionItem 风格保持一致:纯文字、无 icon。remote 项目隐藏「查看文件 / 在文件管理器中打开 / 复制深链 / 同步 Codex」四项:@@ -508,118 +616,82 @@ export const ProjectNode = memo(function ProjectNode({前一并屏蔽。remote 菜单收敛为 [搜索] - [全部归档]。注:handleBrowseFiles 的 remote 重定向 + WorkdirBrowseRoute 路由守卫保留,作为直达 /cc-agent/files/:id 的安全兜底。 */}- <DropdownMenuItem- onClick={() => {- setMenuPos(null);- onOpenConversationSearch(project);- }}- className={MENU_ITEM_CLASS}- >- {t('ccAgent.sidebar.projectAction.search')}- </DropdownMenuItem>- {!isRemote && (- <>- <DropdownMenuItem- onClick={() => {- setMenuPos(null);- onBrowseFiles(project);- }}- className={MENU_ITEM_CLASS}- >- {t('ccAgent.sidebar.projectAction.showFiles')}- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => {- setMenuPos(null);- onOpenInExplorer(project.workingDir);- }}- className={MENU_ITEM_CLASS}- >- {t('ccAgent.sidebar.projectAction.openInExplorer')}- </DropdownMenuItem>- <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />- <DropdownMenuItem- onClick={() => {- setMenuPos(null);- void handleCopyDeepLink();- }}- className={MENU_ITEM_CLASS}- >- {t('ccAgent.sidebar.projectAction.copyDeepLink')}- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => {- setMenuPos(null);- onLinkCodexProject(project);- }}- disabled={linkingCodexProject}- className={MENU_ITEM_CLASS}- >- {t('ccAgent.sidebar.projectAction.syncCodex')}- </DropdownMenuItem>- </>- )}- <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />- {project.scope === 'local' && (- <DropdownMenuItem onClick={handleRemoveFromSidebar} className={MENU_ITEM_CLASS}>- {t('ccAgent.sidebar.projectAction.removeFromSidebar')}- </DropdownMenuItem>- )}- <DropdownMenuItem- disabled={projectWritesBlocked}- onClick={() => {- handleArchiveAll();- }}- className={MENU_ITEM_CLASS}- >- {t(- bulkArchiveAction === 'unarchive'- ? 'ccAgent.sidebar.projectAction.unarchiveAll'- : 'ccAgent.sidebar.projectAction.archivedAll',+ <DropdownMenuItem+ onClick={() => {+ setMenuPos(null);+ onOpenConversationSearch(project);+ }}+ className={MENU_ITEM_CLASS}+ >+ {t('ccAgent.sidebar.projectAction.search')}+ </DropdownMenuItem>+ {!isRemote && (+ <>+ <DropdownMenuItem+ onClick={() => {+ setMenuPos(null);+ onBrowseFiles(project);+ }}+ className={MENU_ITEM_CLASS}+ >+ {t('ccAgent.sidebar.projectAction.showFiles')}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => {+ setMenuPos(null);+ onOpenInExplorer(project.workingDir);+ }}+ className={MENU_ITEM_CLASS}+ >+ {t('ccAgent.sidebar.projectAction.openInExplorer')}+ </DropdownMenuItem>+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />+ <DropdownMenuItem+ onClick={() => {+ setMenuPos(null);+ void handleCopyDeepLink();+ }}+ className={MENU_ITEM_CLASS}+ >+ {t('ccAgent.sidebar.projectAction.copyDeepLink')}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => {+ setMenuPos(null);+ onLinkCodexProject(project);+ }}+ disabled={linkingCodexProject}+ className={MENU_ITEM_CLASS}+ >+ {t('ccAgent.sidebar.projectAction.syncCodex')}+ </DropdownMenuItem>+ </>+ )}+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />+ {project.scope === 'local' && (+ <DropdownMenuItem onClick={handleRemoveFromSidebar} className={MENU_ITEM_CLASS}>+ {t('ccAgent.sidebar.projectAction.removeFromSidebar')}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ disabled={projectWritesBlocked}+ onClick={() => {+ handleArchiveAll();+ }}+ className={MENU_ITEM_CLASS}+ >+ {t(+ bulkArchiveAction === 'unarchive'+ ? 'ccAgent.sidebar.projectAction.unarchiveAll'+ : 'ccAgent.sidebar.projectAction.archivedAll',+ )}+ </DropdownMenuItem>+ </>)}- </DropdownMenuItem>+ </MountedMenuContent></DropdownMenuContent></DropdownMenu>-- {/* Project Sessions(容器只负责 gap + 顶部 padding;左缩进由 SessionItem 自身承担)- 展开/收起走 SectionCollapse 高度动画;「显示全部」在收起动画结束后复位。- data-no-drag: 拦截 SortableList 默认 filter,阻止"鼠标落在子 session 上按下"- 被父层 ProjectsSection SortableList 当成"拖动整个 ProjectNode"的起点。- SessionItem 的 root 是 role="button" 而非 <button> 标签,默认 filter 拦不下来。 */}- <SectionCollapse collapsed={isCollapsed} data-no-drag>- {/* pb-1.5:展开块与下一个项目标题之间的间距(4px 树 gap + 6px = 10px),- 大于会话行间距(gap-0.5),让项目块之间有分组呼吸(参考 Codex,2026-07 定稿)。 */}- <div- className={cn(- 'flex flex-col gap-0.5 pt-0.5 pb-1.5 pr-0',- sessionVariant === 'list' ? 'pl-3' : 'pl-0',- )}- >- <SessionEntryList- sessions={displaySessions ?? project.sessions}- activeSessionId={activeSessionId}- runningSessionIds={runningSessionIds}- attachedSessionIds={attachedSessionIds}- notifications={notifications}- scheduleSessionIndex={scheduleSessionIndex}- selectedSessionIds={selectedSessionIds}- collapsible- collapseLimit={getProjectSessionCollapseLimit()}- disableCollapse={disableSessionCollapse}- sectionCollapsed={isCollapsed || parentSectionCollapsed}- onSessionClick={onSessionClick}- onAction={onAction}- onRename={onRename}- onTogglePin={onTogglePin}- onMoveSession={onMoveSession}- projectOptions={projectOptions}- onScheduleAction={onScheduleAction}- indented- sessionVariant={sessionVariant}- />- </div>- </SectionCollapse>- </div>+ </>);});diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsxindex 6a2775b594..51200982e4 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx@@ -33,7 +33,7 @@ import {MonitorSmartphone,SquarePen,} from 'lucide-react';-import { useTranslation } from 'react-i18next';+import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';import { cn } from '@/lib/utils';import { Tip } from '@/components/ui/tooltip';@@ -50,6 +50,7 @@ import {useRemoteHostProjectOrders,} from '../../hooks/useRemoteHostProjectOrders';import { SortableList } from '@/components/sidebar/SortableList';+import { useMainListEntries } from '../../hooks/useMainListEntries';import { useReducedMotion } from '@/hooks/useReducedMotion';import { useSidebarMainViewMode } from '@/hooks/useSidebarCardMode';import { ProjectNode } from './ProjectNode';@@ -68,7 +69,6 @@ import {DIALOGUE_GROUP_ALL_KEY,} from '../../hooks/helpers/sidebarFilterCore';import {- buildMainListEntries,getMainListEntrySessions,holdViewedPriorityRank,splitEntriesByDevice,@@ -247,11 +247,13 @@ export interface ProjectsSectionProps {isCreateDialogueDisabled?: boolean;}+const EMPTY_BOTS: BotGroupNode[] = [];+export function ProjectsSection({unclassified,projects,dialogues,- bots = [],+ bots = EMPTY_BOTS,onOpenBot,allKnownProjects,dialogueCount = 0,@@ -305,22 +307,36 @@ export function ProjectsSection({const mainSessionVariant: 'text' | 'list' = mainViewMode === 'list' ? 'list' : 'text';// SortableList 只在自定义项目顺序且按项目分组时挂载。// 折叠溢出且未点「显示全部」时禁用,避免只重排可见前缀。- const projectOrderScope = projectOrderWriteScopeForSelection(selectedMachineForOrder);+ const projectOrderScope = useMemo(+ () => projectOrderWriteScopeForSelection(selectedMachineForOrder),+ [selectedMachineForOrder],+ );const hostSnapshotForDisplay =projectOrderScope.kind === 'host' && projectOrderScope.deviceId === null? localHostProjectOrder.snapshot: projectOrderScope.kind === 'host' && projectOrderScope.deviceId? remoteHostProjectOrders.orders.get(projectOrderScope.deviceId): undefined;- const displayedProjectOrder = resolveDisplayedProjectOrder(- projectOrderScope,- hostSnapshotForDisplay,- filter,- projectOrderScope.kind === 'host' && projectOrderScope.deviceId === null- ? localHostProjectOrder.snapshot.manualProjectOrder- : projectOrderScope.kind === 'host' && projectOrderScope.deviceId- ? (controllerManualOrderForDevice(projectOrderScope.deviceId, hostSnapshotForDisplay) ?? [])- : [],+ const displayedProjectOrder = useMemo(+ () =>+ resolveDisplayedProjectOrder(+ projectOrderScope,+ hostSnapshotForDisplay,+ { projectOrder: filter.projectOrder, manualProjectOrder: filter.manualProjectOrder },+ projectOrderScope.kind === 'host' && projectOrderScope.deviceId === null+ ? localHostProjectOrder.snapshot.manualProjectOrder+ : projectOrderScope.kind === 'host' && projectOrderScope.deviceId+ ? (controllerManualOrderForDevice(projectOrderScope.deviceId, hostSnapshotForDisplay) ??+ [])+ : [],+ ),+ [+ projectOrderScope,+ hostSnapshotForDisplay,+ filter.projectOrder,+ filter.manualProjectOrder,+ localHostProjectOrder.snapshot.manualProjectOrder,+ ],);const customProjectOrder =filter.groupBy === 'project' && displayedProjectOrder.projectOrder === 'custom';@@ -489,6 +505,8 @@ export function ProjectsSection({[naturalPriorityContext, hold],);+ const sortingPriorityContext = filter.sortBy === 'priority' ? priorityContext : undefined;+// starting 只让位给真实 in-flight:本地 isRunning(见 useStartingSessionIds),// 远程 running / needs-interaction。终态 attention 不再吸收 —— 旧终态会误伤// 新发送,新终态又要代次才能和旧的区分,两边补丁会来回打。没经过 running@@ -530,38 +548,20 @@ export function ProjectsSection({// 混排模型(D 期):项目行 / 散排对话 / 对话组统一为顶层条目并按同一口径排序。// 这有意推翻旧「Dialogue 固定段在 Projects 之后」的裁决(mainListModel.ts 文件头)。// 设备分组开启时,未分类草稿并进混排再按设备切段;单段路径仍走顶部独立段。- const mixedEntries = useMemo(- () =>- buildMainListEntries({- projects,- dialogues,- bots,- unclassified: deviceGroupingActive && !unclassifiedHidden ? unclassified : [],- groupBy: filter.groupBy,- groupDialogue: filter.groupDialogue,- sortBy: filter.sortBy,- projectOrder: displayedProjectOrder.projectOrder,- manualProjectOrder: displayedProjectOrder.manualProjectOrder,- priorityContext,- notifications,- scheduleSessionIndex,- }),- [- projects,- dialogues,- bots,- unclassified,- unclassifiedHidden,- deviceGroupingActive,- filter.groupBy,- filter.groupDialogue,- filter.sortBy,- displayedProjectOrder,- priorityContext,- notifications,- scheduleSessionIndex,- ],- );+ const mixedEntries = useMainListEntries({+ projects,+ dialogues,+ bots,+ unclassified: deviceGroupingActive && !unclassifiedHidden ? unclassified : undefined,+ groupBy: filter.groupBy,+ groupDialogue: filter.groupDialogue,+ sortBy: filter.sortBy,+ projectOrder: displayedProjectOrder.projectOrder,+ manualProjectOrder: displayedProjectOrder.manualProjectOrder,+ priorityContext,+ notifications,+ scheduleSessionIndex,+ });// 顶层条目折叠:最多显示 N 条,超出收起 + 「显示全部 N 项」。与会话同一套// 规则(getSessionListCollapseView):始终保留"有需关注会话"的条目、以及包含当前会话的@@ -638,7 +638,7 @@ export function ProjectsSection({sortBy: filter.sortBy,projectOrder: filter.projectOrder,manualProjectOrder: filter.manualProjectOrder,- priorityContext,+ priorityContext: sortingPriorityContext,});}, [deviceGroupingActive,@@ -648,7 +648,7 @@ export function ProjectsSection({filter.sortBy,filter.projectOrder,filter.manualProjectOrder,- priorityContext,+ sortingPriorityContext,]);// 设备段折叠(E 期):本机段 key 'local'。const [collapsedDevices, setCollapsedDevices] = useState<ReadonlySet<string>>(new Set());diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarNavigation.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarNavigation.tsxnew file mode 100644index 0000000000..6c27da653b--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarNavigation.tsx@@ -0,0 +1,36 @@+import { memo, useCallback, useLayoutEffect, useRef, type ComponentType } from 'react';+import {+ useNavigate,+ type NavigateFunction,+ type NavigateOptions,+ type To,+} from 'react-router-dom';++export interface SidebarNavigationProps {+ navigate: NavigateFunction;+}++/** Keep event handlers stable while retaining the latest router-relative semantics. */+export function useSidebarNavigate(): NavigateFunction {+ const navigate = useNavigate();+ const latest = useRef(navigate);+ useLayoutEffect(() => {+ latest.current = navigate;+ }, [navigate]);+ return useCallback((to: To | number, options?: NavigateOptions) => {+ if (typeof to === 'number') return latest.current(to);+ if (options === undefined) return latest.current(to);+ return latest.current(to, options);+ }, []);+}++/** Only this small adapter subscribes to route changes, not the row's UI tree. */+export function withSidebarNavigation<P extends object>(+ Component: ComponentType<P & SidebarNavigationProps>,+) {+ const Row = memo(Component);+ return memo(function SidebarNavigationRow(props: P) {+ const navigate = useSidebarNavigate();+ return <Row {...props} navigate={navigate} />;+ });+}diff --git a/apps/desktop/src/renderer/hooks/useStableTranslation.ts b/apps/desktop/src/renderer/hooks/useStableTranslation.tsnew file mode 100644index 0000000000..5e4d2e65d8--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useStableTranslation.ts@@ -0,0 +1,9 @@+import { useTranslation } from 'react-i18next';++// react-i18next includes options in its subscription dependencies. Its default+// empty object is new on every render; share it without changing language events.+const DEFAULT_OPTIONS = {};++export function useStableTranslation() {+ return useTranslation(undefined, DEFAULT_OPTIONS);+}diff --git a/apps/desktop/src/renderer/lib/agent-actions/workActivityProjection.ts b/apps/desktop/src/renderer/lib/agent-actions/workActivityProjection.tsindex 145b084ad0..3d5bb83816 100644--- a/apps/desktop/src/renderer/lib/agent-actions/workActivityProjection.ts+++ b/apps/desktop/src/renderer/lib/agent-actions/workActivityProjection.ts@@ -12,12 +12,15 @@ import {} from '@cindy/maker-shared/work-activity-projection';import type { ChatMessage } from '@/lib/makerChatStore';+import { createMessageProjectionCache } from '@/components/chat/messageProjectionCache';export type { ExplorationActivity, ExplorationActivityKind, ProjectedThinkingActivity };export type ProjectedToolActivity = SharedProjectedToolActivity<ChatMessage>;export type ProjectedWorkActivity = SharedProjectedWorkActivity<ChatMessage>;export type WorkActivityProjection = SharedWorkActivityProjection<ChatMessage>;+const projectSnapshot = createMessageProjectionCache<ChatMessage, WorkActivityProjection>();+export function projectRecentWorkActivities(childItems: readonly ProjectableWorkChild<ChatMessage>[],isStreaming: boolean,@@ -30,5 +33,28 @@ export function projectWorkActivities(childItems: readonly ProjectableWorkChild<ChatMessage>[],isStreaming: boolean,): WorkActivityProjection {- return projectSharedWorkActivities(childItems, isStreaming);+ // Group wrappers and result Maps are reconstructed on mount. Their immutable+ // source messages and the exact values consumed by the projector are stable.+ // Never retain rendered-child closures in the cross-mount cache.+ const dependencies: unknown[] = [isStreaming];+ let first: ChatMessage | undefined;+ for (const child of childItems) {+ dependencies.push(child.kind, child.key);+ if (child.kind === 'tools') {+ for (const message of child.toolCalls ?? []) {+ first ??= message;+ dependencies.push(+ message,+ child.resultMap?.has(message.clientId),+ child.resultMap?.get(message.clientId),+ child.settledIds?.has(message.clientId),+ );+ }+ } else if (child.kind === 'thinking' && child.message) {+ first ??= child.message;+ dependencies.push(child.message);+ }+ }+ const compute = () => projectSharedWorkActivities(childItems, isStreaming);+ return first ? projectSnapshot(first, dependencies, compute) : compute();}diff --git a/apps/desktop/src/renderer/lib/generatedFiles.ts b/apps/desktop/src/renderer/lib/generatedFiles.tsindex 21c932c924..0f06d7877b 100644--- a/apps/desktop/src/renderer/lib/generatedFiles.ts+++ b/apps/desktop/src/renderer/lib/generatedFiles.ts@@ -293,11 +293,6 @@ function canonicalizeWindowsShape(abs: string): string {return /^[a-zA-Z]:[\\/]/.test(abs) ? abs.replace(/\//g, '\\').replace(/\\{2,}/g, '\\') : abs;}-/** 单条 tool_use 消息 → 它新建的文件原始路径列表(可能为空)。判定在共享包里。 */-function createdPathsFromToolUse(toolName: string, input: unknown): string[] {- return createdPathsFromDescriptor(describeToolUse(toolName, input));-}-/*** 一组消息(通常是一个 turn 的切片,但对任意切片都成立)→ 新建文件的有序去重@@ -310,6 +305,17 @@ export function collectGeneratedFiles(messages: readonly ToolUseLike[],workingDir: string,): GeneratedFileRef[] {+ // The edit/create/command/source passes inspect the same tools. Parse each+ // descriptor once even on a cold history mount (command parsing is expensive).+ const descriptors = new Map<ToolUseLike, ReturnType<typeof describeToolUse>>();+ const descriptorFor = (message: ToolUseLike) => {+ let descriptor = descriptors.get(message);+ if (!descriptor) {+ descriptor = describeToolUse(message.toolName ?? '', message.toolInput);+ descriptors.set(message, descriptor);+ }+ return descriptor;+ };const resultByToolUseId = new Map<string, string>();for (const message of messages) {if (@@ -330,7 +336,7 @@ export function collectGeneratedFiles(const resultContent = msg.toolUseId ? resultByToolUseId.get(msg.toolUseId) : undefined;if (msg.toolUseId && resultContent === undefined) continue;if (isExplicitFailedToolResult(resultContent)) continue;- const d = describeToolUse(msg.toolName, msg.toolInput);+ const d = descriptorFor(msg);if (d.kind === 'file' && d.action === 'edit' && d.filePath) {editedKeys.add(dedupeKeyForPath(resolveToolFilePath(d.filePath, workingDir)));} else if (d.kind === 'fileChange') {@@ -370,7 +376,7 @@ export function collectGeneratedFiles(});};- for (const rawPath of createdPathsFromToolUse(toolName, msg.toolInput)) {+ for (const rawPath of createdPathsFromDescriptor(descriptorFor(msg))) {addPath(rawPath, 'tool');}const artifact = extractDocumentArtifactMetadata(toolName, msg.toolInput, resultContent);@@ -405,7 +411,7 @@ export function collectGeneratedFiles(}}}- const descriptor = describeToolUse(toolName, msg.toolInput);+ const descriptor = descriptorFor(msg);if (descriptor.kind === 'command' && descriptor.command) {for (const rawPath of extractCommandOutputPathCandidates(descriptor.command)) {addPath(rawPath, 'command');@@ -426,7 +432,7 @@ export function collectGeneratedFiles(// 求交集而不是猜字段名,所以只有真产出过的文件才可能被摘。for (const msg of messages) {if (msg.role !== 'tool_use' || !msg.toolName) continue;- const d = describeToolUse(msg.toolName, msg.toolInput);+ const d = descriptorFor(msg);for (const raw of sourcePathCandidatesFromDescriptor(d)) {byKey.delete(dedupeKeyForPath(canonicalizeWindowsShape(resolveToolFilePath(raw, workingDir))));}diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 5c2d86f7a6..ddd3dabf00 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -143,6 +143,7 @@ import { clearSessionStarting, markSessionStarting } from '@/lib/sessionStartingimport { createLogger } from '@/lib/logger';import {markSessionAutomaticHistoryLoadCompleted,+ readSessionScroll,resetSessionAutomaticHistoryLoadCompletion,} from '@/lib/sessionScrollStore';import {@@ -3789,7 +3790,42 @@ function retainedWindowKeepsGapCursor(return cursorIndex > 0;}-function _trimMessagesIfNeeded(sessionId: string): void {+// A just-closed reading window is still a warm navigation target. Trimming it+// to the tail forces an around-message IPC/backfill before restoring the reader.+// Reuse existing session storage, with bounded reservations derived from current+// state so clear/purge/epoch changes cannot resurrect a separate stale copy.+const WARM_READING_WINDOWS = 2;+const WARM_READING_MAX_MESSAGES = 1000;+const WARM_READING_MAX_CHARACTERS = 32 * 1024 * 1024;++function _trimMessagesIfNeeded(): void {+ const retained = new Set<string>();+ let characters = 0;+ const now = Date.now();+ // Reverse before sorting so equal timestamps also prefer the latest leave.+ const recent = [..._lastViewedAt.entries()].reverse().sort((a, b) => b[1] - a[1]);+ for (const [id, lastViewed] of recent) {+ if (retained.size >= WARM_READING_WINDOWS) break;+ const state = sessions.get(id);+ const scroll = readSessionScroll(id);+ if (!state?.historyLoaded || _activeViewSessions.has(id) || _isSessionBusy(id, state) ||+ now - lastViewed >= DEMOTE_IDLE_MS || scroll?.isNearBottom !== false ||+ state.messages.length <= TRIM_THRESHOLD || state.messages.length > WARM_READING_MAX_MESSAGES) continue;+ const anchor = scroll.messageClientId ?? scroll.restoreClientId;+ if (!anchor || !state.messages.some((message) => message.clientId === anchor)) continue;+ const size = state.messages.reduce((sum, message) => sum + message.content.length, 0);+ if (characters + size > WARM_READING_MAX_CHARACTERS) continue;+ characters += size;+ retained.add(id);+ }+ // Admission or a background update can displace another window. Apply the+ // original guarded/epoch-aware trim to it immediately, not on its next visit.+ for (const id of sessions.keys()) {+ if (!retained.has(id)) _trimSessionMessages(id);+ }+}++function _trimSessionMessages(sessionId: string): void {const state = sessions.get(sessionId);if (!state || state.messages.length <= TRIM_THRESHOLD) return;if (_isSessionBusy(sessionId, state)) return;@@ -4049,7 +4085,7 @@ function leaveView(sessionId: string): void {: {}),}));}- _trimMessagesIfNeeded(sessionId);+ _trimMessagesIfNeeded();}function _demoteIdleSessions(): void {@@ -7855,7 +7891,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {: s,);// MEM-OPT-1: trim non-active sessions after turn completes- queueMicrotask(() => _trimMessagesIfNeeded(sessionId));+ queueMicrotask(_trimMessagesIfNeeded);}// 视觉桥用户提示事件(source==='vision-bridge' + reason 枚举 + isTerminal:false):// 已在 dispatchStreamEventPayload 的 case 'error' 分流为 toast,不进 error-banner /@@ -16772,7 +16808,9 @@ function collapseConsecutiveAutoResumeRows(messages: ChatMessage[]): ChatMessage}continue;}- if (isSubstantiveChatRow(message)) sawCardSinceContent = false;+ // Without a later resume card there is no boundary to resolve. In particular,+ // refreshing input projection for cached history must not rescan old tool text.+ if (sawCardSinceContent && isSubstantiveChatRow(message)) sawCardSinceContent = false;}return changed && out ? out : messages;}diff --git a/apps/desktop/src/renderer/lib/sessionScrollStore.ts b/apps/desktop/src/renderer/lib/sessionScrollStore.tsindex f349c1c815..684ef7e499 100644--- a/apps/desktop/src/renderer/lib/sessionScrollStore.ts+++ b/apps/desktop/src/renderer/lib/sessionScrollStore.ts@@ -21,10 +21,12 @@ export interface SessionScrollSnapshot {windowAnchorKey: string | null;/** 离开时视口顶端那条 render-item 的 stable key。 */viewportTopKey: string;- /** viewportTopKey 这条 item 的顶端被滚到视口上方的像素数(>=0)。 */+ /** 条目顶端相对视口的偏移;负值保留视口顶部到条目之间的间距。 */offset: number;/** Visible message inside a work group; optional for older snapshots. */messageClientId?: string;+ /** Source message used to reload an evicted reading position. */+ restoreClientId?: string;messageOffset?: number;/** Intrinsic estimates for the last mounted window, valid at this content width. */itemHeights?: { width: number; byKey: Record<string, number> };diff --git a/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts b/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.tsindex 203de9e322..f766748a34 100644--- a/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts+++ b/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts@@ -728,6 +728,7 @@ class KeepAliveMicSession {activation?.onInterrupted?.('Microphone input stopped unexpectedly. Please try again.');}this.trackCleanup.splice(0).forEach((cleanup) => cleanup());+ this.worklet?.port.postMessage({ type: 'dispose' });this.worklet?.port.close();this.worklet?.disconnect();this.sink?.disconnect();@@ -1334,6 +1335,7 @@ export class WebMicAudioEngine {if (this.context) this.context.onstatechange = null;if (this.processor) this.processor.onaudioprocess = null;this.flushPendingFrame(Date.now());+ this.worklet?.port.postMessage({ type: 'dispose' });this.worklet?.port.close();this.worklet?.disconnect();this.processor?.disconnect();diff --git a/apps/desktop/src/renderer/voice-input/__tests__/WebMicAudioEngine.keepAliveIdle.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/WebMicAudioEngine.keepAliveIdle.test.tsindex 3f25b72867..469b9d2a3c 100644--- a/apps/desktop/src/renderer/voice-input/__tests__/WebMicAudioEngine.keepAliveIdle.test.ts+++ b/apps/desktop/src/renderer/voice-input/__tests__/WebMicAudioEngine.keepAliveIdle.test.ts@@ -115,6 +115,47 @@ describe('keep-alive microphone idle window', () => {expect(track.stopped).toBe(true);});+ it('terminates a direct processor before closing its port on stop', async () => {+ const engine = new mod.WebMicAudioEngine({ workletUrl: WORKLET_URL, keepAlive: false });+ await engine.start();+ const worklet = vi.mocked(AudioWorkletNode).mock.results[0].value as AudioWorkletNode;+ await engine.stop();+ await engine.stop();++ const messages = vi.mocked(worklet.port.postMessage).mock;+ const disposalIndex = messages.calls.findIndex(([message]) => message.type === 'dispose');+ expect(messages.calls.filter(([message]) => message.type === 'dispose')).toHaveLength(1);+ expect(messages.invocationCallOrder[disposalIndex]).toBeLessThan(+ vi.mocked(worklet.port.close).mock.invocationCallOrder[0],+ );+ expect(track.stopped).toBe(true);+ });++ it('reuses a paused keep-alive processor and only terminates it at final disposal', async () => {+ const first = new mod.WebMicAudioEngine({ workletUrl: WORKLET_URL, keepAlive: true });+ await first.start();+ const worklet = vi.mocked(AudioWorkletNode).mock.results[0].value as AudioWorkletNode;+ await first.stop();+ expect(worklet.port.postMessage).not.toHaveBeenCalledWith({ type: 'dispose' });++ const second = new mod.WebMicAudioEngine({ workletUrl: WORKLET_URL, keepAlive: true });+ await second.start();+ expect(AudioWorkletNode).toHaveBeenCalledTimes(1);+ expect(worklet.port.postMessage).toHaveBeenLastCalledWith({+ type: 'setActive', active: true, reset: true,+ });+ await second.stop();+ await mod.disposeKeepAliveVoiceInputMicrophone('test_final_dispose');++ const messages = vi.mocked(worklet.port.postMessage).mock;+ const disposalIndex = messages.calls.findIndex(([message]) => message.type === 'dispose');+ expect(disposalIndex).toBeGreaterThanOrEqual(0);+ expect(messages.invocationCallOrder[disposalIndex]).toBeLessThan(+ vi.mocked(worklet.port.close).mock.invocationCallOrder[0],+ );+ expect(track.stopped).toBe(true);+ });+it('does not extend the idle window when prewarm re-asserts keep-alive intent', async () => {await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });diff --git a/apps/desktop/src/renderer/voice-input/__tests__/pcm16kWorklet.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/pcm16kWorklet.test.tsindex 2066c3b124..0b39169652 100644--- a/apps/desktop/src/renderer/voice-input/__tests__/pcm16kWorklet.test.ts+++ b/apps/desktop/src/renderer/voice-input/__tests__/pcm16kWorklet.test.ts@@ -87,4 +87,52 @@ describe('PCM16k worklet', () => {expect(processor.carry).toBe(0);});++ it('permanently stops processing after disposal, including without inputs', () => {+ const Processor = loadProcessor();+ const processor = new Processor();+ const resample = vi.spyOn(processor, 'resample');++ processor.port.onmessage?.({ data: { type: 'dispose' } });+ processor.port.onmessage?.({ data: { type: 'dispose' } });+ processor.port.onmessage?.({ data: { type: 'setActive', active: true, reset: true } });+ processor.port.onmessage?.({ data: { type: 'config', chunkMs: 10 } });++ expect(processor.process([])).toBe(false);+ expect(processor.process([[new Float32Array(480).fill(0.5)]])).toBe(false);+ expect(resample).not.toHaveBeenCalled();+ expect(processor.port.postMessage).not.toHaveBeenCalled();+ });++ it('keeps temporary deactivation resumable', () => {+ const Processor = loadProcessor();+ const processor = new Processor();+ processor.port.onmessage?.({ data: { type: 'config', chunkMs: 10 } });+ processor.port.onmessage?.({ data: { type: 'setActive', active: false, reset: true } });+ expect(processor.process([])).toBe(true);+ expect(processor.process([[new Float32Array(480)]])).toBe(true);+ expect(processor.port.postMessage).not.toHaveBeenCalled();++ processor.port.onmessage?.({ data: { type: 'setActive', active: true, reset: true } });+ expect(processor.process([[new Float32Array(480).fill(0.5)]])).toBe(true);+ expect(processor.port.postMessage).toHaveBeenCalledTimes(1);+ expect(processor.port.postMessage.mock.calls[0][0]).toMatchObject({ type: 'pcm16k' });+ });++ it('allows draining before disposal and drops buffered audio after disposal', () => {+ const Processor = loadProcessor();+ const processor = new Processor();+ processor.process([[new Float32Array(128).fill(0.5)]]);+ expect(processor.port.postMessage).not.toHaveBeenCalled();+ processor.port.onmessage?.({ data: { type: 'flush', flushId: 'last-frame' } });+ expect(processor.port.postMessage.mock.calls.map(([message]) => message.type))+ .toEqual(['pcm16k', 'flushed']);++ processor.process([[new Float32Array(128).fill(0.5)]]);+ processor.port.postMessage.mockClear();+ processor.port.onmessage?.({ data: { type: 'dispose' } });+ processor.port.onmessage?.({ data: { type: 'flush', flushId: 'too-late' } });+ expect(processor.process([])).toBe(false);+ expect(processor.port.postMessage).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/renderer/voice-input/pcm16k-worklet.js b/apps/desktop/src/renderer/voice-input/pcm16k-worklet.jsindex 99c4ac9a0f..d2e8882622 100644--- a/apps/desktop/src/renderer/voice-input/pcm16k-worklet.js+++ b/apps/desktop/src/renderer/voice-input/pcm16k-worklet.js@@ -11,8 +11,16 @@ class PCM16kWorklet extends AudioWorkletProcessor {this.previousSample = 0;this.chunkIndex = 0;this.active = true;+ this.disposed = false;this.port.onmessage = (event) => {+ if (this.disposed) return;+ if (event.data?.type === 'dispose') {+ this.disposed = true;+ this.active = false;+ this.pending = [];+ return;+ }if (event.data?.type === 'config') {this.targetSampleRate = event.data.targetSampleRate || 16000;this.chunkSamples = Math.max(@@ -43,6 +51,10 @@ class PCM16kWorklet extends AudioWorkletProcessor {}process(inputs) {+ // Disconnecting the node does not stop a processor that keeps returning+ // true. The shared context outlives recordings, so permanent disposal must+ // explicitly release the processor's active-source lifetime.+ if (this.disposed) return false;const input = inputs[0]?.[0];if (!input || input.length === 0) return true;if (!this.active) return true;diff --git a/apps/desktop/src/shared/__tests__/visibleText.test.ts b/apps/desktop/src/shared/__tests__/visibleText.test.tsindex 12b079d887..fb1521cc99 100644Binary files a/apps/desktop/src/shared/__tests__/visibleText.test.ts and b/apps/desktop/src/shared/__tests__/visibleText.test.ts differdiff --git a/apps/desktop/src/shared/visibleText.ts b/apps/desktop/src/shared/visibleText.tsindex 5079134bb3..89bb1f80b3 100644--- a/apps/desktop/src/shared/visibleText.ts+++ b/apps/desktop/src/shared/visibleText.ts@@ -18,11 +18,11 @@* 合法字形也算成不可见反而会把真实产出误判成空。*/-/** 所有不可见字符:空白 + Unicode 格式字符 + 控制字符。 */-const INVISIBLE_PATTERN = /[\s\p{Cf}\p{Cc}]/gu;+/** 找到首个可见字符即可,不为布尔判断扫描并复制整段工具输出。不能加 g。 */+const VISIBLE_PATTERN = /[^\s\p{Cf}\p{Cc}]/u;/** 这段文本去掉不可见字符后还有内容吗(非字符串一律 false)。 */export function hasUserVisibleText(text: unknown): boolean {if (typeof text !== 'string' || text.length === 0) return false;- return text.replace(INVISIBLE_PATTERN, '').length > 0;+ return VISIBLE_PATTERN.test(text);}diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex 43e300e04e..90e42d7575 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -18,12 +18,12 @@| `desktop.auth.add-account` | desktop | 添加账号 | hash `/add-account`(ProtectedRoute → AddAccountLoginPage) | AddAccountLoginPage | apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx, apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 21 || `desktop.auth.legacy-migration` | desktop | 首登数据迁移弹窗 | App 顶层挂载 LegacyMigrationDialog(仅主窗;main 检测到旧版 userData 经 `legacy-migration:state` 驱动) | LegacyMigrationDialog | apps/desktop/src/renderer/components/auth/LegacyMigrationDialog.tsx | 8 | 0 | 2 || `desktop.auth.login` | desktop | 登录页 | hash `/login`(GuestRoute → LoginPage) | LoginBrandStage, LoginCaptchaOverlay, LoginControls, LoginPage | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 21 |-| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/BotsSidebar.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 293 | 43 | 489 |+| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/BotsSidebar.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 293 | 43 | 489 || `desktop.chat.files` | desktop | 工作目录文件浏览 | hash `/cc-agent/files/:sessionId`(WorkdirBrowseRoute) | FileBodyView, FileTreeView, WorkdirBrowseRoute | apps/desktop/src/renderer/features/cc-agent/workdir-browse/DocSearchBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/DrawioPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileFilterInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FilterResultList.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/ImagePreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/UnrenderablePlaceholder.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailCollapsed.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailResize.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useConfirmSwitchAwayIfDirty.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useDelayedFlag.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useOpenTabs.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useProjectFileList.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useRevealFileInTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/activeFileBodyHandle.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/docModeSwitchProjects.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/drawioExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/expandedStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileContentCache.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileIcon.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileMeta.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileScrollStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileSelectionParams.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/filterFiles.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/markdownAutosave.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/openTabsStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/pdfExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/selectedFileStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchPanel.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchResults.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/hooks/useProjectSearch.ts | 22 | 7 | 64 || `desktop.chat.new-draft` | desktop | 新建任务草稿页 | hash `/cc-agent/new`(NewMakerDraftRoute) | NewMakerDraftRoute | apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx | 15 | 0 | 2 |-| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 273 | 43 | 395 |+| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 273 | 43 | 395 || `desktop.chat.scheduled` | desktop | 调度任务列表 | hash `/cc-agent/scheduled`(SchedulerPage) | SchedulerPage | apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx, apps/desktop/src/renderer/features/scheduler/components/AgentMark.tsx, apps/desktop/src/renderer/features/scheduler/components/BoundSessionCard.tsx, apps/desktop/src/renderer/features/scheduler/components/ProjectAutomationNotifyBridge.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryPane.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleSessionIndexOwner.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleStatusChip.tsx, apps/desktop/src/renderer/features/scheduler/components/ScriptCapabilityMultiSelect.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListFilterPopover.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateCard.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateGallery.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateParamForm.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useDeleteScheduleWithSessions.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useReadFailedScheduleRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRunNowBusyGuard.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSchedules.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSessionReferences.ts, apps/desktop/src/renderer/features/scheduler/hooks/useTemplates.ts, apps/desktop/src/renderer/features/scheduler/index.ts, apps/desktop/src/renderer/features/scheduler/lib/cronCodexPreset.ts, apps/desktop/src/renderer/features/scheduler/lib/cronToHuman.ts, apps/desktop/src/renderer/features/scheduler/lib/failedScheduleDismissal.ts, apps/desktop/src/renderer/features/scheduler/lib/formatters.ts, apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts, apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts, apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts, apps/desktop/src/renderer/features/scheduler/lib/runHistoryGrouping.ts, apps/desktop/src/renderer/features/scheduler/lib/runUnread.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleRunReadSync.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSessionBinding.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts, apps/desktop/src/renderer/features/scheduler/lib/schedulesStore.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilter.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilterStorage.ts, apps/desktop/src/renderer/features/scheduler/lib/templateLocalization.ts, apps/desktop/src/renderer/features/scheduler/lib/usageLimitScheduleCreateIntent.ts | 44 | 0 | 118 |-| `desktop.chat.session` | desktop | 会话工作台 | hash `/cc-agent/:sessionId`;副窗经 `/cc-agent/boot` 解析后落到同一会话视图 | AssistantMessage, CCAgentFeatureLayout, CCAgentSessionView, ChatInput, PermissionPrompt | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 273 | 43 | 394 |+| `desktop.chat.session` | desktop | 会话工作台 | hash `/cc-agent/:sessionId`;副窗经 `/cc-agent/boot` 解析后落到同一会话视图 | AssistantMessage, CCAgentFeatureLayout, CCAgentSessionView, ChatInput, PermissionPrompt | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 273 | 43 | 394 || `desktop.dev.maker-experimental` | desktop | Maker 实验诊断页 | hash `/maker-experimental`(MakerExperimentalView;EXPERIMENTAL_FEATURES 现为空,仍是生产路由) | MakerExperimentalView | apps/desktop/src/renderer/features/maker-experimental/MakerExperimentalView.tsx | 10 | 0 | 11 || `desktop.issues.guide` | desktop | Issue 引导页 | hash `/issues`(IssueTrackerFeatureLayout,已迁 GitHub 后的引导页) | IssueTrackerFeatureLayout | apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx, apps/desktop/src/renderer/features/issue-tracker/MyIssueList.tsx, apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts, apps/desktop/src/renderer/features/issue-tracker/lib/myIssuesNotices.ts, apps/desktop/src/renderer/features/issue-tracker/lib/startIssueChat.ts | 0 | 0 | 8 || `desktop.native.app-menu` | desktop | 应用菜单 | Menu.setApplicationMenu(用户可见出口,不展开业务逻辑) | applicationMenuLabels | apps/desktop/src/main/applicationMenuLabels.ts | 0 | 0 | 0 |