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): 收窄侧栏观察范围并优化任务投影 (#4192)

DavidShenXD6c62c5150650
diff --git a/apps/desktop/src/renderer/__tests__/sidebarTaskObserver.test.ts b/apps/desktop/src/renderer/__tests__/sidebarTaskObserver.test.ts
new file mode 100644
index 0000000000..162fe1426c
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/sidebarTaskObserver.test.ts
@@ -0,0 +1,172 @@
+// @vitest-environment jsdom
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getVisibleSidebarSessionIds } from '@/features/cc-agent/lib/sessionRemovalNavigation';
+import { observeSidebarTaskChanges } from '@/features/cc-agent/lib/sidebarTaskObserver';
+
+describe('sidebar task observation', () => {
+ let root: HTMLElement;
+ let aside: HTMLElement;
+ let content: HTMLElement;
+ let chat: HTMLElement;
+ let disconnect: (() => void) | undefined;
+ let frameId: number;
+ let frames: Map<number, FrameRequestCallback>;
+
+ beforeEach(() => {
+ document.body.innerHTML = `
+ <style>.invisible { visibility: hidden; opacity: 0; }</style>
+ <div>
+ <aside aria-hidden="false"><div id="content"><div id="sidebar">
+ <div id="expanded" hidden>
+ <div data-sidebar-session-row="true" data-session-id="expanded"></div>
+ </div>
+ <div id="rail">
+ <div data-sidebar-session-row="true" data-session-id="rail-b" data-sidebar-row-order="1"></div>
+ <div data-sidebar-session-row="true" data-session-id="rail-a" data-sidebar-row-order="0"></div>
+ </div>
+ </div></div></aside>
+ <main id="chat"></main>
+ </div>`;
+ root = document.getElementById('sidebar')!;
+ aside = document.querySelector('aside')!;
+ content = document.getElementById('content')!;
+ chat = document.getElementById('chat')!;
+ frameId = 0;
+ frames = new Map();
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ frames.set(++frameId, callback);
+ return frameId;
+ });
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id));
+ });
+
+ afterEach(() => {
+ disconnect?.();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ });
+
+ async function flushFrame() {
+ // Deliver the real MutationObserver microtask before the next animation frame.
+ await Promise.resolve();
+ const pending = [...frames.values()];
+ frames.clear();
+ for (const callback of pending) callback(0);
+ }
+
+ function watchVisibleRows() {
+ const published: string[][] = [];
+ const publish = vi.fn(() => published.push(getVisibleSidebarSessionIds()));
+ publish();
+ disconnect = observeSidebarTaskChanges(root, publish);
+ return { publish, published };
+ }
+
+ function finishTransition(target: HTMLElement, propertyName: string) {
+ const event = new Event('transitionend', { bubbles: true });
+ Object.defineProperty(event, 'propertyName', { value: propertyName });
+ target.dispatchEvent(event);
+ }
+
+ it('clears and restores rail order when only the outer sidebar shell is hidden', async () => {
+ const { publish, published } = watchVisibleRows();
+ expect(published).toEqual([['rail-a', 'rail-b']]);
+ const unchangedRail = root.innerHTML;
+
+ aside.setAttribute('aria-hidden', 'true');
+ content.className = 'invisible';
+ await flushFrame();
+ expect(published.at(-1)).toEqual([]);
+ expect(publish).toHaveBeenCalledTimes(2);
+
+ aside.setAttribute('aria-hidden', 'false');
+ content.className = '';
+ await flushFrame();
+ expect(published.at(-1)).toEqual(['rail-a', 'rail-b']);
+ expect(publish).toHaveBeenCalledTimes(3);
+ expect(root.innerHTML).toBe(unchangedRail);
+ });
+
+ it('still observes expanded/rail switches and merges mutations into one frame', async () => {
+ const { publish, published } = watchVisibleRows();
+ document.getElementById('expanded')!.hidden = false;
+ document.getElementById('rail')!.hidden = true;
+ await flushFrame();
+ expect(published.at(-1)).toEqual(['expanded']);
+ expect(publish).toHaveBeenCalledTimes(2);
+ });
+
+ it('publishes final ancestor fade visibility without another class mutation', async () => {
+ const { publish, published } = watchVisibleRows();
+ // jsdom has no CSS animations; model the final computed opacity separately
+ // from class changes. Inline style is intentionally outside the observer filter.
+ content.style.opacity = '0';
+ await flushFrame();
+ expect(publish).toHaveBeenCalledTimes(1);
+ finishTransition(content, 'opacity');
+ finishTransition(content, 'visibility');
+ await flushFrame();
+ expect(published.at(-1)).toEqual([]);
+ expect(publish).toHaveBeenCalledTimes(2);
+
+ content.style.opacity = '1';
+ finishTransition(content, 'opacity');
+ await flushFrame();
+ expect(published.at(-1)).toEqual(['rail-a', 'rail-b']);
+ expect(publish).toHaveBeenCalledTimes(3);
+ });
+
+ it('does not schedule publishing for streamed chat changes or unrelated body children', async () => {
+ const { publish } = watchVisibleRows();
+ for (let i = 0; i < 100; i += 1) {
+ chat.append(document.createElement('span'));
+ chat.className = `stream-${i}`;
+ }
+ finishTransition(chat, 'opacity');
+ finishTransition(root.querySelector<HTMLElement>('[data-session-id]')!, 'opacity');
+ finishTransition(content, 'width');
+ document.body.append(document.createElement('div'));
+ await flushFrame();
+ expect(publish).toHaveBeenCalledTimes(1);
+ expect(frames.size).toBe(0);
+ });
+
+ it('publishes portal mount, content changes and removal including an empty final list', async () => {
+ content.className = 'invisible';
+ const { published } = watchVisibleRows();
+ const portal = document.createElement('div');
+ portal.innerHTML = `<div data-rail-panel>
+ <div data-sidebar-session-row="true" data-session-id="portal"></div>
+ </div>`;
+ document.body.append(portal);
+ await flushFrame();
+ expect(published.at(-1)).toEqual(['portal']);
+
+ portal.querySelector<HTMLElement>('[data-session-id]')!.hidden = true;
+ await flushFrame();
+ expect(published.at(-1)).toEqual([]);
+ portal.querySelector<HTMLElement>('[data-session-id]')!.hidden = false;
+ await flushFrame();
+ expect(published.at(-1)).toEqual(['portal']);
+
+ portal.remove();
+ await flushFrame();
+ expect(published).toEqual([[], ['portal'], [], ['portal'], []]);
+ });
+
+ it('disconnects observers and cancels a pending publish on teardown', async () => {
+ const { publish } = watchVisibleRows();
+ root.append(document.createElement('div'));
+ await Promise.resolve();
+ expect(frames.size).toBe(1);
+ disconnect!();
+ root.append(document.createElement('div'));
+ content.className = 'invisible';
+ finishTransition(content, 'opacity');
+ await flushFrame();
+ expect(publish).toHaveBeenCalledTimes(1);
+ expect(frames.size).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index d99c2a7d48..8626e30643 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -142,6 +142,7 @@ import {
} from './lib/projectBulkArchiveAction';
import { sessionActivityMs } from './lib/dateSessionGrouping';
import { matchesSidebarSessionStatus } from './lib/sidebarSessionStatusFilter';
+import { observeSidebarTaskChanges } from './lib/sidebarTaskObserver';
import { sortProjectsForSidebar, sortSessionsForSidebar } from './lib/sidebarProjectSorting';
import { resolveDisplayedProjectOrder } from '@cindy/maker-shared/project-order-sync';
import {
@@ -562,6 +563,7 @@ export function CCAgentSidebarUpper() {
* 不限定容器:展开态与 rail 折叠态是两个不同组件,扫整个 document 才能两种形态
* 都覆盖。只送键盘需要的三个字段,不整份 session 过 IPC。 */
const publishedTaskKeyRef = useRef<string>('');
+ const sidebarRootRef = useRef<HTMLDivElement>(null);
const publishSidebarTasks = useCallback(() => {
if (isSecondaryWindow()) return;
const renderedIds = getVisibleSidebarSessionIds();
@@ -570,8 +572,9 @@ export function CCAgentSidebarUpper() {
// 否则 AG 键还会打开上一份已经看不见的任务。完整活动表仍要带上,最近发送
// / 优先 / 自定义不能被折叠裁掉。
const catalogSessions = sessionsWithRemote.filter((session) => session.status === 'active');
+ const catalogSessionIds = new Set(catalogSessions.map((session) => session.id));
const visibleProjection = visibleSessionsWithRemote
- .filter((session) => !catalogSessions.some((active) => active.id === session.id))
+ .filter((session) => !catalogSessionIds.has(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(
@@ -604,26 +607,9 @@ export function CCAgentSidebarUpper() {
// 展开/折叠项目、分组重排这类纯 UI 变化不会动 visibleSessionsWithRemote,
// 但会改渲染顺序 —— 跟序号徽标同样的做法,靠 DOM 变化跟住。
if (typeof MutationObserver === 'undefined' || typeof document === 'undefined') return;
- // 观察面是整个 document(展开态与 rail 是两个组件),流式输出时 mutation 会非常
- // 密集 —— 每帧最多重算一次,别让它变成热路径。
- let frame: number | null = null;
- const observer = new MutationObserver(() => {
- if (frame !== null) return;
- frame = requestAnimationFrame(() => {
- frame = null;
- publishSidebarTasks();
- });
- });
- observer.observe(document.body, {
- childList: true,
- subtree: true,
- attributes: true,
- attributeFilter: ['class', 'hidden', 'aria-hidden'],
- });
- return () => {
- observer.disconnect();
- if (frame !== null) cancelAnimationFrame(frame);
- };
+ const sidebarRoot = sidebarRootRef.current;
+ if (!sidebarRoot) return;
+ return observeSidebarTaskChanges(sidebarRoot, publishSidebarTasks);
}, [publishSidebarTasks]);
// rail 未读集与展开态(ExpandedView.sidebarNotifications)同口径:把"定时任务有未读运行"的
@@ -670,7 +656,7 @@ export function CCAgentSidebarUpper() {
// 路过几行热态就丢了,体感退回"每行都要重新等 500ms"(session-git-pr-context)。
<Tooltip.Provider skipDelayDuration={1500}>
<SessionAttentionUrgencyProvider urgentSessionIds={unreadFailedScheduleSessionIds}>
- <div className="relative flex flex-1 flex-col overflow-hidden">
+ <div ref={sidebarRootRef} className="relative flex flex-1 flex-col overflow-hidden">
{/* Expanded — fade out when collapsed.
min-w-0 让内层跟着外层 aside 的实际宽度走,配合 SessionItem 里的
`min-w-0 flex-1 truncate` 才能正确截断。原来写死 min-w-[260px] 是
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarTaskObserver.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarTaskObserver.ts
new file mode 100644
index 0000000000..d8553f3483
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarTaskObserver.ts
@@ -0,0 +1,75 @@
+/** Coalesce sidebar and portal mutations without observing the chat subtree. */
+export function observeSidebarTaskChanges(sidebarRoot: HTMLElement, publish: () => void): () => void {
+ let frame: number | null = null;
+ const schedulePublish = () => {
+ if (frame !== null) return;
+ frame = requestAnimationFrame(() => {
+ frame = null;
+ publish();
+ });
+ };
+ const observerOptions: MutationObserverInit = {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['class', 'hidden', 'aria-hidden'],
+ };
+ const observer = new MutationObserver(schedulePublish);
+ // In rail mode Cmd/Ctrl+B changes only Sidebar's outer shell: the feature's
+ // collapsed context and both inner trees can remain unchanged.
+ const sidebarShell = sidebarRoot.closest('aside') ?? sidebarRoot;
+ observer.observe(sidebarShell, observerOptions);
+ // The first RAF can still see the old opacity/visibility during Sidebar's
+ // 200ms fade. Re-read once its ancestor transition reaches the final state.
+ const onVisibilityTransitionEnd = (event: TransitionEvent) => {
+ if (
+ (event.propertyName === 'opacity' || event.propertyName === 'visibility') &&
+ event.target instanceof Element &&
+ event.target.contains(sidebarRoot)
+ ) {
+ schedulePublish();
+ }
+ };
+ sidebarShell.addEventListener('transitionend', onVisibilityTransitionEnd);
+ const portalObservers = new Map<Element, MutationObserver>();
+ const portalSelector =
+ '[data-rail-panel],[data-conversation-search-overlay],[data-radix-popper-content-wrapper]';
+ const attachPortalObserver = (portal: Element) => {
+ if (portalObservers.has(portal)) return;
+ const portalObserver = new MutationObserver(schedulePublish);
+ portalObserver.observe(portal, observerOptions);
+ portalObservers.set(portal, portalObserver);
+ };
+ const syncPortalObservers = () => {
+ for (const portal of document.querySelectorAll(portalSelector)) attachPortalObserver(portal);
+ for (const [portal, portalObserver] of portalObservers) {
+ if (!portal.isConnected) {
+ portalObserver.disconnect();
+ portalObservers.delete(portal);
+ }
+ }
+ };
+ syncPortalObservers();
+ const portalLifecycleObserver = new MutationObserver((records) => {
+ if (
+ records.some((record) =>
+ [...record.addedNodes, ...record.removedNodes].some(
+ (node) =>
+ node instanceof Element &&
+ (node.matches(portalSelector) || node.querySelector(portalSelector)),
+ ),
+ )
+ ) {
+ syncPortalObservers();
+ schedulePublish();
+ }
+ });
+ portalLifecycleObserver.observe(document.body, { childList: true });
+ return () => {
+ observer.disconnect();
+ sidebarShell.removeEventListener('transitionend', onVisibilityTransitionEnd);
+ portalLifecycleObserver.disconnect();
+ for (const portalObserver of portalObservers.values()) portalObserver.disconnect();
+ if (frame !== null) cancelAnimationFrame(frame);
+ };
+}