Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(sidebar): 降低千条任务下的打开延迟 (#4484)
Dashab910c7fa977
diff --git a/apps/desktop/scripts/benchmark-sidebar-grouping.ts b/apps/desktop/scripts/benchmark-sidebar-grouping.tsnew file mode 100644index 0000000000..5320e017c3--- /dev/null+++ b/apps/desktop/scripts/benchmark-sidebar-grouping.ts@@ -0,0 +1,92 @@+/** Run: pnpm --filter desktop exec vite-node --config vitest.config.ts scripts/benchmark-sidebar-grouping.ts+ * Pure computation benchmark, not click-to-paint latency. No user data/IPC writes.+ * Expanded sidebar has five variants; with no activity filter two are identical.+ */+import { performance } from 'node:perf_hooks';+import { deepStrictEqual } from 'node:assert';+import type { Session } from '@/lib/ccAgent.types';+import { groupSessions, type GroupSessionsOptions } from '@/features/cc-agent/lib/projectGrouping';+import { createProjectGroupsSelector } from '@/features/cc-agent/lib/projectGroupsSelector';+import { sessionCardVisualCases } from '@/features/cc-agent/sidebar/__fixtures__/sessionCardVisualCases';++const count = 1000;+const iterations = 200;+const rounds = 5;+const seed: Session[] = Array.from({ length: count }, (_, i) => ({+ ...sessionCardVisualCases[0].session,+ id: `benchmark-${i}`,+ title: `Benchmark ${i}`,+ workingDir: `/benchmark/projects/project-${i % 25}`,+ pinnedAt: i % 29 === 0 ? '2026-09-01T00:00:00.000Z' : null,+ userSendAt: new Date(Date.UTC(2026, 8, 1, 0, i)).toISOString(),+ updatedAt: new Date(Date.UTC(2026, 8, 1, 0, i)).toISOString(),+}));+const options: GroupSessionsOptions[] = [+ { includePinnedInProjects: false },+ { includePinnedInProjects: false },+ { includePinnedInProjects: true },+ { includePinnedInProjects: true },+ { includePinnedInProjects: true },+];+function run(optimized: boolean, structural: boolean) {+ let sessions = seed;+ const selectors = options.map(() => createProjectGroupsSelector());+ const project = () => {+ if (!optimized) return options.map((option) => groupSessions(sessions, option));+ const all = selectors[0](sessions, options[0]);+ const pinned = selectors[2](sessions, options[2]);+ return [all, all, pinned, pinned, selectors[4](sessions, options[4])];+ };+ project();+ const times: number[] = [];+ for (let i = 0; i < iterations; i++) {+ const index = i % count;+ sessions = sessions.slice();+ const updatedAt = new Date(Date.UTC(2026, 8, 15, 0, i)).toISOString();+ sessions[index] = {+ ...sessions[index],+ updatedAt,+ ...(structural ? { userSendAt: updatedAt } : {}),+ };+ const start = performance.now();+ project();+ times.push(performance.now() - start);+ }+ const results = project();+ for (let i = 0; i < options.length; i++)+ deepStrictEqual(results[i], groupSessions(sessions, options[i]));+ return times;+}+const summary = (values: number[]) => {+ const sorted = values.slice().sort((a, b) => a - b);+ return {+ samples: sorted.length,+ medianMs: +sorted[Math.floor(sorted.length / 2)].toFixed(3),+ p95Ms: +sorted[Math.ceil(sorted.length * 0.95) - 1].toFixed(3),+ totalMs: +sorted.reduce((a, b) => a + b, 0).toFixed(1),+ };+};+// Warm JIT for both algorithms; alternate order across rounds.+run(false, false);+run(true, false);+const result: Record<string, unknown> = {+ count,+ projects: 25,+ iterations,+ rounds,+ node: process.version,+};+for (const structural of [false, true]) {+ const before: number[] = [],+ after: number[] = [];+ for (let round = 0; round < rounds; round++) {+ for (const optimized of round % 2 ? [true, false] : [false, true]) {+ (optimized ? after : before).push(...run(optimized, structural));+ }+ }+ result[structural ? 'sortKeyUpdate' : 'timestampOnlyUpdate'] = {+ before: summary(before),+ after: summary(after),+ };+}+console.log(JSON.stringify(result, null, 2));diff --git a/apps/desktop/src/renderer/__tests__/automationSessionButton.test.tsx b/apps/desktop/src/renderer/__tests__/automationSessionButton.test.tsxnew file mode 100644index 0000000000..bfebc81191--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/automationSessionButton.test.tsx@@ -0,0 +1,67 @@+// @vitest-environment jsdom+import type { ReactNode } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter, useLocation } from 'react-router-dom';+import { AutomationSessionButton } from '@/features/cc-agent/sidebar/AutomationSessionButton';+import { loadScheduleSidebarIndexRuns } from '@/features/scheduler/lib/scheduleSidebarIndexRuns';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/components/ui/tooltip', () => ({+ Tip: ({ children }: { children: ReactNode }) => children,+}));+vi.mock('@/features/scheduler/lib/scheduleSidebarIndexRuns', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/features/scheduler/lib/scheduleSidebarIndexRuns')>()),+ loadScheduleSidebarIndexRuns: vi.fn(),+}));+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});+function Location() {+ const location = useLocation();+ return (+ <output data-testid="location">+ {location.pathname}+ {location.search}+ </output>+ );+}+function setup() {+ const parentClick = vi.fn();+ render(+ <MemoryRouter initialEntries={['/cc-agent/example']}>+ <div onClick={parentClick}>+ <AutomationSessionButton sessionId="task" size={10} activeForeground={false} />+ </div>+ <Location />+ </MemoryRouter>,+ );+ return parentClick;+}+describe('automation task navigation', () => {+ it('loads on demand, opens the latest matching schedule, and does not select the row', async () => {+ vi.mocked(loadScheduleSidebarIndexRuns).mockResolvedValue([+ { runId: 'older', scheduleId: 'old', sessionId: 'task', firedAt: 1 },+ { runId: 'newer', scheduleId: 'new schedule', sessionId: 'task', firedAt: 2 },+ ] as Awaited<ReturnType<typeof loadScheduleSidebarIndexRuns>>);+ const parentClick = setup();+ expect(loadScheduleSidebarIndexRuns).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button'));+ await waitFor(() =>+ expect(screen.getByTestId('location').textContent).toBe(+ '/cc-agent/scheduled?focus=new%20schedule',+ ),+ );+ expect(parentClick).not.toHaveBeenCalled();+ });+ it.each(['missing', 'error'])('falls back to the automation page when %s', async (kind) => {+ if (kind === 'missing') vi.mocked(loadScheduleSidebarIndexRuns).mockResolvedValue([]);+ else vi.mocked(loadScheduleSidebarIndexRuns).mockRejectedValue(new Error('offline'));+ setup();+ fireEvent.click(screen.getByRole('button'));+ await waitFor(() =>+ expect(screen.getByTestId('location').textContent).toBe('/cc-agent/scheduled'),+ );+ });+});diff --git a/apps/desktop/src/renderer/__tests__/iconButtonTooltips.test.ts b/apps/desktop/src/renderer/__tests__/iconButtonTooltips.test.tsindex c42d9c94b4..14896c978f 100644--- a/apps/desktop/src/renderer/__tests__/iconButtonTooltips.test.ts+++ b/apps/desktop/src/renderer/__tests__/iconButtonTooltips.test.ts@@ -230,8 +230,7 @@ function tooltipContractViolations(): string[] {const tooltipExemption = jsxAttribute(node, 'data-tooltip-exempt', sourceFile);const isWindowsSystemControlException =rendererRelativePath === WINDOWS_SYSTEM_CONTROL_PATH &&- staticAttributeValue(tooltipExemption) ===- WINDOWS_SYSTEM_CONTROL_TOOLTIP_EXEMPTION;+ staticAttributeValue(tooltipExemption) === WINDOWS_SYSTEM_CONTROL_TOOLTIP_EXEMPTION;const isIconControl =isInteractiveControl(node, sourceFile) &&!isHiddenFromAccessibilityTree &&@@ -239,9 +238,7 @@ function tooltipContractViolations(): string[] {if ((nativeTitle && isInteractiveControl(node, sourceFile) && !isTruncatedTextException) ||- (isIconControl &&- !isWindowsSystemControlException &&- !hasManagedTip(node, sourceFile))+ (isIconControl && !isWindowsSystemControlException && !hasManagedTip(node, sourceFile))) {const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));violations.push(`${rendererRelativePath}:${line + 1}`);@@ -290,9 +287,7 @@ describe('icon-only button tooltip coverage', () => {expect(menuButton).toContain("import { Tip } from '@/components/ui/tooltip';");expect(menuButton).toContain("text={t('titleBar.menu')}");expect(menuButton).toContain('const [menuOpen, setMenuOpen] = useState(false)');- expect(menuButton).toContain(- '<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>',- );+ expect(menuButton).toContain('<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>');expect(menuButton).toContain('<Tip text={t(\'titleBar.menu\')} side="bottom" controlledOpen={menuOpen ? false : undefined}>',);@@ -306,9 +301,7 @@ describe('icon-only button tooltip coverage', () => {);expect(windowControls).not.toContain("import { Tip } from '@/components/ui/tooltip';");expect(windowControls).not.toContain('<Tip');- expect(- windowControls.match(/data-tooltip-exempt="windows-system-control"/g),- ).toHaveLength(4);+ expect(windowControls.match(/data-tooltip-exempt="windows-system-control"/g)).toHaveLength(4);expect(windowControls).toContain("aria-label={t('titleBar.minimize')}");expect(windowControls).toContain("aria-label={t('titleBar.maximizeOrRestore')}");expect(windowControls).toContain("aria-label={t('titleBar.close')}");@@ -329,6 +322,9 @@ describe('icon-only button tooltip coverage', () => {it('does not exempt session-row icon actions from visible tips', () => {const sessionItem = rendererSource('features/cc-agent/sidebar/SessionItem.tsx');const sessionCard = rendererSource('features/cc-agent/sidebar/SessionCard.tsx');+ const automationButton = rendererSource(+ 'features/cc-agent/sidebar/AutomationSessionButton.tsx',+ );const actionStart = sessionItem.indexOf('function SessionAction(');const cardActionStart = sessionCard.indexOf('function CardAction(');@@ -336,8 +332,9 @@ describe('icon-only button tooltip coverage', () => {expect(cardActionStart).toBeGreaterThanOrEqual(0);expect(sessionItem.slice(actionStart)).toContain('<Tip text={label}');expect(sessionCard.slice(cardActionStart)).toContain('<Tip text={label}');- expect(sessionItem).toContain("<Tip text={t('ccAgent.sidebar.scheduleBinding.viewTask')}");- expect(sessionCard).toContain("<Tip text={t('ccAgent.sidebar.scheduleBinding.viewTask')}");+ expect(sessionItem).toContain('<AutomationSessionButton');+ expect(sessionCard).toContain('<AutomationSessionButton');+ expect(automationButton).toContain("<Tip text={t('ccAgent.sidebar.scheduleBinding.viewTask')}");expect(sessionItem).not.toContain("<Tip text={t('ccAgent.sidebar.automationGenerated')}");expect(sessionCard).not.toContain("<Tip text={t('ccAgent.sidebar.automationGenerated')}");expect(sessionItem).not.toContain('故意不挂 Tip 浮层');diff --git a/apps/desktop/src/renderer/__tests__/projectGroupsSelector.test.ts b/apps/desktop/src/renderer/__tests__/projectGroupsSelector.test.tsnew file mode 100644index 0000000000..5634e4f543--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/projectGroupsSelector.test.ts@@ -0,0 +1,127 @@+import { describe, expect, it } from 'vitest';+import type { Session } from '@/lib/ccAgent.types';+import { groupSessions, type GroupSessionsOptions } from '@/features/cc-agent/lib/projectGrouping';+import { createProjectGroupsSelector } from '@/features/cc-agent/lib/projectGroupsSelector';+import { sessionCardVisualCases } from '@/features/cc-agent/sidebar/__fixtures__/sessionCardVisualCases';++function fixtures(): Session[] {+ return Array.from({ length: 1000 }, (_, i) => ({+ ...sessionCardVisualCases[0].session,+ id: `task-${i}`,+ title: `Task ${i}`,+ workingDir: `/projects/project-${i % 25}`,+ pinnedAt: i % 29 === 0 ? '2026-09-01T00:00:00.000Z' : null,+ userSendAt: new Date(Date.UTC(2026, 8, 1, 0, i)).toISOString(),+ updatedAt: new Date(Date.UTC(2026, 8, 1, 0, i)).toISOString(),+ }));+}++describe('project grouping structural reuse', () => {+ it('updates timestamp/preview/spend without rebuilding untouched groups or stale row data', () => {+ const select = createProjectGroupsSelector();+ const sessions = fixtures();+ const before = select(sessions, {});+ const next = sessions.slice();+ next[1] = {+ ...next[1],+ updatedAt: '2026-09-15T00:00:00.000Z',+ preview: 'new',+ totalCostUsd: 3,+ };+ const after = select(next, {});+ expect(after).toEqual(groupSessions(next));+ expect(after.pinned).toBe(before.pinned);+ expect(after.projects.filter((p, i) => p === before.projects[i])).toHaveLength(24);+ expect(after.projects.flatMap((p) => p.sessions).find((s) => s.id === next[1].id)).toBe(+ next[1],+ );+ expect(select(next.slice(), {})).toBe(after);+ });++ it.each<Partial<Session>>([+ { userSendAt: '2026-09-20T00:00:00.000Z' },+ { workingDir: '/different/project' },+ { workspaceKind: 'dialogue' },+ { status: 'archived' },+ { pinnedAt: '2026-09-20T00:00:00.000Z' },+ { deviceLinkDeviceId: 'remote', deviceLinkDeviceName: 'Machine' },+ { deviceLinkConnectionStatus: 'disconnected' },+ { title: 'renamed' },+ { createdAt: '2020-01-01T00:00:00.000Z' },+ { _count: { messages: 0 } },+ ])('matches canonical grouping after mutation %j', (patch) => {+ const select = createProjectGroupsSelector();+ const sessions = fixtures();+ select(sessions, {});+ const next = sessions.slice();+ next[1] = { ...next[1], ...patch };+ expect(select(next, {})).toEqual(groupSessions(next));+ });++ it('preserves updatedAt sorting fallback for unsent tasks and draft placement', () => {+ const select = createProjectGroupsSelector();+ const sessions = fixtures();+ sessions[1] = { ...sessions[1], userSendAt: null, _count: { messages: 0 } };+ select(sessions, {});+ const next = sessions.slice();+ next[1] = { ...next[1], updatedAt: '2026-09-20T00:00:00.000Z' };+ expect(select(next, {})).toEqual(groupSessions(next));+ const withMessage = next.map((s, i) => (i === 1 ? { ...s, _count: { messages: 1 } } : s));+ expect(select(withMessage, {})).toEqual(groupSessions(withMessage));+ });++ it('invalidates aliases, persistent projects, bots, pin inclusion, insertion and removal', () => {+ const select = createProjectGroupsSelector();+ let sessions = fixtures();+ const options: GroupSessionsOptions[] = [+ {},+ { includePinnedInProjects: true },+ { projectAliases: new Map([['/projects/project-1', 'Alias']]) },+ {+ persistentLocalProjects: [+ { workingDir: '/empty', lastUsedAt: '2026-09-20', knownAgentKinds: ['cc'] },+ ],+ },+ {+ botOwnerBySessionId: new Map([+ ['task-1', { botId: 'bot', displayName: 'Bot', avatar: '', avatarColor: '' }],+ ]),+ },+ ];+ for (const option of options) {+ expect(select(sessions, option)).toEqual(groupSessions(sessions, option));+ sessions = sessions.slice(1);+ expect(select(sessions, option)).toEqual(groupSessions(sessions, option));+ }+ sessions = [...fixtures().slice(0, 1), ...sessions];+ expect(select(sessions, {})).toEqual(groupSessions(sessions));+ });++ it('reuses equivalent persistent catalogues while retaining fresh pinned, dialogue and bot rows', () => {+ const select = createProjectGroupsSelector();+ const sessions = fixtures();+ sessions[1] = { ...sessions[1], workspaceKind: 'dialogue' };+ const options: GroupSessionsOptions = {+ includePinnedInProjects: true,+ persistentLocalProjects: [+ { workingDir: '/empty', lastUsedAt: '2026-09-01', knownAgentKinds: ['cc'] },+ ],+ botOwnerBySessionId: new Map([+ ['task-2', { botId: 'b', displayName: 'Bot', avatar: '', avatarColor: '' }],+ ]),+ };+ const before = select(sessions, options);+ const next = sessions.map((s, i) =>+ i < 3 ? { ...s, title: 'fresh', updatedAt: '2026-09-20' } : s,+ );+ const after = select(next, {+ ...options,+ persistentLocalProjects: structuredClone(options.persistentLocalProjects),+ });+ expect(after).toEqual(groupSessions(next, options));+ expect(after.pinned[0]).toBe(next[0]);+ expect(after.dialogues[0]).toBe(next[1]);+ expect(after.bots[0].sessions[0]).toBe(next[2]);+ expect(after.projects.filter((p, i) => p === before.projects[i]).length).toBeGreaterThan(20);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.ts b/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.tsindex f7031883b8..610e67e831 100644--- a/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.ts+++ b/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.ts@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import {getVisibleSidebarSessionIds,@@ -34,6 +34,32 @@ describe('pickSessionIdAfterRemoval', () => {});describe('getVisibleSidebarSessionIds', () => {+ it('checks shared ancestors once per scan and observes later visibility changes', () => {+ const root = document.createElement('div');+ const group = document.createElement('section');+ root.append(group);+ for (let i = 0; i < 1000; i++) {+ const row = document.createElement('div');+ row.dataset.sidebarSessionRow = 'true';+ row.dataset.sessionId = String(i);+ group.append(row);+ }+ document.body.append(root);+ const spy = vi.spyOn(window, 'getComputedStyle');+ try {+ expect(getVisibleSidebarSessionIds(root)).toHaveLength(1000);+ expect(spy.mock.calls.filter(([node]) => node === group)).toHaveLength(1);+ expect(spy.mock.calls.filter(([node]) => node === root)).toHaveLength(1);+ group.style.opacity = '0';+ expect(getVisibleSidebarSessionIds(root)).toEqual([]);+ group.style.opacity = '1';+ expect(getVisibleSidebarSessionIds(root)).toHaveLength(1000);+ } finally {+ spy.mockRestore();+ root.remove();+ }+ });+it('reads sidebar row ids in DOM order and de-duplicates repeated rows', () => {const root = {querySelectorAll: () => [diff --git a/apps/desktop/src/renderer/__tests__/useProjectGroupsReuse.test.tsx b/apps/desktop/src/renderer/__tests__/useProjectGroupsReuse.test.tsxnew file mode 100644index 0000000000..8018aae7d8--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/useProjectGroupsReuse.test.tsx@@ -0,0 +1,91 @@+// @vitest-environment jsdom+import { memo } from 'react';+import { cleanup, render, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { Session } from '@/lib/ccAgent.types';+import { useProjectGroups } from '@/features/cc-agent/hooks/useProjectGroups';+import { sessionCardVisualCases } from '@/features/cc-agent/sidebar/__fixtures__/sessionCardVisualCases';++const state = vi.hoisted(() => ({ hosts: [] as unknown[], bots: [] as unknown[] }));+vi.mock('@/hooks/useRemoteSshHosts', () => ({ useRemoteSshHosts: () => state.hosts }));+vi.mock('@/features/bots/botStore', () => ({ useBotProfiles: () => state.bots }));+afterEach(cleanup);+const sessions = Array.from({ length: 1000 }, (_, i) => ({+ ...sessionCardVisualCases[0].session,+ id: `task-${i}`,+ pinnedAt: null,+ workingDir: `/projects/project-${i % 25}`,+}));++describe('project grouping hook references', () => {+ it('updates one project and one row on a timestamp patch; selection updates two rows', () => {+ let rowRenders = 0;+ const Row = memo(({ session, active }: { session: Session; active: boolean }) => {+ rowRenders++;+ return (+ <div data-active={active}>+ {session.id}:{session.updatedAt}+ </div>+ );+ });+ function Sidebar({ rows, selected }: { rows: Session[]; selected: string }) {+ const groups = useProjectGroups(rows);+ return groups.projects.map((p) => (+ <section key={p.projectKey}>+ {p.sessions.map((s) => (+ <Row key={s.id} session={s} active={s.id === selected} />+ ))}+ </section>+ ));+ }+ const view = render(<Sidebar rows={sessions} selected="task-0" />);+ expect(rowRenders).toBe(1000);+ const next = sessions.slice();+ next[1] = { ...next[1], updatedAt: '2026-09-15T00:00:00.000Z' };+ rowRenders = 0;+ view.rerender(<Sidebar rows={next} selected="task-0" />);+ expect(rowRenders).toBe(1);+ expect(view.container.textContent).toContain('2026-09-15T00:00:00.000Z');+ rowRenders = 0;+ view.rerender(<Sidebar rows={next} selected="task-2" />);+ expect(rowRenders).toBe(2);+ });++ it('keeps enriched projects stable and shares identical filtered results', () => {+ const { result, rerender } = renderHook(+ ({ rows }) => {+ const all = useProjectGroups(rows);+ const filtered = useProjectGroups(rows, undefined, false, undefined, '', all);+ return { all, filtered };+ },+ { initialProps: { rows: sessions } },+ );+ const before = result.current.all;+ expect(result.current.filtered).toBe(before);+ const rows = sessions.slice();+ rows[1] = { ...rows[1], updatedAt: '2026-09-15T00:00:00.000Z' };+ rerender({ rows });+ expect(result.current.filtered).toBe(result.current.all);+ expect(result.current.all.projects.filter((p, i) => p === before.projects[i])).toHaveLength(24);+ });+ it('refreshes cached machine labels when another device stops sharing its name', () => {+ const rows = sessions.slice(0, 2).map((s, i) => ({+ ...s,+ deviceLinkDeviceId: `device-${i}`,+ deviceLinkDeviceName: 'Same machine',+ }));+ const { result, rerender } = renderHook(({ rows }) => useProjectGroups(rows), {+ initialProps: { rows },+ });+ expect(result.current.projects.every((p) => p.remoteMachineIdentity?.detail)).toBe(true);+ const next = rows.slice();+ next[1] = { ...next[1], deviceLinkDeviceName: 'Renamed machine' };+ rerender({ rows: next });+ expect(result.current.projects.every((p) => p.remoteMachineIdentity?.detail === null)).toBe(+ true,+ );+ expect(+ result.current.projects.some((p) => p.remoteMachineIdentity?.label === 'Renamed machine'),+ ).toBe(true);+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex 0d42a80f69..c319f2f792 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -1127,8 +1127,10 @@ function ExpandedView({},[scheduleSessionIndex, remoteScheduleIndex],);- const { effectiveRunningSessionIds, displayRunningSessionIds } =- useSessionDisplayRunningState(sessions, runningSessionIds);+ const { effectiveRunningSessionIds, displayRunningSessionIds } = useSessionDisplayRunningState(+ sessions,+ runningSessionIds,+ );const collapsedAttentionToneFor = useCallback((sessions: readonly Session[]) =>resolveCollapsedProjectAttentionTone({@@ -1372,12 +1374,26 @@ function ExpandedView({visiblePersistentLocalProjects,localPlatform,);+ // Project pinning is independent from conversation pinning. This catalogue+ // keeps pinned conversations inside their project solely for project identity+ // and project-level actions; the normal project tree above remains deduped.+ const allProjectGroups = useProjectGroups(+ sidebarSessions,+ projectAliases.aliases,+ true,+ visiblePersistentLocalProjects,+ localPlatform,+ );const groups = useProjectGroups(activityFilteredSessions,projectAliases.aliases,false,activityFilteredPersistentLocalProjects,localPlatform,+ activityFilteredSessions === sidebarSessions &&+ activityFilteredPersistentLocalProjects === visiblePersistentLocalProjects+ ? allGroups+ : undefined,);// 普通项目目录也需要保留「所有会话都已单独置顶」的项目身份,供用户继续// 从 ProjectNode 菜单置顶整个项目;实际项目子行在渲染前仍会排除已置顶会话。@@ -1387,16 +1403,10 @@ function ExpandedView({true,activityFilteredPersistentLocalProjects,localPlatform,- );- // Project pinning is independent from conversation pinning. This catalogue- // keeps pinned conversations inside their project solely for project identity- // and project-level actions; the normal project tree above remains deduped.- const allProjectGroups = useProjectGroups(- sidebarSessions,- projectAliases.aliases,- true,- visiblePersistentLocalProjects,- localPlatform,+ activityFilteredSessions === sidebarSessions &&+ activityFilteredPersistentLocalProjects === visiblePersistentLocalProjects+ ? allProjectGroups+ : undefined,);const activeWorkingDirs = useMemo(() => allProjectGroups.projects.map((p) => p.projectKey),@@ -2682,6 +2692,12 @@ function ExpandedView({[filter, t],);+ // Event-only state: metadata updates recreate the collapsed Set even when+ // membership is unchanged. Do not propagate that identity to every task row.+ const collapsedProjectsForMoveRef = useRef(collapse.collapsed);+ useLayoutEffect(() => {+ collapsedProjectsForMoveRef.current = collapse.collapsed;+ }, [collapse.collapsed]);const handleMoveSession = useCallback(async (sessionId: string, target: SessionMoveTarget) => {const session = sessionsByIdRef.current.get(sessionId);@@ -2733,7 +2749,7 @@ function ExpandedView({const normalized = normalizeWorkingDir(targetWorkingDir);if (normalized) {expandedProjectKey = projectIdentityKey('local', normalized, null);- wasExpandedProjectCollapsed = collapse.collapsed.has(expandedProjectKey);+ wasExpandedProjectCollapsed = collapsedProjectsForMoveRef.current.has(expandedProjectKey);collapse.expand(expandedProjectKey);}}@@ -2764,16 +2780,7 @@ function ExpandedView({);}},- // 同理只依赖用到的三个成员,不要整个 collapse —— useCollapsedProjects 也返回- // 新对象字面量。collapsed 是 Set,仅用户手动折叠/展开时换引用,频率可忽略。- [- collapse.collapsed,- collapse.expand,- collapse.setCollapsed,- effectiveRunningSessionIds,- patchLocal,- t,- ],+ [collapse.expand, collapse.setCollapsed, effectiveRunningSessionIds, patchLocal, t],);/* ---- Delete / Archive / Unarchive action handlers ----@@ -3844,8 +3851,10 @@ function CollapsedView({// → lead 点亮)——与展开态 displayRunningSessionIds 同口径。RailNav 会滤掉// worker 行、只聚合 lead,不晋升会出现「面板里 lead 在跑、段灯与置顶瓷砖// 却不亮」(codex review)。- const { displayRunningSessionIds: railRunningIds } =- useSessionDisplayRunningState(sessions, runningSessionIds);+ const { displayRunningSessionIds: railRunningIds } = useSessionDisplayRunningState(+ sessions,+ runningSessionIds,+ );return (<divdiff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.tsindex 66a9baf7d9..cdea9127fd 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts@@ -3,21 +3,20 @@* ---------------------------------------------------------------------------* 包 `groupSessions` 纯函数并用 useMemo 锁结果,避免 render 时重复计算。*- * 注:useCCSessions 当前每次 fetch 都返回新数组引用,因此 sessions 引用变化- * 即触发重算。在 n ≤ 16 的规模下成本可忽略;如需进一步优化,可在- * useCCSessions 内做 deep-equal 短路(属于上游优化,不在本期范围)。+ * Row-only changes reuse grouping and replace just the affected session references.*/import { useMemo } from 'react';+import { createProjectGroupsSelector } from '../lib/projectGroupsSelector';import type { Session } from '@/lib/ccAgent.types';import { useRemoteSshHosts } from '@/hooks/useRemoteSshHosts';import { buildBotSessionOwners } from '@/features/bots/botSessionOwners';import { useBotProfiles } from '@/features/bots/botStore';import {- groupSessions,type PersistentLocalProject,type ProjectGroupsResult,+ type ProjectNode,} from '../lib/projectGrouping';import {collectAmbiguousDeviceNames,@@ -30,8 +29,11 @@ export function useProjectGroups(includePinnedInProjects: boolean = false,persistentLocalProjects?: readonly PersistentLocalProject[],localPlatform: string = '',+ /** Result from an earlier call with identical inputs (e.g. no activity filter). */+ equivalentResult?: ProjectGroupsResult,): ProjectGroupsResult {const sshHosts = useRemoteSshHosts();+ const selectGroups = useMemo(() => createProjectGroupsSelector(), []);/*伙伴归属表。会话行本身不带 botId,归属只有伙伴档案知道 —— 档案还没加载完的那一瞬间这张表是空的,伙伴任务就走原来的分组落到别处,**不会消失**。@@ -39,26 +41,19 @@ export function useProjectGroups(const botProfiles = useBotProfiles();const botOwnerBySessionId = useMemo(() => buildBotSessionOwners(botProfiles), [botProfiles]);- return useMemo(() => {- const groups = groupSessions(sessions, {+ const groups = useMemo(() => {+ if (equivalentResult) return equivalentResult;+ const groups = selectGroups(sessions, {projectAliases,includePinnedInProjects,botOwnerBySessionId,persistentLocalProjects,localPlatform,});- // 撞名判定要看全量项目(哪些设备名对应了多个 deviceId),所以先扫一遍再逐个富化。- const ambiguousDeviceNames = collectAmbiguousDeviceNames(groups.projects);- return {- ...groups,- projects: groups.projects.map((project) => ({- ...project,- remoteMachineIdentity: resolveRemoteProjectMachineIdentity(project, sshHosts, {- ambiguousDeviceNames,- }),- })),- };+ return groups;}, [+ equivalentResult,+ selectGroups,sessions,projectAliases,includePinnedInProjects,@@ -67,4 +62,33 @@ export function useProjectGroups(sshHosts,botOwnerBySessionId,]);+ const ambiguousDeviceNames = useMemo(+ () => collectAmbiguousDeviceNames(groups.projects),+ [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.+ const enrichedProjects = useMemo(+ () => new WeakMap<ProjectNode, ProjectNode>(),+ [sshHosts, ambiguityKey],+ );+ return useMemo(() => {+ if (equivalentResult) return equivalentResult;+ return {+ ...groups,+ projects: groups.projects.map((project) => {+ const cached = enrichedProjects.get(project);+ if (cached) return cached;+ const enriched = {+ ...project,+ remoteMachineIdentity: resolveRemoteProjectMachineIdentity(project, sshHosts, {+ ambiguousDeviceNames,+ }),+ };+ enrichedProjects.set(project, enriched);+ return enriched;+ }),+ };+ }, [groups, equivalentResult, enrichedProjects, sshHosts, ambiguousDeviceNames]);}diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/projectGroupsSelector.ts b/apps/desktop/src/renderer/features/cc-agent/lib/projectGroupsSelector.tsnew file mode 100644index 0000000000..58adb5981e--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/lib/projectGroupsSelector.ts@@ -0,0 +1,126 @@+import type { Session } from '@/lib/ccAgent.types';+import {+ groupSessions,+ type GroupSessionsOptions,+ type PersistentLocalProject,+ type ProjectGroupsResult,+} from './projectGrouping';++// These fields are displayed by rows, but do not determine membership, names,+// or ordering. Unknown/new fields deliberately fall back to full grouping.+const ROW_ONLY_FIELDS = new Set([+ 'title',+ 'preview',+ 'summary',+ 'totalCostUsd',+ 'totalMoney',+ 'totalTokenUsage',+ 'contextTokens',+ 'contextWindow',+ 'updatedAt',+]);++function sameGroupingInput(a: Session, b: Session): boolean {+ if ((a.userSendAt ?? a.updatedAt) !== (b.userSendAt ?? b.updatedAt)) 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]) {+ return false;+ }+ }+ return true;+}++function samePersistentProjects(+ a: readonly PersistentLocalProject[] | undefined,+ b: readonly PersistentLocalProject[] | undefined,+): boolean {+ return (+ a === b ||+ (!!a &&+ !!b &&+ a.length === b.length &&+ a.every((p, i) => {+ const next = b[i];+ return (+ p.workingDir === next.workingDir &&+ p.lastUsedAt === next.lastUsedAt &&+ p.knownAgentKinds.length === next.knownAgentKinds.length &&+ p.knownAgentKinds.every((kind, j) => kind === next.knownAgentKinds[j])+ );+ }))+ );+}++function sameOptions(a: GroupSessionsOptions, b: GroupSessionsOptions): boolean {+ return (+ a.projectAliases === b.projectAliases &&+ a.includePinnedInProjects === b.includePinnedInProjects &&+ a.includeDraftsInProjects === b.includeDraftsInProjects &&+ a.localPlatform === b.localPlatform &&+ a.botOwnerBySessionId === b.botOwnerBySessionId &&+ samePersistentProjects(a.persistentLocalProjects, b.persistentLocalProjects)+ );+}++/** One previous projection per hook; no global cache or retained session history.+ * Timestamp/preview/spend updates replace the affected row in its existing group.+ * All other changes use the canonical algorithm, including draft time fallback,+ * identity, pinning, aliases, bot ownership and remote connection state.+ */+export function createProjectGroupsSelector() {+ let previous:+ | {+ sessions: readonly Session[];+ options: GroupSessionsOptions;+ result: ProjectGroupsResult;+ }+ | undefined;++ return (sessions: readonly Session[], options: GroupSessionsOptions): ProjectGroupsResult => {+ let result: ProjectGroupsResult | undefined;+ if (+ previous &&+ sameOptions(previous.options, options) &&+ previous.sessions.length === sessions.length+ ) {+ const replacements = new Map<Session, Session>();+ const reusable = sessions.every((session, i) => {+ const old = previous!.sessions[i];+ if (old === session) return true;+ if (!sameGroupingInput(old, session)) return false;+ replacements.set(old, session);+ return true;+ });+ if (reusable) {+ const replaceRows = (rows: Session[]): Session[] =>+ rows.some((row) => replacements.has(row))+ ? rows.map((row) => replacements.get(row) ?? row)+ : rows;+ const replaceGroups = <T extends { sessions: Session[] }>(groups: T[]): T[] => {+ let changed = false;+ const next = groups.map((group) => {+ const rows = replaceRows(group.sessions);+ if (rows === group.sessions) return group;+ changed = true;+ return { ...group, sessions: rows };+ });+ return changed ? next : groups;+ };+ result =+ replacements.size === 0+ ? previous.result+ : {+ pinned: replaceRows(previous.result.pinned),+ dialogues: replaceRows(previous.result.dialogues),+ unclassified: replaceRows(previous.result.unclassified),+ bots: replaceGroups(previous.result.bots),+ projects: replaceGroups(previous.result.projects),+ };+ }+ }+ result ??= groupSessions(sessions, options);+ previous = { sessions, options, result };+ return result;+ };+}diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.tsindex c53117a6aa..ea907ffd94 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts@@ -3,11 +3,14 @@ export function getVisibleSidebarSessionIds(root?: Document | Element | null): sconst queryRoot = root ?? document;const ids: string[] = [];const seen = new Set<string>();+ // Local to this synchronous scan: shared ancestors are checked once, and no+ // visibility result survives a DOM/style change between scans.+ const styleVisibility = new Map<HTMLElement, boolean>();const coveringAncestors = findSearchOverlayCoveringAncestors(queryRoot);Array.from(queryRoot.querySelectorAll<HTMLElement>('[data-sidebar-session-row="true"][data-session-id]'),)- .filter((node) => isRenderedVisible(node, coveringAncestors))+ .filter((node) => isRenderedVisible(node, coveringAncestors, styleVisibility)).sort(compareSidebarRowOrder).forEach((node) => {const id = node.dataset.sessionId;@@ -51,7 +54,11 @@ function findSearchOverlayCoveringAncestors(queryRoot: Document | Element): Elemreturn ancestors;}-function isRenderedVisible(node: HTMLElement, coveringAncestors: readonly Element[]): boolean {+function isRenderedVisible(+ node: HTMLElement,+ coveringAncestors: readonly Element[],+ styleVisibility: Map<HTMLElement, boolean>,+): boolean {if (isCoveredBySearchOverlay(node, coveringAncestors)) return false;if (typeof node.closest === 'function' &&@@ -59,22 +66,23 @@ function isRenderedVisible(node: HTMLElement, coveringAncestors: readonly Elemen) {return false;}- const view = node.ownerDocument?.defaultView;- for (let current: HTMLElement | null = node; current != null; current = current.parentElement) {- if (current.hasAttribute?.('hidden')) return false;+ return hasVisibleStyleChain(node, styleVisibility);+}- const style = view?.getComputedStyle?.(current);- if (!style) continue;- if (- style.display === 'none' ||- style.visibility === 'hidden' ||- style.visibility === 'collapse'- ) {- return false;- }- if (style.opacity !== '' && Number(style.opacity) === 0) return false;- }- return true;+function hasVisibleStyleChain(node: HTMLElement, cache: Map<HTMLElement, boolean>): boolean {+ const cached = cache.get(node);+ if (cached !== undefined) return cached;+ const style = node.ownerDocument?.defaultView?.getComputedStyle?.(node);+ const visible =+ !node.hasAttribute?.('hidden') &&+ (!style ||+ (style.display !== 'none' &&+ style.visibility !== 'hidden' &&+ style.visibility !== 'collapse' &&+ (style.opacity === '' || Number(style.opacity) !== 0))) &&+ (!node.parentElement || hasVisibleStyleChain(node.parentElement, cache));+ cache.set(node, visible);+ return visible;}/** Sidebar search sits on top of the real list without hiding it. */diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionButton.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionButton.tsxnew file mode 100644index 0000000000..3f40371135--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionButton.tsx@@ -0,0 +1,56 @@+import { useNavigate } from 'react-router-dom';+import { useTranslation } from 'react-i18next';+import { Tip } from '@/components/ui/tooltip';+import { scheduleFocusPath } from '@/features/scheduler/lib/scheduleSessionBinding';+import {+ findLatestSidebarIndexRunForSession,+ loadScheduleSidebarIndexRuns,+} from '@/features/scheduler/lib/scheduleSidebarIndexRuns';+import { AutomationTimerIcon } from './AutomationTimerIcon';++// Keep the route subscription inside this optional control. Ordinary task rows+// must not subscribe to route changes merely to support an automation shortcut.+export function AutomationSessionButton({+ sessionId,+ size,+ activeForeground,+ centered = false,+}: {+ sessionId: string;+ size: number;+ activeForeground: boolean;+ centered?: boolean;+}) {+ const navigate = useNavigate();+ const { t } = useTranslation();+ const openSchedule = async () => {+ try {+ const runs = await loadScheduleSidebarIndexRuns();+ const hit = findLatestSidebarIndexRunForSession(runs, sessionId);+ navigate(hit ? scheduleFocusPath(hit.scheduleId) : '/cc-agent/scheduled');+ } catch {+ navigate('/cc-agent/scheduled');+ }+ };+ return (+ <Tip text={t('ccAgent.sidebar.scheduleBinding.viewTask')}>+ <button+ type="button"+ className={+ centered+ ? 'inline-flex shrink-0 cursor-pointer items-center justify-center focus:outline-none'+ : 'inline-flex shrink-0 cursor-pointer focus:outline-none'+ }+ aria-label={t('ccAgent.sidebar.scheduleBinding.viewTask')}+ onClick={(event) => {+ event.stopPropagation();+ void openSchedule();+ }}+ onKeyDown={centered ? (event) => event.stopPropagation() : undefined}+ onPointerDown={(event) => event.stopPropagation()}+ >+ <AutomationTimerIcon size={size} activeForeground={activeForeground} />+ </button>+ </Tip>+ );+}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsxindex 6df1bb3746..13ddd4e7d8 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx@@ -30,12 +30,11 @@ import type {} from 'react';import { Archive, ChevronRight, EllipsisVertical, Undo } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { useNavigate } from 'react-router-dom';import { cn } from '@/lib/utils';import { SessionStatusIcon } from './SessionStatusIcon';import { ScheduleBindingBadge } from './ScheduleBindingBadge';-import { AutomationTimerIcon } from './AutomationTimerIcon';+import { AutomationSessionButton } from './AutomationSessionButton';import { SessionOrdinalBadgeKbd, useSessionOrdinalBadge } from './sessionOrdinalBadges';import { useAgentIslandActivity } from '@/state/agentIslandActivity';import { makerChatStore } from '@/lib/makerChatStore';@@ -85,14 +84,7 @@ import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';import { useSessionAttentionUrgency } from '../contexts/SessionAttentionUrgencyContext';import { useRemoteSessionScheduleInfo } from '@/features/device-link/remoteProjectsStore';import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';-import {- useSessionBoundSchedules,- scheduleFocusPath,-} from '@/features/scheduler/lib/scheduleSessionBinding';-import {- findLatestSidebarIndexRunForSession,- loadScheduleSidebarIndexRuns,-} from '@/features/scheduler/lib/scheduleSidebarIndexRuns';+import { useSessionBoundSchedules } from '@/features/scheduler/lib/scheduleSessionBinding';import { projectSidebarSessionActivity, resolveSidebarRightStatus } from './sidebarRightStatus';import { Tip } from '@/components/ui/tooltip';import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';@@ -163,7 +155,6 @@ export const SessionCard = memo(function SessionCard({hideBottomDivider = false,}: SessionCardProps) {const { t } = useTranslation();- const navigate = useNavigate();const cindyMakePreparing = useCindyMakePreparing(session);// mod+1..9 序号徽标:模块 store 按 sessionId 精准订阅,非按住态恒为 null。const ordinalBadgeLabel = useSessionOrdinalBadge(session.id);@@ -508,20 +499,6 @@ export const SessionCard = memo(function SessionCard({setShareExportOpen(true);}, []);- const handleAutomationIconClick = useCallback(- async (e: React.MouseEvent) => {- e.stopPropagation();- try {- const runs = await loadScheduleSidebarIndexRuns();- const hit = findLatestSidebarIndexRunForSession(runs, session.id);- navigate(hit ? scheduleFocusPath(hit.scheduleId) : '/cc-agent/scheduled');- } catch {- navigate('/cc-agent/scheduled');- }- },- [session.id, navigate],- );-// 远程会话把归属设备冻进 `?device=`:发送时的引用解析不再依赖被控端此刻在线。const handleCopyDeepLinkSelect = useCallback(async () => {const link = buildSessionDeepLink(session.id, { deviceId: session.deviceLinkDeviceId });@@ -608,18 +585,12 @@ export const SessionCard = memo(function SessionCard({activeForeground={isActive}/>) : showAutomationTimer ? (- <Tip text={t('ccAgent.sidebar.scheduleBinding.viewTask')}>- <button- type="button"- className="inline-flex shrink-0 cursor-pointer items-center justify-center focus:outline-none"- aria-label={t('ccAgent.sidebar.scheduleBinding.viewTask')}- onClick={(e) => void handleAutomationIconClick(e)}- onKeyDown={(e) => e.stopPropagation()}- onPointerDown={(e) => e.stopPropagation()}- >- <AutomationTimerIcon size={iconSize} activeForeground={isActive} />- </button>- </Tip>+ <AutomationSessionButton+ sessionId={session.id}+ size={iconSize}+ activeForeground={isActive}+ centered+ />) : null;// list 变体标题前缀:状态图标 + 自动化徽章 + 间隔(保持 main 既有行为不变)。diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsxindex 67c89b370e..c087a7c999 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx@@ -32,7 +32,6 @@import { memo, 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 { useNavigate } from 'react-router-dom';import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';@@ -80,7 +79,6 @@ import {type ScheduleSidebarIndexRun,} from '@/features/scheduler/lib/scheduleSidebarIndexRuns';import { useSchedulesSnapshot } from '@/features/scheduler/lib/schedulesStore';-import { scheduleFocusPath } from '@/features/scheduler/lib/scheduleSessionBinding';import { ScheduleBindingBadge } from './ScheduleBindingBadge';import { SessionOrdinalBadgeKbd, useSessionOrdinalBadge } from './sessionOrdinalBadges';import { SessionProjectMoveSubmenu } from './SessionProjectMoveSubmenu';@@ -97,7 +95,7 @@ import { useRemoteSessionScheduleInfo } from '@/features/device-link/remoteProjeimport { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';import { useAgentIslandActivity } from '@/state/agentIslandActivity';import { projectSidebarSessionActivity, resolveSidebarRightStatus } from './sidebarRightStatus';-import { AutomationTimerIcon } from './AutomationTimerIcon';+import { AutomationSessionButton } from './AutomationSessionButton';import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';import {finishSessionDrag,@@ -436,19 +434,6 @@ export const SessionItem = memo(function SessionItem({// schedulesStore 'changed' 刷新 → 列表为空 → 徽章消失。const boundSchedules = useSessionBoundSchedules(session.id);const hasAutomationMeta = boundSchedules.length > 0 || isAutomationGenerated;- const navigate = useNavigate();- // 自动化创建(非绑定)会话的 Timer 点击:scheduleId 不在 Session 上,点击时查- // sidebar index runs(sessionId → scheduleId)再跳;查不到(run 已删等)退化为- // 直接打开自动化页。一次性点击查询,不在渲染路径上常驻拉数据。- const handleAutomationIconClick = useCallback(async () => {- try {- const runs = await loadScheduleSidebarIndexRuns();- const hit = findLatestSidebarIndexRunForSession(runs, session.id);- navigate(hit ? scheduleFocusPath(hit.scheduleId) : '/cc-agent/scheduled');- } catch {- navigate('/cc-agent/scheduled');- }- }, [session.id, navigate]);// 单个 automation-generated 会话行的「schedule 反查」:sessionId → scheduleId 走// sidebar-index-runs(Session 上没有 scheduleId 字段)。用于两处:// 1. 门控 Run 按钮的可见性 —— schedule 已被删除但会话保留(disposition@@ -1039,20 +1024,7 @@ export const SessionItem = memo(function SessionItem({{boundSchedules.length > 0 ? (<ScheduleBindingBadge schedules={boundSchedules} activeForeground={isActive} />) : isAutomationGenerated ? (- <Tip text={t('ccAgent.sidebar.scheduleBinding.viewTask')}>- <button- type="button"- className="inline-flex shrink-0 cursor-pointer focus:outline-none"- aria-label={t('ccAgent.sidebar.scheduleBinding.viewTask')}- onClick={(e) => {- e.stopPropagation();- void handleAutomationIconClick();- }}- onPointerDown={(e) => e.stopPropagation()}- >- <AutomationTimerIcon size={10} activeForeground={isActive} />- </button>- </Tip>+ <AutomationSessionButton sessionId={session.id} size={10} activeForeground={isActive} />) : null}<SidebarTitleMarqueetitle={displayTitle}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.tsindex cdf42b464b..8f27c65253 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts@@ -7,6 +7,10 @@ const sidebarDir = resolve(__dirname, '..');const sessionCardSource = readFileSync(resolve(sidebarDir, 'SessionCard.tsx'), 'utf8');const sessionEntryListSource = readFileSync(resolve(sidebarDir, 'SessionEntryList.tsx'), 'utf8');const sessionItemSource = readFileSync(resolve(sidebarDir, 'SessionItem.tsx'), 'utf8');+const automationSessionButtonSource = readFileSync(+ resolve(sidebarDir, 'AutomationSessionButton.tsx'),+ 'utf8',+);const sessionOrdinalBadgeSource = readFileSync(resolve(sidebarDir, 'sessionOrdinalBadges.tsx'),'utf8',@@ -162,8 +166,10 @@ describe('SessionCard review regressions', () => {);// schedule 绑定与普通自动化都复用 AutomationTimerIcon;绑定态优先承载更多状态。expect(sessionCardSource).toMatch(- /const renderAutomationMeta = \(iconSize: number\) =>[\s\S]*?showScheduleBindingBadge \? \([\s\S]*?<ScheduleBindingBadge[\s\S]*?schedules=\{boundSchedules\}[\s\S]*?size=\{iconSize\}[\s\S]*?activeForeground=\{isActive\}[\s\S]*?\) : showAutomationTimer \? \([\s\S]*?<AutomationTimerIcon size=\{iconSize\}/,+ /const renderAutomationMeta = \(iconSize: number\) =>[\s\S]*?showScheduleBindingBadge \? \([\s\S]*?<ScheduleBindingBadge[\s\S]*?schedules=\{boundSchedules\}[\s\S]*?size=\{iconSize\}[\s\S]*?activeForeground=\{isActive\}[\s\S]*?\) : showAutomationTimer \? \([\s\S]*?<AutomationSessionButton[\s\S]*?size=\{iconSize\}/,);+ expect(automationSessionButtonSource.match(/<AutomationTimerIcon\b/g)).toHaveLength(1);+ expect(automationSessionButtonSource).toContain('size={size}');expect(sessionCardSource).toContain('{renderAutomationMeta(10)}');expect(sessionCardSource).toContain('{renderAutomationMeta(11)}');});@@ -403,7 +409,10 @@ describe('SessionCard review regressions', () => {// 否则红胶囊上 Timer 仍是 meta 灰;普通自动化分支也必须透传 activeForeground。expect(sessionCardSource).toContain('activeForeground={isActive}');expect(sessionCardSource).toMatch(- /showAutomationTimer \? \([\s\S]*?<AutomationTimerIcon[\s\S]*?activeForeground=\{isActive\}/,+ /showAutomationTimer \? \([\s\S]*?<AutomationSessionButton[\s\S]*?activeForeground=\{isActive\}/,+ );+ expect(automationSessionButtonSource).toMatch(+ /<AutomationTimerIcon[\s\S]*?activeForeground=\{activeForeground\}/,);});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 c0a71545e7..c7981d6734 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@@ -305,11 +305,12 @@ export function ProjectsSection({// SortableList 只在自定义项目顺序且按项目分组时挂载。// 折叠溢出且未点「显示全部」时禁用,避免只重排可见前缀。const projectOrderScope = projectOrderWriteScopeForSelection(selectedMachineForOrder);- const hostSnapshotForDisplay = projectOrderScope.kind === 'host' && projectOrderScope.deviceId === null- ? localHostProjectOrder.snapshot- : projectOrderScope.kind === 'host' && projectOrderScope.deviceId- ? remoteHostProjectOrders.orders.get(projectOrderScope.deviceId)- : undefined;+ 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,@@ -317,10 +318,11 @@ export function ProjectsSection({projectOrderScope.kind === 'host' && projectOrderScope.deviceId === null? localHostProjectOrder.snapshot.manualProjectOrder: projectOrderScope.kind === 'host' && projectOrderScope.deviceId- ? controllerManualOrderForDevice(projectOrderScope.deviceId, hostSnapshotForDisplay) ?? []+ ? (controllerManualOrderForDevice(projectOrderScope.deviceId, hostSnapshotForDisplay) ?? []): [],);- const customProjectOrder = filter.groupBy === 'project' && displayedProjectOrder.projectOrder === 'custom';+ const customProjectOrder =+ filter.groupBy === 'project' && displayedProjectOrder.projectOrder === 'custom';const projectDragEnabled = customProjectOrder;const projectKeysForOrderBaseline = allProjectKeysForOrder;// 段级收起已随「全部任务 = 范围下拉」取消(2026-08-13 用户定稿):标题的点击@@ -341,18 +343,27 @@ export function ProjectsSection({// 语义(mergeVisibleReorder),而不是把它们甩到末尾(否则切回「所有」时其它机器项目的相对// 位置会被无关拖拽悄悄打乱)。做法:先取全量规范顺序作 baseline,再把可见新序原位填回。const scope = projectOrderWriteScopeForSelection(selectedMachineForOrder);- const hostSnapshot = scope.kind === 'host' && scope.deviceId === null- ? localHostProjectOrder.snapshot- : scope.kind === 'host' && scope.deviceId- ? remoteHostProjectOrders.orders.get(scope.deviceId)- : undefined;+ const hostSnapshot =+ scope.kind === 'host' && scope.deviceId === null+ ? localHostProjectOrder.snapshot+ : scope.kind === 'host' && scope.deviceId+ ? remoteHostProjectOrders.orders.get(scope.deviceId)+ : undefined;const persistViewer = (order: readonly string[]) => {- const fullOrder = normalizeManualProjectOrder(filter.manualProjectOrder, projectKeysForOrderBaseline, localPlatform);+ const fullOrder = normalizeManualProjectOrder(+ filter.manualProjectOrder,+ projectKeysForOrderBaseline,+ localPlatform,+ );const merged = mergeVisibleReorder(fullOrder, order, projectComparisonKey);filter.setManualProjectOrder(merged, projectKeysForOrderBaseline);if (filter.projectOrder !== 'custom') filter.setProjectOrder('custom');};- if (projectOrderWriteLedger(scope, hostSnapshot) === 'host' && scope.kind === 'host' && scope.deviceId === null) {+ if (+ projectOrderWriteLedger(scope, hostSnapshot) === 'host' &&+ scope.kind === 'host' &&+ scope.deviceId === null+ ) {const localKeys = projectKeysForOrderBaseline.filter((key) => key.startsWith('local:'));const fullOrder = normalizeManualProjectOrder(localHostProjectOrder.snapshot.manualProjectOrder,@@ -360,29 +371,38 @@ export function ProjectsSection({localPlatform,);const next = mergeVisibleReorder(fullOrder, visibleNewOrder, projectComparisonKey);- void localHostProjectOrder.apply({- manualProjectOrder: next,- projectOrder: 'custom',- }).then((result) => {- if (result.kind === 'unavailable') persistViewer(visibleNewOrder);- });+ void localHostProjectOrder+ .apply({+ manualProjectOrder: next,+ projectOrder: 'custom',+ })+ .then((result) => {+ if (result.kind === 'unavailable') persistViewer(visibleNewOrder);+ });return;}- if (projectOrderWriteLedger(scope, hostSnapshot) === 'host' && scope.kind === 'host' && scope.deviceId) {+ if (+ projectOrderWriteLedger(scope, hostSnapshot) === 'host' &&+ scope.kind === 'host' &&+ scope.deviceId+ ) {const deviceId = scope.deviceId;- const remoteKeys = projectKeysForOrderBaseline.filter((key) => key.startsWith(`device:${encodeURIComponent(deviceId)}:`));- const current = controllerManualOrderForDevice(- deviceId,- remoteHostProjectOrders.orders.get(deviceId),- ) ?? [];+ const remoteKeys = projectKeysForOrderBaseline.filter((key) =>+ key.startsWith(`device:${encodeURIComponent(deviceId)}:`),+ );+ const current =+ controllerManualOrderForDevice(deviceId, remoteHostProjectOrders.orders.get(deviceId)) ??+ [];const fullOrder = normalizeManualProjectOrder(current, remoteKeys, localPlatform);const next = mergeVisibleReorder(fullOrder, visibleNewOrder, projectComparisonKey);- void remoteHostProjectOrders.apply(deviceId, {- manualProjectOrder: next,- projectOrder: 'custom',- }).then((result) => {- if (result.kind === 'unavailable') persistViewer(visibleNewOrder);- });+ void remoteHostProjectOrders+ .apply(deviceId, {+ manualProjectOrder: next,+ projectOrder: 'custom',+ })+ .then((result) => {+ if (result.kind === 'unavailable') persistViewer(visibleNewOrder);+ });return;}persistViewer(visibleNewOrder);@@ -429,7 +449,8 @@ export function ProjectsSection({notifications,attentionKinds,urgentSessionIds: urgentSet,- remotePhaseOf: (sessionId, deviceId) => getRemoteSessionActivity(sessionId, deviceId)?.phase,+ remotePhaseOf: (sessionId, deviceId) =>+ getRemoteSessionActivity(sessionId, deviceId)?.phase,}),// eslint-disable-next-line react-hooks/exhaustive-deps -- remoteActivityRevision 代表 getRemoteSessionActivity 读到的整表内容[runningSessionIds, notifications, attentionKinds, urgentSet, remoteActivityRevision],@@ -495,7 +516,11 @@ export function ProjectsSection({useEffect(() => {const settled = new Set<string>();const considerRemote = (session: Session) => {- if (isRemoteSessionActivityActive(getRemoteSessionActivity(session.id, session.deviceLinkDeviceId))) {+ if (+ isRemoteSessionActivityActive(+ getRemoteSessionActivity(session.id, session.deviceLinkDeviceId),+ )+ ) {settled.add(session.id);}};@@ -820,7 +845,13 @@ export function ProjectsSection({collapsed.has(project.projectKey) ? collapsedAttentionToneFor(project.sessions) : null}parentSectionCollapsed={false}- activeSessionId={activeSessionId}+ // Unrelated projects keep an undefined selection prop across navigation,+ // so ProjectNode's memo need not rebuild every session list on a click.+ activeSessionId={+ project.sessions.some((session) => session.id === activeSessionId)+ ? activeSessionId+ : undefined+ }runningSessionIds={runningSessionIds}attachedSessionIds={attachedSessionIds}notifications={notifications}@@ -997,184 +1028,184 @@ export function ProjectsSection({}/>{hasMainListContent ? (- <div className="relative flex flex-col gap-1 pt-1 pr-0 pl-3">- {!deviceGroupingActive ? (- <UnclassifiedSection- sessions={unclassified}- hidden={unclassifiedHidden}- activeSessionId={activeSessionId}- runningSessionIds={runningSessionIds}- attachedSessionIds={attachedSessionIds}- notifications={notifications}- scheduleSessionIndex={scheduleSessionIndex}- selectedSessionIds={selectedSessionIds}- onSessionClick={onSessionClick}- onAction={onAction}- onRename={onRename}- onTogglePin={onTogglePin}- onMoveSession={onMoveSession}- projectOptions={projectOptions}- onScheduleAction={onScheduleAction}- sessionVariant={mainSessionVariant}- />- ) : null}- {/* 混排渲染(D / E 期):+ <div className="relative flex flex-col gap-1 pt-1 pr-0 pl-3">+ {!deviceGroupingActive ? (+ <UnclassifiedSection+ sessions={unclassified}+ hidden={unclassifiedHidden}+ activeSessionId={activeSessionId}+ runningSessionIds={runningSessionIds}+ attachedSessionIds={attachedSessionIds}+ notifications={notifications}+ scheduleSessionIndex={scheduleSessionIndex}+ selectedSessionIds={selectedSessionIds}+ onSessionClick={onSessionClick}+ onAction={onAction}+ onRename={onRename}+ onTogglePin={onTogglePin}+ onMoveSession={onMoveSession}+ projectOptions={projectOptions}+ onScheduleAction={onScheduleAction}+ sessionVariant={mainSessionVariant}+ />+ ) : null}+ {/* 混排渲染(D / E 期):- 自定义项目顺序:模型保证项目行连续在前 → 项目段走 SortableList,其后是散排对话 / 对话组。折叠+溢出时禁用拖拽,点「显示全部」后再拖。可与设备分组叠加:每段各自拖本段项目。- 按最近活动:按 deviceSections 切段(设备分组开启时),段内项目行与散排对话按任务排序口径交错,项目行不可拖。 */}- {customProjectOrder && !deviceGroupingActive ? (- <>- <SortableList- items={visibleProjectNodes}- getId={getProjectId}- onReorder={handleReorder}- disabled={!projectDragEnabled || (projectsOverflow && !showAllProjects)}- reducedMotion={reducedMotion}- handle={MANUAL_PROJECT_SORT_HANDLE}- filter={MANUAL_PROJECT_SORT_FILTER}- className="flex flex-col gap-1"- renderItem={(project) => renderProjectNode(project)}- />- {visibleMixedEntries- .filter((entry) => entry.kind !== 'project')- .map((entry) => renderNonProjectEntry(entry, DIALOGUE_GROUP_ALL_KEY))}- </>- ) : deviceGroupingActive ? (- <div className="flex flex-col gap-1">- {deviceSections.map((section) => {- const key = deviceSectionKey(section.deviceId);- const device = section.deviceId- ? remoteDeviceIndex?.get(section.deviceId)- : undefined;- const name = section.deviceId- ? (device?.name ?? section.deviceId)- : t('ccAgent.sidebar.deviceGroup.local');- const online = section.deviceId ? (device?.online ?? false) : true;- const sectionCollapsed = collapsedDevices.has(key);- return (- <div key={key} className="flex flex-col gap-1">- {/* 设备分组头:可折叠。在线设备不画状态点;离线设备保留灰点与文字提示。 */}- <DeviceSectionHeader deviceId={section.deviceId} name={name}>- <button- type="button"- onClick={() => toggleDeviceSection(key)}- aria-expanded={!sectionCollapsed}- aria-label={- sectionCollapsed- ? t('ccAgent.sidebar.deviceGroup.expand')- : t('ccAgent.sidebar.deviceGroup.collapse')- }- className={cn(- 'flex h-6 min-w-0 flex-1 items-center gap-1.5 rounded-full px-1.5',- 'text-[var(--sidebar-list-muted)] transition-colors hover:text-[var(--sidebar-nav-text)]',- )}- >- {sectionCollapsed ? (- <ChevronRight size={12} strokeWidth={2} className="shrink-0" />- ) : (- <ChevronDown size={12} strokeWidth={2} className="shrink-0" />- )}- <MonitorSmartphone size={13} strokeWidth={2} className="shrink-0" />- <span className="min-w-0 truncate text-xs font-medium">{name}</span>- {!online && (- <span- aria-hidden- className="size-1.5 shrink-0 rounded-full bg-[var(--text-tertiary)]"- />- )}- {/* 条数已去掉(2026-08-12 用户裁决):它数的是顶层条目+ {customProjectOrder && !deviceGroupingActive ? (+ <>+ <SortableList+ items={visibleProjectNodes}+ getId={getProjectId}+ onReorder={handleReorder}+ disabled={!projectDragEnabled || (projectsOverflow && !showAllProjects)}+ reducedMotion={reducedMotion}+ handle={MANUAL_PROJECT_SORT_HANDLE}+ filter={MANUAL_PROJECT_SORT_FILTER}+ className="flex flex-col gap-1"+ renderItem={(project) => renderProjectNode(project)}+ />+ {visibleMixedEntries+ .filter((entry) => entry.kind !== 'project')+ .map((entry) => renderNonProjectEntry(entry, DIALOGUE_GROUP_ALL_KEY))}+ </>+ ) : deviceGroupingActive ? (+ <div className="flex flex-col gap-1">+ {deviceSections.map((section) => {+ const key = deviceSectionKey(section.deviceId);+ const device = section.deviceId+ ? remoteDeviceIndex?.get(section.deviceId)+ : undefined;+ const name = section.deviceId+ ? (device?.name ?? section.deviceId)+ : t('ccAgent.sidebar.deviceGroup.local');+ const online = section.deviceId ? (device?.online ?? false) : true;+ const sectionCollapsed = collapsedDevices.has(key);+ return (+ <div key={key} className="flex flex-col gap-1">+ {/* 设备分组头:可折叠。在线设备不画状态点;离线设备保留灰点与文字提示。 */}+ <DeviceSectionHeader deviceId={section.deviceId} name={name}>+ <button+ type="button"+ onClick={() => toggleDeviceSection(key)}+ aria-expanded={!sectionCollapsed}+ aria-label={+ sectionCollapsed+ ? t('ccAgent.sidebar.deviceGroup.expand')+ : t('ccAgent.sidebar.deviceGroup.collapse')+ }+ className={cn(+ 'flex h-6 min-w-0 flex-1 items-center gap-1.5 rounded-full px-1.5',+ 'text-[var(--sidebar-list-muted)] transition-colors hover:text-[var(--sidebar-nav-text)]',+ )}+ >+ {sectionCollapsed ? (+ <ChevronRight size={12} strokeWidth={2} className="shrink-0" />+ ) : (+ <ChevronDown size={12} strokeWidth={2} className="shrink-0" />+ )}+ <MonitorSmartphone size={13} strokeWidth={2} className="shrink-0" />+ <span className="min-w-0 truncate text-xs font-medium">{name}</span>+ {!online && (+ <span+ aria-hidden+ className="size-1.5 shrink-0 rounded-full bg-[var(--text-tertiary)]"+ />+ )}+ {/* 条数已去掉(2026-08-12 用户裁决):它数的是顶层条目(项目行 + 散排对话 + 对话组),不是任务数,读起来只会误导;段展开后内容本身就是答案。「离线」接手 ml-auto 保持靠右。 */}- {!online && (- <span className="ml-auto shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">- {t('ccAgent.sidebar.deviceGroup.offline')}- </span>- )}- </button>- </DeviceSectionHeader>- <SectionCollapse collapsed={sectionCollapsed}>- <div className="flex flex-col gap-1 pl-2">- {/* 折叠上限每段独立应用(切段在前,见 deviceSections 注释);+ {!online && (+ <span className="ml-auto shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">+ {t('ccAgent.sidebar.deviceGroup.offline')}+ </span>+ )}+ </button>+ </DeviceSectionHeader>+ <SectionCollapse collapsed={sectionCollapsed}>+ <div className="flex flex-col gap-1 pl-2">+ {/* 折叠上限每段独立应用(切段在前,见 deviceSections 注释);「显示全部」的作用域同样是段内(expandedDeviceSections)。 */}- {(() => {- const sectionView = collapseEntries(- section.entries,- expandedDeviceSections.has(key),- );- const sectionDialogueTarget = section.deviceId- ? { deviceId: section.deviceId, deviceName: name }- : null;- const sectionProjects = sectionView.visibleEntries- .filter(- (entry): entry is Extract<MainListEntry, { kind: 'project' }> =>- entry.kind === 'project',- )- .map((entry) => entry.project);- return (- <>- {customProjectOrder ? (- <>- <SortableList- items={sectionProjects}- getId={getProjectId}- onReorder={handleReorder}- disabled={- !projectDragEnabled ||- (sectionView.isOverflowing &&- !expandedDeviceSections.has(key))+ {(() => {+ const sectionView = collapseEntries(+ section.entries,+ expandedDeviceSections.has(key),+ );+ const sectionDialogueTarget = section.deviceId+ ? { deviceId: section.deviceId, deviceName: name }+ : null;+ const sectionProjects = sectionView.visibleEntries+ .filter(+ (entry): entry is Extract<MainListEntry, { kind: 'project' }> =>+ entry.kind === 'project',+ )+ .map((entry) => entry.project);+ return (+ <>+ {customProjectOrder ? (+ <>+ <SortableList+ items={sectionProjects}+ getId={getProjectId}+ onReorder={handleReorder}+ disabled={+ !projectDragEnabled ||+ (sectionView.isOverflowing &&+ !expandedDeviceSections.has(key))+ }+ reducedMotion={reducedMotion}+ handle={MANUAL_PROJECT_SORT_HANDLE}+ filter={MANUAL_PROJECT_SORT_FILTER}+ className="flex flex-col gap-1"+ renderItem={(project) => renderProjectNode(project)}+ />+ {sectionView.visibleEntries+ .filter((entry) => entry.kind !== 'project')+ .map((entry) =>+ renderNonProjectEntry(entry, key, sectionDialogueTarget),+ )}+ </>+ ) : (+ sectionView.visibleEntries.map((entry) =>+ entry.kind === 'project'+ ? renderProjectNode(entry.project)+ : renderNonProjectEntry(entry, key, sectionDialogueTarget),+ )+ )}+ {sectionView.isOverflowing && (+ <ShowAllEntriesButton+ count={sectionView.totalCount}+ onClick={() =>+ setExpandedDeviceSections((prev) => new Set(prev).add(key))}- reducedMotion={reducedMotion}- handle={MANUAL_PROJECT_SORT_HANDLE}- filter={MANUAL_PROJECT_SORT_FILTER}- className="flex flex-col gap-1"- renderItem={(project) => renderProjectNode(project)}/>- {sectionView.visibleEntries- .filter((entry) => entry.kind !== 'project')- .map((entry) =>- renderNonProjectEntry(entry, key, sectionDialogueTarget),- )}- </>- ) : (- sectionView.visibleEntries.map((entry) =>- entry.kind === 'project'- ? renderProjectNode(entry.project)- : renderNonProjectEntry(entry, key, sectionDialogueTarget),- )- )}- {sectionView.isOverflowing && (- <ShowAllEntriesButton- count={sectionView.totalCount}- onClick={() =>- setExpandedDeviceSections((prev) => new Set(prev).add(key))- }- />- )}- </>- );- })()}- </div>- </SectionCollapse>- </div>- );- })}- </div>- ) : (- <div className="flex flex-col gap-1">- {visibleMixedEntries.map((entry) =>- entry.kind === 'project'- ? renderProjectNode(entry.project)- : renderNonProjectEntry(entry, DIALOGUE_GROUP_ALL_KEY),- )}- </div>- )}- {/* 全局「显示全部」只属于未按设备分组的单段路径;设备分组下折叠与 footer 都在段内。 */}- {!deviceGroupingActive && projectsOverflow && (- <ShowAllEntriesButton count={projectsTotal} onClick={() => setShowAllProjects(true)} />- )}- </div>+ )}+ </>+ );+ })()}+ </div>+ </SectionCollapse>+ </div>+ );+ })}+ </div>+ ) : (+ <div className="flex flex-col gap-1">+ {visibleMixedEntries.map((entry) =>+ entry.kind === 'project'+ ? renderProjectNode(entry.project)+ : renderNonProjectEntry(entry, DIALOGUE_GROUP_ALL_KEY),+ )}+ </div>+ )}+ {/* 全局「显示全部」只属于未按设备分组的单段路径;设备分组下折叠与 footer 都在段内。 */}+ {!deviceGroupingActive && projectsOverflow && (+ <ShowAllEntriesButton count={projectsTotal} onClick={() => setShowAllProjects(true)} />+ )}+ </div>) : null}</div>);diff --git a/apps/desktop/src/renderer/hooks/useCCSessions.ts b/apps/desktop/src/renderer/hooks/useCCSessions.tsindex 5870b7f6c5..48a0b67f95 100644--- a/apps/desktop/src/renderer/hooks/useCCSessions.ts+++ b/apps/desktop/src/renderer/hooks/useCCSessions.ts@@ -125,7 +125,9 @@ export function useCCSessions(options?: UseCCSessionsOptions): UseCCSessionsRetu}// 只在新桶有确切数据时才覆盖, 否则其它桶的变化不应擦掉当前视图。if (next !== null) {- setSnapshotState({ data: next, filter });+ setSnapshotState((previous) =>+ previous.data === next && previous.filter === filter ? previous : { data: next, filter },+ );setIsLoading(false);setError(null);}