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): worktree 恢复失败时保持对话可继续 (#4614)

Dash9f99cafc984f
diff --git a/apps/desktop/src/main/__tests__/worktreeRestore.test.ts b/apps/desktop/src/main/__tests__/worktreeRestore.test.ts
index 76b451c2df..48b3b11930 100644
--- a/apps/desktop/src/main/__tests__/worktreeRestore.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeRestore.test.ts
@@ -23,6 +23,7 @@ const storeGetAllMock = vi.fn();
const storeDelMock = vi.fn();
const applyIncludeMock = vi.fn();
const copyClaudeSiviDirsMock = vi.fn();
+let dbFailure = false;
let dbWorktreePath: string | null = null;
let dbWorkingDir: string | null = null;
let dbBindingRows: Array<{
@@ -61,6 +62,7 @@ vi.mock('../localDb/client/current', () => ({
select: (selection: Record<string, unknown>) => ({
from: () => ({
where: () => {
+ if (dbFailure) throw new Error('database temporarily unavailable');
if ('id' in selection) return dbOwnerRows;
if (dbBindingRows.length > 0) return [dbBindingRows.shift()!];
return dbWorktreePath === undefined
@@ -99,6 +101,7 @@ describe('worktree restore', () => {
dbWorktreePath = wtPath;
dbWorkingDir = wtPath;
dbBindingRows = [];
+ dbFailure = false;
dbOwnerRows = [];
gitExecMock.mockReset().mockResolvedValue({ stdout: '', stderr: '' });
storeSetMock.mockReset().mockResolvedValue(undefined);
@@ -562,6 +565,30 @@ describe('worktree restore', () => {
expect(createBranchIndex).toBeLessThan(addWorktreeIndex);
});
+ it('does not classify a healthy directory as gone after a transient DB failure', async () => {
+ fsSync.mkdirSync(wtPath, { recursive: true });
+ dbWorktreePath = null;
+ dbFailure = true;
+ await expect(mod.getManagedWorktreeReadinessForSession('s1', wtPath)).resolves.toBe('retry');
+ dbFailure = false;
+ await expect(mod.getManagedWorktreeReadinessForSession('s1', wtPath)).resolves.toBe('ready');
+ expect(gitExecMock).not.toHaveBeenCalled();
+ });
+
+ it('only reports gone after a successful branch inventory confirms missing refs', async () => {
+ await expect(mod.getManagedWorktreeReadinessForSession('s1', wtPath)).resolves.toBe('gone');
+ gitExecMock.mockRejectedValue(new Error('git temporarily unavailable'));
+ await expect(mod.getManagedWorktreeReadinessForSession('s1', wtPath)).resolves.toBe('retry');
+ });
+
+ it('does not select fallback when ref probes failed but branch inventory still has the branch', async () => {
+ gitExecMock.mockImplementation(async (args: string[]) => {
+ if (args[0] === 'for-each-ref') return { stdout: 'refs/heads/cindy/wt1\n', stderr: '' };
+ throw new Error('probe unavailable');
+ });
+ await expect(mod.getManagedWorktreeReadinessForSession('s1', wtPath)).resolves.toBe('retry');
+ });
+
it('send-time restore only accepts the DB-authoritative managed path', async () => {
const stalePath = path.join(baseRepo, '.cindy-worktrees', 'stale');
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index 78aa36f695..26b0887a39 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -26,6 +26,8 @@ import {
} from '../makerSendTransaction';
import type { MakerSessionCreateOpts } from '../sessionRequest';
import { CredentialModeSwitchBusyError } from '../../maker-host/codex-credential-switch';
+import path from 'node:path';
+import { createWorkingDirectoryRecovery } from '../workingDirectoryRecovery';
function createSession(overrides: Partial<MakerSendTransactionSession> = {}): MakerSendTransactionSession {
return {
@@ -1256,6 +1258,100 @@ describe('maker SEND transaction', () => {
expect(recovered.send).toHaveBeenCalledWith(expect.stringContaining('Original filesystem unavailable'), expect.anything());
});
+ it.each(['error', 'missing'] as const)('does not bootstrap a queued fallback without the DB binding (%s)', async (failure) => {
+ const fallback = '/owned/dialogues/worktree-recovery/key';
+ const original = '/repo/.cindy-worktrees/task';
+ let dbReady = false;
+ const { deps } = createDeps({
+ getSession: () => undefined,
+ readSessionWorkingDirFromDb: async () => {
+ if (dbReady) return original;
+ if (failure === 'error') throw new Error('DB unavailable');
+ return null;
+ },
+ isPersistedWorktreeFallback: (dir) => dir === fallback,
+ });
+ const transaction = createMakerSendTransaction(deps);
+ const opts = { agentKind: 'codex' as const, workingDir: fallback };
+ await expect(transaction.sendToAgentAccepted('session-1', 'queued', opts))
+ .resolves.toMatchObject({ accepted: false, reason: 'WORKDIR_MISSING' });
+ expect(deps.checkWorkDirExists).not.toHaveBeenCalled();
+ expect(deps.bootstrapSession).not.toHaveBeenCalled();
+ dbReady = true;
+ await transaction.sendToAgentAccepted('session-1', 'retry', opts);
+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({ workingDir: original }));
+ });
+
+ it.each([true, false])('rechecks the DB worktree after restarting with a queued fallback (restored: %s)', async (restored) => {
+ const original = '/repo/.cindy-worktrees/task';
+ const fallback = '/owned/dialogues/worktree-recovery/key';
+ let current: MakerSendTransactionSession | undefined;
+ const check = vi.fn(async (_id: string, _dir: string | undefined | null) => true);
+ const { deps } = createDeps({
+ getSession: () => current,
+ readSessionWorkingDirFromDb: async () => original,
+ isPersistedWorktreeFallback: (dir) => dir === fallback,
+ checkWorkDirExists: check,
+ resolveRecoveredWorkingDir: (_id, dir) => restored ? dir : fallback,
+ peekWorkingDirectoryRecoveryNote: () => restored ? null : 'worktree still unavailable after restart',
+ bootstrapSession: vi.fn(async (opts) => {
+ current = createSession({ workDir: opts.workingDir });
+ return { session: current, didInjectOrcaInstructions: false, didInjectProjectContext: false };
+ }),
+ });
+ await createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'queued', {
+ agentKind: 'codex', workingDir: fallback, resumeSessionId: 'native-history',
+ });
+ expect(check.mock.calls[0]?.[1]).toBe(original);
+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({
+ workingDir: restored ? original : fallback, resumeSessionId: 'native-history',
+ }));
+ expect(current!.send).toHaveBeenCalledOnce();
+ if (!restored) expect(current!.send).toHaveBeenCalledWith(expect.stringContaining('still unavailable after restart'), expect.anything());
+ });
+
+ it.each([false, true])('sends once after an unrestorable worktree falls back (live runtime: %s)', async (live) => {
+ const original = path.resolve('/repo/.cindy-worktrees/missing');
+ const fallback = path.resolve('/owned/dialogues/task');
+ const recovery = createWorkingDirectoryRecovery({
+ stat: vi.fn(async () => ({ isDirectory: () => true })), mkdir: vi.fn(),
+ }, async () => fallback);
+ let current = live ? createSession({ workDir: original }) : undefined;
+ const old = current;
+ const persisted = { workingDir: original, worktreePath: original, resumeSessionId: 'native-history', model: 'gpt-5.4' };
+ const { deps } = createDeps({
+ getSession: () => current,
+ readSessionWorkingDirFromDb: async () => persisted.workingDir,
+ readWorkingDirectoryRecoveryCreateOpts: async () => ({ agentKind: 'codex', ...persisted }),
+ checkWorkDirExists: async (id, dir) => recovery.isFallback(id, dir!)
+ ? recovery.recover(id, dir!)
+ : recovery.recover(id, dir!, undefined, [], 'unrestored-worktree'),
+ resolveRecoveredWorkingDir: (id, dir) => recovery.resolve(id, dir),
+ peekWorkingDirectoryRecoveryNote: (id, dir) => recovery.peek(id, dir),
+ consumeWorkingDirectoryRecoveryNote: (id, note) => recovery.consume(id, note),
+ bootstrapSession: vi.fn(async (opts) => {
+ current = createSession({ workDir: opts.workingDir });
+ return { session: current, didInjectOrcaInstructions: false, didInjectProjectContext: false };
+ }),
+ });
+ const transaction = createMakerSendTransaction(deps);
+ await expect(transaction.sendToAgentAccepted('session-1', 'continue', {
+ agentKind: 'codex', ...persisted,
+ })).resolves.toMatchObject({ accepted: true });
+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({
+ workingDir: fallback, resumeSessionId: 'native-history',
+ }));
+ if (old) expect(old.send).not.toHaveBeenCalled();
+ expect(current!.send).toHaveBeenCalledOnce();
+ expect(current!.send).toHaveBeenCalledWith(expect.stringContaining('could not restore'), expect.anything());
+ expect(recovery.peek('session-1')).toBeNull();
+ expect(persisted.workingDir).toBe(original);
+ expect(persisted.worktreePath).toBe(original);
+ await transaction.sendToAgentAccepted('session-1', 'next');
+ expect(deps.bootstrapSession).toHaveBeenCalledOnce();
+ expect(current!.send).toHaveBeenCalledTimes(2);
+ });
+
it('keeps the old runtime when Bot resource preflight fails, then resumes normally after repair', async () => {
const session = createSession({ agentKind: 'pi' });
const { deps } = createDeps({
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryRecovery.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryRecovery.test.ts
index e23eaa4464..ead33c1373 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryRecovery.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/workingDirectoryRecovery.test.ts
@@ -2,7 +2,7 @@ import fsp from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { createWorkingDirectoryRecovery } from '../workingDirectoryRecovery';
+import { createWorkingDirectoryRecovery, worktreeConversationFallbackDir } from '../workingDirectoryRecovery';
const roots: string[] = [];
afterEach(async () => {
@@ -10,6 +10,70 @@ afterEach(async () => {
});
describe('working directory conversation recovery', () => {
+ it('reuses recovery files across restarts while isolating owners, tasks and original worktrees', async () => {
+ const root = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-fallback-'));
+ roots.push(root);
+ const original = path.join(root, 'repo', '.cindy-worktrees', 'missing');
+ const fallback = worktreeConversationFallbackDir(root, 'task', original);
+ const allocate = async () => { await fsp.mkdir(fallback, { recursive: true }); return fallback; };
+ const first = createWorkingDirectoryRecovery(fsp, allocate);
+ expect(await first.recover('task', original, undefined, [], 'unrestored-worktree')).toBe(true);
+ await fsp.writeFile(path.join(fallback, 'notes.txt'), 'keep');
+ const restarted = createWorkingDirectoryRecovery(fsp, allocate);
+ expect(await restarted.recover('task', original, undefined, [], 'unrestored-worktree')).toBe(true);
+ expect(restarted.resolve('task', original)).toBe(fallback);
+ expect(await fsp.readFile(path.join(fallback, 'notes.txt'), 'utf8')).toBe('keep');
+ expect(worktreeConversationFallbackDir(root, 'other', original)).not.toBe(fallback);
+ expect(worktreeConversationFallbackDir(root, 'task', `${original}-other`)).not.toBe(fallback);
+ expect(worktreeConversationFallbackDir(path.join(root, 'other-owner'), 'task', original)).not.toBe(fallback);
+ });
+
+ it('continues in a conversation directory after Git restore fails without touching the worktree', async () => {
+ const original = path.resolve('/repo/.cindy-worktrees/missing');
+ const fallback = path.resolve('/owned/dialogues/task');
+ const io = { stat: vi.fn(async () => ({ isDirectory: () => true })), mkdir: vi.fn() };
+ const allocate = vi.fn(async () => fallback);
+ const recovery = createWorkingDirectoryRecovery(io, allocate);
+ expect(await recovery.recover('task', original, undefined, [], 'unrestored-worktree')).toBe(true);
+ expect(io.stat).not.toHaveBeenCalled();
+ expect(io.mkdir).not.toHaveBeenCalled();
+ expect(recovery.resolve('task', original)).toBe(fallback);
+ const note = recovery.peek('task', fallback)!;
+ expect(note).toContain('could not restore');
+ expect(note).toContain('original project and worktree');
+ expect(note).toContain(JSON.stringify(original));
+ expect(note).toContain('Do not create an empty replacement');
+ recovery.consume('task', note);
+ expect(await recovery.recover('task', original, undefined, [], 'unrestored-worktree')).toBe(true);
+ expect(allocate).toHaveBeenCalledOnce();
+ expect(recovery.resolve('task', original)).toBe(fallback);
+ expect(recovery.peek('task')).toBeNull();
+ });
+
+ it.each(['discard', 'clear', 'move'] as const)('does not revive worktree fallback after %s during allocation', async (operation) => {
+ let finish!: (dir: string) => void;
+ const allocate = vi.fn(() => new Promise<string>((resolve) => { finish = resolve; }));
+ const recovery = createWorkingDirectoryRecovery({ stat: vi.fn(), mkdir: vi.fn() }, allocate);
+ const pending = recovery.recover('task', '/repo/.cindy-worktrees/task', undefined, [], 'unrestored-worktree');
+ await vi.waitFor(() => expect(allocate).toHaveBeenCalledOnce());
+ if (operation === 'clear') recovery.clear();
+ else if (operation === 'discard') recovery.discard('task');
+ else recovery.resolve('task', '/chosen-project');
+ finish('/conversation');
+ expect(await pending).toBe(false);
+ expect(recovery.peek('task')).toBeNull();
+ });
+
+ it('keeps worktree recovery unsuccessful when the conversation directory cannot be allocated', async () => {
+ const mkdir = vi.fn();
+ const recovery = createWorkingDirectoryRecovery({ stat: vi.fn(), mkdir }, async () => {
+ throw Object.assign(new Error('disk full'), { code: 'ENOSPC' });
+ });
+ expect(await recovery.recover('task', '/repo/.cindy-worktrees/task', undefined, [], 'unrestored-worktree')).toBe(false);
+ expect(mkdir).not.toHaveBeenCalled();
+ expect(recovery.peek('task')).toBeNull();
+ });
+
it('records same-directory fallback and a later failed fallback probe without changing recovery behavior', async () => {
const dir = path.resolve('/private/dialogue');
const log = { info: vi.fn(), warn: vi.fn() };
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index 5581aa7443..c6531c4b76 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -345,6 +345,7 @@ export interface MakerSendTransactionDeps {
opts?: { suppressMissingBroadcast?: boolean },
): Promise<boolean>;
resolveRecoveredWorkingDir?(sessionId: string, workingDir: string): string;
+ isPersistedWorktreeFallback?(workingDir: string): boolean;
/**
* 读 DB 里既有会话的权威 working_dir(行不存在 → null)。lazy-create /
* rehydrate 在 caller 传入的 workingDir 校验失败时用它兜底——输入队列崩溃
@@ -660,6 +661,15 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
});
return null;
});
+ // A queued runtime cwd may be a recovery directory from a previous process.
+ // Start from the durable binding so the new process retries Git restoration
+ // and, if still unavailable, supplies a fresh recovery note. In-process
+ // recovery.resolve continues to preserve the already selected fallback.
+ if (!createOpts.remoteHostId && createOpts.workingDir &&
+ deps.isPersistedWorktreeFallback?.(createOpts.workingDir)) {
+ if (!dbDir) return false;
+ createOpts.workingDir = dbDir;
+ }
const fallbackDir = dbDir && dbDir !== createOpts.workingDir ? dbDir : null;
if (fallbackDir) deps.workdirDiagnostics?.info('workdir DB fallback candidate', {
...workdirDiagnosticContext(sessionId, createOpts.workingDir), source: 'bootstrap',
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 8af3612bac..0728710663 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -232,7 +232,7 @@ import {
isDbClientNotReadyError,
} from '../localDb/client/current.js';
import { createBotRuntimeRestoreCoordinator } from './botRuntimeRestore.js';
-import { createWorkingDirectoryRecovery, isUnavailableFilesystemError } from './workingDirectoryRecovery.js';
+import { createWorkingDirectoryRecovery, isUnavailableFilesystemError, worktreeConversationFallbackDir } from './workingDirectoryRecovery.js';
import { workdirDiagnosticContext, workdirDiagnosticErrorCode, workdirDiagnosticId } from '../workdirDiagnostics.js';
import { statWorkingDirectory, mkdirWorkingDirectory, realpathWorkingDirectory, findSimilarWorkingDirectory } from '../workdir-probe-host/index.js';
import { getMessagesForHistory } from '../localDb/chatHistoryReader.js';
@@ -660,7 +660,7 @@ import { registerNewMakerWorktreePreferenceHandler } from './newMakerWorktreePre
import { registerNewMakerWorktreeBranchPreferenceHandler } from './newMakerWorktreeBranchPreferenceHandler.js';
import {
resolveFreshSourceBranch,
- restoreMissingManagedWorktreeForSession,
+ getManagedWorktreeReadinessForSession,
WorktreeManager as worktreeManager,
worktreeStore,
} from '../worktree/index.js';
@@ -1105,8 +1105,14 @@ import { installSessionTurnObserver } from './sessionTurnObserver.js';
const log = createLogger('maker-ipc');
const workdirLog = createLogger('workdir-diagnostics');
-const workingDirectoryRecovery = createWorkingDirectoryRecovery({ stat: statWorkingDirectory, mkdir: mkdirWorkingDirectory, realpath: realpathWorkingDirectory }, async (sessionId) =>
- ensureDialogueWorkspaceDir(sessionId, Date.now()), workdirLog);
+const workingDirectoryRecovery = createWorkingDirectoryRecovery({ stat: statWorkingDirectory, mkdir: mkdirWorkingDirectory, realpath: realpathWorkingDirectory }, async (sessionId, workingDir, mode) => {
+ if (mode === 'unrestored-worktree') {
+ const fallback = worktreeConversationFallbackDir(dialogueWorkspaceRootDir(), sessionId, workingDir);
+ await fsp.mkdir(fallback, { recursive: true });
+ return fallback;
+ }
+ return ensureDialogueWorkspaceDir(sessionId, Date.now());
+}, workdirLog);
function localModelWindowSwitchErrorCode(code: IpcErrorCode): IpcErrorCode {
return isDeviceLinkInvoke() ? 'PRECONDITION_FAILED' : code;
@@ -9897,7 +9903,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const createOpts = buildCreateOptsWithStderr({
id: sessionId,
agentKind: meta.agentKind,
- workingDir: meta.workDir,
+ workingDir: row.workingDir ?? meta.workDir,
model: meta.model,
providerId: row.providerId,
resumeSessionId: meta.sdkSessionId,
@@ -12165,6 +12171,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
checkWorkDirExists,
resolveRecoveredWorkingDir: (sessionId, dir) => workingDirectoryRecovery.resolve(sessionId, dir),
+ isPersistedWorktreeFallback: (dir) => path.dirname(path.resolve(dir)) ===
+ path.join(dialogueWorkspaceRootDir(), 'worktree-recovery'),
preflightBotRuntimeResources: async (opts) => { await preflightBotRuntimeResources(opts); },
readWorkingDirectoryRecoveryCreateOpts: async (sessionId) => {
const [row] = await getDbClient().drizzle.select().from(sessions)
@@ -18120,8 +18128,9 @@ async function checkWorkDirExists(
// deliberately leaves the directory present while keeping the session blocked.
const normalizedWorkingDir = path.resolve(workingDir).replace(/\\/g, '/');
if (getManagedWorktreeBasePath(normalizedWorkingDir) !== null) {
- const ready = await restoreMissingManagedWorktreeForSession(sessionId, workingDir);
- if (!ready) {
+ const ready = await getManagedWorktreeReadinessForSession(sessionId, workingDir);
+ if (ready !== 'ready') {
+ if (ready === 'gone' && !suppress && await workingDirectoryRecovery.recover(sessionId, workingDir, undefined, [], 'unrestored-worktree')) return true;
workdirLog.warn('workdir preflight rejected', { ...diagnosticContext, reason: 'managed-worktree-not-ready' });
if (suppress) {
log.warn('send: managed worktree not ready (broadcast suppressed, caller has fallback)', {
@@ -18158,8 +18167,8 @@ async function checkWorkDirExists(
}
// Cindy 托管 worktree 被外部 PR cleanup / 手动 git 命令移除时,先按 DB 中
// 的精确 worktree_path 从本地或 origin tracking 分支重建,保留原代码与快照。
- const restored = await restoreMissingManagedWorktreeForSession(sessionId, workingDir);
- if (restored) {
+ const restored = await getManagedWorktreeReadinessForSession(sessionId, workingDir);
+ if (restored === 'ready') {
workdirLog.info('workdir preflight recovered', { ...diagnosticContext, action: 'managed-worktree-restored' });
log.info('send: restored missing managed worktree', { sessionId, workingDir });
return true;
@@ -18168,6 +18177,12 @@ async function checkWorkDirExists(
// A fuzzy match is a lead for the agent, not authority to switch project identity.
const unavailable = isUnavailableFilesystemError(error);
let similar: string | null = null;
+ if (
+ restored === 'gone' && !suppress &&
+ ((error as NodeJS.ErrnoException).code === 'ENOENT' || unavailable) &&
+ getManagedWorktreeBasePath(path.resolve(workingDir).replace(/\\/g, '/')) !== null &&
+ await workingDirectoryRecovery.recover(sessionId, workingDir, undefined, [], 'unrestored-worktree')
+ ) return true;
// A missing ordinary/dialogue cwd must not stop the conversation. Prefer a repaired
// DB path when the caller has one; never turn a managed Git recovery into
// an empty project, or treat permission/non-directory failures as ENOENT.
diff --git a/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts b/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts
index a992ab63a1..7f987adeac 100644
--- a/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts
+++ b/apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts
@@ -1,5 +1,6 @@
import fsp from 'node:fs/promises';
import path from 'node:path';
+import { createHash } from 'node:crypto';
import {
workdirDiagnosticContext, workdirDiagnosticErrorCode, workdirDiagnosticId,
type WorkdirDiagnosticLogger,
@@ -10,12 +11,20 @@ export function isUnavailableFilesystemError(error: unknown): boolean {
.includes((error as NodeJS.ErrnoException | null)?.code ?? '');
}
-/** Ordinary local directories only; managed Git worktrees keep their own restore path. */
+/** Reuse recovery artifacts when Git restoration still fails after a restart.
+ * Its identity includes the original binding; changing projects cannot reuse it.
+ */
+export function worktreeConversationFallbackDir(dialoguesRoot: string, sessionId: string, workingDir: string): string {
+ const key = createHash('sha256').update(JSON.stringify([sessionId, path.resolve(workingDir)])).digest('hex');
+ return path.join(dialoguesRoot, 'worktree-recovery', key);
+}
+
+/** Local directory recovery; failed Git restores may explicitly request conversation fallback. */
export function createWorkingDirectoryRecovery(io: {
stat(dir: string): Promise<{ isDirectory(): boolean; dev?: number }>;
mkdir(dir: string, opts: { recursive: true }): Promise<unknown>;
realpath?(dir: string): Promise<string>;
-} = fsp, allocateFallback?: (sessionId: string) => Promise<string>, log?: WorkdirDiagnosticLogger) {
+} = fsp, allocateFallback?: (sessionId: string, workingDir: string, mode: 'ordinary' | 'unrestored-worktree') => Promise<string>, log?: WorkdirDiagnosticLogger) {
const pending = new Map<string, { workingDir: string; note: string | null; device?: number; fallback?: string }>();
function entryFor(sessionId: string, dir: string) {
const entry = pending.get(sessionId);
@@ -88,7 +97,7 @@ export function createWorkingDirectoryRecovery(io: {
isFallback(sessionId: string, workingDir: string): boolean {
return !!entryFor(sessionId, workingDir)?.fallback;
},
- async recover(sessionId: string, workingDir: string, similarPath?: string | null | (() => Promise<string | null>), candidates: { id: string; workingDir: string }[] = []): Promise<boolean> {
+ async recover(sessionId: string, workingDir: string, similarPath?: string | null | (() => Promise<string | null>), candidates: { id: string; workingDir: string }[] = [], mode: 'ordinary' | 'unrestored-worktree' = 'ordinary'): Promise<boolean> {
entryFor(sessionId, workingDir);
const sessions = new Map(candidates.map((session) => [session.id, session.workingDir]));
sessions.set(sessionId, workingDir);
@@ -115,13 +124,19 @@ export function createWorkingDirectoryRecovery(io: {
});
return false;
}
- const fallback = path.resolve(await allocateFallback(sessionId));
+ const fallback = path.resolve(await allocateFallback(sessionId, workingDir, mode));
if (pending.get(sessionId) !== own) return false;
pending.set(sessionId, { ...own, fallback, note: [
'[Working directory recovery]',
- `The filesystem for ${JSON.stringify(workingDir)} is unavailable or has changed. Cindy is using ${JSON.stringify(fallback)} as a temporary conversation workspace.`,
- 'The original directory and files have not been restored or copied. Do not create a substitute directory at the original mount location. Files written here stay here when the disk reconnects; do not move them or switch back without discussing it with the user.',
- 'Continue responding. If the task needs the original files, investigate the disconnected disk or network share, or ask the user in this conversation. No folder-selection interface is required.',
+ ...(mode === 'unrestored-worktree' ? [
+ `Cindy could not restore the task worktree at ${JSON.stringify(workingDir)}. Cindy is using ${JSON.stringify(fallback)} as a temporary conversation workspace; the task remains associated with its original project and worktree.`,
+ 'The original code, branch and uncommitted changes have not been restored or copied. Do not create an empty replacement at the original path or continue editing in the project root as if it were the original worktree. Investigate the original branch and snapshots before resuming project edits.',
+ 'Continue responding to the user and explain the unavailable worktree. Files created in this conversation workspace remain here; do not move them or switch workspaces without discussing it with the user. No folder-selection interface is required just to continue the conversation.',
+ ] : [
+ `The filesystem for ${JSON.stringify(workingDir)} is unavailable or has changed. Cindy is using ${JSON.stringify(fallback)} as a temporary conversation workspace.`,
+ 'The original directory and files have not been restored or copied. Do not create a substitute directory at the original mount location. Files written here stay here when the disk reconnects; do not move them or switch back without discussing it with the user.',
+ 'Continue responding. If the task needs the original files, investigate the disconnected disk or network share, or ask the user in this conversation. No folder-selection interface is required.',
+ ]),
].join('\n') });
log?.info('workdir recovery completed', {
...context, action: 'fallback-selected', fallbackRef: workdirDiagnosticId(fallback),
@@ -155,6 +170,9 @@ export function createWorkingDirectoryRecovery(io: {
});
return true;
}
+ // Git restoration already failed. Never probe/mkdir the original path as
+ // an ordinary directory: an empty folder is not a restored worktree.
+ if (mode === 'unrestored-worktree') return await useFallback();
if (own && allocateFallback && await mountUnavailable(workingDir, own, (details) => {
log?.warn('workdir recovery unavailable', { ...context, ...details });
})) {
diff --git a/apps/desktop/src/main/worktree/index.ts b/apps/desktop/src/main/worktree/index.ts
index 829ad003aa..73ea840a37 100644
--- a/apps/desktop/src/main/worktree/index.ts
+++ b/apps/desktop/src/main/worktree/index.ts
@@ -36,6 +36,7 @@ export {
export { reconcilePendingSafeDirectoryCleanups } from './WorktreeManager';
export {
getWorktreeRestoreStatus,
+ getManagedWorktreeReadinessForSession,
restoreMissingManagedWorktreeForSession,
restoreWorktreeForSession,
type WorktreeRestoreStatus,
diff --git a/apps/desktop/src/main/worktree/restore.ts b/apps/desktop/src/main/worktree/restore.ts
index 818f361553..496dd9e62e 100644
--- a/apps/desktop/src/main/worktree/restore.ts
+++ b/apps/desktop/src/main/worktree/restore.ts
@@ -559,12 +559,35 @@ async function markSendReadyIfMutationStable(
return ready;
}
+export type ManagedWorktreeReadiness = 'ready' | 'gone' | 'retry';
+
+// Legacy restore status folds probe errors into `gone`. Require successful probes
+// before letting a send permanently select a conversation fallback.
+async function confirmedMissingWorktree(worktreePath: string): Promise<boolean> {
+ try {
+ await fs.stat(worktreePath);
+ return false;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return false;
+ }
+ const parsed = parseManagedWorktreePath(worktreePath);
+ if (!parsed) return false;
+ try {
+ const { stdout } = await gitExec(['for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes/origin'], parsed.baseRepo);
+ const refs = new Set(stdout.trim().split(/\r?\n/));
+ return getManagedWorktreeBranchCandidates(parsed.name).every((branch) =>
+ !refs.has(localBranchRef(branch)) && !refs.has(originBranchRef(branch)));
+ } catch {
+ return false;
+ }
+}
+
async function ensureOwnedWorktreeReady(
ownerSessionId: string,
worktreePath: string,
-): Promise<boolean> {
+): Promise<ManagedWorktreeReadiness> {
const worktreeKey = pathKey(worktreePath);
- if (!worktreeKey) return false;
+ if (!worktreeKey) return 'retry';
const readinessKey = `${ownerSessionId}\0${worktreeKey}`;
// `git worktree add` creates the directory before a pending snapshot is applied. A second
@@ -575,14 +598,14 @@ async function ensureOwnedWorktreeReady(
restoreInFlightVersions.get(ownerSessionId) ??
getWorktreeRestoreMutationVersion(ownerSessionId);
const result = await restoring;
- if (!result.ok || result.snapshotApplied === false) return false;
+ if (!result.ok || result.snapshotApplied === false) return result.reason === 'gone' && await confirmedMissingWorktree(worktreePath) ? 'gone' : 'retry';
const ready = await markSendReadyIfMutationStable(
ownerSessionId,
worktreePath,
readinessKey,
restoreVersion,
);
- return ready ?? ensureOwnedWorktreeReady(ownerSessionId, worktreePath);
+ return ready === null ? ensureOwnedWorktreeReady(ownerSessionId, worktreePath) : ready ? 'ready' : 'retry';
}
// Recycle cancellation/removal also owns this lock while the snapshot is detached from the
@@ -602,7 +625,7 @@ async function ensureOwnedWorktreeReady(
sendReadyWorktrees.get(readinessKey) === currentMutationVersion &&
getWorktreeRestoreMutationVersion(ownerSessionId) === currentMutationVersion
) {
- return true;
+ return 'ready';
}
const restore = restoreWorktreeForSession(ownerSessionId);
@@ -610,41 +633,41 @@ async function ensureOwnedWorktreeReady(
restoreInFlightVersions.get(ownerSessionId) ??
getWorktreeRestoreMutationVersion(ownerSessionId);
const result = await restore;
- if (!result.ok || result.snapshotApplied === false) return false;
+ if (!result.ok || result.snapshotApplied === false) return result.reason === 'gone' && await confirmedMissingWorktree(worktreePath) ? 'gone' : 'retry';
const ready = await markSendReadyIfMutationStable(
ownerSessionId,
worktreePath,
readinessKey,
restoreVersion,
);
- return ready ?? ensureOwnedWorktreeReady(ownerSessionId, worktreePath);
+ return ready === null ? ensureOwnedWorktreeReady(ownerSessionId, worktreePath) : ready ? 'ready' : 'retry';
}
/**
* 发送期自愈入口。DB working_dir 必须与 caller cwd 精确相同;cwd 可以是托管
* worktree 根目录或其子目录。恢复与 snapshot readiness 始终按 owning session 的
* worktree 根目录串行;其它 session 借用该目录时也必须等待 owner 的 pending
- * snapshot。快照 apply 冲突时返回 false,绝不带着缺失的 WIP 静默继续。
+ * snapshot。快照 apply 冲突时返回 retry,绝不带着缺失的 WIP 静默继续。
*/
-export async function restoreMissingManagedWorktreeForSession(
+export async function getManagedWorktreeReadinessForSession(
sessionId: string,
expectedWorkingDir: string,
-): Promise<boolean> {
+): Promise<ManagedWorktreeReadiness> {
const expectedKey = pathKey(expectedWorkingDir);
- if (!expectedKey) return false;
+ if (!expectedKey) return 'retry';
let binding: SessionWorktreeBinding | null;
try {
binding = await readSessionWorktreeBinding(sessionId);
} catch {
- return false;
+ return 'retry';
}
- if (pathKey(binding?.workingDir) !== expectedKey) return false;
+ if (pathKey(binding?.workingDir) !== expectedKey) return 'retry';
const worktreePath = findManagedWorktreeRoot(expectedWorkingDir);
- if (!worktreePath) return false;
+ if (!worktreePath) return 'retry';
const worktreeKey = pathKey(worktreePath);
- if (!worktreeKey) return false;
+ if (!worktreeKey) return 'retry';
let ownerSessionId: string | null;
if (pathKey(binding?.worktreePath) === worktreeKey) {
@@ -653,13 +676,18 @@ export async function restoreMissingManagedWorktreeForSession(
try {
ownerSessionId = await readWorktreeOwnerSessionId(worktreePath);
} catch {
- return false;
+ return 'retry';
}
}
// An unowned managed directory remains usable as an ordinary cwd, but cannot be recreated.
- if (!ownerSessionId) return await pathIsDirectory(expectedWorkingDir);
+ if (!ownerSessionId) return await pathIsDirectory(expectedWorkingDir) ? 'ready' : 'retry';
const ready = await ensureOwnedWorktreeReady(ownerSessionId, worktreePath);
- return ready && (await pathIsDirectory(expectedWorkingDir));
+ return ready === 'ready' ? (await pathIsDirectory(expectedWorkingDir) ? 'ready' : 'retry') : ready;
+}
+
+/** Compatibility wrapper for callers that only need readiness. */
+export async function restoreMissingManagedWorktreeForSession(sessionId: string, expectedWorkingDir: string): Promise<boolean> {
+ return await getManagedWorktreeReadinessForSession(sessionId, expectedWorkingDir) === 'ready';
}
diff --git a/docs/dev-rules/development-workflow.md b/docs/dev-rules/development-workflow.md
index 6de2ae2d7e..fba49fca40 100644
--- a/docs/dev-rules/development-workflow.md
+++ b/docs/dev-rules/development-workflow.md
@@ -34,6 +34,24 @@ worktree 会话契约、直推 `main` 的额外门禁与 review 严重度口径
## 2. 提 PR 与直推 `main`
+### 托管 worktree 不可用时的任务连续性
+
+本机任务发送前优先按原分支和快照恢复托管 worktree。仅在确认目录缺失、且成功枚举
+Git 引用后确认原分支不存在时,使用当前 owner 的
+托管对话目录继续运行,保留数据库里的项目工作目录和 worktree 绑定;备用目录按任务 ID
+与原工作目录的哈希定位。重启后重新优先恢复原 worktree;仍失败则复用同一备用目录,
+不搬运或删除其中的文件。DB / Git 临时错误、绑定不匹配与快照冲突保留原目录重试,
+不登记备用目录。同一运行期不自动切回。明确换到另一工作目录时不复用旧绑定
+的备用目录。原地重建普通目录的现有行为保持不变,不把失败的 Git
+worktree 建成空目录或自动切到项目根继续修改代码。
+
+恢复说明随本轮消息传给 Agent,明确原路径、文件未恢复和当前运行位置;消息被接受
+之后才消费说明。SSH 不使用本机备用目录;设备互联和手机沿用被控 Desktop 的发送链。
+实现见 `apps/desktop/src/main/maker-ipc/workingDirectoryRecovery.ts` 与 `register.ts`,
+回归见 `workingDirectoryRecovery.test.ts` 和 `makerSendTransaction.test.ts`。
+
+### 提交门禁
+
- 本仓默认 **PR-first**:代码和文档通常从非默认分支通过 PR 进入 `main`;直推 `main` 只由
具备 bypass 权限的维护者明确选择,并执行本节的额外门禁。
- PR 的 Title/Description 以 [`../../.github/PULL_REQUEST_TEMPLATE.md`](../../.github/PULL_REQUEST_TEMPLATE.md)