Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(desktop): 降低侧栏全部展开后切换任务的卡顿 (#3611)

Dash70c920f86130
diff --git a/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.ts b/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.ts
index f9355c11d4..f7031883b8 100644
--- a/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.ts
@@ -180,6 +180,22 @@ describe('getVisibleSidebarSessionIds', () => {
}
});
+ it('skips rows inside a collapsed sidebar section without walking computed style', () => {
+ const root = document.createElement('div');
+ const collapsed = document.createElement('div');
+ collapsed.dataset.sidebarSectionCollapsed = 'true';
+ const hidden = document.createElement('div');
+ hidden.dataset.sidebarSessionRow = 'true';
+ hidden.dataset.sessionId = 'hidden';
+ collapsed.append(hidden);
+ const visible = document.createElement('div');
+ visible.dataset.sidebarSessionRow = 'true';
+ visible.dataset.sessionId = 'visible';
+ root.append(collapsed, visible);
+
+ expect(getVisibleSidebarSessionIds(root)).toEqual(['visible']);
+ });
+
it('keeps the real sidebar list when only the resident search input is marked', () => {
const aside = document.createElement('aside');
const search = document.createElement('div');
diff --git a/apps/desktop/src/renderer/__tests__/sidebarCollapseReset.test.tsx b/apps/desktop/src/renderer/__tests__/sidebarCollapseReset.test.tsx
index 039871d7ac..0de672eb12 100644
--- a/apps/desktop/src/renderer/__tests__/sidebarCollapseReset.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/sidebarCollapseReset.test.tsx
@@ -1,9 +1,12 @@
// @vitest-environment jsdom
-import { act, renderHook } from '@testing-library/react';
+import { act, render, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { SECTION_COLLAPSE_DURATION_MS } from '../features/cc-agent/sidebar/SectionCollapse';
+import {
+ SectionCollapse,
+ SECTION_COLLAPSE_DURATION_MS,
+} from '../features/cc-agent/sidebar/SectionCollapse';
import { useCollapsibleShowAll } from '../features/cc-agent/sidebar/hooks/useCollapsibleShowAll';
function renderShowAll(initialCollapsed = false) {
@@ -75,3 +78,55 @@ describe('useCollapsibleShowAll', () => {
expect(result.current.showAll).toBe(true);
});
});
+
+describe('SectionCollapse unmount after animation', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.runOnlyPendingTimers();
+ vi.useRealTimers();
+ });
+
+ it('does not mount children when first rendered collapsed', () => {
+ const { queryByText } = render(<SectionCollapse collapsed>hidden</SectionCollapse>);
+ expect(queryByText('hidden')).toBeNull();
+ });
+
+ it('keeps children during collapse and unmounts after the animation ends', () => {
+ const { rerender, queryByText } = render(
+ <SectionCollapse collapsed={false}>visible</SectionCollapse>,
+ );
+ expect(queryByText('visible')).not.toBeNull();
+
+ rerender(<SectionCollapse collapsed>visible</SectionCollapse>);
+ expect(queryByText('visible')).not.toBeNull();
+
+ act(() => {
+ vi.advanceTimersByTime(SECTION_COLLAPSE_DURATION_MS - 1);
+ });
+ expect(queryByText('visible')).not.toBeNull();
+
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(queryByText('visible')).toBeNull();
+ });
+
+ it('remounts immediately when re-expanded before the animation ends', () => {
+ const { rerender, queryByText } = render(
+ <SectionCollapse collapsed={false}>visible</SectionCollapse>,
+ );
+ rerender(<SectionCollapse collapsed>visible</SectionCollapse>);
+ act(() => {
+ vi.advanceTimersByTime(SECTION_COLLAPSE_DURATION_MS / 2);
+ });
+ rerender(<SectionCollapse collapsed={false}>visible</SectionCollapse>);
+ expect(queryByText('visible')).not.toBeNull();
+ act(() => {
+ vi.advanceTimersByTime(SECTION_COLLAPSE_DURATION_MS);
+ });
+ expect(queryByText('visible')).not.toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 16f75d6394..108a128354 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -109,7 +109,10 @@ import {
} from '@/lib/sessionAttentionStore';
import { patchDraft as patchNewMakerDraft } from '@/state/newMakerDraft';
import { consumePendingProjectFocus, usePendingProjectFocus } from '@/state/pendingProjectFocus';
-import { requestConversationSearch, useConversationSearchRequest } from '@/state/conversationSearchRequest';
+import {
+ requestConversationSearch,
+ useConversationSearchRequest,
+} from '@/state/conversationSearchRequest';
import { searchDevicesFromSwitcher } from '@/lib/conversationSearchFanout';
import { emitRefresh, onPatch } from '@/lib/sessionsBus';
@@ -588,20 +591,22 @@ export function CCAgentSidebarUpper() {
.filter((session) => !catalogSessions.some((active) => active.id === session.id))
.slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT);
const remainingCatalogSlots = Math.max(0, 100 - visibleProjection.length);
- const tasks = [...visibleProjection, ...catalogSessions.slice(0, remainingCatalogSlots)].map((session) => {
- const pinnedAtMs = session.pinnedAt ? Date.parse(session.pinnedAt) : Number.NaN;
- const userSendAtMs = session.userSendAt ? Date.parse(session.userSendAt) : Number.NaN;
- const order = sidebarOrder.get(session.id);
- const isActiveCatalog = session.status === 'active';
- return {
- id: session.id,
- title: session.title ?? null,
- pinnedAt: Number.isFinite(pinnedAtMs) ? pinnedAtMs : null,
- userSendAt: Number.isFinite(userSendAtMs) ? userSendAtMs : null,
- ...(order === undefined ? {} : { sidebarOrder: order }),
- ...(isActiveCatalog ? {} : { catalogEligible: false }),
- };
- });
+ const tasks = [...visibleProjection, ...catalogSessions.slice(0, remainingCatalogSlots)].map(
+ (session) => {
+ const pinnedAtMs = session.pinnedAt ? Date.parse(session.pinnedAt) : Number.NaN;
+ const userSendAtMs = session.userSendAt ? Date.parse(session.userSendAt) : Number.NaN;
+ const order = sidebarOrder.get(session.id);
+ const isActiveCatalog = session.status === 'active';
+ return {
+ id: session.id,
+ title: session.title ?? null,
+ pinnedAt: Number.isFinite(pinnedAtMs) ? pinnedAtMs : null,
+ userSendAt: Number.isFinite(userSendAtMs) ? userSendAtMs : null,
+ ...(order === undefined ? {} : { sidebarOrder: order }),
+ ...(isActiveCatalog ? {} : { catalogEligible: false }),
+ };
+ },
+ );
// 侧栏会因为各种无关状态重算;内容没变就不打扰主进程。
const key = JSON.stringify(tasks);
if (key === publishedTaskKeyRef.current) return;
@@ -883,9 +888,8 @@ function ExpandedView({
const sessionIds = group.sessions.map((session) => session.id);
clearSessionAttentionMany(sessionIds);
try {
- const { processed, failed } = await window.electronAPI.localDb.sessions.dismissPendingAlerts(
- sessionIds,
- );
+ const { processed, failed } =
+ await window.electronAPI.localDb.sessions.dismissPendingAlerts(sessionIds);
clearSessionAttentionMany(processed, { intent: 'explicit' });
if (failed.length > 0) log.warn('some pending alerts were not dismissed', failed);
} catch (e) {
@@ -1653,9 +1657,7 @@ function ExpandedView({
);
const visibleDialogues = useMemo(() => {
- const sessions = vendorPredicate
- ? groups.dialogues.filter(vendorPredicate)
- : groups.dialogues;
+ const sessions = vendorPredicate ? groups.dialogues.filter(vendorPredicate) : groups.dialogues;
if (filter.projectsAsSet === null) return sessions;
return filter.projectsAsSet.has(DIALOGUE_FILTER_KEY) ? sessions : [];
}, [groups.dialogues, vendorPredicate, filter.projectsAsSet]);
@@ -1671,22 +1673,19 @@ function ExpandedView({
const hostProjectSort = useMemo(() => {
const scope = projectOrderWriteScopeForSelection(selectedMachineId);
- const hostSnapshot = scope.kind === 'host' && scope.deviceId === null
- ? localHostProjectOrder.snapshot
- : scope.kind === 'host' && scope.deviceId
- ? remoteHostProjectOrders.get(scope.deviceId)
- : undefined;
- const hostManual = scope.kind === 'host' && scope.deviceId === null
- ? localHostProjectOrder.snapshot.manualProjectOrder
- : scope.kind === 'host' && scope.deviceId
- ? controllerManualOrderForDevice(scope.deviceId, hostSnapshot) ?? []
- : [];
- const displayed = resolveDisplayedProjectOrder(
- scope,
- hostSnapshot,
- filter,
- hostManual,
- );
+ const hostSnapshot =
+ scope.kind === 'host' && scope.deviceId === null
+ ? localHostProjectOrder.snapshot
+ : scope.kind === 'host' && scope.deviceId
+ ? remoteHostProjectOrders.get(scope.deviceId)
+ : undefined;
+ const hostManual =
+ scope.kind === 'host' && scope.deviceId === null
+ ? localHostProjectOrder.snapshot.manualProjectOrder
+ : scope.kind === 'host' && scope.deviceId
+ ? (controllerManualOrderForDevice(scope.deviceId, hostSnapshot) ?? [])
+ : [];
+ const displayed = resolveDisplayedProjectOrder(scope, hostSnapshot, filter, hostManual);
return {
order: displayed.manualProjectOrder,
projectOrder: displayed.projectOrder,
@@ -1723,12 +1722,7 @@ function ExpandedView({
hostProjectSort.order,
hostProjectSort.projectOrder,
);
- }, [
- visibleProjects,
- pinnedProjectKeys,
- vendorPredicate,
- hostProjectSort,
- ]);
+ }, [visibleProjects, pinnedProjectKeys, vendorPredicate, hostProjectSort]);
// 折叠 rail 没有独立的 Pinned 项目瓷砖,因此项目面板必须保留置顶项目,
// 否则侧栏折叠后这些项目及其取消置顶入口都会完全不可达。
@@ -1798,12 +1792,22 @@ function ExpandedView({
const [selectedSessionIds, setSelectedSessionIds] = useState<Set<string>>(() => new Set());
const [selectionAnchorSessionId, setSelectionAnchorSessionId] = useState<string | null>(null);
- // 这三个值 handleSessionClick 只在「点击那一刻」读一次。留在它的 deps 里会让
+ // 这几个值 handleSessionClick 只在「点击那一刻」读一次。留在它的 deps 里会让
// 每次点击(:setSelectionAnchorSessionId 必触发)和每次切换都重建 handler,
// 行的 onClick 跟着换引用 → 整表 memo 失效重画一遍(SessionItem.tsx 不变量 #3)。
// 经 ref 读还顺带避开闭包陈旧:拿到的是最新值而非渲染时快照。
+ // attention / running / 未读集合更是:点进去会先清通知,若留在 deps 里,刚点的
+ // 那一下就会换掉整表 onClick,把「切任务」变成「全表重画」。
const activeSessionIdRef = useRef(activeSessionId);
activeSessionIdRef.current = activeSessionId;
+ const urgentSetRef = useRef(urgentSet);
+ urgentSetRef.current = urgentSet;
+ const attentionKindsRef = useRef(attentionKinds);
+ attentionKindsRef.current = attentionKinds;
+ const runningSessionIdsRef = useRef(runningSessionIds);
+ runningSessionIdsRef.current = runningSessionIds;
+ const sidebarNotificationsRef = useRef(sidebarNotifications);
+ sidebarNotificationsRef.current = sidebarNotifications;
// viewedSessionId 同理:handleActionClick 只在触发归档那一刻用它算重定向目标。
const viewedSessionIdRef = useRef(viewedSessionId);
viewedSessionIdRef.current = viewedSessionId;
@@ -2001,6 +2005,9 @@ function ExpandedView({
);
const pruneSelectionToRenderedRows = useCallback(() => {
+ if (selectedSessionIdsRef.current.size === 0 && selectionAnchorSessionIdRef.current == null) {
+ return;
+ }
const renderedSessionIds = new Set(getVisibleSidebarSessionIds(sidebarScrollRef.current));
setSelectedSessionIds((prev) => {
const next = new Set([...prev].filter((id) => renderedSessionIds.has(id)));
@@ -2009,17 +2016,19 @@ function ExpandedView({
setSelectionAnchorSessionId((prev) => (prev && renderedSessionIds.has(prev) ? prev : null));
}, []);
+ // 只在真有多选集合时才盯 DOM。单击也会写下 selectionAnchorSessionId 当
+ // Shift 范围锚点,那不算多选;锚点失效时 Shift 点击会现场用可见行校验。
+ // 若把锚点算进去,首次点击后观察器会一直挂着,运行态/未读子节点增删又把
+ // getVisibleSidebarSessionIds 打回整表布局税。
+ const hasSidebarSelection = selectedSessionIds.size > 0;
useEffect(() => {
- pruneSelectionToRenderedRows();
- });
-
- useEffect(() => {
+ if (!hasSidebarSelection) return undefined;
const root = sidebarScrollRef.current;
if (!root) return undefined;
const observer = new MutationObserver(pruneSelectionToRenderedRows);
observer.observe(root, { childList: true, subtree: true });
return () => observer.disconnect();
- }, [pruneSelectionToRenderedRows]);
+ }, [hasSidebarSelection, pruneSelectionToRenderedRows]);
const handleClearSelection = useCallback(() => {
setSelectedSessionIds((prev) => (prev.size === 0 ? prev : new Set()));
@@ -2138,13 +2147,13 @@ function ExpandedView({
setSelectionAnchorSessionId(id);
// 清点会先于路由更新抹掉 attention。必须先按当前档位钉住,否则
// ProjectsSection 首次 hold 只能读到 rest,刚打开的完成未读仍会立刻沉底。
- const waiting = new Set(urgentSet);
- for (const [sessionId, kind] of attentionKinds) {
+ const waiting = new Set(urgentSetRef.current);
+ for (const [sessionId, kind] of attentionKindsRef.current) {
if (kind === 'awaiting' || kind === 'error') waiting.add(sessionId);
}
holdSidebarViewedPriority(id, {
- runningSessionIds,
- attentionSessionIds: sidebarNotifications,
+ runningSessionIds: runningSessionIdsRef.current,
+ attentionSessionIds: sidebarNotificationsRef.current,
waitingSessionIds: waiting,
});
// F-SB-7: Clear done notification on click
@@ -2156,15 +2165,7 @@ function ExpandedView({
const target = sessionsRef.current.find((s) => s.id === id);
navigate(await resolveSessionRoute(id, target));
},
- [
- navigate,
- clearNotification,
- markAutomationSessionRunsRead,
- urgentSet,
- attentionKinds,
- runningSessionIds,
- sidebarNotifications,
- ],
+ [navigate, clearNotification, markAutomationSessionRunsRead],
);
/* ---- mod+1..9 快速切换对话 + 按住修饰键浮现序号徽标(复刻 Codex 桌面版) ----
@@ -3451,209 +3452,209 @@ function ExpandedView({
) : null}
{/* 搜索时原列表只隐藏、不卸载:置顶段折叠等本地 state 才能保住。 */}
<div hidden={searchActive} className="flex flex-col gap-2">
- {remoteDeviceDirectoryStatus === 'error' && !hasVisibleSidebarContent ? (
- <>
- <MainListScopeHeader
- filter={filter}
- allKnownProjects={visibleProjectUniverse}
- dialogueCount={allGroups.dialogues.length}
- hasRemoteDevices={deviceGroupingAvailable}
- />
- <RemoteSidebarLoadNotice
- kind="devices"
- status="error"
- partial={false}
- onRetry={retryDeviceLinkDeviceList}
- />
- </>
- ) : remoteSessionBootstrapFailures.length > 0 && !hasVisibleSidebarContent ? (
- <>
- <MainListScopeHeader
- filter={filter}
- allKnownProjects={visibleProjectUniverse}
- dialogueCount={allGroups.dialogues.length}
- hasRemoteDevices={deviceGroupingAvailable}
- />
- <RemoteSidebarLoadNotice
- kind="tasks"
- status="error"
- deviceLabel={failedRemoteDeviceLabel}
- partial={false}
- />
- </>
- ) : remoteDeviceDirectoryStatus === 'loading' && !hasVisibleSidebarContent ? (
- <>
- <MainListScopeHeader
- filter={filter}
- allKnownProjects={visibleProjectUniverse}
- dialogueCount={allGroups.dialogues.length}
- hasRemoteDevices={deviceGroupingAvailable}
- />
- <RemoteSidebarLoadNotice kind="devices" status="loading" partial={false} />
- </>
- ) : remoteSessionBootstrapLoadingDevices.length > 0 && !hasVisibleSidebarContent ? (
- <>
- <MainListScopeHeader
- filter={filter}
- allKnownProjects={visibleProjectUniverse}
- dialogueCount={allGroups.dialogues.length}
- hasRemoteDevices={deviceGroupingAvailable}
- />
- <RemoteSidebarLoadNotice
- kind="tasks"
- status="loading"
- deviceLabel={loadingRemoteDeviceLabel}
- partial={false}
- />
- </>
- ) : selectedMachineConnecting ? (
- // 选中机器连接中:会话还没同步,显示「连接中」而非「暂无对话」。
- // 范围标题恒在,可从菜单切回「所有 / 本机」,不会被困在占位页。
- <>
- <MainListScopeHeader
- filter={filter}
- allKnownProjects={visibleProjectUniverse}
- dialogueCount={allGroups.dialogues.length}
- hasRemoteDevices={deviceGroupingAvailable}
- />
- <div className="flex flex-col items-center justify-center px-3 py-12 text-center">
- <span className="animate-pulse text-xs text-[var(--text-tertiary)]">
- {t('ccAgent.sidebar.machineSwitcher.connecting')}
- </span>
- </div>
- </>
- ) : (
- <>
- {remoteDeviceDirectoryStatus === 'error' && (
+ {remoteDeviceDirectoryStatus === 'error' && !hasVisibleSidebarContent ? (
+ <>
+ <MainListScopeHeader
+ filter={filter}
+ allKnownProjects={visibleProjectUniverse}
+ dialogueCount={allGroups.dialogues.length}
+ hasRemoteDevices={deviceGroupingAvailable}
+ />
<RemoteSidebarLoadNotice
kind="devices"
status="error"
- partial
+ partial={false}
onRetry={retryDeviceLinkDeviceList}
/>
- )}
- {remoteSessionBootstrapFailures.length > 0 && (
+ </>
+ ) : remoteSessionBootstrapFailures.length > 0 && !hasVisibleSidebarContent ? (
+ <>
+ <MainListScopeHeader
+ filter={filter}
+ allKnownProjects={visibleProjectUniverse}
+ dialogueCount={allGroups.dialogues.length}
+ hasRemoteDevices={deviceGroupingAvailable}
+ />
<RemoteSidebarLoadNotice
kind="tasks"
status="error"
deviceLabel={failedRemoteDeviceLabel}
- partial
+ partial={false}
/>
- )}
- {/*
- * 远程任务 / 设备目录的 loading 只在上面的「无内容」分支显示。
- * 这里可能已经有本地或旧的远程快照;把后台重拉提示插进普通文档流会让
- * 整个侧栏在 loading↔ready 间上下移动,造成可见闪烁。错误提示仍保留
- * 在列表前,便于用户知道已有内容不是本轮权威结果。
- */}
- <PinnedSection
- entries={visiblePinnedEntries}
- allKnownProjects={visibleProjectUniverse}
- renderProject={(
- project,
- displaySessions,
- parentSectionCollapsed,
- sessionVariant,
- ) => (
- <ProjectNodeView
- project={project}
- displaySessions={displaySessions}
- sessionVariant={sessionVariant}
- statusFilter={filter.status}
- isCollapsed={collapse.collapsed.has(project.projectKey)}
- collapsedAttentionTone={
- collapse.collapsed.has(project.projectKey)
- ? collapsedAttentionToneFor(displaySessions ?? project.sessions)
- : null
- }
- parentSectionCollapsed={parentSectionCollapsed}
- activeSessionId={activeSessionId}
- runningSessionIds={displayRunningSessionIds}
- attachedSessionIds={attachedSessionIds}
- notifications={sidebarNotifications}
- scheduleSessionIndex={scheduleSessionIndex}
- selectedSessionIds={selectedSessionIds}
- disableSessionCollapse={false}
- onToggle={collapse.toggle}
- isProjectPinned
- onToggleProjectPin={handleToggleProjectPin}
- onRenameProject={handleProjectAliasChange}
- onRemoveFromSidebar={handleRemoveProjectFromSidebar}
- onSessionClick={handleSessionClick}
- onAction={handleActionClick}
- onRename={handleRename}
- onTogglePin={handleTogglePin}
- onMoveSession={handleMoveSession}
- projectOptions={projectPickerOptions}
- onScheduleAction={handleScheduleAction}
- onCreateInProject={handleCreateInProject}
- onOpenConversationSearch={handleOpenConversationSearch}
- onOpenInExplorer={handleOpenInExplorer}
- onLinkCodexProject={handleLinkCodexProject}
- linkingCodexProject={linkingCodexProject === project.projectKey}
- onBrowseFiles={handleBrowseFiles}
- onArchiveAll={handleArchiveAllInProject}
+ </>
+ ) : remoteDeviceDirectoryStatus === 'loading' && !hasVisibleSidebarContent ? (
+ <>
+ <MainListScopeHeader
+ filter={filter}
+ allKnownProjects={visibleProjectUniverse}
+ dialogueCount={allGroups.dialogues.length}
+ hasRemoteDevices={deviceGroupingAvailable}
+ />
+ <RemoteSidebarLoadNotice kind="devices" status="loading" partial={false} />
+ </>
+ ) : remoteSessionBootstrapLoadingDevices.length > 0 && !hasVisibleSidebarContent ? (
+ <>
+ <MainListScopeHeader
+ filter={filter}
+ allKnownProjects={visibleProjectUniverse}
+ dialogueCount={allGroups.dialogues.length}
+ hasRemoteDevices={deviceGroupingAvailable}
+ />
+ <RemoteSidebarLoadNotice
+ kind="tasks"
+ status="loading"
+ deviceLabel={loadingRemoteDeviceLabel}
+ partial={false}
+ />
+ </>
+ ) : selectedMachineConnecting ? (
+ // 选中机器连接中:会话还没同步,显示「连接中」而非「暂无对话」。
+ // 范围标题恒在,可从菜单切回「所有 / 本机」,不会被困在占位页。
+ <>
+ <MainListScopeHeader
+ filter={filter}
+ allKnownProjects={visibleProjectUniverse}
+ dialogueCount={allGroups.dialogues.length}
+ hasRemoteDevices={deviceGroupingAvailable}
+ />
+ <div className="flex flex-col items-center justify-center px-3 py-12 text-center">
+ <span className="animate-pulse text-xs text-[var(--text-tertiary)]">
+ {t('ccAgent.sidebar.machineSwitcher.connecting')}
+ </span>
+ </div>
+ </>
+ ) : (
+ <>
+ {remoteDeviceDirectoryStatus === 'error' && (
+ <RemoteSidebarLoadNotice
+ kind="devices"
+ status="error"
+ partial
+ onRetry={retryDeviceLinkDeviceList}
/>
)}
- activeSessionId={activeSessionId}
- runningSessionIds={displayRunningSessionIds}
- attachedSessionIds={attachedSessionIds}
- notifications={sidebarNotifications}
- selectedSessionIds={selectedSessionIds}
- onSessionClick={handleSessionClick}
- onAction={handleActionClick}
- onRename={handleRename}
- onTogglePin={handleTogglePin}
- onMoveSession={handleMoveSession}
- projectOptions={projectPickerOptions}
- onReorder={handlePinnedReorder}
- />
- {/* D 期:主列表 = 混排模型(项目行 + 散排对话 / 对话组,ProjectsSection
+ {remoteSessionBootstrapFailures.length > 0 && (
+ <RemoteSidebarLoadNotice
+ kind="tasks"
+ status="error"
+ deviceLabel={failedRemoteDeviceLabel}
+ partial
+ />
+ )}
+ {/*
+ * 远程任务 / 设备目录的 loading 只在上面的「无内容」分支显示。
+ * 这里可能已经有本地或旧的远程快照;把后台重拉提示插进普通文档流会让
+ * 整个侧栏在 loading↔ready 间上下移动,造成可见闪烁。错误提示仍保留
+ * 在列表前,便于用户知道已有内容不是本轮权威结果。
+ */}
+ <PinnedSection
+ entries={visiblePinnedEntries}
+ allKnownProjects={visibleProjectUniverse}
+ renderProject={(
+ project,
+ displaySessions,
+ parentSectionCollapsed,
+ sessionVariant,
+ ) => (
+ <ProjectNodeView
+ project={project}
+ displaySessions={displaySessions}
+ sessionVariant={sessionVariant}
+ statusFilter={filter.status}
+ isCollapsed={collapse.collapsed.has(project.projectKey)}
+ collapsedAttentionTone={
+ collapse.collapsed.has(project.projectKey)
+ ? collapsedAttentionToneFor(displaySessions ?? project.sessions)
+ : null
+ }
+ parentSectionCollapsed={parentSectionCollapsed}
+ activeSessionId={activeSessionId}
+ runningSessionIds={displayRunningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={sidebarNotifications}
+ scheduleSessionIndex={scheduleSessionIndex}
+ selectedSessionIds={selectedSessionIds}
+ disableSessionCollapse={false}
+ onToggle={collapse.toggle}
+ isProjectPinned
+ onToggleProjectPin={handleToggleProjectPin}
+ onRenameProject={handleProjectAliasChange}
+ onRemoveFromSidebar={handleRemoveProjectFromSidebar}
+ onSessionClick={handleSessionClick}
+ onAction={handleActionClick}
+ onRename={handleRename}
+ onTogglePin={handleTogglePin}
+ onMoveSession={handleMoveSession}
+ projectOptions={projectPickerOptions}
+ onScheduleAction={handleScheduleAction}
+ onCreateInProject={handleCreateInProject}
+ onOpenConversationSearch={handleOpenConversationSearch}
+ onOpenInExplorer={handleOpenInExplorer}
+ onLinkCodexProject={handleLinkCodexProject}
+ linkingCodexProject={linkingCodexProject === project.projectKey}
+ onBrowseFiles={handleBrowseFiles}
+ onArchiveAll={handleArchiveAllInProject}
+ />
+ )}
+ activeSessionId={activeSessionId}
+ runningSessionIds={displayRunningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={sidebarNotifications}
+ selectedSessionIds={selectedSessionIds}
+ onSessionClick={handleSessionClick}
+ onAction={handleActionClick}
+ onRename={handleRename}
+ onTogglePin={handleTogglePin}
+ onMoveSession={handleMoveSession}
+ projectOptions={projectPickerOptions}
+ onReorder={handlePinnedReorder}
+ />
+ {/* D 期:主列表 = 混排模型(项目行 + 散排对话 / 对话组,ProjectsSection
内部按 mainListModel 统一排序)。按日期分组与固定 Dialogue 段已删除。 */}
- <ProjectsSection
- unclassified={visibleUnclassified}
- projects={visibleProjectsWithVendor}
- dialogues={visibleDialogues}
- allKnownProjects={visibleProjectUniverse}
- dialogueCount={allGroups.dialogues.length}
- allProjectKeysForOrder={gcProjectKeys}
- filter={filter}
- collapsed={collapse.collapsed}
- isAllCollapsed={collapse.isAllCollapsed}
- activeSessionId={activeSessionId}
- viewedSessionId={viewedSessionId}
- runningSessionIds={displayRunningSessionIds}
- attachedSessionIds={attachedSessionIds}
- notifications={sidebarNotifications}
- scheduleSessionIndex={scheduleSessionIndex}
- selectedSessionIds={selectedSessionIds}
- onSessionClick={handleSessionClick}
- onAction={handleActionClick}
- onRename={handleRename}
- onTogglePin={handleTogglePin}
- onMoveSession={handleMoveSession}
- projectOptions={projectPickerOptions}
- onScheduleAction={handleScheduleAction}
- onToggleProject={collapse.toggle}
- onToggleProjectPin={handleToggleProjectPin}
- onRenameProject={handleProjectAliasChange}
- onRemoveFromSidebar={handleRemoveProjectFromSidebar}
- onCollapseAll={collapse.collapseAll}
- onExpandAll={collapse.expandAll}
- onCreateProject={handleCreateProject}
- onCreateInProject={handleCreateInProject}
- onOpenConversationSearch={handleOpenConversationSearch}
- onOpenInExplorer={handleOpenInExplorer}
- onLinkCodexProject={handleLinkCodexProject}
- linkingCodexProject={linkingCodexProject}
- onBrowseFiles={handleBrowseFiles}
- onArchiveAll={handleArchiveAllInProject}
- remoteDeviceIndex={remoteDeviceIndex}
- onCreateDialogue={handleCreateDialogue}
- isCreateDialogueDisabled={dialogueCreatePending}
- />
- </>
- )}
+ <ProjectsSection
+ unclassified={visibleUnclassified}
+ projects={visibleProjectsWithVendor}
+ dialogues={visibleDialogues}
+ allKnownProjects={visibleProjectUniverse}
+ dialogueCount={allGroups.dialogues.length}
+ allProjectKeysForOrder={gcProjectKeys}
+ filter={filter}
+ collapsed={collapse.collapsed}
+ isAllCollapsed={collapse.isAllCollapsed}
+ activeSessionId={activeSessionId}
+ viewedSessionId={viewedSessionId}
+ runningSessionIds={displayRunningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={sidebarNotifications}
+ scheduleSessionIndex={scheduleSessionIndex}
+ selectedSessionIds={selectedSessionIds}
+ onSessionClick={handleSessionClick}
+ onAction={handleActionClick}
+ onRename={handleRename}
+ onTogglePin={handleTogglePin}
+ onMoveSession={handleMoveSession}
+ projectOptions={projectPickerOptions}
+ onScheduleAction={handleScheduleAction}
+ onToggleProject={collapse.toggle}
+ onToggleProjectPin={handleToggleProjectPin}
+ onRenameProject={handleProjectAliasChange}
+ onRemoveFromSidebar={handleRemoveProjectFromSidebar}
+ onCollapseAll={collapse.collapseAll}
+ onExpandAll={collapse.expandAll}
+ onCreateProject={handleCreateProject}
+ onCreateInProject={handleCreateInProject}
+ onOpenConversationSearch={handleOpenConversationSearch}
+ onOpenInExplorer={handleOpenInExplorer}
+ onLinkCodexProject={handleLinkCodexProject}
+ linkingCodexProject={linkingCodexProject}
+ onBrowseFiles={handleBrowseFiles}
+ onArchiveAll={handleArchiveAllInProject}
+ remoteDeviceIndex={remoteDeviceIndex}
+ onCreateDialogue={handleCreateDialogue}
+ isCreateDialogueDisabled={dialogueCreatePending}
+ />
+ </>
+ )}
</div>
</div>
</div>
@@ -3882,10 +3883,7 @@ function CollapsedView({
showDot={hasGhostUnread}
onClick={() => navigateToView('plugins')}
/>
- <GhostPanelRestoreEntry
- variant="rail"
- className={SIDEBAR_RAIL_ICON_BUTTON_CLASS}
- />
+ <GhostPanelRestoreEntry variant="rail" className={SIDEBAR_RAIL_ICON_BUTTON_CLASS} />
<ConversationSearchBox
navigate={navigate}
allKnownProjects={allSearchProjects}
@@ -4368,8 +4366,7 @@ function RailPanels({
disabled = false,
disabledReason?: string,
) => {
- const label =
- disabled && disabledReason ? `${actionLabel} — ${disabledReason}` : actionLabel;
+ const label = disabled && disabledReason ? `${actionLabel} — ${disabledReason}` : actionLabel;
return (
<Tip text={label} side="bottom">
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts
index 0c4e8587dd..c53117a6aa 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts
@@ -3,8 +3,11 @@ export function getVisibleSidebarSessionIds(root?: Document | Element | null): s
const queryRoot = root ?? document;
const ids: string[] = [];
const seen = new Set<string>();
- Array.from(queryRoot.querySelectorAll<HTMLElement>('[data-sidebar-session-row="true"][data-session-id]'))
- .filter(isRenderedVisible)
+ const coveringAncestors = findSearchOverlayCoveringAncestors(queryRoot);
+ Array.from(
+ queryRoot.querySelectorAll<HTMLElement>('[data-sidebar-session-row="true"][data-session-id]'),
+ )
+ .filter((node) => isRenderedVisible(node, coveringAncestors))
.sort(compareSidebarRowOrder)
.forEach((node) => {
const id = node.dataset.sessionId;
@@ -25,24 +28,48 @@ function compareSidebarRowOrder(a: HTMLElement, b: HTMLElement): number {
}
function getSidebarRowOrder(node: HTMLElement): number | null {
- const orderedRow = typeof node.closest === 'function'
- ? node.closest<HTMLElement>('[data-sidebar-row-order]')
- : null;
+ const orderedRow =
+ typeof node.closest === 'function'
+ ? node.closest<HTMLElement>('[data-sidebar-row-order]')
+ : null;
const raw = orderedRow?.dataset.sidebarRowOrder;
if (raw == null) return null;
const parsed = Number.parseInt(raw, 10);
return Number.isFinite(parsed) ? parsed : null;
}
-function isRenderedVisible(node: HTMLElement): boolean {
+function findSearchOverlayCoveringAncestors(queryRoot: Document | Element): Element[] {
+ const searchRoot =
+ queryRoot instanceof Document ? queryRoot : (queryRoot.ownerDocument ?? queryRoot);
+ if (typeof searchRoot.querySelectorAll !== 'function') return [];
+ const ancestors: Element[] = [];
+ for (const overlay of searchRoot.querySelectorAll('[data-conversation-search-overlay]')) {
+ if (!(overlay instanceof HTMLElement)) continue;
+ const ancestor = overlay.closest('aside, [data-sidebar], nav');
+ if (ancestor) ancestors.push(ancestor);
+ }
+ return ancestors;
+}
+
+function isRenderedVisible(node: HTMLElement, coveringAncestors: readonly Element[]): boolean {
+ if (isCoveredBySearchOverlay(node, coveringAncestors)) return false;
+ if (
+ typeof node.closest === 'function' &&
+ node.closest('[data-sidebar-section-collapsed="true"]')
+ ) {
+ return false;
+ }
const view = node.ownerDocument?.defaultView;
- if (isCoveredBySearchOverlay(node)) return false;
for (let current: HTMLElement | null = node; current != null; current = current.parentElement) {
if (current.hasAttribute?.('hidden')) return false;
const style = view?.getComputedStyle?.(current);
if (!style) continue;
- if (style.display === 'none' || style.visibility === 'hidden' || style.visibility === 'collapse') {
+ if (
+ style.display === 'none' ||
+ style.visibility === 'hidden' ||
+ style.visibility === 'collapse'
+ ) {
return false;
}
if (style.opacity !== '' && Number(style.opacity) === 0) return false;
@@ -51,18 +78,14 @@ function isRenderedVisible(node: HTMLElement): boolean {
}
/** Sidebar search sits on top of the real list without hiding it. */
-function isCoveredBySearchOverlay(node: HTMLElement): boolean {
+function isCoveredBySearchOverlay(
+ node: HTMLElement,
+ coveringAncestors: readonly Element[],
+): boolean {
+ if (coveringAncestors.length === 0) return false;
if (typeof node.closest !== 'function') return false;
if (node.closest('[data-conversation-search-overlay]')) return false;
- const root = node.ownerDocument;
- if (!root) return false;
- for (const overlay of root.querySelectorAll('[data-conversation-search-overlay]')) {
- if (!(overlay instanceof HTMLElement)) continue;
- if (overlay.contains(node)) continue;
- const ancestor = node.closest('aside, [data-sidebar], nav');
- if (ancestor && ancestor.contains(overlay)) return true;
- }
- return false;
+ return coveringAncestors.some((ancestor) => ancestor.contains(node));
}
export function pickSessionIdAfterRemoval(
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
index 45abbf43c6..5c4df0c077 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { memo, 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';
@@ -96,7 +96,7 @@ function isAutomationGroupInlineAction(target: EventTarget | null): boolean {
);
}
-export function AutomationSessionGroupItem({
+export const AutomationSessionGroupItem = memo(function AutomationSessionGroupItem({
group,
activeSessionId,
runningSessionIds,
@@ -835,4 +835,4 @@ export function AutomationSessionGroupItem({
)}
</div>
);
-}
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SectionCollapse.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SectionCollapse.tsx
index bd87cb0118..c8498b8654 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SectionCollapse.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SectionCollapse.tsx
@@ -2,9 +2,9 @@
* SectionCollapse —— 侧栏段落 / 项目树的展开收起高度动画容器。
* ---------------------------------------------------------------------------
* 用 CSS grid-template-rows 0fr ↔ 1fr 技巧做高度过渡:无需测量内容高度,
- * 任意动态内容都能平滑收展;内容保持挂载(列表滚动位置等内部状态默认不因
- * 卸载丢失),收起后由 min-h-0 + overflow-hidden 裁掉。调用方可按业务需要
- * 在收起动画完成后自行复位局部状态。
+ * 任意动态内容都能平滑收展。收起动画进行中仍挂载 children,播完后卸载,
+ * 避免「全部展开再收起」后隐藏子树继续占 React 协调成本。调用方可按业务
+ * 需要在收起动画完成后自行复位局部状态;卸载本身也会丢掉内部 state。
*
* 同步做透明度渐变(高度收起的同时文字渐隐,对齐 Codex 的收起手感);
* visibility 参与过渡 —— 收起动画播完后才隐藏(挡键盘焦点/交互),展开瞬间恢复。
@@ -14,6 +14,8 @@
* 额外 props(如 data-no-drag)透传到外层 grid 容器。
*/
+import { useEffect, useState } from 'react';
+
import { cn } from '@/lib/utils';
export const SECTION_COLLAPSE_DURATION_MS = 200;
@@ -32,6 +34,23 @@ export function SectionCollapse({
children,
...rest
}: SectionCollapseProps) {
+ const [keepChildren, setKeepChildren] = useState(!collapsed);
+
+ useEffect(() => {
+ if (!collapsed) {
+ setKeepChildren(true);
+ return undefined;
+ }
+ const timeoutId = window.setTimeout(() => {
+ setKeepChildren(false);
+ }, SECTION_COLLAPSE_DURATION_MS);
+ return () => {
+ window.clearTimeout(timeoutId);
+ };
+ }, [collapsed]);
+
+ const mounted = !collapsed || keepChildren;
+
return (
<div
{...rest}
@@ -43,6 +62,7 @@ export function SectionCollapse({
>
<div
aria-hidden={collapsed || undefined}
+ data-sidebar-section-collapsed={collapsed ? 'true' : undefined}
className={cn(
'min-h-0 overflow-hidden',
'transition-[opacity,visibility] duration-[200ms] ease-[cubic-bezier(0.4,0,0.2,1)] motion-reduce:duration-0',
@@ -50,7 +70,7 @@ export function SectionCollapse({
innerClassName,
)}
>
- {children}
+ {mounted ? children : null}
</div>
</div>
);
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
index 9b8f0ff590..ce62a35f59 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 { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { memo, useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import type {
DragEvent as ReactDragEvent,
MouseEvent as ReactMouseEvent,
@@ -140,7 +140,7 @@ export type SessionCardProps = SessionItemProps & {
hideBottomDivider?: boolean;
};
-export function SessionCard({
+export const SessionCard = memo(function SessionCard({
session,
isActive,
isRunning,
@@ -1186,7 +1186,7 @@ export function SessionCard({
)}
</div>
);
-}
+});
/** 右上角时间槽位——card / list 变体共用。默认显示 [worktree + 时间];hover/菜单打开
* 时整组让位给操作按钮(More + Archive/Undo),archivePending 时显示红色二次确认胶囊。
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.ts
index 3b10690856..ad4ac8a48d 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
@@ -18,16 +18,21 @@
*/
import { createElement, Fragment } from 'react';
-import { act, cleanup, createEvent, fireEvent, render, screen, within } from '@testing-library/react';
+import {
+ act,
+ cleanup,
+ createEvent,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { Session } from '@/lib/ccAgent.types';
-import {
- addSessionAttention,
- clearSessionAttention,
-} from '@/lib/sessionAttentionStore';
+import { addSessionAttention, clearSessionAttention } from '@/lib/sessionAttentionStore';
import { SessionAttentionUrgencyProvider } from '../../contexts/SessionAttentionUrgencyContext';
import { SPLIT_GROUP_SESSION_MIME } from '../../splitGroupDnd';
@@ -48,8 +53,7 @@ vi.mock('../SessionStatusIcon', () => ({
vi.mock('react-i18next', () => ({
useTranslation: () => ({
- t: (key: string, fallback?: unknown) =>
- typeof fallback === 'string' ? fallback : key,
+ t: (key: string, fallback?: unknown) => (typeof fallback === 'string' ? fallback : key),
}),
// 某些传递依赖(renderer/i18n/index.ts)在 import 期就调 initReactI18next,
// 提供最小 3rdParty 插件桩让它安静通过。
@@ -424,10 +428,7 @@ describe('父层 — 行级 handler 的引用稳定性', () => {
];
it('deps 里不得出现每条消息都换引用的 sessions / sessionsById', () => {
- const source = readFileSync(
- resolve(__dirname, '..', '..', 'CCAgentSidebarUpper.tsx'),
- 'utf8',
- );
+ const source = readFileSync(resolve(__dirname, '..', '..', 'CCAgentSidebarUpper.tsx'), 'utf8');
for (const name of ROW_HANDLERS) {
const deps = useCallbackDeps(source, name);
// 词边界保证 sessionsRef / sessionsByIdRef 不误伤。
@@ -440,10 +441,7 @@ describe('父层 — 行级 handler 的引用稳定性', () => {
// useSidebarFilter / useCollapsedProjects 都返回裸对象字面量,每次调用换引用。
// 必须依赖到具体成员(filter.promotePin、collapse.expand …),故用 (?!\.) 放行
// 成员访问、只拦整个对象。
- const source = readFileSync(
- resolve(__dirname, '..', '..', 'CCAgentSidebarUpper.tsx'),
- 'utf8',
- );
+ 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(?!\.)/);
@@ -452,31 +450,61 @@ describe('父层 — 行级 handler 的引用稳定性', () => {
});
it('deps 里不得出现随路由切换而变的 viewedSessionId', () => {
- const source = readFileSync(
- resolve(__dirname, '..', '..', 'CCAgentSidebarUpper.tsx'),
- 'utf8',
- );
+ 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/,
- );
+ expect(deps, `${name} 的 deps 不得含 viewedSessionId`).not.toMatch(/\bviewedSessionId\b/);
}
});
it('handleSessionClick 的 deps 不得含每次点击/切换都变的选择态', () => {
// 这三个只在点击那一刻读,却会被 setSelectionAnchorSessionId(每次点击必调)
// 和路由切换带着变 —— 留在 deps 里等于每切换一次就整表重画一遍。
- const source = readFileSync(
- resolve(__dirname, '..', '..', 'CCAgentSidebarUpper.tsx'),
- 'utf8',
- );
+ 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('handleSessionClick 的 deps 不得含点击清通知就会换引用的集合', () => {
+ // 点进去会先 clearNotification / 清 attention。这些 Set/Map 若留在 deps 里,
+ // 刚点的那一下就会重建 onClick,把「切任务」打成整表重画。
+ const source = readFileSync(resolve(__dirname, '..', '..', 'CCAgentSidebarUpper.tsx'), 'utf8');
+ const deps = useCallbackDeps(source, 'handleSessionClick');
+ expect(deps).not.toMatch(/\burgentSet\b/);
+ expect(deps).not.toMatch(/\battentionKinds\b/);
+ expect(deps).not.toMatch(/\brunningSessionIds\b/);
+ expect(deps).not.toMatch(/\bsidebarNotifications\b/);
+ });
+
+ it('无多选时不得每渲染扫描可见行', () => {
+ const source = readFileSync(resolve(__dirname, '..', '..', 'CCAgentSidebarUpper.tsx'), 'utf8');
+ expect(source).not.toMatch(
+ /useEffect\(\s*\(\)\s*=>\s*\{\s*pruneSelectionToRenderedRows\(\);\s*\}\s*\)/,
+ );
+ expect(source).toMatch(/if \(!hasSidebarSelection\) return undefined;/);
+ // 单击锚点不算多选:handleSessionClick 每次普通点击都会写
+ // selectionAnchorSessionId,观察器必须只由非空 selectedSessionIds 驱动。
+ expect(source).toMatch(/const hasSidebarSelection = selectedSessionIds\.size > 0;/);
+ expect(source).not.toMatch(/hasSidebarSelection = selectedSessionIds\.size > 0 \|\|/);
+ });
+
+ it('SessionCard / ProjectNode / AutomationSessionGroupItem 必须 memo 包裹', () => {
+ const sessionCard = readFileSync(resolve(__dirname, '..', 'SessionCard.tsx'), 'utf8');
+ const projectNode = readFileSync(
+ resolve(__dirname, '..', 'sections', 'ProjectNode.tsx'),
+ 'utf8',
+ );
+ const automationGroup = readFileSync(
+ resolve(__dirname, '..', 'AutomationSessionGroupItem.tsx'),
+ 'utf8',
+ );
+ expect(sessionCard).toMatch(/export const SessionCard = memo\(/);
+ expect(projectNode).toMatch(/export const ProjectNode = memo\(/);
+ expect(automationGroup).toMatch(/export const AutomationSessionGroupItem = memo\(/);
+ });
+
it('runningSessionIds 必须 memo 化(否则每渲染 new Set 打穿整表)', () => {
const source = readFileSync(
resolve(__dirname, '..', '..', '..', '..', 'hooks', 'useSessionRunningStatus.ts'),
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/hooks/useCollapsibleShowAll.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/hooks/useCollapsibleShowAll.ts
index 193d6bf555..4edb5f9c3b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/hooks/useCollapsibleShowAll.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/hooks/useCollapsibleShowAll.ts
@@ -5,8 +5,8 @@ import { SECTION_COLLAPSE_DURATION_MS } from '../SectionCollapse';
/**
* 「最多 N 条 + 显示全部」列表的 showAll 状态,段落收起后自动复位。
*
- * SectionCollapse 收起时内容保持挂载,showAll 不会随卸载归零,这里在收起后
- * 主动复位;复位延后到 200ms 收起动画结束后执行,避免动画过程中列表数量
+ * SectionCollapse 收起动画期间内容仍挂载,showAll 不会立刻随卸载归零,这里在
+ * 收起后主动复位;复位延后到 200ms 收起动画结束后执行,避免动画过程中列表数量
* 先缩短再收起造成视觉跳变。sectionCollapsed 只能传项目 / 段落自身的折叠态,
* 不要传 Sidebar peek / pinning 这类外壳状态;浮层预览和固定展开切换必须保留
* 列表内部状态。
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx
index 7a5d2ff224..7d5ca136be 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx
@@ -364,7 +364,7 @@ export function PinnedSection({
scrollbar-gutter:stable 预留的 12px(= pl-3,与全局 12px 滚动条等宽)补齐,
两侧视觉对称。卡片模式原先用 px-[11px],右侧在 gutter 之外又叠了 11px padding,
导致右留白(~23px)明显宽于左(11px)——改为 pr-0 后两侧都≈12px 且更窄。 */}
- {/* 段级收起走 SectionCollapse 高度动画(内容保持挂载)。 */}
+ {/* 段级收起走 SectionCollapse 高度动画,播完卸载子树。 */}
<SectionCollapse collapsed={collapsed}>
<div className={cn('flex flex-col gap-0.5', isCardLike ? 'pr-0 pl-3' : 'pt-1 pr-0 pl-3')}>
{/* 三种显示模式:
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.tsx
index 5a8309ec79..b8e47789ec 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
@@ -16,7 +16,7 @@
* - aria-expanded 反映 !isCollapsed
*/
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
import {
ChevronDown,
ChevronRight,
@@ -121,7 +121,7 @@ export interface ProjectNodeProps {
onArchiveAll: (project: ProjectNodeData) => void;
}
-export function ProjectNode({
+export const ProjectNode = memo(function ProjectNode({
project,
displaySessions,
sessionVariant = 'text',
@@ -621,7 +621,7 @@ export function ProjectNode({
</SectionCollapse>
</div>
);
-}
+});
interface ProjectActionProps {
label: string;