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(desktop): 保留暂停探测状态并规范探测错误

DavidShene3df7acda0f0
diff --git a/apps/desktop/src/main/__tests__/worktreeReveal.test.ts b/apps/desktop/src/main/__tests__/worktreeReveal.test.ts
index 41ff7ccfd1..bae3131cbd 100644
--- a/apps/desktop/src/main/__tests__/worktreeReveal.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeReveal.test.ts
@@ -8,10 +8,12 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import path from 'node:path';
+import { extractIpcError } from '../../renderer/utils/ipcError';
// ── mock electron 的 ipcMain + shell ──────────────────────────────────────
const showItemInFolderMock = vi.fn();
const suggestNameMock = vi.fn();
+const detectCwdMock = vi.fn();
type Handler = (event: unknown, req: unknown) => unknown | Promise<unknown>;
const handlers = new Map<string, Handler>();
const ipcMainMock = {
@@ -40,7 +42,7 @@ vi.mock('../worktree/worktreeStore', () => ({
// 业务依赖 (避免触达真实 git 调用)
vi.mock('../worktree/WorktreeManager', () => ({
createWorktree: vi.fn(),
- detectCwd: vi.fn(),
+ detectCwd: (...args: unknown[]) => detectCwdMock(...args),
getForSession: vi.fn(),
listAll: vi.fn(),
suggestName: (...args: unknown[]) => suggestNameMock(...args),
@@ -52,6 +54,7 @@ let registerWorktreeIpc: typeof import('../worktree/index').registerWorktreeIpc;
beforeEach(async () => {
showItemInFolderMock.mockReset();
suggestNameMock.mockReset();
+ detectCwdMock.mockReset();
getAllPathsMock.mockReset();
handlers.clear();
if (!registerWorktreeIpc) {
@@ -73,6 +76,46 @@ function callSuggestName(req: unknown): Promise<unknown> {
return Promise.resolve(handler({}, req));
}
+async function callDetectCwd(req: unknown): Promise<unknown> {
+ const handler = handlers.get('worktree:detect-cwd');
+ if (!handler) throw new Error('worktree:detect-cwd handler not registered');
+ return handler({}, req);
+}
+
+describe('worktree:detect-cwd IPC contract', () => {
+ it.each([true, false])('preserves successful probe responses (inside worktree: %s)', async (inside) => {
+ const cwd = path.resolve('/tmp/worktree');
+ const response = { isGitRepo: inside, isInsideWorktree: inside, gitInstalled: true };
+ detectCwdMock.mockResolvedValue(response);
+ await expect(callDetectCwd({ cwd })).resolves.toEqual(response);
+ expect(detectCwdMock).toHaveBeenCalledExactlyOnceWith(cwd);
+ });
+
+ it.each(['timeout', 'unexpected'])('encodes %s failures without leaking raw Git details', async (kind) => {
+ const { GitExecError } = await import('../worktree/gitExec');
+ const cwd = path.resolve('/private/worktree');
+ const rawError = kind === 'timeout'
+ ? new GitExecError({
+ args: ['rev-parse'], exitCode: null, timedOut: true,
+ stdout: 'private output', stderr: `probe stalled in ${cwd}`,
+ })
+ : new Error(`failed in ${cwd}`);
+ detectCwdMock.mockRejectedValue(rawError);
+
+ const error = await callDetectCwd({ cwd }).catch((err: unknown) => err);
+ expect(error).toBeInstanceOf(Error);
+ expect(error).toMatchObject({ code: 'INTERNAL' });
+ // Electron only preserves the message; the renderer must still decode it.
+ const serialized = new Error(`Error invoking remote method 'worktree:detect-cwd': ${(error as Error).toString()}`);
+ expect(extractIpcError(serialized)).toEqual({
+ code: 'INTERNAL', message: 'Worktree directory probe failed',
+ });
+ expect(serialized.message).not.toContain(cwd);
+ expect(serialized.message).not.toContain('rev-parse');
+ expect(serialized.message).not.toContain('private output');
+ });
+});
+
describe('worktree:suggest-name IPC contract', () => {
it('wraps the generated name in the declared response shape', async () => {
suggestNameMock.mockResolvedValue('pensive-lederberg');
diff --git a/apps/desktop/src/main/worktree/index.ts b/apps/desktop/src/main/worktree/index.ts
index 8986bcbdca..829ad003aa 100644
--- a/apps/desktop/src/main/worktree/index.ts
+++ b/apps/desktop/src/main/worktree/index.ts
@@ -13,6 +13,7 @@ import * as WorktreeManager from './WorktreeManager';
import * as worktreeStore from './worktreeStore';
import { getWorktreeRestoreStatus, restoreWorktreeForSession } from './restore';
import { createLogger } from '../logger';
+import { throwIpcError } from '../utils/ipcValidate';
const log = createLogger('worktree');
@@ -51,9 +52,15 @@ export function registerWorktreeIpc(ipcMain: IpcMain = ipcMainType): void {
WorktreeManager.createWorktree(req),
);
- ipcMain.handle('worktree:detect-cwd', (_e, req: DetectCwdReq) =>
- WorktreeManager.detectCwd(req.cwd),
- );
+ ipcMain.handle('worktree:detect-cwd', async (_e, req: DetectCwdReq) => {
+ try {
+ return await WorktreeManager.detectCwd(req.cwd);
+ } catch {
+ // Keep probe failure distinct from a missing directory, without sending
+ // raw Git output or internal paths across the IPC boundary.
+ throwIpcError('INTERNAL', 'Worktree directory probe failed');
+ }
+ });
ipcMain.handle('worktree:get-for-session', (_e, sessionId: string) =>
WorktreeManager.getForSession(sessionId),
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionWorktreeInfoRefresh.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionWorktreeInfoRefresh.test.tsx
index 047e64002b..012245d662 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionWorktreeInfoRefresh.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionWorktreeInfoRefresh.test.tsx
@@ -81,9 +81,9 @@ describe('opened worktree refresh', () => {
it('resets liveness from the new snapshot when switching tasks in place', async () => {
const metaA = { path: '/tmp/wt/a', name: 'a', branch: 'feature-a' };
const metaB = { path: '/tmp/wt/b', name: 'b', branch: 'feature-b' };
- mocks.official.mockImplementation((task: { id: string }, options?: { includeInvalid?: boolean }) => {
- if (options?.includeInvalid) return task.id === 'a' ? metaA : metaB;
- return task.id === 'a' ? null : metaB;
+ mocks.official.mockImplementation((sessionId: string, options?: { includeInvalid?: boolean }) => {
+ if (options?.includeInvalid) return sessionId === 'a' ? metaA : metaB;
+ return sessionId === 'a' ? null : metaB;
});
mocks.detect.mockResolvedValue({ isInsideWorktree: false });
const view = renderHook(
@@ -98,6 +98,63 @@ describe('opened worktree refresh', () => {
expect(view.result.current?.source).toBe('managed');
});
+ it('keeps invalid liveness through disable, delayed re-enable, and a failed probe', async () => {
+ mocks.detect.mockResolvedValue({ isInsideWorktree: false });
+ const view = renderHook(
+ ({ enabled }) => useTaskInfoWorktree(session, enabled, { observeTelemetry: true }),
+ { initialProps: { enabled: true } },
+ );
+ await act(async () => {});
+ expect(view.result.current).toBeNull();
+
+ view.rerender({ enabled: false });
+ await act(async () => switchFocus());
+ expect(view.result.current).toBeNull();
+ expect(mocks.detect).toHaveBeenCalledOnce();
+ expect(mocks.listeners.size).toBe(0);
+
+ let reject!: (error: Error) => void;
+ mocks.detect.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));
+ view.rerender({ enabled: true });
+ expect(view.result.current).toBeNull();
+ await act(async () => reject(new Error('[INTERNAL] Worktree directory probe failed')));
+ expect(view.result.current).toBeNull();
+ expect(mocks.reportLiveness).toHaveBeenCalledTimes(1);
+
+ mocks.detect.mockResolvedValue({ isInsideWorktree: true });
+ await act(async () => switchFocus());
+ expect(view.result.current?.source).toBe('managed');
+ expect(mocks.reportLiveness).toHaveBeenLastCalledWith(expect.anything(), true);
+ });
+
+ it('updates liveness after a route switch even when the previous task had the same probe result', async () => {
+ const metaA = { path: '/tmp/wt/a', name: 'a', branch: 'feature-a' };
+ const metaB = { path: '/tmp/wt/b', name: 'b', branch: 'feature-b' };
+ mocks.official.mockImplementation((sessionId: string, options?: { includeInvalid?: boolean }) => {
+ if (options?.includeInvalid) return sessionId === 'a' ? metaA : metaB;
+ return sessionId === 'a' ? metaA : null;
+ });
+ const view = renderHook(
+ ({ id }) => useTaskInfoWorktree({ ...session, id }, true, { observeTelemetry: true }),
+ { initialProps: { id: 'a' } },
+ );
+ await act(async () => {});
+ expect(view.result.current?.path).toBe(metaA.path);
+
+ let finish!: (value: { isInsideWorktree: boolean }) => void;
+ mocks.detect.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
+ view.rerender({ id: 'b' });
+ expect(view.result.current).toBeNull();
+ await act(async () => finish({ isInsideWorktree: true }));
+ expect(view.result.current?.path).toBe(metaB.path);
+
+ mocks.detect.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
+ view.rerender({ id: 'a' });
+ expect(view.result.current?.path).toBe(metaA.path);
+ await act(async () => finish({ isInsideWorktree: false }));
+ expect(view.result.current).toBeNull();
+ });
+
it('applies recycle and restore events immediately', async () => {
const { result } = renderHook(() => useTaskInfoWorktree(session, true, { observeTelemetry: true }));
await act(async () => {});
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionWorktreeInfo.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionWorktreeInfo.ts
index 7f71d6c55a..15d31ba571 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionWorktreeInfo.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionWorktreeInfo.ts
@@ -9,7 +9,7 @@
* 不写 store、不改变回收。目录没了摘掉徽标。外部 observed 不可 reveal。
*/
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useState } from 'react';
import { groupingWorktreeBaseRepo } from '@cindy/maker-shared/worktree-paths';
@@ -110,15 +110,16 @@ export function useTaskInfoWorktree(
const managed = resolveManagedWorktree(official);
const [observed, setObserved] = useState<SessionWorktreeInfo | null>(null);
const initialOfficialStillLive = !observeTelemetry || liveOfficial !== null;
- const [officialStillLive, setOfficialStillLive] = useState(initialOfficialStillLive);
- const livenessRef = useRef({ sessionId: session.id, live: initialOfficialStillLive });
- if (livenessRef.current.sessionId !== session.id) {
+ const [liveness, setLiveness] = useState({ sessionId: session.id, live: initialOfficialStillLive });
+ if (liveness.sessionId !== session.id) {
// The hook instance is reused when the route changes. Reset synchronously
// from the new snapshot so the previous task's state cannot leak for a
// render while the effect starts its probe.
- livenessRef.current = { sessionId: session.id, live: initialOfficialStillLive };
+ setLiveness({ sessionId: session.id, live: initialOfficialStillLive });
}
- const displayedOfficialStillLive = livenessRef.current.live;
+ const displayedOfficialStillLive = liveness.sessionId === session.id
+ ? liveness.live
+ : initialOfficialStillLive;
const officialPath = official?.path ?? null;
const deviceId = session.deviceLinkDeviceId ?? null;
const isRemote = Boolean(deviceId || session.remoteHostId);
@@ -126,8 +127,8 @@ export function useTaskInfoWorktree(
useEffect(() => {
setObserved(null);
if (!enabled || isRemote || !observeTelemetry) {
- livenessRef.current = { sessionId: session.id, live: !isRemote };
- setOfficialStillLive(!isRemote);
+ // Pausing probes says nothing about directory liveness. Preserve the last
+ // result until a resumed probe actually confirms deletion or restoration.
return;
}
let cancelled = false;
@@ -140,16 +141,14 @@ export function useTaskInfoWorktree(
const live = await probeIsInsideWorktree(officialPath, deviceId);
if (cancelled || gen !== generation) return;
if (live === null) return; // IPC 失败不代表目录已被删除,保留上次状态。
- livenessRef.current = { sessionId: session.id, live };
- setOfficialStillLive(live);
+ setLiveness({ sessionId: session.id, live });
if (official) reportLiveness(official, live);
if (live) {
setObserved(null);
return;
}
} else if (gen === generation) {
- livenessRef.current = { sessionId: session.id, live: false };
- setOfficialStillLive(false);
+ setLiveness({ sessionId: session.id, live: false });
}
if (isRemote) {
if (!cancelled && gen === generation) setObserved(null);