Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复侧边栏会话行 memo 被整表打穿 (#536)
Dash9a8886f1d5c0
diff --git a/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts b/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.tsindex 0cfe4f5b9c..1c9261ee36 100644--- a/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts@@ -110,8 +110,11 @@ describe('Project 行内 + 也对标统一 New(delayed-create)', () => {describe('inline archive dirty-worktree warning', () => {it('preflights archive-now and opens the warning dialog before archiving a dirty worktree', () => {+ // 钉的是预检顺序,不是排版:末段用 [\s\S]*? 容忍换行。activeSessionId 取+ // viewedSessionIdRef.current(而非 viewedSessionId)是为了让 handleActionClick+ // 的 useCallback deps 保持稳定,见 sessionRowRenderIsolation 的行渲染隔离不变量。expect(sidebarSource).toMatch(- /if \(action === 'archive-now'\) \{[\s\S]*?fetchDirtyWorktreeForRemoval\([\s\S]*?if \(dirtyWorktree\) \{[\s\S]*?setConfirm\(\{ open: true, sessionId, action: 'archive', dirtyWorktree: true \}\);[\s\S]*?return;[\s\S]*?await runSessionAction\(sessionId, 'archive', \{ activeSessionId: viewedSessionId \}\);/,+ /if \(action === 'archive-now'\) \{[\s\S]*?fetchDirtyWorktreeForRemoval\([\s\S]*?if \(dirtyWorktree\) \{[\s\S]*?setConfirm\(\{ open: true, sessionId, action: 'archive', dirtyWorktree: true \}\);[\s\S]*?return;[\s\S]*?await runSessionAction\(sessionId, 'archive', \{[\s\S]*?activeSessionId: viewedSessionIdRef\.current,[\s\S]*?\}\);/,);});});diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex 5577efdd39..215f18ed90 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -1251,6 +1251,19 @@ function ExpandedView({const [selectedSessionIds, setSelectedSessionIds] = useState<Set<string>>(() => new Set());const [selectionAnchorSessionId, setSelectionAnchorSessionId] = useState<string | null>(null);+ // 这三个值 handleSessionClick 只在「点击那一刻」读一次。留在它的 deps 里会让+ // 每次点击(:setSelectionAnchorSessionId 必触发)和每次切换都重建 handler,+ // 行的 onClick 跟着换引用 → 整表 memo 失效重画一遍(SessionItem.tsx 不变量 #3)。+ // 经 ref 读还顺带避开闭包陈旧:拿到的是最新值而非渲染时快照。+ const activeSessionIdRef = useRef(activeSessionId);+ activeSessionIdRef.current = activeSessionId;+ // viewedSessionId 同理:handleActionClick 只在触发归档那一刻用它算重定向目标。+ const viewedSessionIdRef = useRef(viewedSessionId);+ 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);// 含远程会话:device-link 远程行也渲染在可选行里,bulk 选择/归档/删除必须能解析到它们@@ -1259,6 +1272,10 @@ function ExpandedView({() => new Map([...sessions, ...remoteProjectSessions].map((session) => [session.id, session])),[sessions, remoteProjectSessions],);+ // 与 sessionsRef 同理:行级 handler 只在「点击那一刻」查表,不该因为表换了引用就+ // 重建自身 —— 否则 SessionItem 的 memo 会被整表打穿(SessionItem.tsx 不变量第 3 条)。+ const sessionsByIdRef = useRef(sessionsById);+ sessionsByIdRef.current = sessionsById;const selectedSessions = useMemo(() =>[...selectedSessionIds]@@ -1381,10 +1398,9 @@ function ExpandedView({if (modifiers?.shiftKey) {const visibleIds = getVisibleSidebarSessionIds(sidebarScrollRef.current);const visibleIdSet = new Set(visibleIds);+ const anchorSessionId = selectionAnchorSessionIdRef.current;const anchor =- selectionAnchorSessionId && visibleIds.includes(selectionAnchorSessionId)- ? selectionAnchorSessionId- : id;+ anchorSessionId && visibleIds.includes(anchorSessionId) ? anchorSessionId : id;const anchorIndex = visibleIds.indexOf(anchor);const targetIndex = visibleIds.indexOf(id);const rangeIds =@@ -1418,7 +1434,7 @@ function ExpandedView({return;}- if (selectedSessionIds.size > 0) {+ if (selectedSessionIdsRef.current.size > 0) {setSelectedSessionIds(new Set());}setSelectionAnchorSessionId(id);@@ -1426,20 +1442,15 @@ function ExpandedView({clearNotification(id);markAutomationSessionRunsRead(id);clearSystemSessionAttention(id);- if (id === activeSessionId) return; // No duplicate navigate.+ if (id === activeSessionIdRef.current) return; // No duplicate navigate.if (import.meta.env.DEV) perfLog.debug(`sidebar:click sid=${id}`); // 纯诊断,生产剔除- const target = sessions.find((s) => s.id === id);+ const target = sessionsRef.current.find((s) => s.id === id);navigate(await resolveSessionRoute(id, target));},- [- activeSessionId,- navigate,- clearNotification,- markAutomationSessionRunsRead,- sessions,- selectedSessionIds.size,- selectionAnchorSessionId,- ],+ // deps 只剩三个天然稳定的引用:navigate(router)、clearNotification(空 deps+ // useCallback)、markAutomationSessionRunsRead(随 scheduleSessionIndex,仅+ // schedule 真变时换)。至此 onClick 在运行期与切换时都不再换引用。+ [navigate, clearNotification, markAutomationSessionRunsRead],);/* ---- Project 行内的 + 按钮:对标顶部 "+ New"——预填该 project 的 workingDir 后进 draft 路由 ----@@ -1584,13 +1595,15 @@ function ExpandedView({/* ---- Rename handler ---- */const handleRename = useCallback(async (sessionId: string, newTitle: string) => {- const session = sessionsById.get(sessionId);+ const session = sessionsByIdRef.current.get(sessionId);if (isRemoteSessionWriteBlocked(session)) {toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));return;}// 取旧值用于失败回滚,乐观先 patch(不刷整列表,列表顺序保持稳定)- const oldTitle = sessions.find((s) => s.id === sessionId)?.title;+ // 保持读 sessions(而非 sessionsById):后者含 remoteProjectSessions,换源会连带+ // 改变远程会话的回滚行为,不在本次修复范围内。+ const oldTitle = sessionsRef.current.find((s) => s.id === sessionId)?.title;patchLocal(sessionId, { title: newTitle });try {// 远程会话:patch-meta 经隧道写被控端 → 广播 sessions:patched → applyPatch 更新远程分片(纯镜像)。@@ -1601,7 +1614,7 @@ function ExpandedView({if (oldTitle !== undefined) patchLocal(sessionId, { title: oldTitle });}},- [sessions, sessionsById, patchLocal, t],+ [patchLocal, t],);const handleProjectAliasChange = useCallback(@@ -1620,12 +1633,13 @@ function ExpandedView({/* ---- Pin / Unpin handler ---- */const handleTogglePin = useCallback(async (sessionId: string, currentlyPinned: boolean) => {- const session = sessionsById.get(sessionId);+ const session = sessionsByIdRef.current.get(sessionId);if (isRemoteSessionWriteBlocked(session)) {toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));return;}- const oldPinnedAt = sessions.find((s) => s.id === sessionId)?.pinnedAt ?? null;+ // 同 handleRename:回滚值刻意仍读 sessions,不换成 sessionsById。+ const oldPinnedAt = sessionsRef.current.find((s) => s.id === sessionId)?.pinnedAt ?? null;const newPinnedAt = currentlyPinned ? null : new Date().toISOString();patchLocal(sessionId, { pinnedAt: newPinnedAt });// pin / re-pin 时把它顶到 manualPinnedOrder 首位,否则带着老 rank 会卡回原位。@@ -1640,7 +1654,9 @@ function ExpandedView({patchLocal(sessionId, { pinnedAt: oldPinnedAt });}},- [filter, patchLocal, sessions, sessionsById, t],+ // 只依赖 filter.promotePin(useCallback 稳定),不要整个 filter ——+ // useSidebarFilter 每次调用都返回新对象字面量,带上它等于每渲染换引用。+ [filter.promotePin, patchLocal, t],);const handleToggleProjectPin = useCallback(@@ -1658,7 +1674,7 @@ function ExpandedView({const handleMoveSession = useCallback(async (sessionId: string, target: SessionMoveTarget) => {- const session = sessionsById.get(sessionId);+ const session = sessionsByIdRef.current.get(sessionId);if (!session) return;if (session.remoteHostId || session.deviceLinkDeviceId) {toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectRemoteUnsupported'));@@ -1738,7 +1754,16 @@ function ExpandedView({);}},- [collapse, effectiveRunningSessionIds, patchLocal, sessionsById, t],+ // 同理只依赖用到的三个成员,不要整个 collapse —— useCollapsedProjects 也返回+ // 新对象字面量。collapsed 是 Set,仅用户手动折叠/展开时换引用,频率可忽略。+ [+ collapse.collapsed,+ collapse.expand,+ collapse.setCollapsed,+ effectiveRunningSessionIds,+ patchLocal,+ t,+ ],);/* ---- Delete / Archive / Unarchive action handlers ----@@ -1759,7 +1784,7 @@ function ExpandedView({const handleActionClick = useCallback(async (sessionId: string, action: 'delete' | 'archive' | 'archive-now' | 'unarchive') => {- const session = sessionsById.get(sessionId);+ const session = sessionsByIdRef.current.get(sessionId);if (isRemoteSessionWriteBlocked(session)) {toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));return;@@ -1794,8 +1819,11 @@ function ExpandedView({return;}// 重定向判定用 viewedSessionId:files 路由下归档「正在浏览的会话」也要- // 跳离失效的文件视图(codex review;正常路由下两者恒等)。- await runSessionAction(sessionId, 'archive', { activeSessionId: viewedSessionId });+ // 跳离失效的文件视图(codex review;正常路由下两者恒等)。经 ref 读:它随+ // 路由切换而变,留在 deps 里会让本 handler 每次切换都重建、打穿整表 memo。+ await runSessionAction(sessionId, 'archive', {+ activeSessionId: viewedSessionIdRef.current,+ });return;}if (action !== 'unarchive') {@@ -1810,10 +1838,8 @@ function ExpandedView({await unarchiveSession(sessionId);},[- viewedSessionId,runningSessionIds,runSessionAction,- sessionsById,unarchiveSession,t,],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 ad6c421ba6..773b8d1362 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@@ -235,3 +235,111 @@ describe('SessionItem — 父层与 urgency 隔离', () => {expect(renderCounts.get('session-b')).toBe(baselineB);});});++// ── 不变量 4:父层传给行的 props 必须运行期引用稳定 ──────────────────────────+//+// 上面三条都在「隔离环境 + 稳定 noop props」下成立,抓不到真正的历史 bug:+// 真实父组件(CCAgentSidebarUpper)把每渲染换引用的东西放进 handler 的 useCallback+// deps,memo 在生产里从未生效。渲染真实父组件需要 mock 掉 router + 十几个 store,+// 成本远超收益,故这里退一步做源码级断言 —— 脆,但能钉住确切的回归点。+//+// 历史:2026-07 单击切换卡顿排查发现两处+// a) useSessionRunningStatus 的 runningSessionIds 裸调 deriveRunningSet,每渲染 new Set;+// b) 5 个行级 handler 的 deps 里带着 sessions / sessionsById(它们随每条消息换引用)。+// 两者都会让 onAction / onMoveSession / onClick 等 prop 每渲染换引用,打穿整表 memo。++/** 取 `const <name> = useCallback(...)` 的 deps 数组文本(括号配平扫描)。 */+function useCallbackDeps(source: string, name: string): string {+ const start = source.indexOf(`const ${name} = useCallback(`);+ if (start < 0) throw new Error(`未找到 handler: ${name}`);+ let depth = 0;+ let i = source.indexOf('(', start);+ const open = i;+ for (; i < source.length; i += 1) {+ if (source[i] === '(') depth += 1;+ else if (source[i] === ')') {+ depth -= 1;+ if (depth === 0) break;+ }+ }+ const body = source.slice(open, i);+ const depsStart = body.lastIndexOf('[');+ const depsEnd = body.lastIndexOf(']');+ if (depsStart < 0 || depsEnd < depsStart) throw new Error(`${name} 没有 deps 数组`);+ return body.slice(depsStart, depsEnd + 1);+}++describe('父层 — 行级 handler 的引用稳定性', () => {+ /** 这 5 个是 SessionItem 的直接 props(onClick/onAction/onRename/onTogglePin/onMoveSession)。 */+ const ROW_HANDLERS = [+ 'handleSessionClick',+ 'handleRename',+ 'handleTogglePin',+ 'handleMoveSession',+ 'handleActionClick',+ ];++ it('deps 里不得出现每条消息都换引用的 sessions / sessionsById', () => {+ const source = readFileSync(+ resolve(__dirname, '..', '..', 'CCAgentSidebarUpper.tsx'),+ 'utf8',+ );+ for (const name of ROW_HANDLERS) {+ const deps = useCallbackDeps(source, name);+ // 词边界保证 sessionsRef / sessionsByIdRef 不误伤。+ expect(deps, `${name} 的 deps 不得含裸 sessions`).not.toMatch(/\bsessions\b/);+ expect(deps, `${name} 的 deps 不得含裸 sessionsById`).not.toMatch(/\bsessionsById\b/);+ }+ });++ it('deps 里不得出现每渲染重建的 hook 返回对象(filter / collapse)', () => {+ // useSidebarFilter / useCollapsedProjects 都返回裸对象字面量,每次调用换引用。+ // 必须依赖到具体成员(filter.promotePin、collapse.expand …),故用 (?!\.) 放行+ // 成员访问、只拦整个对象。+ const source = readFileSync(+ resolve(__dirname, '..', '..', 'CCAgentSidebarUpper.tsx'),+ 'utf8',+ );+ for (const name of ROW_HANDLERS) {+ const deps = useCallbackDeps(source, name);+ expect(deps, `${name} 的 deps 不得含整个 filter`).not.toMatch(/\bfilter\b(?!\.)/);+ expect(deps, `${name} 的 deps 不得含整个 collapse`).not.toMatch(/\bcollapse\b(?!\.)/);+ }+ });++ it('deps 里不得出现随路由切换而变的 viewedSessionId', () => {+ const source = readFileSync(+ resolve(__dirname, '..', '..', 'CCAgentSidebarUpper.tsx'),+ 'utf8',+ );+ for (const name of ROW_HANDLERS) {+ const deps = useCallbackDeps(source, name);+ expect(deps, `${name} 的 deps 不得含 viewedSessionId`).not.toMatch(+ /\bviewedSessionId\b/,+ );+ }+ });++ it('handleSessionClick 的 deps 不得含每次点击/切换都变的选择态', () => {+ // 这三个只在点击那一刻读,却会被 setSelectionAnchorSessionId(每次点击必调)+ // 和路由切换带着变 —— 留在 deps 里等于每切换一次就整表重画一遍。+ const source = readFileSync(+ resolve(__dirname, '..', '..', 'CCAgentSidebarUpper.tsx'),+ 'utf8',+ );+ const deps = useCallbackDeps(source, 'handleSessionClick');+ expect(deps).not.toMatch(/\bactiveSessionId\b/);+ expect(deps).not.toMatch(/\bselectedSessionIds\b/);+ expect(deps).not.toMatch(/\bselectionAnchorSessionId\b/);+ });++ it('runningSessionIds 必须 memo 化(否则每渲染 new Set 打穿整表)', () => {+ const source = readFileSync(+ resolve(__dirname, '..', '..', '..', '..', 'hooks', 'useSessionRunningStatus.ts'),+ 'utf8',+ );+ expect(source).toMatch(+ /const runningSessionIds = useMemo\(\s*\(\)\s*=>\s*deriveRunningSet\(statusMap\),\s*\[statusMap\]\s*\)/,+ );+ });+});diff --git a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.tsindex 5d42eb6a23..04c2c7df74 100644--- a/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts+++ b/apps/desktop/src/renderer/hooks/useSessionRunningStatus.ts@@ -37,7 +37,7 @@* 静默完成不走去抖(见下方分支)。*/-import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';+import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';import { makerChatStore } from '@/lib/makerChatStore';import type { SessionStatusInfo } from '@/lib/makerChatStore';import {@@ -329,7 +329,11 @@ export function useSessionRunningStatus();// Derive running set for the return value (outside effect, for rendering).- const runningSessionIds = deriveRunningSet(statusMap);+ // 必须 memo:裸调用每渲染都 new Set,会顺着 effectiveRunningSessionIds →+ // handleActionClick / handleMoveSession 一路换引用,把 SessionItem 的 memo+ // 全表打穿(见 sidebar/SessionItem.tsx 的性能不变量第 3 条)。statusMap 来自+ // useSyncExternalStore,只在真实状态变化时换引用,故这里的缓存是安全的。+ const runningSessionIds = useMemo(() => deriveRunningSet(statusMap), [statusMap]);return {/** Set of session IDs currently running. */