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。

fix(cindy-make): close failed lookups and hidden task notifications

MagicLizi0fedc01db6b6
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index f6da03231b..913828ed42 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -432,7 +432,10 @@ export function CCAgentSidebarUpper() {
: allSessionsForAttentionRaw.filter((session) => !isCindyMakeSource(session.source)),
[allSessionsForAttentionRaw],
);
- const remoteProjectSessionsRaw = useRemoteProjectSessions();
+ const remoteProjectSessionsRaw = useSyncExternalStore(
+ remoteProjectsStore.subscribe,
+ remoteProjectsStore.getMergedRemoteSessions,
+ );
const remoteProjectSessions = useMemo(
() => CINDY_MAKE_ENABLED
? remoteProjectSessionsRaw
@@ -761,7 +764,8 @@ export function CCAgentSidebarUpper() {
<ExpandedView
sessionsHook={sessionsHook}
allSessionsForAttention={allSessionsForAttention}
- remoteSessionsForNotification={remoteProjectSessions}
+ allSessionsForNotification={allSessionsForAttentionRaw}
+ remoteSessionsForNotification={remoteProjectSessionsRaw}
navigate={navigate}
activeSessionId={activeSessionId}
// 兜底直接用路由参数而非 filesSession?.id:filesSession 只从本地
@@ -812,6 +816,7 @@ type SessionsHook = ReturnType<typeof useCCSessions>;
interface ExpandedProps {
sessionsHook: SessionsHook;
allSessionsForAttention: Session[];
+ allSessionsForNotification: Session[];
remoteSessionsForNotification: Session[];
navigate: ReturnType<typeof useNavigate>;
activeSessionId: string | undefined;
@@ -853,6 +858,7 @@ const CONFIRM_INITIAL: ConfirmState = {
function ExpandedView({
sessionsHook,
allSessionsForAttention,
+ allSessionsForNotification,
remoteSessionsForNotification,
navigate,
activeSessionId,
@@ -872,12 +878,6 @@ function ExpandedView({
: sessionsHook.sessions.filter((session) => !isCindyMakeSource(session.source)),
[sessionsHook.sessions],
);
- const visibleRemoteSessionsForNotification = useMemo(
- () => CINDY_MAKE_ENABLED
- ? remoteSessionsForNotification
- : remoteSessionsForNotification.filter((session) => !isCindyMakeSource(session.source)),
- [remoteSessionsForNotification],
- );
const { refreshSessions, patchLocal, effectiveIncludeArchived } = sessionsHook;
const {
hiddenProjectKeys,
@@ -1153,10 +1153,10 @@ function ExpandedView({
sessionsRef.current = sessions;
// 通知不能只查当前侧栏桶:活跃筛选、归档切换和远程会话镜像都可能让目标
// 不在 sessionsRef 里。保留同步查找和原有兜底,避免标题解析影响通知发送。
- const allSessionsForNotificationRef = useRef(allSessionsForAttention);
- allSessionsForNotificationRef.current = allSessionsForAttention;
- const remoteSessionsForNotificationRef = useRef(visibleRemoteSessionsForNotification);
- remoteSessionsForNotificationRef.current = visibleRemoteSessionsForNotification;
+ const allSessionsForNotificationRef = useRef(allSessionsForNotification);
+ allSessionsForNotificationRef.current = allSessionsForNotification;
+ const remoteSessionsForNotificationRef = useRef(remoteSessionsForNotification);
+ remoteSessionsForNotificationRef.current = remoteSessionsForNotification;
// 通知文案里的「尚未起名」兜底。走 ref 与 sessionsRef 同款:fireSessionNotification
// 是 `[]` 依赖的稳定回调,直接闭包 t 会钉住首次渲染的语言。
const unnamedLabelRef = useRef('');
@@ -1168,6 +1168,7 @@ function ExpandedView({
allSessionsForNotificationRef.current,
remoteSessionsForNotificationRef.current,
]);
+ if (!CINDY_MAKE_ENABLED && session && isCindyMakeSource(session.source)) return;
// Orca worker 自身状态翻转不发独立通知 —— 等 lead 接到 worker_report 处理完
// 再以 lead 名义统一推一条,避免同一事件双重打扰。语义上用户应回到 lead 主对话
// 查看,而非跳到 worker 实现细节;与 effectiveRunningSessionIds 的角色聚合口径一致。
diff --git a/apps/desktop/src/renderer/features/cc-agent/CindyMakeSessionGate.tsx b/apps/desktop/src/renderer/features/cc-agent/CindyMakeSessionGate.tsx
index 15e3530ed3..ecda2b7d55 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CindyMakeSessionGate.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CindyMakeSessionGate.tsx
@@ -21,9 +21,11 @@ export function CindyMakeSessionGate({ sessionId, children }: {
useEffect(() => {
if (CINDY_MAKE_ENABLED || !sessionId || knownSource !== undefined) return;
let cancelled = false;
- void getSessionFor(sessionId).catch(() => null).then(session => {
- if (!cancelled) setLoaded({ id: sessionId, source: session?.source ?? null });
- });
+ void getSessionFor(sessionId).then(session => {
+ if (!cancelled && session?.id === sessionId) {
+ setLoaded({ id: session.id, source: session.source ?? null });
+ }
+ }).catch(() => undefined);
return () => { cancelled = true; };
}, [sessionId, knownSource]);
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionGate.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionGate.test.tsx
index bce9b51449..94afb1c1de 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionGate.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionGate.test.tsx
@@ -4,16 +4,29 @@ import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CindyMakeSessionGate } from '../CindyMakeSessionGate';
-const state = vi.hoisted(() => ({ remote: [] as Array<{ id: string; source: string }>, localSource: undefined as string | undefined, getSession: vi.fn() }));
+const state = vi.hoisted(() => ({
+ remote: [] as Array<{ id: string; source: string }>,
+ localSource: undefined as string | undefined,
+ getSession: vi.fn(),
+ localListeners: new Set<() => void>(),
+}));
vi.mock('@/features/device-link/remoteProjectsStore', () => ({ remoteProjectsStore: {
subscribe: () => () => {}, getMergedRemoteSessions: () => state.remote,
} }));
vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: {
- subscribe: () => () => {}, findById: () => state.localSource ? { source: state.localSource } : null,
+ subscribe: (listener: () => void) => {
+ state.localListeners.add(listener);
+ return () => { state.localListeners.delete(listener); };
+ },
+ findById: () => state.localSource ? { source: state.localSource } : null,
} }));
vi.mock('@/lib/makerTransport', () => ({ getSessionFor: state.getSession }));
afterEach(cleanup);
-beforeEach(() => { state.remote = []; state.localSource = undefined; state.getSession.mockReset(); });
+beforeEach(() => {
+ state.remote = [];
+ state.localSource = undefined;
+ state.getSession.mockReset().mockResolvedValue(null);
+});
function mount(child: React.ReactNode = <div>Composer</div>) {
return render(<MemoryRouter initialEntries={['/old-task']}>
@@ -35,12 +48,12 @@ describe('old Cindy Make links', () => {
});
it('waits for metadata and redirects a hidden task missing from visible lists', async () => {
- let resolve!: (value: { source: string }) => void;
+ let resolve!: (value: { id: string; source: string }) => void;
state.getSession.mockReturnValue(new Promise(res => { resolve = res; }));
const Composer = vi.fn(() => <div>Composer</div>);
mount(<Composer />);
expect(Composer).not.toHaveBeenCalled();
- await act(async () => resolve({ source: 'cindy-make' }));
+ await act(async () => resolve({ id: 'old-task', source: 'cindy-make' }));
expect(screen.getByText('Task list')).toBeTruthy();
expect(Composer).not.toHaveBeenCalled();
});
@@ -51,4 +64,39 @@ describe('old Cindy Make links', () => {
expect(screen.getByText('Composer')).toBeTruthy();
expect(state.getSession).not.toHaveBeenCalled();
});
+
+ it.each([
+ { label: 'a rejected lookup', getSession: () => Promise.reject(new Error('offline')) },
+ { label: 'a missing row', getSession: () => Promise.resolve(null) },
+ { label: 'a mismatched row', getSession: () => Promise.resolve({ id: 'another-task', source: 'desktop' }) },
+ ])('keeps the subtree unmounted after $label', async ({ getSession }) => {
+ state.getSession.mockImplementation(getSession);
+ const Composer = vi.fn(() => <div>Composer</div>);
+ await act(async () => { mount(<Composer />); });
+ expect(Composer).not.toHaveBeenCalled();
+ expect(screen.queryByText('Task list')).toBeNull();
+ });
+
+ it.each([undefined, null, 'desktop'])('opens matching ordinary metadata with source %s', async (source) => {
+ state.getSession.mockResolvedValue({ id: 'old-task', source });
+ await act(async () => { mount(); });
+ expect(screen.getByText('Composer')).toBeTruthy();
+ });
+
+ it.each(['desktop', 'cindy-make', 'cindy-make-merge'])('recovers from a failed lookup when the mirror confirms %s', async (source) => {
+ state.getSession.mockRejectedValue(new Error('offline'));
+ const Composer = vi.fn(() => <div>Composer</div>);
+ await act(async () => { mount(<Composer />); });
+ expect(Composer).not.toHaveBeenCalled();
+ act(() => {
+ state.localSource = source;
+ for (const listener of state.localListeners) listener();
+ });
+ if (source === 'desktop') {
+ expect(screen.getByText('Composer')).toBeTruthy();
+ } else {
+ expect(screen.getByText('Task list')).toBeTruthy();
+ expect(Composer).not.toHaveBeenCalled();
+ }
+ });
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts
new file mode 100644
index 0000000000..3584e15103
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts
@@ -0,0 +1,139 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
+import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
+import { isOrcaWorkerSession } from '@/lib/orcaSessionIdentity';
+import { BOT_GROUP_LANE_SESSION, findSessionNotificationSession } from '@/lib/sessionEventNotification';
+import { isReviewSessionSource } from '../../../../shared/sessionSource';
+
+const source = ts.createSourceFile('sidebar.tsx', readFileSync(resolve(
+ process.cwd(), 'src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx',
+), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const expanded = source.statements.find((statement): statement is ts.FunctionDeclaration =>
+ ts.isFunctionDeclaration(statement) && statement.name?.text === 'ExpandedView',
+)!;
+const declarationNames = new Set([
+ 'sessions', 'visibleRemoteSessionsForNotification', 'sessionsRef',
+ 'allSessionsForNotificationRef', 'remoteSessionsForNotificationRef',
+ 'unnamedLabelRef', 'fireSessionNotification',
+]);
+const refNames = new Set([
+ 'sessionsRef', 'allSessionsForNotificationRef', 'remoteSessionsForNotificationRef', 'unnamedLabelRef',
+]);
+const statements = expanded.body!.statements.filter(statement => {
+ if (ts.isVariableStatement(statement)) {
+ return statement.declarationList.declarations.some(declaration =>
+ ts.isIdentifier(declaration.name) && declarationNames.has(declaration.name.text),
+ );
+ }
+ if (!ts.isExpressionStatement(statement) || !ts.isBinaryExpression(statement.expression)) return false;
+ const target = statement.expression.left;
+ return ts.isPropertyAccessExpression(target) && ts.isIdentifier(target.expression)
+ && refNames.has(target.expression.text);
+});
+const emitted = ts.transpileModule(
+ statements.map(statement => statement.getText(source)).join('\n') + '\nreturn fireSessionNotification;',
+ { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None } },
+).outputText;
+
+type NotificationSession = {
+ id: string;
+ title: string;
+ source: string;
+ status?: 'active' | 'archived';
+ deviceLinkDeviceId?: string;
+};
+const send = vi.fn();
+const reviewTarget = vi.fn(async () => false);
+const botTitle = vi.fn(async (): Promise<string | null> => null);
+beforeEach(() => { vi.clearAllMocks(); });
+
+function dispatcher(local: NotificationSession[], remote: NotificationSession[] = []) {
+ const bindings = {
+ useMemo: (factory: () => unknown) => factory(),
+ useRef: (current: unknown) => ({ current }),
+ useCallback: (callback: unknown) => callback,
+ sessionsHook: { sessions: local.filter(session => session.status !== 'archived') },
+ allSessionsForAttention: local.filter(session => !isCindyMakeSource(session.source)),
+ allSessionsForNotification: local,
+ remoteSessionsForNotification: remote,
+ CINDY_MAKE_ENABLED: false,
+ isCindyMakeSource,
+ findSessionNotificationSession,
+ isOrcaWorkerSession,
+ isReviewSessionSource,
+ projectDraftSessionTitle,
+ sendSessionEventNotification: send,
+ isReviewSessionNotificationTarget: reviewTarget,
+ botOwnedSessionNotificationTitle: botTitle,
+ BOT_GROUP_LANE_SESSION,
+ t: () => 'Unnamed task',
+ };
+ return new Function(...Object.keys(bindings), emitted)(...Object.values(bindings)) as (
+ sessionId: string, kind: 'done' | 'error' | 'needs-reply',
+ ) => void;
+}
+
+describe('disabled Make notification dispatch', () => {
+ it.each(['cindy-make', 'cindy-make-merge'].flatMap(source =>
+ (['local', 'archived', 'remote'] as const).flatMap(location =>
+ (['done', 'error', 'needs-reply'] as const).map(kind => ({ source, location, kind })),
+ ),
+ ))('suppresses $kind for $location $source metadata omitted from UI lists', async ({ source, location, kind }) => {
+ const session: NotificationSession = {
+ id: 'hidden', title: 'Hidden Make task', source,
+ status: location === 'archived' ? 'archived' : 'active',
+ ...(location === 'remote' ? { deviceLinkDeviceId: 'host' } : {}),
+ };
+ const fire = dispatcher(location === 'remote' ? [] : [session], location === 'remote' ? [session] : []);
+ fire('hidden', kind);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(send).not.toHaveBeenCalled();
+ expect(reviewTarget).not.toHaveBeenCalled();
+ expect(botTitle).not.toHaveBeenCalled();
+ });
+
+ it('keeps ordinary local and remote notifications', () => {
+ dispatcher([{ id: 'ordinary', title: 'Ordinary task', source: 'desktop' }])('ordinary', 'done');
+ expect(send).toHaveBeenCalledWith('ordinary', 'Ordinary task', 'done', {
+ remoteDevice: false, remoteDeviceId: undefined,
+ });
+ dispatcher([], [{ id: 'remote', title: 'Remote task', source: 'desktop', deviceLinkDeviceId: 'host' }])('remote', 'needs-reply');
+ expect(send).toHaveBeenCalledWith('remote', 'Remote task', 'needs-reply', {
+ remoteDevice: true, remoteDeviceId: 'host',
+ });
+ });
+
+ it('preserves the unknown-task fallback', async () => {
+ dispatcher([])('unknown', 'error');
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(send).toHaveBeenCalledWith('unknown', 'Unnamed task', 'error');
+ });
+
+ it('passes unfiltered local and remote metadata to notification dispatch', () => {
+ let rawRemote: string | undefined;
+ const props = new Map<string, string>();
+ function visit(node: ts.Node): void {
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === 'remoteProjectSessionsRaw' && !rawRemote) {
+ rawRemote = node.initializer?.getText(source);
+ }
+ if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(source) === 'ExpandedView') {
+ for (const attribute of node.attributes.properties) {
+ if (ts.isJsxAttribute(attribute) && attribute.initializer && ts.isJsxExpression(attribute.initializer)) {
+ props.set(attribute.name.getText(source), attribute.initializer.expression?.getText(source) ?? '');
+ }
+ }
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ expect(rawRemote).toContain('useSyncExternalStore');
+ expect(rawRemote).toContain('remoteProjectsStore.getMergedRemoteSessions');
+ expect(props.get('allSessionsForNotification')).toBe('allSessionsForAttentionRaw');
+ expect(props.get('remoteSessionsForNotification')).toBe('remoteProjectSessionsRaw');
+ });
+});