Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(worktree): 修复远程创建失败后的回收与草稿恢复 (#5502)
DavidShenXDa5c582f4ebf6
diff --git a/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.tsindex b63d34282b..d39d9a4f8e 100644--- a/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts@@ -8,14 +8,26 @@ import type { WorktreeMeta } from '../worktree/types';const gitExecMock = vi.fn();const storeMap = new Map<string, WorktreeMeta>();const storeSetMock = vi.fn();+const profile = vi.hoisted(() => ({ root: '' }));+vi.mock('electron', () => ({ app: { getPath: () => profile.root } }));+vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ readLocalWorktreeReferences: async () => [] }) }));+vi.mock('../worktree/piSubagentReferences', () => ({ readPiSubagentWorktreeReferences: async () => new Map() }));+vi.mock('../worktree/runtimeLeases', () => ({+ readWorktreeRuntimePaths: async () => new Set(),+ acquireWorktreeRuntimeLease: async () => ({}),+ releaseWorktreeRuntimeLease: async () => {},+}));+const includeMock = vi.hoisted(() => vi.fn(async () => []));vi.mock('../worktree/gitExec', () => ({gitExec: (...args: unknown[]) => gitExecMock(...args),GitExecError: class GitExecError extends Error {},+ globalSafeDirectoryLockPath: () => path.join(profile.root, 'git-config.lock'),+ safeDirectorySpellings: (value: string) => [value],}));vi.mock('../worktree/includePatternsEngine', () => ({- applyWorktreeIncludeFile: vi.fn(async () => []),+ applyWorktreeIncludeFile: includeMock,listChangedWorktreeIncludeFiles: vi.fn(async () => []),}));@@ -25,6 +37,8 @@ vi.mock('../worktree/worktreeStore', () => ({getAllPaths: () => [...storeMap.values()].map((meta) => meta.path),set: (...args: unknown[]) => storeSetMock(...args),del: (sessionId: string) => storeMap.delete(sessionId),+ addPendingSafeDirectoryCleanups: async () => {},+ removePendingSafeDirectoryCleanups: async () => {},}));describe('createWorktree naming authority', () => {@@ -35,14 +49,21 @@ describe('createWorktree naming authority', () => {beforeEach(async () => {tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-worktree-create-'));+ profile.root = path.join(tmpRoot, 'profile');+ fs.mkdirSync(profile.root);baseRepo = path.join(tmpRoot, 'repo');fs.mkdirSync(baseRepo, { recursive: true });storeMap.clear();+ includeMock.mockReset().mockResolvedValue([]);storeSetMock.mockReset().mockImplementation(async (sessionId: string, meta: WorktreeMeta) => {storeMap.set(sessionId, meta);});randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0);- gitExecMock.mockReset().mockImplementation(async (args: string[]) => {+ gitExecMock.mockReset().mockImplementation(async (args: string[], cwd?: string) => {+ if (args[0] === 'symbolic-ref') {+ const meta = [...storeMap.values()].find((value) => value.path === cwd);+ return { stdout: `refs/heads/${meta?.branch ?? 'main'}\n`, stderr: '' };+ }if (args[0] === '--version') {return { stdout: 'git version 2.50.0\n', stderr: '' };}@@ -149,4 +170,81 @@ describe('createWorktree naming authority', () => {},});});++ it.each(['setup', 'metadata'])('serializes cancellation from a separate manager while creation awaits %s', async (stage) => {+ // Independent module instances model separate process-local queues. The+ // profile lock and cancellation marker are real shared filesystem state.+ const creator = manager;+ vi.resetModules();+ const canceller = await import('../worktree/WorktreeManager');+ let release!: () => void;+ let entered!: () => void;+ const ready = new Promise<void>((resolve) => { entered = resolve; });+ const pause = new Promise<void>((resolve) => { release = resolve; });+ if (stage === 'setup') {+ includeMock.mockImplementationOnce(async () => { entered(); await pause; return []; });+ } else {+ storeSetMock.mockImplementationOnce(async (id: string, meta: WorktreeMeta) => {+ entered(); await pause; storeMap.set(id, meta);+ });+ }+ const request = { sessionId: 'cross-process', baseRepo, name: 'race', sourceBranch: 'main', recoveryKey: 'cross-process-recovery' };+ const creating = creator.createWorktree(request);+ await ready;+ let cancellation: ReturnType<typeof manager.cancelPrecreatedWorktree> | undefined;+ try {+ cancellation = canceller.cancelPrecreatedWorktree(request.sessionId,+ { recoveryKey: request.recoveryKey }, { canRemove: async () => true });+ expect(await Promise.race([+ cancellation.then(() => 'cancelled'),+ new Promise<string>((resolve) => setTimeout(() => resolve('waiting'), 100)),+ ])).toBe('waiting');+ await expect(canceller.createWorktree({ ...request, sessionId: 'other-task', name: 'other' }))+ .resolves.toMatchObject({ ok: true });+ } finally {+ release();+ await creating;+ await cancellation;+ }+ expect(await creating).toMatchObject({ ok: true });+ expect(await cancellation).toMatchObject({ status: 'discarded' });+ expect(storeMap.has(request.sessionId)).toBe(false);+ expect(storeMap.has('other-task')).toBe(true);+ await expect(creator.createWorktree(request)).rejects.toThrow('PRECONDITION_FAILED');+ });++ it('rechecks a cancellation published during setup before registering metadata', async () => {+ const { sealPrecreatedSessionCancellation } = await import('../worktree/precreatedCancellation');+ const previousGit = gitExecMock.getMockImplementation()!;+ let finishCheckout!: () => void;+ const checkout = new Promise<{ stdout: string; stderr: string }>((resolve) => {+ finishCheckout = () => resolve({ stdout: '', stderr: '' });+ });+ gitExecMock.mockImplementation((args: string[], ...rest: unknown[]) =>+ args[0] === 'checkout' && args.includes(':(exclude).sivi') ? checkout : previousGit(args, ...rest));+ let marked!: () => void;+ const markReady = new Promise<void>((resolve) => { marked = resolve; });+ includeMock.mockImplementationOnce(async () => {+ // A peer on an older version may not participate in the new lock yet.+ sealPrecreatedSessionCancellation('cancel-during-setup');+ marked();+ return [];+ });+ const creating = create('cancelled', 'cancel-during-setup');+ await markReady;+ try {+ expect(await Promise.race([+ creating.then(() => 'completed'),+ new Promise<string>((resolve) => setTimeout(() => resolve('waiting'), 100)),+ ])).toBe('waiting');+ expect(gitExecMock).not.toHaveBeenCalledWith(['worktree', 'remove', path.join(baseRepo, '.cindy-worktrees', 'cancelled')], baseRepo);+ } finally {+ finishCheckout();+ await creating;+ }+ expect(await creating).toMatchObject({ ok: false });+ expect(storeSetMock).not.toHaveBeenCalled();+ expect(storeMap.has('cancel-during-setup')).toBe(false);+ expect(gitExecMock).toHaveBeenCalledWith(['worktree', 'remove', path.join(baseRepo, '.cindy-worktrees', 'cancelled')], baseRepo);+ });});diff --git a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.tsindex 0a442e7c3a..ec5456322f 100644--- a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts@@ -17,6 +17,14 @@ import fsSync from 'node:fs';import os from 'node:os';import type { WorktreeMeta } from '../worktree/types';+const cancelledIds = vi.hoisted(() => new Set<string>());+vi.mock('../worktree/precreatedCancellation', () => ({+ withPrecreatedSessionOperationLock: (_id: string, task: () => Promise<unknown>) => task(),+ sealPrecreatedSessionCancellation: (id: string) => { cancelledIds.add(id); },+ assertPrecreatedSessionNotCancelled: (id: string) => {+ if (cancelledIds.has(id)) throw new Error('PRECONDITION_FAILED: cancelled');+ },+}));import { withWorktreeRestoreMutation } from '../worktree/restoreLock';const gitExecMock = vi.fn();@@ -127,6 +135,7 @@ describe('removeWorktreeForSession', () => {beforeEach(async () => {vi.clearAllMocks();storeMap.clear();+ cancelledIds.clear();pendingSafeDirectoryCleanups.length = 0;liveSessionRows.length = 0;liveSessionRows.push({@@ -287,7 +296,38 @@ describe('removeWorktreeForSession', () => {expect(storeMap.get('s1')).toBe(meta);});- it('discard pre-created: recovery waits for an in-flight create before deciding the record is absent', async () => {+ it('cancellation seals an absent creation against a late worktree request', async () => {+ await expect(manager.cancelPrecreatedWorktree('late', { recoveryKey: 'key' }, { canRemove: async () => true }))+ .resolves.toEqual({ status: 'absent' });+ await expect(manager.createWorktree({ sessionId: 'late', baseRepo: BASE_REPO, name: 'late', sourceBranch: 'main', recoveryKey: 'key' }))+ .rejects.toThrow('PRECONDITION_FAILED');+ expect(gitExecMock).not.toHaveBeenCalled();+ });++ it('cancellation refuses mismatched or claimed records without sealing them', async () => {+ const meta = { ...makeMeta('s1'), recoveryKey: 'right' };+ storeMap.set('s1', meta);+ await expect(manager.cancelPrecreatedWorktree('s1', { recoveryKey: 'wrong' }, { canRemove: async () => true }))+ .resolves.toEqual({ status: 'path-mismatch' });+ await expect(manager.cancelPrecreatedWorktree('s1', { recoveryKey: 'right' }, { canRemove: async () => false }))+ .resolves.toEqual({ status: 'preserved' });+ expect(cancelledIds.size).toBe(0);+ expect(storeMap.get('s1')).toBe(meta);+ expect(gitExecMock).not.toHaveBeenCalled();+ });++ it('cancellation preserves dirty content while fencing late recreation', async () => {+ const meta = { ...makeMeta('s1'), recoveryKey: 'right' };+ storeMap.set('s1', meta);+ isWorktreeDirtyMock.mockResolvedValue(true);+ await expect(manager.cancelPrecreatedWorktree('s1', { recoveryKey: 'right' }, { canRemove: async () => true }))+ .resolves.toEqual({ status: 'preserved' });+ expect(cancelledIds.has('s1')).toBe(true);+ expect(storeMap.get('s1')).toBe(meta);+ expect(gitExecMock).not.toHaveBeenCalledWith(['worktree', 'remove', meta.path], BASE_REPO);+ });++ it.each(['discard', 'cancel'])('%s waits for an in-flight create before deciding the record is absent', async (operation) => {let releaseGitProbe!: () => void;gitExecMock.mockImplementationOnce(() =>@@ -316,8 +356,9 @@ describe('removeWorktreeForSession', () => {});let discardSettled = false;- const discard = manager- .discardPrecreatedWorktreeByRecoveryKey('s1', recoveryKey)+ const discard = (operation === 'cancel'+ ? manager.cancelPrecreatedWorktree('s1', { recoveryKey }, { canRemove: async () => true })+ : manager.discardPrecreatedWorktreeByRecoveryKey('s1', recoveryKey)).finally(() => {discardSettled = true;});@@ -327,6 +368,7 @@ describe('removeWorktreeForSession', () => {releaseGitProbe();await expect(create).resolves.toMatchObject({ ok: false });await expect(discard).resolves.toEqual({ status: 'absent' });+ expect(cancelledIds.has('s1')).toBe(operation === 'cancel');});it('discard pre-created: a matching recovery key resolves the registered path and reuses cleanup guards', async () => {diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex e260c32d67..9509ec5054 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -30,6 +30,7 @@ import { getActiveAuthRealm } from '../authManager.js';import { getCustomProvider, updateCustomProviderIfUnchanged } from './custom-provider-store.js';import { refreshCustomProvidersIntoCatalog } from './createDesktopProviderService.js';import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease, type WorktreeRuntimeLease } from '../worktree/runtimeLeases';+import { assertPrecreatedSessionNotCancelled } from '../worktree/precreatedCancellation';import { readCodexContextWindowInfo } from './codex-context-window.js';import { app, BrowserWindow } from 'electron';import { createHash, randomUUID } from 'node:crypto';@@ -2728,6 +2729,9 @@ export function getMaker(): Maker {if (!createOpts.remoteHostId && createOpts.workingDir) {const lease = await acquireWorktreeRuntimeLease(sessionId, createOpts.workingDir);if (lease) worktreeRuntimeLeases.set(opts, lease);+ // Recheck after acquiring the directory lease: cancellation may have+ // arrived during preparation or through another local instance.+ assertPrecreatedSessionNotCancelled(sessionId);}let skillLinksChanged = false;if (!createOpts.remoteHostId && createOpts.workingDir) {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/precreatedWorktreeDiscardHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/precreatedWorktreeDiscardHandler.test.tsindex afcb5d7f64..f6d3a3683b 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/precreatedWorktreeDiscardHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/precreatedWorktreeDiscardHandler.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest';import {registerPrecreatedWorktreeDiscardHandler,WORKTREE_DISCARD_PRECREATED_CHANNEL,+ WORKTREE_CANCEL_PRECREATED_CHANNEL,type PrecreatedWorktreeDiscardHandlerDeps,} from '../precreatedWorktreeDiscardHandler';import { IpcHarness } from './helpers/ipcHarness';@@ -27,6 +28,36 @@ function createDeps(}describe('worktree:discard-precreated IPC handler', () => {+ it('serializes cancellation with create and rechecks ownership at removal', async () => {+ const harness = new IpcHarness();+ let locked = false;+ const cancel = vi.fn<NonNullable<PrecreatedWorktreeDiscardHandlerDeps['cancel']>>(async (_id, _locator, options) => {+ expect(locked).toBe(true);+ expect(await options.canRemove()).toBe(true);+ return { status: 'absent' as const };+ });+ const deps = createDeps({ cancel, withSessionLock: async (_id, task) => {+ locked = true;+ try { return await task(); } finally { locked = false; }+ } });+ registerPrecreatedWorktreeDiscardHandler(harness, deps);+ await expect(harness.invoke(WORKTREE_CANCEL_PRECREATED_CHANNEL, { sessionId: 'id', recoveryKey: 'key' }))+ .resolves.toEqual({ discarded: true });+ expect(deps.isSessionClaimed).toHaveBeenCalledTimes(2);+ expect(deps.discard).not.toHaveBeenCalled();+ expect(deps.discardByRecoveryKey).not.toHaveBeenCalled();+ });++ it.each([true, 'unreadable'])('does not cancel when ownership is %s', async (ownership) => {+ const harness = new IpcHarness();+ const deps = createDeps({+ cancel: vi.fn(),+ isSessionClaimed: async () => { if (ownership === 'unreadable') throw new Error('DB unavailable'); return true; },+ });+ registerPrecreatedWorktreeDiscardHandler(harness, deps);+ await expect(harness.invoke(WORKTREE_CANCEL_PRECREATED_CHANNEL, { sessionId: 'id', path: '/repo/worktree' })).rejects.toThrow();+ expect(deps.cancel).not.toHaveBeenCalled();+ });it('validates the caller and payload before touching ownership or worktree state', async () => {const harness = new IpcHarness();const deps = createDeps();diff --git a/apps/desktop/src/main/maker-ipc/precreatedWorktreeDiscardHandler.ts b/apps/desktop/src/main/maker-ipc/precreatedWorktreeDiscardHandler.tsindex de20a02cc1..a651acde2b 100644--- a/apps/desktop/src/main/maker-ipc/precreatedWorktreeDiscardHandler.ts+++ b/apps/desktop/src/main/maker-ipc/precreatedWorktreeDiscardHandler.ts@@ -11,6 +11,7 @@ import { requireObject, requireString, throwIpcError } from '../utils/ipcValidatimport type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';export const WORKTREE_DISCARD_PRECREATED_CHANNEL = 'worktree:discard-precreated';+export const WORKTREE_CANCEL_PRECREATED_CHANNEL = 'worktree:cancel-precreated';const MAX_SESSION_ID_LENGTH = 256;const MAX_EXPECTED_PATH_LENGTH = 4_096;@@ -31,6 +32,11 @@ export interface PrecreatedWorktreeDiscardHandlerDeps {recoveryKey: string,options: { canRemove: () => Promise<boolean> },): Promise<DiscardPrecreatedWorktreeResult>;+ cancel?: (+ sessionId: string,+ locator: { path?: string; recoveryKey?: string },+ options: { canRemove: () => Promise<boolean> },+ ) => Promise<DiscardPrecreatedWorktreeResult>;}async function readSessionClaimed(@@ -49,7 +55,7 @@ export function registerPrecreatedWorktreeDiscardHandler(registry: IpcHandlerRegistry,deps: PrecreatedWorktreeDiscardHandlerDeps,): void {- registry.handle(WORKTREE_DISCARD_PRECREATED_CHANNEL, async (event, raw: unknown) => {+ const register = (channel: string, cancel: boolean) => registry.handle(channel, async (event, raw: unknown) => {deps.assertCaller(event);const body = requireObject(raw, 'discard pre-created worktree request');const sessionId = requireString(body.sessionId, 'sessionId');@@ -84,7 +90,11 @@ export function registerPrecreatedWorktreeDiscardHandler(// WorktreeManager 在真正删除前再次调用,封住 ownership 查询后的竞态窗口。canRemove: async () => !(await readSessionClaimed(deps, sessionId)),};- if (expectedPath !== null) {+ if (cancel) {+ if (!deps.cancel) throw new Error('Cancellation unavailable');+ result = await deps.cancel(sessionId,+ expectedPath !== null ? { path: expectedPath } : { recoveryKey: recoveryKey! }, options);+ } else if (expectedPath !== null) {result = await deps.discard(sessionId, expectedPath, options);} else if (recoveryKey !== null) {result = await deps.discardByRecoveryKey(sessionId, recoveryKey, options);@@ -110,4 +120,6 @@ export function registerPrecreatedWorktreeDiscardHandler(};});});+ register(WORKTREE_DISCARD_PRECREATED_CHANNEL, false);+ if (deps.cancel) register(WORKTREE_CANCEL_PRECREATED_CHANNEL, true);}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 0162aff3f6..0d45d58e13 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -7092,6 +7092,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)didInjectProjectContext: boolean;}> {assertAccess?.();+ if (o.id && !o.remoteHostId) worktreeManager.assertPrecreatedSessionNotCancelled(o.id);if (o.id && o.workingDir && !o.remoteHostId) {o.workingDir = workingDirectoryRecovery.resolve(o.id, o.workingDir);await workingDirectoryRecovery.observe(o.id, o.workingDir).catch((error) => {@@ -8624,6 +8625,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)worktreeManager.discardPrecreatedWorktree(sessionId, expectedPath, options),discardByRecoveryKey: (sessionId, recoveryKey, options) =>worktreeManager.discardPrecreatedWorktreeByRecoveryKey(sessionId, recoveryKey, options),+ cancel: (sessionId, locator, options) =>+ worktreeManager.cancelPrecreatedWorktree(sessionId, locator, options),});// turn 运行中登记的切换意图(下一条消息发送时刻由 send 事务 apply)。diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.tsindex 8cac09b540..92ea6478fd 100644--- a/apps/desktop/src/main/worktree/WorktreeManager.ts+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts@@ -47,6 +47,7 @@ import { recycleManagedWorktree } from './managedRecycle';import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease } from './runtimeLeases';import * as store from './worktreeStore';+import { assertPrecreatedSessionNotCancelled, sealPrecreatedSessionCancellation, withPrecreatedSessionOperationLock } from './precreatedCancellation';import { createLogger } from '../logger';import { getDbClient } from '../localDb/client/current';import {@@ -385,7 +386,7 @@ async function withPrecreatedWorktreeOperationQueue<T>(await previous.catch(() => {});try {- return await fn();+ return await withPrecreatedSessionOperationLock(sessionId, fn);} finally {releaseCurrent();if (precreatedWorktreeOperationQueues.get(sessionId) === queued) {@@ -1016,10 +1017,11 @@ export async function copyClaudeSiviDirs(* 删除/归档时由 removeWorktreeForSession 清理该 path 的条目, 见 #2627)*/export async function createWorktree(req: CreateWorktreeReq): Promise<CreateWorktreeResp> {- const create = () => withCreateWorktreeQueue(req.baseRepo, () => createWorktreeInner(req));- return req.recoveryKey === undefined- ? create()- : withPrecreatedWorktreeOperationQueue(req.sessionId, create);+ const create = () => withCreateWorktreeQueue(req.baseRepo, () => {+ assertPrecreatedSessionNotCancelled(req.sessionId);+ return createWorktreeInner(req);+ });+ return withPrecreatedWorktreeOperationQueue(req.sessionId, create);}async function createWorktreeInner(req: CreateWorktreeReq): Promise<CreateWorktreeResp> {@@ -1213,7 +1215,16 @@ async function createWorktreeInner(req: CreateWorktreeReq): Promise<CreateWorktr);}- // 9. store + DB+ // 9. Recheck after asynchronous Git/setup work before publishing metadata.+ // The profile/session lock also closes the check -> store.set window.+ try {+ assertPrecreatedSessionNotCancelled(req.sessionId);+ } catch (error) {+ // Rollback must not race our own background checkout writer.+ await bgPromise?.catch(() => undefined);+ throw error;+ }+ // store + DBconst meta: WorktreeMeta = {sessionId: req.sessionId,name,@@ -1597,6 +1608,30 @@ export type DiscardPrecreatedWorktreeResult =| { status: 'preserved' }| { status: 'discarded'; branchDeleted: boolean };+/** Caller holds the session-create lock. Seal before deleting so a late create+ * cannot resurrect the cancelled id. Keep the seal even if dirty files prevent+ * removal; the same explicit cancellation can safely be retried later. */+export async function cancelPrecreatedWorktree(+ sessionId: string,+ locator: { path?: string; recoveryKey?: string },+ options: Pick<RemoveWorktreeOptions, 'canRemove'>,+): Promise<DiscardPrecreatedWorktreeResult> {+ return withPrecreatedWorktreeOperationQueue(sessionId, async () => {+ const meta = store.get(sessionId);+ if (meta && (locator.recoveryKey !== undefined+ ? meta.recoveryKey !== locator.recoveryKey+ : !locator.path || (path.resolve(meta.path) !== path.resolve(locator.path)+ && (!meta.quarantinePath || path.resolve(meta.quarantinePath) !== path.resolve(locator.path))))) {+ return { status: 'path-mismatch' };+ }+ if (meta?.ephemeral) return { status: 'preserved' };+ if (!options.canRemove || !(await options.canRemove())) return { status: 'preserved' };+ sealPrecreatedSessionCancellation(sessionId);+ return meta ? discardPrecreatedWorktree(sessionId, meta.path, options) : { status: 'absent' };+ });+}+export { assertPrecreatedSessionNotCancelled } from './precreatedCancellation';+/*** 手机在 worktree:create 之前先持久化 sessionId + recoveryKey;若进程在 create* 回包前退出,恢复端拿不到 path。这里仅在随机关联键与被控端持久元数据精确匹配时diff --git a/apps/desktop/src/main/worktree/__tests__/precreatedCancellation.test.ts b/apps/desktop/src/main/worktree/__tests__/precreatedCancellation.test.tsnew file mode 100644index 0000000000..6292bb2910--- /dev/null+++ b/apps/desktop/src/main/worktree/__tests__/precreatedCancellation.test.ts@@ -0,0 +1,39 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const profile = vi.hoisted(() => ({ root: '' }));+vi.mock('electron', () => ({ app: { getPath: () => profile.root } }));+import { assertPrecreatedSessionNotCancelled, sealPrecreatedSessionCancellation, withPrecreatedSessionOperationLock } from '../precreatedCancellation';++describe('durable precreated cancellation', () => {+ beforeEach(() => { profile.root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-cancel-test-')); });+ afterEach(() => { fs.rmSync(profile.root, { recursive: true, force: true }); });++ it('survives module reload, is idempotent, and fences only the cancelled id', async () => {+ assertPrecreatedSessionNotCancelled('cancelled');+ sealPrecreatedSessionCancellation('cancelled');+ sealPrecreatedSessionCancellation('cancelled');+ vi.resetModules();+ const fresh = await import('../precreatedCancellation');+ expect(() => fresh.assertPrecreatedSessionNotCancelled('cancelled')).toThrow('PRECONDITION_FAILED');+ expect(() => fresh.assertPrecreatedSessionNotCancelled('other')).not.toThrow();+ expect(fs.readdirSync(path.join(profile.root, 'worktree-cancelled-creations'))).toHaveLength(1);+ });++ it('does not interpret a caller-controlled id as a path', () => {+ sealPrecreatedSessionCancellation('../../outside');+ const files = fs.readdirSync(path.join(profile.root, 'worktree-cancelled-creations'));+ expect(files).toEqual([expect.stringMatching(/^[a-f0-9]{64}$/)]);+ });++ it('fails closed when the cancellation store is unreadable', async () => {+ fs.writeFileSync(path.join(profile.root, 'worktree-cancelled-creations'), 'not a directory');+ expect(() => assertPrecreatedSessionNotCancelled('id')).toThrow();+ expect(() => sealPrecreatedSessionCancellation('id')).toThrow();+ const operation = vi.fn(async () => {});+ await expect(withPrecreatedSessionOperationLock('id', operation)).rejects.toThrow();+ expect(operation).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/worktree/precreatedCancellation.ts b/apps/desktop/src/main/worktree/precreatedCancellation.tsnew file mode 100644index 0000000000..dd6298460c--- /dev/null+++ b/apps/desktop/src/main/worktree/precreatedCancellation.ts@@ -0,0 +1,49 @@+import { createHash } from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';+import { app } from 'electron';+import { withCrossProcessLock } from '../device-link/crossProcessLock';++// A cancelled creation id must never be reused, including after a restart. An+// empty, exclusively-created file is an atomic tombstone; no user content or+// recovery key is stored. Unlike a negative DB query it also fences late calls.+function marker(sessionId: string): string {+ return path.join(app.getPath('userData'), 'worktree-cancelled-creations',+ createHash('sha256').update(sessionId).digest('hex'));+}++/** Serialize creation/registration and cancellation across processes sharing a profile. */+export async function withPrecreatedSessionOperationLock<T>(sessionId: string, task: () => Promise<T>): Promise<T> {+ const lockPath = `${marker(sessionId)}.lock`;+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ return withCrossProcessLock(lockPath, { label: 'precreated-worktree', waitMs: 10_000 }, async (status) => {+ if (!status.held) throw new Error('PRECONDITION_FAILED: Worktree creation or cancellation is still in progress');+ return task();+ });+}++export function assertPrecreatedSessionNotCancelled(sessionId: string): void {+ const file = marker(sessionId);+ try {+ // Windows can return ENOENT for a child of a non-directory. Check the+ // store itself before treating a missing marker as permission to create.+ const root = fs.lstatSync(path.dirname(file));+ if (!root.isDirectory() || root.isSymbolicLink()) throw new Error('Invalid worktree cancellation store');+ fs.statSync(file);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;+ throw error;+ }+ throw new Error('PRECONDITION_FAILED: Worktree creation was cancelled; create a new task');+}++export function sealPrecreatedSessionCancellation(sessionId: string): void {+ const file = marker(sessionId);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ try {+ const fd = fs.openSync(file, 'wx', 0o600);+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;+ }+}diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex 02604f7571..25a82451b6 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -1,3 +1,4 @@+import { completePrecreatedWorktreeRecovery } from '@/session/completePrecreatedWorktreeRecovery';import { recentTaskKey } from '@/session/recentTasks';import { readComposerEntry } from '@/session/composerMorph';import { RecentMessageHistoriesProvider } from '@/session/RecentMessageHistories';@@ -301,6 +302,8 @@ function PrecreatedWorktreeRecoveryBridge() {'worktree:discard-precreated',[input],),+ cancelPrecreated: (deviceId, input) => invoke(deviceId, 'worktree:cancel-precreated', [input]),+ onDiscarded: completePrecreatedWorktreeRecovery,isSessionClaimed: (deviceId, sessionId) => isExactRemoteSessionClaimed(sessionId,(id) => invoke(deviceId, 'local-db:sessions:get', [id]),diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 5d490c3061..3b50e560f6 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -1,4 +1,6 @@import { modelNeedsReselection } from '@/session/modelReselection';+import { completePrecreatedWorktreeRecovery } from '@/session/completePrecreatedWorktreeRecovery';+import { outboxCreationRetryIdentity } from '@/session/cancelledCreationDraft';import { isRemoteTaskSuggestionId } from '@/session/remoteTaskSuggestionsModel';import { mobileDurableOutbox, holdDurableOutboxCreation, getCurrentMobileOutboxRecords } from '@/session/mobileDurableOutbox';import { retainOutboxFile, durableOutboxUploadUri, removeRetainedOutboxFiles, outboxAttachmentNeedsLocalBytes } from '@/session/durableOutboxFiles';@@ -4412,11 +4414,10 @@ export default function NewRemoteSessionScreen() {},});const worktreeAccountId = authOwnerAtCreate.accountId;- if (- worktreeIntent.applicable+ const creatingWorktree = worktreeIntent.applicable&& worktreeIntent.enabled- && worktreeIntent.eligibility.status === 'eligible'- ) {+ && worktreeIntent.eligibility.status === 'eligible';+ if (creatingWorktree || outboxRecoveryRef.current) {// 两步创建必须先有可归属的账号账本。不能先在工作端落盘,再发现本地// 无法按账号持久化 cleanup obligation。if (!worktreeAccountId) {@@ -4435,6 +4436,10 @@ export default function NewRemoteSessionScreen() {discardPrecreated: async (_deviceId, input) => (maker.worktree.discardPrecreated(input)),+ cancelPrecreated: maker.worktree.cancelPrecreated+ ? async (_deviceId, input) => maker.worktree.cancelPrecreated!(input)+ : undefined,+ onDiscarded: completePrecreatedWorktreeRecovery,isSessionClaimed: async (_deviceId, pendingSessionId) => (isExactRemoteSessionClaimed(pendingSessionId,@@ -4443,6 +4448,7 @@ export default function NewRemoteSessionScreen() {),shouldDefer: (record) => (record.deviceId !== selectedDeviceId+ || (!creatingWorktree && record.sessionId !== outboxRecoveryRef.current?.item.sessionId)|| obligationOwnedByLiveTask(record.sessionId)),isCurrent: isCurrentOwner,@@ -4457,7 +4463,7 @@ export default function NewRemoteSessionScreen() {setError(t('session.new.worktreeCleanupPending'));return;}- if (!isWorktreeCreateIntentCurrent(worktreeIntent)) {+ if (creatingWorktree && !isWorktreeCreateIntentCurrent(worktreeIntent)) {setError(t(resolveWorktreeCreateErrorKey()));return;}@@ -4466,25 +4472,102 @@ export default function NewRemoteSessionScreen() {// 幂等),点创建**立即**进入会话页;openLink / 鉴权 revalidate / createSession// / 首条消息 enqueue 全部由 newSessionCreation 模块级后台管线完成(本页// unmount 不终止),失败重试面在会话页(横幅:重试 / 返回编辑)。- const recovering = outboxRecoveryRef.current;+ // Recovery may have cancelled this creation while the editor was already open.+ const previousRecovery = outboxRecoveryRef.current;+ const recovering = previousRecovery+ ? getCurrentMobileOutboxRecords().find((r) => r.deviceId === previousRecovery.deviceId+ && r.item.clientId === previousRecovery.item.clientId+ && r.item.sessionId === previousRecovery.item.sessionId)+ : null;+ if (previousRecovery && !recovering) throw new Error('OUTBOX_STALE_WRITE');if (recovering && recovering.deviceId !== selectedDeviceId) {throw new Error(t('session.outbox.recoveryTarget'));}- const sessionId = recovering?.item.sessionId ?? createNewSessionId();+ if (recovering?.creation?.cancelled && previousRecovery?.creation+ && effectiveDraft.workingDir === previousRecovery.creation.draft.workingDir+ && effectiveDraft.workingDir !== recovering.creation.draft.workingDir) {+ // Eligibility and branch preference belong to the old directory. Let the+ // form probe the restored target before accepting another submission.+ outboxRecoveryRef.current = recovering;+ setDraft((current) => ({ ...current, workingDir: recovering.creation!.draft.workingDir }));+ return;+ }+ const recoveryIdentity = recovering ? outboxCreationRetryIdentity(recovering, createNewSessionId) : null;+ const sessionId = recoveryIdentity?.sessionId ?? createNewSessionId();if (recovering) {// Editing creation parameters is allowed only after the original task is proven absent.let found = false;- try { found = !!(await maker.getSession(sessionId)); }+ try { found = !!(await maker.getSession(recovering.item.sessionId)); }catch (error) {if (!formatRemoteError(error).includes('NOT_FOUND')) throw error;}if (!isCurrentOwner()) return;if (found) {- const latest = getCurrentMobileOutboxRecords().find((r) => r.item.clientId === recovering.item.clientId && r.item.sessionId === sessionId);+ const latest = getCurrentMobileOutboxRecords().find((r) => r.item.clientId === recovering.item.clientId && r.item.sessionId === recovering.item.sessionId);if (latest && !latest.prepared) await mobileDurableOutbox.update(latest, { suspended: false, state: 'queued' });throw new Error(t('session.outbox.taskAlreadyCreated'));}}+ // Preserve input and attachment bytes before reserving or creating a remote worktree.+ const agentKindSnapshot = effectiveDraft.agentKind;+ const deviceIdSnapshot = selectedDeviceId;+ // 老协议 plan 一次性语义(对齐桌面 PR#494):入队后恢复进入前的底层权限档。+ const legacyPlanRestore = effectiveDraft.permissionMode === 'plan'+ ? (() => {+ const fallback = runtimeOptions.permissionOptions.find((option) => option.id !== 'plan')?.id ?? 'ask';+ const remembered = prePlanPermissionModeRef.current;+ return remembered && remembered !== 'plan' ? remembered : fallback;+ })()+ : null;+ if (!isCurrentOwner()) return;+ releaseDurableCreation = holdDurableOutboxCreation(sessionId);+ const firstMessageClientId = recovering?.item.clientId ?? createOutboxClientId();+ // Legacy Plan requires a live session-wide permission change. Keep its existing+ // online creation pipeline instead of introducing deferred permission mutations.+ const useDurableCreation = legacyPlanRestore === null;+ if (recovering && !useDurableCreation) throw new Error(t('session.outbox.legacyPlanRecovery'));+ if (useDurableCreation) {+ let firstRecord: DurableOutboxRecord = {+ version: 1, accountId: authOwnerAtCreate.accountKey, deviceId: deviceIdSnapshot,+ ...(recoveryIdentity ? { storageSessionId: recoveryIdentity.storageSessionId } : {}),+ createdAt: recovering?.createdAt ?? Date.now(), state: 'queued', suspended: creatingWorktree, uploads: [], clearBoundaryMs: null,+ creation: { draft: effectiveDraft, deviceName: selectedDeviceName,+ ...(creatingWorktree ? { originalWorkingDir: effectiveDraft.workingDir } : {}),+ planModeArm: planModeCapability && planModeDraftOn, restorePermissionMode: legacyPlanRestore },+ item: buildOutboxItem({+ clientId: firstMessageClientId, sessionId, text: effectiveDraft.firstMessage,+ quotesEncoded: false, agentReferences: [], pastedTextRanges: [], slashCommandRanges: [],+ permissionModeAtSend: effectiveDraft.permissionMode, readyAttachments: sendAttachments,+ readyPreviews: sendAttachments.map((a) => attachmentPreviews[a.id] ?? null), claimedUploads: [],+ }),+ };+ let filesCommitted = false;+ try {+ for (let slot = 0; slot < sendAttachments.length; slot++) {+ const attachment = sendAttachments[slot];+ const source = getUploadedSource(attachment.id);+ const oldSlot = recovering?.item.attachmentSlots.findIndex((a) => a?.id === attachment.id);+ const oldUpload = recovering?.uploads.find((u) => u.slot === oldSlot);+ if (source) firstRecord.uploads.push(await retainOutboxFile(firstRecord, slot, source));+ else if (recovering && oldUpload) firstRecord.uploads.push(await retainOutboxFile(firstRecord, slot, {+ ...oldUpload, uri: durableOutboxUploadUri(recovering, oldUpload),+ }));+ else if (outboxAttachmentNeedsLocalBytes(attachment)) throw new Error(t('session.screen.attachmentsNotCarriedBack', { count: 1 }));+ }+ if (!isCurrentOwner() || !ensureDeviceAlive()) return;+ if (recovering) {+ const latest = getCurrentMobileOutboxRecords().find((r) => r.item.clientId === firstMessageClientId && r.item.sessionId === recovering.item.sessionId);+ if (latest !== recovering || latest.prepared) throw new Error('OUTBOX_STALE_WRITE');+ firstRecord = await mobileDurableOutbox.update(latest, firstRecord);+ } else await mobileDurableOutbox.add(firstRecord);+ filesCommitted = true;+ } finally {+ if (!filesCommitted) await removeRetainedOutboxFiles(firstRecord).catch(() => undefined);+ }+ outboxRecoveryRef.current = firstRecord;+ if (!isCurrentOwner() || !ensureDeviceAlive()) return;+ releaseUploadedSources(sendAttachments.map((a) => a.id));+ }let precreatedWorktree: {path: string;recoveryKey: string;@@ -4643,62 +4726,14 @@ export default function NewRemoteSessionScreen() {return;}}- const agentKindSnapshot = effectiveDraft.agentKind;- const deviceIdSnapshot = selectedDeviceId;- // 老协议 plan 一次性语义(对齐桌面 PR#494):入队后恢复进入前的底层权限档。- const legacyPlanRestore = effectiveDraft.permissionMode === 'plan'- ? (() => {- const fallback = runtimeOptions.permissionOptions.find((option) => option.id !== 'plan')?.id ?? 'ask';- const remembered = prePlanPermissionModeRef.current;- return remembered && remembered !== 'plan' ? remembered : fallback;- })()- : null;- if (!isCurrentOwner()) return;- releaseDurableCreation = holdDurableOutboxCreation(sessionId);- const firstMessageClientId = recovering?.item.clientId ?? createOutboxClientId();- // Legacy Plan requires a live session-wide permission change. Keep its existing- // online creation pipeline instead of introducing deferred permission mutations.- const useDurableCreation = legacyPlanRestore === null;- if (recovering && !useDurableCreation) throw new Error(t('session.outbox.legacyPlanRecovery'));- if (useDurableCreation) {- const firstRecord: DurableOutboxRecord = {- version: 1, accountId: authOwnerAtCreate.accountKey, deviceId: deviceIdSnapshot,- createdAt: recovering?.createdAt ?? Date.now(), state: 'queued', suspended: false, uploads: [], clearBoundaryMs: null,- creation: { draft: effectiveDraft, deviceName: selectedDeviceName,- planModeArm: planModeCapability && planModeDraftOn, restorePermissionMode: legacyPlanRestore },- item: buildOutboxItem({- clientId: firstMessageClientId, sessionId, text: effectiveDraft.firstMessage,- quotesEncoded: false, agentReferences: [], pastedTextRanges: [], slashCommandRanges: [],- permissionModeAtSend: effectiveDraft.permissionMode, readyAttachments: sendAttachments,- readyPreviews: sendAttachments.map((a) => attachmentPreviews[a.id] ?? null), claimedUploads: [],- }),- };- let filesCommitted = false;- try {- for (let slot = 0; slot < sendAttachments.length; slot++) {- const attachment = sendAttachments[slot];- const source = getUploadedSource(attachment.id);- const oldSlot = recovering?.item.attachmentSlots.findIndex((a) => a?.id === attachment.id);- const oldUpload = recovering?.uploads.find((u) => u.slot === oldSlot);- if (source) firstRecord.uploads.push(await retainOutboxFile(firstRecord, slot, source));- else if (recovering && oldUpload) firstRecord.uploads.push(await retainOutboxFile(firstRecord, slot, {- ...oldUpload, uri: durableOutboxUploadUri(recovering, oldUpload),- }));- else if (outboxAttachmentNeedsLocalBytes(attachment)) throw new Error(t('session.screen.attachmentsNotCarriedBack', { count: 1 }));- }- if (!isCurrentOwner() || !ensureDeviceAlive()) return;- if (recovering) {- const latest = getCurrentMobileOutboxRecords().find((r) => r.item.clientId === firstMessageClientId && r.item.sessionId === sessionId);- if (!latest || latest.prepared) throw new Error('OUTBOX_STALE_WRITE');- await mobileDurableOutbox.update(latest, firstRecord);- } else await mobileDurableOutbox.add(firstRecord);- filesCommitted = true;- } finally {- if (!filesCommitted) await removeRetainedOutboxFiles(firstRecord).catch(() => undefined);- }- outboxRecoveryRef.current = firstRecord;+ if (useDurableCreation && precreatedWorktree) {+ const current = outboxRecoveryRef.current;+ if (!current?.creation || current.item.sessionId !== sessionId) throw new Error('OUTBOX_STALE_WRITE');+ const updated = await mobileDurableOutbox.update(current, {+ creation: { ...current.creation, draft: effectiveDraft }, suspended: false,+ });+ outboxRecoveryRef.current = updated;if (!isCurrentOwner() || !ensureDeviceAlive()) return;- releaseUploadedSources(sendAttachments.map((a) => a.id));}// 提交点联合终检(Greptile/Codex review P1):目录就绪后的清理 effect 跑在渲染后,// 用户可能在清理生效前点创建——创建路径自身必须守卫;来源失效时 model 随之一并@@ -5092,6 +5127,10 @@ export default function NewRemoteSessionScreen() {discardPrecreated: async (_deviceId, recoveryInput) => (maker.worktree.discardPrecreated(recoveryInput)),+ cancelPrecreated: maker.worktree.cancelPrecreated+ ? async (_deviceId, input) => maker.worktree.cancelPrecreated!(input)+ : undefined,+ onDiscarded: completePrecreatedWorktreeRecovery,isSessionClaimed: async (_deviceId, pendingSessionId) => (isExactRemoteSessionClaimed(pendingSessionId,diff --git a/apps/mobile/src/__tests__/durableOutbox.test.ts b/apps/mobile/src/__tests__/durableOutbox.test.tsindex a57bdbf0bf..9aeccbee15 100644--- a/apps/mobile/src/__tests__/durableOutbox.test.ts+++ b/apps/mobile/src/__tests__/durableOutbox.test.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi } from "vitest";import { accountVaultKey } from '@cindy/auth-client';+import { cancelledCreationDraft, outboxCreationRetryIdentity } from '../session/cancelledCreationDraft';import {createDurableOutbox,isDurableOutboxUnsent,@@ -65,6 +66,66 @@ function message(},};}++describe('cancelled worktree draft recovery across restarts', () => {+ it('retains one durable record and its attachments while successive retries rotate remote IDs', async () => {+ const storage = disk();+ let store = createDurableOutbox(storage);+ await store.activate('alice');+ const initial = message();+ initial.creation = {+ draft: { workingDir: '/repo/.cindy-worktrees/failed', firstMessage: initial.item.text } as NonNullable<DurableOutboxRecord['creation']>['draft'],+ originalWorkingDir: '/repo/subdir', deviceName: 'Mac', planModeArm: false, restorePermissionMode: null,+ };+ initial.uploads = [{ slot: 0, fileName: 'slot-0.png', name: 'image.png', kind: 'image', size: 12 }];+ await store.add(initial);+ const originalKey = [...storage.data.keys()][0];+ for (const newId of ['retry-1', 'retry-2']) {+ // Cold start, host cancellation ACK, persist, another cold start, then user resubmits.+ store = createDurableOutbox(storage);+ await store.activate('alice');+ let row = store.getSnapshot()[0];+ await store.update(row, cancelledCreationDraft(row));+ store = createDurableOutbox(storage);+ await store.activate('alice');+ row = store.getSnapshot()[0];+ expect(row.creation?.draft.workingDir).toBe('/repo/subdir');+ expect(row.suspended).toBe(true);+ const identity = outboxCreationRetryIdentity(row, () => newId);+ expect(identity.sessionId).toBe(newId);+ await store.update(row, { storageSessionId: identity.storageSessionId,+ item: { ...row.item, sessionId: identity.sessionId },+ creation: { ...row.creation!, cancelled: undefined }, suspended: false,+ });+ store = createDurableOutbox(storage);+ await store.activate('alice');+ expect(store.getSnapshot()).toHaveLength(1);+ expect(store.getSnapshot()[0]).toMatchObject({ item: { sessionId: newId, text: initial.item.text }, uploads: initial.uploads });+ expect([...storage.data.keys()]).toEqual([originalKey]);+ }+ await store.remove(store.getSnapshot()[0]);+ expect(storage.data.size).toBe(0);+ });++ it('preserves the cancelled draft after a failed resubmission write', async () => {+ const storage = disk();+ const store = createDurableOutbox(storage);+ await store.activate('alice');+ const initial = message();+ initial.creation = { draft: { workingDir: 'D:\\repo\\.cindy-worktrees\\failed' } as NonNullable<DurableOutboxRecord['creation']>['draft'],+ deviceName: 'PC', planModeArm: false, restorePermissionMode: null };+ const row = cancelledCreationDraft(initial);+ expect(row.creation?.draft.workingDir).toBe('D:\\repo');+ await store.add(row);+ storage.setItem = async () => { throw new Error('disk full'); };+ const identity = outboxCreationRetryIdentity(row, () => 'fresh');+ await expect(store.update(row, { storageSessionId: identity.storageSessionId,+ item: { ...row.item, sessionId: identity.sessionId } })).rejects.toThrow('disk full');+ const restarted = createDurableOutbox(storage);+ await restarted.activate('alice');+ expect(restarted.getSnapshot()[0]).toEqual(row);+ });+});function projection(clientId = "id-1",state: "unknown" | "pending" | "accepted" | "removed" = "unknown",diff --git a/apps/mobile/src/__tests__/durableOutboxFiles.test.ts b/apps/mobile/src/__tests__/durableOutboxFiles.test.tsindex 31efb0a278..8496fdf57b 100644--- a/apps/mobile/src/__tests__/durableOutboxFiles.test.ts+++ b/apps/mobile/src/__tests__/durableOutboxFiles.test.ts@@ -60,6 +60,7 @@ beforeEach(() => {delete (globalThis as { __cindyOutboxFilesInitialized?: Promise<void> }).__cindyOutboxFilesInitialized;fs.ledger.clear();fs.directories.clear();+ fs.readDirectoryAsync.mockImplementation(async (uri) => fs.directories.get(uri) ?? []);fs.stageExists = true;fs.stagePaths.length = 0;fs.removeStage.mockReset();@@ -71,24 +72,53 @@ beforeEach(() => {});});describe("outbox-owned attachment bytes", () => {+ it('preserves retained bytes when native directory listings decode realm-qualified account names', async () => {+ const r = { ...record, version: 1, accountId: '["global","qa-user"]', deviceId: 'host',+ storageSessionId: 'original.id', item: { sessionId: 'new-id', clientId: 'message' },+ uploads: [{ fileName: 'slot-0.txt' }] } as DurableOutboxRecord;+ const root = fs.documentDirectory + 'message-outbox/';+ const parts = [r.accountId, r.deviceId, r.storageSessionId!, r.item.clientId];+ let uri = root;+ for (const name of parts) {+ fs.directories.set(decodeURIComponent(uri), [name]); // Native filesystem names are decoded.+ uri += encodeURIComponent(name).replace(/\./g, '%2E') + '/';+ }+ fs.directories.set(decodeURIComponent(uri), ['slot-0.txt', 'slot-1.txt']);+ fs.ledger.set('cindy.mobile.outbox.v1.fixture', JSON.stringify(r));+ fs.readDirectoryAsync.mockImplementation(async (path) => fs.directories.get(decodeURIComponent(path)) ?? []);+ fs.getInfoAsync.mockImplementation(async (path) => ({ exists: true, isDirectory: fs.directories.has(decodeURIComponent(path)), size: 24 }));+ await initializeOutboxFiles();+ expect(fs.deleteAsync).toHaveBeenCalledExactlyOnceWith(uri + 'slot-1.txt', { idempotent: true });+ });+ it('keeps retained bytes at the stable location after a cancelled creation rotates session ID', async () => {+ const replacement = { ...record, storageSessionId: record.item.sessionId,+ item: { ...record.item, sessionId: 'fresh-session' } };+ expect(durableOutboxDirectory(replacement)).toBe(durableOutboxDirectory(record));+ const upload: DurableUpload = { slot: 0, fileName: 'slot-0.jpg', name: 'photo.jpg', kind: 'image', size: 123 };+ const retained = await retainOutboxFile(replacement, 0, {+ ...upload, uri: durableOutboxUploadUri(record, upload),+ });+ expect(fs.copyAsync).toHaveBeenCalledWith({ from: durableOutboxUploadUri(record, upload), to: durableOutboxUploadUri(replacement, retained) });+ expect(retained.fileName).not.toBe(upload.fileName);+ });it('reclaims pre-commit and replaced files while preserving every account ledger', async () => {const root = fs.documentDirectory + 'message-outbox/';fs.directories.set(root, ['alice', 'bob']);for (const accountId of ['alice', 'bob']) {- const r = { ...record, version: 1, accountId, uploads: [{ fileName: 'slot-0.jpg' }] } as DurableOutboxRecord;+ const r = { ...record, version: 1, accountId, item: { ...record.item, sessionId: 'session.name' }, uploads: [{ fileName: 'slot-0.jpg' }] } as DurableOutboxRecord;const dir = durableOutboxDirectory(r);fs.ledger.set(`cindy.mobile.outbox.v1.${accountId}/mac/session/id`, JSON.stringify(r));fs.directories.set(root + accountId + '/', ['mac']);- fs.directories.set(root + accountId + '/mac/', ['%2E%2E%2Fsession']);- fs.directories.set(root + accountId + '/mac/%2E%2E%2Fsession/', ['id', 'uncommitted']);+ fs.directories.set(root + accountId + '/mac/', ['session.name']);+ fs.directories.set(root + accountId + '/mac/session%2Ename/', ['id', 'uncommitted']);fs.directories.set(dir, ['slot-0.jpg', 'slot-1.jpg']);fs.directories.set(dir.replace('/id/', '/uncommitted/'), ['slot-0.jpg']);}fs.getInfoAsync.mockImplementation(async (uri) => ({ exists: true, isDirectory: fs.directories.has(uri), size: 123 }));await initializeOutboxFiles();expect(fs.deleteAsync).toHaveBeenCalledTimes(4);- expect(fs.deleteAsync.mock.calls.flat()).not.toContain(durableOutboxDirectory({ ...record, accountId: 'alice' }) + 'slot-0.jpg');- expect(fs.deleteAsync.mock.calls.flat()).not.toContain(durableOutboxDirectory({ ...record, accountId: 'bob' }) + 'slot-0.jpg');+ expect(fs.deleteAsync.mock.calls.flat()).not.toContain(durableOutboxDirectory({ ...record, accountId: 'alice', item: { ...record.item, sessionId: 'session.name' } }) + 'slot-0.jpg');+ expect(fs.deleteAsync.mock.calls.flat()).not.toContain(durableOutboxDirectory({ ...record, accountId: 'bob', item: { ...record.item, sessionId: 'session.name' } }) + 'slot-0.jpg');await retainOutboxFile(record, 0, source);await initializeOutboxFiles();expect(fs.deleteAsync).toHaveBeenCalledTimes(4);diff --git a/apps/mobile/src/__tests__/mobileDurableOutboxOwner.test.ts b/apps/mobile/src/__tests__/mobileDurableOutboxOwner.test.tsindex 66e92fc27a..538f714401 100644--- a/apps/mobile/src/__tests__/mobileDurableOutboxOwner.test.ts+++ b/apps/mobile/src/__tests__/mobileDurableOutboxOwner.test.ts@@ -11,7 +11,7 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ default: {} }));vi.mock('../session/durableOutboxFiles', () => ({ durableOutboxUploadUri: vi.fn(), removeOutboxFiles: mocks.removeFiles }));vi.mock('../session/mobileAttachmentUpload', () => ({ discardMobileUploadedAttachment: mocks.discard }));-import { cleanupOutboxResources, discardOutboxUploads, getCurrentMobileOutboxRecords, mobileDurableOutbox } from '../session/mobileDurableOutbox';+import { cleanupOutboxResources, discardOutboxUploads, getCurrentMobileOutboxRecords, mobileDurableOutbox, persistCancelledCreationDraft } from '../session/mobileDurableOutbox';function record(): DurableOutboxRecord {return { version: 1, accountId: getMobileAuthOwner().accountKey, deviceId: 'mac', createdAt: 1,@@ -33,6 +33,31 @@ beforeEach(async () => {await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);});+it('persists cancellation for only the matching device and restores it after a cold activation', async () => {+ const own = record();+ own.creation = { draft: { workingDir: '/repo/.cindy-worktrees/failed', firstMessage: 'draft' } as NonNullable<DurableOutboxRecord['creation']>['draft'],+ originalWorkingDir: '/repo', deviceName: 'PC', planModeArm: false, restorePermissionMode: null };+ await mobileDurableOutbox.add(own);+ const other = { ...own, deviceId: 'other-device' };+ await mobileDurableOutbox.add(other);+ await persistCancelledCreationDraft({ sessionId: 'task', deviceId: 'mac' });+ await mobileDurableOutbox.activate('');+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);+ const restored = getCurrentMobileOutboxRecords().find((r) => r.deviceId === 'mac')!;+ expect(restored).toMatchObject({ suspended: true, state: 'failed', item: own.item,+ creation: { cancelled: true, draft: { workingDir: '/repo', firstMessage: 'draft' } } });+ expect(getCurrentMobileOutboxRecords().find((r) => r.deviceId === 'other-device')).toEqual(other);+});++it('does not cancel another account draft when the owner switches during activation', async () => {+ await mobileDurableOutbox.add(record());+ const original = new Map(mocks.data);+ const pending = persistCancelledCreationDraft({ sessionId: 'task', deviceId: 'mac' });+ setMobileAuthOwner('bob', 'global');+ await expect(pending).rejects.toThrow('OUTBOX_OWNER_CHANGED');+ expect(mocks.data).toEqual(original);+});+it('still disposes confirmed-cancelled uploads when local deletion rejects', async () => {mocks.removeFiles.mockRejectedValueOnce(new Error('filesystem unavailable'));await expect(cleanupOutboxResources(record(), getMobileAuthOwner(), async () => 'token', true)).rejects.toThrow('filesystem unavailable');diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.tsindex 9e0182475d..5a58487dbb 100644--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts@@ -409,6 +409,7 @@ describe("mobile maker transport", () => {"worktree:suggest-name","worktree:create","worktree:discard-precreated",+ "worktree:cancel-precreated","text-file:read-preview","file-browser:remote-op",]);@@ -939,6 +940,15 @@ describe("mobile maker transport", () => {]);});+ it("routes terminal worktree cancellation through its distinct host channel", async () => {+ const { calls, maker } = harness();+ const input = { sessionId: "uncertain-create", recoveryKey: "recovery-key-1234567890" };+ await maker.worktree.cancelPrecreated!(input);+ expect(calls.map((call) => [call.channel, call.args])).toEqual([+ ["worktree:cancel-precreated", [input]],+ ]);+ });+it("routes fork, native tree, rewind and delete actions through maker namespace", async () => {const { calls, maker } = harness();diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.tsindex 2f3a0f0673..ba44e41034 100644--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@ -2250,7 +2250,7 @@ describe('new session worktree wiring (source locks)', () => {recovery,);const sessionId = newSource.indexOf(- 'const sessionId = recovering?.item.sessionId ?? createNewSessionId();',+ 'const sessionId = recoveryIdentity?.sessionId ?? createNewSessionId();',pendingGuard,);const worktreeCreate = newSource.indexOf(diff --git a/apps/mobile/src/__tests__/newSessionCreation.test.ts b/apps/mobile/src/__tests__/newSessionCreation.test.tsindex 0d5aa98f4d..1165f9ba3a 100644--- a/apps/mobile/src/__tests__/newSessionCreation.test.ts+++ b/apps/mobile/src/__tests__/newSessionCreation.test.ts@@ -8,9 +8,16 @@* - retry(同 id 幂等)与 dismiss(返回编辑)收口。*/import { beforeEach, describe, expect, it, vi } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';+import { isDurableOutboxSettled, type DurableOutboxRecord } from '@/session/durableOutbox';+import { buildOutboxItem, outboxItemAttachments } from '@/session/sessionOutbox';const recoveryStorage = vi.hoisted(() => new Map<string, string>());+const persistCancelledDraft = vi.hoisted(() => vi.fn(async () => {}));+vi.mock('@/session/mobileDurableOutbox', () => ({ persistCancelledCreationDraft: persistCancelledDraft }));const recoveryAsyncStorage = vi.hoisted(() => ({getItem: vi.fn(async (key: string) => recoveryStorage.get(key) ?? null),setItem: vi.fn(async (key: string, value: string) => {@@ -32,6 +39,7 @@ vi.mock('expo-crypto', () => ({}));import {dismissNewSessionCreation,+ dismissRecoveredPrecreatedSession,drainStashedNewSessionDraft,getNewSessionCreationTask,prepareNewSessionCreationForEdit,@@ -62,6 +70,41 @@ const DRAFT: NewSessionDraft = {firstMessage: 'hello world',};+// Execute the bridge's actual refresh callback with the real session store.+// This includes hydration, cancellation cleanup and message-work lease release.+const bridgeSource = ts.createSourceFile('MobileOutboxBridge.tsx', readFileSync(resolve(+ process.cwd(), 'src/session/MobileOutboxBridge.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+let refreshSource = '';+function findRefresh(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(bridgeSource) === 'refreshLeases') {+ refreshSource = node.initializer!.getText(bridgeSource);+ }+ ts.forEachChild(node, findRefresh);+}+findRefresh(bridgeSource);+if (!refreshSource) throw new Error('Missing outbox lease refresh callback');+function outboxLeaseHarness(initial: DurableOutboxRecord[]) {+ let records = initial;+ const leases = new Map<string, ReturnType<typeof remoteSessionStore.acquireSessionMessageWork>>();+ const bindings = { isCurrent: () => true, mobileDurableOutbox: { getSnapshot: () => records },+ isDurableOutboxSettled, remoteSessionStore, sessionFromCreateResult, outboxItemAttachments,+ dismissRecoveredPrecreatedSession, leases,+ leaseKey: (record: DurableOutboxRecord) => JSON.stringify([record.deviceId, record.item.sessionId]) };+ const compiled = ts.transpileModule(`function create(bindings) {+ const { ${Object.keys(bindings).join(', ')} } = bindings;+ return ${refreshSource};+ }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+ const create = new Function(`${compiled}; return create;`)() as (values: typeof bindings) => () => void;+ return { refresh: create(bindings), leases, setRecords: (next: DurableOutboxRecord[]) => { records = next; } };+}+function recoveryOutboxRecord(sessionId: string): DurableOutboxRecord {+ return { version: 1, accountId: 'owner-a', deviceId: 'dev-1', createdAt: 1, state: 'failed', uploads: [],+ creation: { draft: DRAFT, deviceName: 'PC', planModeArm: false, restorePermissionMode: null },+ item: buildOutboxItem({ clientId: `message-${sessionId}`, sessionId, text: DRAFT.firstMessage,+ quotesEncoded: false, agentReferences: [], pastedTextRanges: [], slashCommandRanges: [],+ permissionModeAtSend: DRAFT.permissionMode, readyAttachments: [], readyPreviews: [], claimedUploads: [] }) };+}+interface MakerMock {createSession: ReturnType<typeof vi.fn>;getSession: ReturnType<typeof vi.fn>;@@ -70,6 +113,7 @@ interface MakerMock {setPermissionMode: ReturnType<typeof vi.fn>;worktree: {discardPrecreated: ReturnType<typeof vi.fn>;+ cancelPrecreated?: ReturnType<typeof vi.fn>;};input: {enqueue: ReturnType<typeof vi.fn>;@@ -132,6 +176,7 @@ async function flushPipeline(): Promise<void> {describe('newSessionCreation pipeline', () => {beforeEach(async () => {+ persistCancelledDraft.mockReset();await recoveryTesting.drainMutations();recoveryStorage.clear();recoveryTesting.resetVolatileLedgers();@@ -796,6 +841,115 @@ describe('newSessionCreation pipeline', () => {}]);});+ it('returns the original draft after an uncertain create is cancelled by the host', async () => {+ const record = { sessionId: 'cancel-me', deviceId: 'dev-1', path: '/repo/.cindy-worktrees/orphan', recoveryKey: 'recovery-cancel-key', createdAt: Date.now(), phase: 'precreated' as const };+ await registerPendingPrecreatedWorktree('owner-a', record);+ const maker = makeMaker({+ createSession: vi.fn(async () => { throw new Error('INVOKE_TIMEOUT'); }),+ worktree: { discardPrecreated: vi.fn(), cancelPrecreated: vi.fn(async () => ({ discarded: true })) },+ });+ startNewSessionCreation(makeParams(record.sessionId, maker, {+ draft: { ...DRAFT, workingDir: record.path },+ precreatedWorktree: { path: record.path, recoveryKey: record.recoveryKey, originalWorkingDir: '/repo', createdAt: record.createdAt },+ precreatedWorktreeAccountId: 'owner-a',+ }));+ await flushPipeline();+ const task = await prepareNewSessionCreationForEdit(record.sessionId);+ expect(task?.draft.firstMessage).toBe(DRAFT.firstMessage);+ expect(task?.precreatedWorktree?.originalWorkingDir).toBe('/repo');+ expect(maker.worktree.cancelPrecreated).toHaveBeenCalledWith({ sessionId: record.sessionId, recoveryKey: record.recoveryKey });+ expect(maker.worktree.discardPrecreated).not.toHaveBeenCalled();+ expect(persistCancelledDraft).toHaveBeenCalledWith({ sessionId: record.sessionId, deviceId: record.deviceId, originalWorkingDir: '/repo' });+ expect(await listPendingPrecreatedWorktrees('owner-a')).toEqual([]);+ });++ it('retry reconciles a late exact-id success without another create', async () => {+ const maker = makeMaker({ createSession: vi.fn(async () => { throw new Error('INVOKE_TIMEOUT'); }) });+ startNewSessionCreation(makeParams('late-success', maker, {+ precreatedWorktree: { path: '/repo/worktree', recoveryKey: 'late-recovery-key', originalWorkingDir: '/repo' },+ precreatedWorktreeAccountId: 'owner-a',+ }));+ await flushPipeline();+ expect(getNewSessionCreationTask('late-success')?.status).toBe('create-failed');+ maker.getSession.mockResolvedValue(sessionFromCreateResult({ sessionId: 'late-success', workDir: '/repo/worktree' }, DRAFT));+ retryNewSessionCreation('late-success');+ await flushPipeline();+ expect(maker.createSession).toHaveBeenCalledTimes(1);+ expect(maker.input.enqueue).toHaveBeenCalledTimes(1);+ expect(getNewSessionCreationTask('late-success')).toBeNull();+ });++ it('keeps the edit recovery obligation when persisting the cancelled draft fails', async () => {+ const record = { sessionId: 'cancel-save-fails', deviceId: 'dev-1', path: '/repo/.cindy-worktrees/orphan',+ recoveryKey: 'recovery-cancel-save-key', createdAt: Date.now(), phase: 'precreated' as const };+ await registerPendingPrecreatedWorktree('owner-a', record);+ const maker = makeMaker({ createSession: vi.fn(async () => { throw new Error('INVOKE_TIMEOUT'); }),+ worktree: { discardPrecreated: vi.fn(), cancelPrecreated: vi.fn(async () => ({ discarded: true })) } });+ startNewSessionCreation(makeParams(record.sessionId, maker, {+ draft: { ...DRAFT, workingDir: record.path }, precreatedWorktreeAccountId: 'owner-a',+ precreatedWorktree: { path: record.path, recoveryKey: record.recoveryKey, originalWorkingDir: '/repo', createdAt: record.createdAt },+ }));+ await flushPipeline();+ persistCancelledDraft.mockRejectedValueOnce(new Error('disk full'));+ await expect(prepareNewSessionCreationForEdit(record.sessionId)).rejects.toThrow('disk full');+ expect(await listPendingPrecreatedWorktrees('owner-a')).toHaveLength(1);+ expect(getNewSessionCreationTask(record.sessionId)?.status).toBe('create-failed');+ await prepareNewSessionCreationForEdit(record.sessionId);+ expect(await listPendingPrecreatedWorktrees('owner-a')).toEqual([]);+ dismissNewSessionCreation(record.sessionId);+ });++ it.each([true, false, undefined])('removes the host-confirmed cancelled row on the matching device (pendingLocalCreation=%s)', (pendingLocalCreation) => {+ const row = { ...sessionFromCreateResult({ sessionId: 'orphan' }, DRAFT), pendingLocalCreation };+ remoteSessionStore.upsertDeviceSession('dev-1', 'PC', row);+ dismissRecoveredPrecreatedSession({ sessionId: 'orphan', deviceId: 'other-device' });+ expect(remoteSessionStore.getSessions()).toHaveLength(1);+ dismissRecoveredPrecreatedSession({ sessionId: 'orphan', deviceId: 'dev-1' });+ expect(remoteSessionStore.getSessions()).toHaveLength(0);+ });++ it('does not dismiss a row still owned by a live creation pipeline', async () => {+ const maker = makeMaker({ createSession: vi.fn(async () => { throw new Error('failed startup'); }) });+ startNewSessionCreation(makeParams('s1', maker));+ dismissRecoveredPrecreatedSession({ sessionId: 's1', deviceId: 'dev-1' });+ expect(remoteSessionStore.getSessions().find((row) => row.id === 's1')).toBeDefined();+ expect(getNewSessionCreationTask('s1')).not.toBeNull();+ await flushPipeline();+ dismissNewSessionCreation('s1');+ });++ it('removes a cold-hydrated cancelled row and releases only its lease without resurrecting it', () => {+ const orphan = recoveryOutboxRecord('cold-orphan');+ const other = recoveryOutboxRecord('other-draft');+ const bridge = outboxLeaseHarness([orphan, other]);+ bridge.refresh();+ expect(remoteSessionStore.getSessions().find((row) => row.id === 'cold-orphan')?.pendingLocalCreation).toBeUndefined();+ expect(bridge.leases.size).toBe(2);+ const releaseOrphan = vi.spyOn(bridge.leases.get(JSON.stringify(['dev-1', 'cold-orphan']))!, 'release');+ const releaseOther = vi.spyOn(bridge.leases.get(JSON.stringify(['dev-1', 'other-draft']))!, 'release');+ const cancelled = { ...orphan, suspended: true, creation: { ...orphan.creation!, cancelled: true as const } };+ bridge.setRecords([cancelled, other]);+ bridge.refresh();+ expect(remoteSessionStore.getSessions().map((row) => row.id)).toEqual(['other-draft']);+ expect(releaseOrphan).toHaveBeenCalledOnce();+ expect(releaseOther).not.toHaveBeenCalled();+ bridge.refresh();+ expect(remoteSessionStore.getSessions().map((row) => row.id)).toEqual(['other-draft']);+ expect(cancelled.item.text).toBe(DRAFT.firstMessage);+ expect(cancelled.creation.cancelled).toBe(true);+ bridge.setRecords([]);+ bridge.refresh();+ });++ it('does not materialize an already cancelled draft on cold startup', () => {+ const orphan = recoveryOutboxRecord('cancelled-before-restart');+ const bridge = outboxLeaseHarness([{ ...orphan, creation: { ...orphan.creation!, cancelled: true } }]);+ bridge.refresh();+ bridge.refresh();+ expect(remoteSessionStore.getSessions()).toEqual([]);+ expect(bridge.leases.size).toBe(0);+ });+it.each([['null', null],['empty object', {}],@@ -836,7 +990,7 @@ describe('newSessionCreation pipeline', () => {retryNewSessionCreation('s20');await flushPipeline();expect(maker.createSession).toHaveBeenCalledTimes(1);- expect(maker.getSession).toHaveBeenCalledTimes(1);+ expect(maker.getSession).toHaveBeenCalledTimes(2);await expect(prepareNewSessionCreationForEdit('s20')).rejects.toThrow('worktree');expect(maker.worktree.discardPrecreated).not.toHaveBeenCalled();await expect(listPendingPrecreatedWorktrees('owner-a')).resolves.toEqual([{diff --git a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.tsnew file mode 100644index 0000000000..cd8e8eb071--- /dev/null+++ b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts@@ -0,0 +1,198 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { beforeEach, expect, it, vi } from 'vitest';+import { getMobileAuthOwner, setMobileAuthOwner } from '../auth/authOwnerGeneration';+import type { DurableOutboxRecord } from '../session/durableOutbox';+import { cancelledCreationDraft, outboxCreationRetryIdentity } from '../session/cancelledCreationDraft';+import { buildOutboxItem } from '../session/sessionOutbox';++const disk = vi.hoisted(() => ({ data: new Map<string, string>(), fail: false }));+vi.mock('@react-native-async-storage/async-storage', () => ({ default: {+ getAllKeys: async () => [...disk.data.keys()],+ getItem: async (key: string) => disk.data.get(key) ?? null,+ setItem: async (key: string, value: string) => {+ if (disk.fail) throw new Error('disk unavailable');+ disk.data.set(key, value);+ },+ removeItem: async (key: string) => { disk.data.delete(key); },+} }));+vi.mock('../session/durableOutboxFiles', () => ({ durableOutboxUploadUri: vi.fn(), removeOutboxFiles: vi.fn() }));+vi.mock('../session/mobileAttachmentUpload', () => ({ discardMobileUploadedAttachment: vi.fn() }));+import { getCurrentMobileOutboxRecords, mobileDurableOutbox, persistCancelledCreationDraft } from '../session/mobileDurableOutbox';++// Run the page's actual recovery -> durable save -> worktree creation statements.+// Extract AST nodes, as in newSessionWorktreeSync, so ordering is tested without+// duplicating the production pipeline or mounting unrelated native UI modules.+const source = ts.createSourceFile('new.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8'),+ ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+let statements: readonly ts.Statement[] | undefined;+function visit(node: ts.Node) {+ if (ts.isBlock(node) && node.statements.some((s) => ts.isVariableStatement(s)+ && s.declarationList.declarations.some((d) => d.name.getText(source) === 'previousRecovery'))) {+ const start = node.statements.findIndex((s) => ts.isVariableStatement(s)+ && s.declarationList.declarations.some((d) => d.name.getText(source) === 'previousRecovery'));+ const end = node.statements.findIndex((s) => ts.isBlock(s)+ && s.getText(source).includes('resolveSubmitGuardCatalog'));+ if (end < start) throw new Error('Missing page creation persistence boundary');+ statements = node.statements.slice(start, end);+ }+ ts.forEachChild(node, visit);+}+visit(source);+if (!statements) throw new Error('Missing page creation pipeline');++beforeEach(async () => {+ setMobileAuthOwner(null);+ await mobileDurableOutbox.activate('');+ disk.data.clear();+ disk.fail = false;+ setMobileAuthOwner('alice', 'global');+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);+});++function harness(previous: DurableOutboxRecord | null = null) {+ let sequence = 0;+ const draft = { agentKind: 'codex', workspaceKind: 'project', workingDir: '/repo', model: 'model',+ providerId: null, effort: 'high', permissionMode: 'ask', fastMode: false, firstMessage: 'keep my input' };+ const bindings = {+ effectiveDraft: { ...draft, ...previous?.creation?.draft },+ outboxRecoveryRef: { current: previous },+ getCurrentMobileOutboxRecords, mobileDurableOutbox, outboxCreationRetryIdentity, buildOutboxItem,+ selectedDeviceId: 'pc', selectedDeviceName: 'PC', authOwnerAtCreate: getMobileAuthOwner(),+ worktreeAccountId: 'alice', creatingWorktree: true,+ worktreeIntent: { applicable: true, enabled: true, eligibility: { status: 'eligible', baseRepo: '/repo' }, sourceBranch: 'main' },+ isCurrentOwner: () => true, ensureDeviceAlive: () => true, isWorktreeCreateIntentCurrent: () => true,+ createNewSessionId: () => `session-${++sequence}`, createOutboxClientId: () => 'message',+ runtimeOptions: { permissionOptions: [] }, prePlanPermissionModeRef: { current: null },+ planModeCapability: false, planModeDraftOn: false,+ holdDurableOutboxCreation: () => () => {}, holdPrecreatedWorktreeRegistration: () => () => {},+ sendAttachments: [{ id: 'photo', path: 'oss://photo', name: 'photo.png', ext: 'png', size: 3, category: 'image', mimeType: 'image/png' }],+ attachmentPreviews: {}, getUploadedSource: () => ({ uri: 'file:///photo.png' }),+ retainOutboxFile: vi.fn(async () => ({ slot: 0, fileName: 'slot-0.png', name: 'photo.png', size: 3, kind: 'image' })),+ removeRetainedOutboxFiles: vi.fn(async () => {}), releaseUploadedSources: vi.fn(),+ outboxAttachmentNeedsLocalBytes: () => true,+ registerPendingPrecreatedWorktree: vi.fn(async () => true), forgetPendingPrecreatedWorktree: vi.fn(),+ buildWorktreeCreateRequest: (input: unknown) => input,+ parseWorktreeCreateResult: (input: unknown) => input,+ maker: { getSession: vi.fn(async () => null), worktree: {+ suggestName: vi.fn(async () => ({ name: 'new' })),+ create: vi.fn(async () => ({ ok: true, meta: { path: '/repo/.cindy-worktrees/new' } })),+ } },+ t: (key: string) => key, setError: vi.fn(), setDraft: vi.fn(),+ formatRemoteError: (error: Error) => error.message,+ };+ const compiled = ts.transpileModule(`async function run(bindings) {+ let { ${Object.keys(bindings).join(', ')} } = bindings;+ let releaseDurableCreation, releasePrecreatedRegistration;+ try {+ ${statements!.map((node) => node.getText(source)).join('\n')}+ return { effectiveDraft, sessionId };+ } finally { releaseDurableCreation?.(); releasePrecreatedRegistration?.(); }+ }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+ const run = new Function(`${compiled}; return run;`)() as (input: typeof bindings) => Promise<unknown>;+ return { bindings, run: () => run(bindings) };+}++it('persists the draft and attachments before reserving and dispatching worktree creation', async () => {+ const h = harness();+ h.bindings.registerPendingPrecreatedWorktree.mockImplementation(async () => {+ const saved = [...disk.data.values()].map((value) => JSON.parse(value) as DurableOutboxRecord)[0];+ expect(saved).toMatchObject({ suspended: true, item: { text: 'keep my input' },+ creation: { originalWorkingDir: '/repo', draft: { workingDir: '/repo' } },+ uploads: [{ fileName: 'slot-0.png' }] });+ return true;+ });+ await h.run();+ expect(h.bindings.maker.worktree.create).toHaveBeenCalledOnce();+ expect(getCurrentMobileOutboxRecords()[0]).toMatchObject({ suspended: false,+ creation: { originalWorkingDir: '/repo', draft: { workingDir: '/repo/.cindy-worktrees/new' } } });+});++it('recovers the input after a lost create reply and cold outbox activation', async () => {+ const h = harness();+ h.bindings.maker.worktree.create.mockRejectedValueOnce(new Error('reply lost'));+ await h.run();+ expect(h.bindings.setError).toHaveBeenCalledWith('session.new.worktreeCleanupPending');+ await mobileDurableOutbox.activate('');+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);+ await persistCancelledCreationDraft({ sessionId: 'session-1', deviceId: 'pc' });+ await mobileDurableOutbox.activate('');+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);+ expect(getCurrentMobileOutboxRecords()[0]).toMatchObject({ suspended: true, state: 'failed',+ item: { text: 'keep my input', attachmentSlots: [{ id: 'photo' }] }, uploads: [{ fileName: 'slot-0.png' }],+ creation: { cancelled: true, draft: { workingDir: '/repo', firstMessage: 'keep my input' } } });+});++it('does not reserve or dispatch a worktree if saving its draft fails', async () => {+ const h = harness();+ disk.fail = true;+ await expect(h.run()).rejects.toThrow('disk unavailable');+ expect(h.bindings.registerPendingPrecreatedWorktree).not.toHaveBeenCalled();+ expect(h.bindings.maker.worktree.create).not.toHaveBeenCalled();+ expect(h.bindings.removeRetainedOutboxFiles).toHaveBeenCalledOnce();+});++it('keeps the original durable input when patching the successful worktree path fails', async () => {+ const h = harness();+ h.bindings.maker.worktree.create.mockImplementationOnce(async () => {+ disk.fail = true;+ return { ok: true, meta: { path: '/repo/.cindy-worktrees/new' } };+ });+ await expect(h.run()).rejects.toThrow('disk unavailable');+ disk.fail = false;+ await mobileDurableOutbox.activate('');+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);+ expect(getCurrentMobileOutboxRecords()[0]).toMatchObject({ suspended: true,+ creation: { draft: { workingDir: '/repo', firstMessage: 'keep my input' } } });+ await persistCancelledCreationDraft({ sessionId: 'session-1', deviceId: 'pc' });+ expect(getCurrentMobileOutboxRecords()[0].creation?.cancelled).toBe(true);+});++it.each([true, false])('reprobes a restored directory instead of submitting old eligibility (enabled=%s)', async (enabled) => {+ await harness().run();+ const previous = getCurrentMobileOutboxRecords()[0];+ await mobileDurableOutbox.update(previous, cancelledCreationDraft(previous));+ const h = harness(previous);+ Object.assign(h.bindings.worktreeIntent, { enabled, eligibility: { status: 'ineligible', reason: 'alreadyInWorktree' } });+ h.bindings.creatingWorktree = false;+ expect(await h.run()).toBeUndefined();+ expect(h.bindings.setDraft).toHaveBeenCalledOnce();+ const restored = h.bindings.setDraft.mock.calls[0][0](h.bindings.effectiveDraft);+ expect(restored).toMatchObject({ workingDir: '/repo', firstMessage: 'keep my input' });+ expect(h.bindings.maker.getSession).not.toHaveBeenCalled();+ expect(h.bindings.maker.worktree.create).not.toHaveBeenCalled();+ expect(getCurrentMobileOutboxRecords()).toHaveLength(1);+ expect(getCurrentMobileOutboxRecords()[0].creation?.cancelled).toBe(true);+});++it('retries a cancelled draft under one durable key and patches its new worktree path', async () => {+ await harness().run();+ const previous = getCurrentMobileOutboxRecords()[0];+ const cancelled = await mobileDurableOutbox.update(previous, cancelledCreationDraft(previous));+ const h = harness(cancelled);+ h.bindings.createNewSessionId = () => 'retry-session';+ await h.run();+ expect(h.bindings.setDraft).not.toHaveBeenCalled();+ expect(getCurrentMobileOutboxRecords()).toHaveLength(1);+ expect(getCurrentMobileOutboxRecords()[0]).toMatchObject({ storageSessionId: 'session-1',+ item: { sessionId: 'retry-session', clientId: 'message' }, suspended: false,+ creation: { draft: { workingDir: '/repo/.cindy-worktrees/new' } } });+ expect(getCurrentMobileOutboxRecords()[0].creation?.cancelled).toBeUndefined();+});++it('preserves a directory explicitly selected by the user while cancellation completes', async () => {+ await harness().run();+ const previous = getCurrentMobileOutboxRecords()[0];+ await mobileDurableOutbox.update(previous, cancelledCreationDraft(previous));+ const h = harness(previous);+ h.bindings.effectiveDraft.workingDir = '/other-repo';+ h.bindings.worktreeIntent.eligibility.baseRepo = '/other-repo';+ h.bindings.createNewSessionId = () => 'user-retry';+ await h.run();+ expect(h.bindings.setDraft).not.toHaveBeenCalled();+ expect(h.bindings.maker.worktree.create).toHaveBeenCalledWith(expect.objectContaining({+ eligibility: expect.objectContaining({ baseRepo: '/other-repo' }),+ }));+ expect(getCurrentMobileOutboxRecords()[0].creation?.originalWorkingDir).toBe('/other-repo');+});diff --git a/apps/mobile/src/__tests__/precreatedWorktreeRecovery.test.ts b/apps/mobile/src/__tests__/precreatedWorktreeRecovery.test.tsindex 48326b93eb..fb35f02499 100644--- a/apps/mobile/src/__tests__/precreatedWorktreeRecovery.test.ts+++ b/apps/mobile/src/__tests__/precreatedWorktreeRecovery.test.ts@@ -43,6 +43,59 @@ const RESERVATION = {};describe('precreated worktree recovery ledger', () => {+ it('fences a timed-out reservation before a delayed create arrives', async () => {+ await registerPendingPrecreatedWorktree(ACCOUNT, RESERVATION);+ const cancelled = new Set<string>();+ const directories = new Set<string>();+ const discardPrecreated = vi.fn(async () => ({ discarded: true }));+ const result = await recoverPendingPrecreatedWorktrees(ACCOUNT, {+ openLink: async () => {}, discardPrecreated,+ cancelPrecreated: async (_device, input) => {+ cancelled.add(input.sessionId);+ return { discarded: true };+ },+ isSessionClaimed: async () => false,+ });+ // The original create is delivered after cancellation's ACK, without a create ACK on mobile.+ if (!cancelled.has(RESERVATION.sessionId)) directories.add(RESERVATION.sessionId);+ expect(result).toMatchObject({ recovered: 1 });+ expect(discardPrecreated).not.toHaveBeenCalled();+ expect(directories.size).toBe(0);+ expect(await listPendingPrecreatedWorktrees(ACCOUNT)).toEqual([]);+ });++ it.each(['reserved', 'precreated', 'session-create-started'] as const)(+ 'retains %s on an old host even when legacy discard could acknowledge absence', async (phase) => {+ await registerPendingPrecreatedWorktree(ACCOUNT, { ...RESERVATION, phase });+ const discardPrecreated = vi.fn(async () => ({ discarded: true }));+ const result = await recoverPendingPrecreatedWorktrees(ACCOUNT, {+ openLink: async () => {}, discardPrecreated, isSessionClaimed: async () => false,+ });+ expect(result).toMatchObject({ recovered: 0, retained: 1 });+ expect(discardPrecreated).not.toHaveBeenCalled();+ expect(await listPendingPrecreatedWorktrees(ACCOUNT)).toHaveLength(1);+ },+ );++ it('awaits durable draft cancellation and retains the ledger if that write fails', async () => {+ await registerPendingPrecreatedWorktree(ACCOUNT, RESERVATION);+ let fail!: (error: Error) => void;+ let writing!: () => void;+ const started = new Promise<void>((resolve) => { writing = resolve; });+ const pending = new Promise<void>((_resolve, reject) => { fail = reject; });+ const recovery = recoverPendingPrecreatedWorktrees(ACCOUNT, {+ openLink: async () => {}, discardPrecreated: vi.fn(),+ cancelPrecreated: async () => ({ discarded: true }),+ isSessionClaimed: async () => false,+ onDiscarded: () => { writing(); return pending; },+ });+ await started;+ expect(await listPendingPrecreatedWorktrees(ACCOUNT)).toHaveLength(1);+ fail(new Error('disk full'));+ expect(await recovery).toMatchObject({ recovered: 0, retained: 1 });+ expect(await listPendingPrecreatedWorktrees(ACCOUNT)).toHaveLength(1);+ });+beforeEach(async () => {await __testing.drainMutations();storage.clear();@@ -103,11 +156,12 @@ describe('precreated worktree recovery ledger', () => {RESERVATION,]);- const discardPrecreated = vi.fn(async () => ({ discarded: true }));+ const cancelPrecreated = vi.fn(async () => ({ discarded: true }));await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(async () => undefined),- discardPrecreated,+ cancelPrecreated,isSessionClaimed: vi.fn(async () => false),sleep: async () => undefined,}),@@ -117,7 +171,7 @@ describe('precreated worktree recovery ledger', () => {retained: 0,storageReadable: true,});- expect(discardPrecreated).toHaveBeenCalledWith('device-1', {+ expect(cancelPrecreated).toHaveBeenCalledWith('device-1', {sessionId: RESERVATION.sessionId,recoveryKey: RESERVATION.recoveryKey,});@@ -160,14 +214,15 @@ describe('precreated worktree recovery ledger', () => {await expect(listPendingPrecreatedWorktrees(ACCOUNT)).resolves.toEqual([RESERVATION,]);- const discardPrecreated = vi.fn(async () => ({ discarded: true }));+ const cancelPrecreated = vi.fn(async () => ({ discarded: true }));await recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(async () => undefined),- discardPrecreated,+ cancelPrecreated,isSessionClaimed: vi.fn(async () => false),sleep: async () => undefined,});- expect(discardPrecreated).toHaveBeenCalledWith('device-1', {+ expect(cancelPrecreated).toHaveBeenCalledWith('device-1', {sessionId: RESERVATION.sessionId,recoveryKey: RESERVATION.recoveryKey,});@@ -256,12 +311,13 @@ describe('precreated worktree recovery ledger', () => {await registerPendingPrecreatedWorktree(ACCOUNT, RECORD);__testing.resetVolatileLedgers();asyncStorage.getItem.mockRejectedValueOnce(new Error('read unavailable'));- const discardPrecreated = vi.fn();+ const cancelPrecreated = vi.fn();await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(),- discardPrecreated,+ cancelPrecreated,isSessionClaimed: vi.fn(),sleep: async () => undefined,}),@@ -271,7 +327,7 @@ describe('precreated worktree recovery ledger', () => {retained: 0,storageReadable: false,});- expect(discardPrecreated).not.toHaveBeenCalled();+ expect(cancelPrecreated).not.toHaveBeenCalled();expect(storage.size).toBe(1);});@@ -279,12 +335,13 @@ describe('precreated worktree recovery ledger', () => {const key = __testing.storageKeyForAccount(ACCOUNT);expect(key).not.toBeNull();storage.set(key as string, '{{{');- const discardPrecreated = vi.fn();+ const cancelPrecreated = vi.fn();await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(),- discardPrecreated,+ cancelPrecreated,isSessionClaimed: vi.fn(),sleep: async () => undefined,}),@@ -294,7 +351,7 @@ describe('precreated worktree recovery ledger', () => {retained: 0,storageReadable: false,});- expect(discardPrecreated).not.toHaveBeenCalled();+ expect(cancelPrecreated).not.toHaveBeenCalled();expect(storage.get(key as string)).toBe('{{{');expect(asyncStorage.removeItem).not.toHaveBeenCalled();@@ -315,12 +372,13 @@ describe('precreated worktree recovery ledger', () => {it('recovers successfully and defers records owned by a live creation task', async () => {await registerPendingPrecreatedWorktree(ACCOUNT, RECORD);const openLink = vi.fn(async () => undefined);- const discardPrecreated = vi.fn(async () => ({ discarded: true }));+ const cancelPrecreated = vi.fn(async () => ({ discarded: true }));await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink,- discardPrecreated,+ cancelPrecreated,isSessionClaimed: vi.fn(async () => false),sleep: async () => undefined,}),@@ -329,7 +387,7 @@ describe('precreated worktree recovery ledger', () => {recovered: 1,retained: 0,});- expect(discardPrecreated).toHaveBeenCalledWith('device-1', {+ expect(cancelPrecreated).toHaveBeenCalledWith('device-1', {sessionId: 'session-1',path: RECORD.path,});@@ -338,8 +396,9 @@ describe('precreated worktree recovery ledger', () => {await registerPendingPrecreatedWorktree(ACCOUNT, RECORD);await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink,- discardPrecreated,+ cancelPrecreated,isSessionClaimed: vi.fn(async () => false),shouldDefer: () => true,sleep: async () => undefined,@@ -361,8 +420,9 @@ describe('precreated worktree recovery ledger', () => {.mockResolvedValueOnce(true);await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(async () => undefined),- discardPrecreated: vi.fn(async () => {+ cancelPrecreated: vi.fn(async () => {throw Object.assign(new Error('session claimed'), {code: 'PRECONDITION_FAILED',});@@ -377,8 +437,9 @@ describe('precreated worktree recovery ledger', () => {await registerPendingPrecreatedWorktree(ACCOUNT, RECORD);await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(async () => undefined),- discardPrecreated: vi.fn(async () => {+ cancelPrecreated: vi.fn(async () => {throw Object.assign(new Error('worktree has changes'), {code: 'PRECONDITION_FAILED',});@@ -394,20 +455,21 @@ describe('precreated worktree recovery ledger', () => {it('clears an already claimed record before calling an unsupported discard channel', async () => {await registerPendingPrecreatedWorktree(ACCOUNT, RECORD);- const discardPrecreated = vi.fn();+ const cancelPrecreated = vi.fn();const isSessionClaimed = vi.fn(async () => true);await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(async () => undefined),- discardPrecreated,+ cancelPrecreated,isSessionClaimed,sleep: async () => undefined,}),).resolves.toMatchObject({ recovered: 1, retained: 0 });expect(isSessionClaimed).toHaveBeenCalledWith('device-1', 'session-1');- expect(discardPrecreated).not.toHaveBeenCalled();+ expect(cancelPrecreated).not.toHaveBeenCalled();await expect(listPendingPrecreatedWorktrees(ACCOUNT)).resolves.toEqual([]);});@@ -416,7 +478,7 @@ describe('precreated worktree recovery ledger', () => {const isSessionClaimed = vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true);- const discardPrecreated = vi.fn(async () => {+ const cancelPrecreated = vi.fn(async () => {throw Object.assign(new Error('old desktop'), {code: 'CHANNEL_NOT_ALLOWED',});@@ -424,14 +486,15 @@ describe('precreated worktree recovery ledger', () => {await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(async () => undefined),- discardPrecreated,+ cancelPrecreated,isSessionClaimed,sleep: async () => undefined,}),).resolves.toMatchObject({ recovered: 1, retained: 0 });- expect(discardPrecreated).toHaveBeenCalledTimes(1);+ expect(cancelPrecreated).toHaveBeenCalledTimes(1);expect(isSessionClaimed).toHaveBeenCalledTimes(2);await expect(listPendingPrecreatedWorktrees(ACCOUNT)).resolves.toEqual([]);});@@ -440,8 +503,9 @@ describe('precreated worktree recovery ledger', () => {await registerPendingPrecreatedWorktree(ACCOUNT, RECORD);await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(async () => undefined),- discardPrecreated: vi.fn(async () => {+ cancelPrecreated: vi.fn(async () => {throw Object.assign(new Error('old desktop'), {code: 'CHANNEL_NOT_ALLOWED',});@@ -457,8 +521,9 @@ describe('precreated worktree recovery ledger', () => {await registerPendingPrecreatedWorktree(ACCOUNT, RECORD);await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(async () => undefined),- discardPrecreated: vi.fn(async () => {+ cancelPrecreated: vi.fn(async () => {throw Object.assign(new Error('registered path mismatch'), {code: 'PERMISSION_DENIED',});@@ -474,8 +539,9 @@ describe('precreated worktree recovery ledger', () => {await registerPendingPrecreatedWorktree(ACCOUNT, RECORD);await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(async () => undefined),- discardPrecreated: vi.fn(async () => {+ cancelPrecreated: vi.fn(async () => {throw Object.assign(new Error('device offline'), {code: 'DEVICE_OFFLINE',});@@ -489,7 +555,7 @@ describe('precreated worktree recovery ledger', () => {]);});- it('never discards a session-create-started or legacy phase-less obligation', async () => {+ it('retains started and legacy obligations when host cancellation is unavailable', async () => {const started = {...RECORD,recoveryKey: 'recovery-key-started-123456',@@ -533,22 +599,72 @@ describe('precreated worktree recovery ledger', () => {]);});+ it.each(['session-create-started', undefined] as const)('recovers %s only after a host cancellation ACK', async (phase) => {+ const record = { ...RECORD, phase };+ storage.set(__testing.storageKeyForAccount(ACCOUNT)!, JSON.stringify({ version: 1, records: [record] }));+ const discardPrecreated = vi.fn();+ const cancelPrecreated = vi.fn(async () => ({ discarded: true }));+ const onDiscarded = vi.fn();+ const result = await recoverPendingPrecreatedWorktrees(ACCOUNT, {+ openLink: async () => {}, discardPrecreated, cancelPrecreated, onDiscarded,+ isSessionClaimed: async () => false,+ });+ expect(result).toMatchObject({ recovered: 1, retained: 0 });+ expect(cancelPrecreated).toHaveBeenCalledWith(RECORD.deviceId, { sessionId: RECORD.sessionId, path: RECORD.path });+ expect(discardPrecreated).not.toHaveBeenCalled();+ expect(onDiscarded).toHaveBeenCalledTimes(1);+ expect(await listPendingPrecreatedWorktrees(ACCOUNT)).toEqual([]);+ });++ it.each(['unsupported', 'malformed', 'occupied'])('retains the record when cancellation is %s', async (failure) => {+ const record = { ...RECORD, phase: 'session-create-started' as const };+ await registerPendingPrecreatedWorktree(ACCOUNT, record);+ const onDiscarded = vi.fn();+ const discardPrecreated = vi.fn();+ const result = await recoverPendingPrecreatedWorktrees(ACCOUNT, {+ openLink: async () => {}, discardPrecreated, onDiscarded,+ cancelPrecreated: async () => {+ if (failure === 'malformed') return {};+ throw Object.assign(new Error(failure), { code: failure === 'unsupported' ? 'CHANNEL_NOT_ALLOWED' : 'PRECONDITION_FAILED' });+ },+ isSessionClaimed: async () => false,+ });+ expect(result).toMatchObject({ recovered: 0, retained: 1 });+ expect(discardPrecreated).not.toHaveBeenCalled();+ expect(onDiscarded).not.toHaveBeenCalled();+ expect(await listPendingPrecreatedWorktrees(ACCOUNT)).toEqual([record]);+ });++ it('does not cancel or hide an exact-id task that was already created', async () => {+ await registerPendingPrecreatedWorktree(ACCOUNT, { ...RECORD, phase: 'session-create-started' });+ const cancelPrecreated = vi.fn();+ const onDiscarded = vi.fn();+ await recoverPendingPrecreatedWorktrees(ACCOUNT, {+ openLink: async () => {}, discardPrecreated: vi.fn(), cancelPrecreated, onDiscarded,+ isSessionClaimed: async () => true,+ });+ expect(cancelPrecreated).not.toHaveBeenCalled();+ expect(onDiscarded).not.toHaveBeenCalled();+ expect(await listPendingPrecreatedWorktrees(ACCOUNT)).toEqual([]);+ });+it('requires a strict discard ACK and prefers recoveryKey over path', async () => {const record = {...RECORD,recoveryKey: 'recovery-key-preferred-123456',};await registerPendingPrecreatedWorktree(ACCOUNT, record);- const discardPrecreated = vi.fn(async () => ({}));+ const cancelPrecreated = vi.fn(async () => ({}));await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(async () => undefined),- discardPrecreated,+ cancelPrecreated,isSessionClaimed: vi.fn(async () => false),sleep: async () => undefined,}),).resolves.toMatchObject({ recovered: 0, retained: 1 });- expect(discardPrecreated).toHaveBeenCalledWith('device-1', {+ expect(cancelPrecreated).toHaveBeenCalledWith('device-1', {sessionId: record.sessionId,recoveryKey: record.recoveryKey,});@@ -597,16 +713,17 @@ describe('precreated worktree recovery ledger', () => {const raw = JSON.stringify(payload);storage.set(key, raw);__testing.resetVolatileLedgers();- const discardPrecreated = vi.fn();+ const cancelPrecreated = vi.fn();await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: vi.fn(),- discardPrecreated,+ cancelPrecreated,isSessionClaimed: vi.fn(),sleep: async () => undefined,}),).resolves.toMatchObject({ storageReadable: false, attempted: 0 });- expect(discardPrecreated).not.toHaveBeenCalled();+ expect(cancelPrecreated).not.toHaveBeenCalled();expect(storage.get(key)).toBe(raw);}});@@ -634,8 +751,9 @@ describe('precreated worktree recovery ledger', () => {await expect(recoverPendingPrecreatedWorktrees(ACCOUNT, {+ discardPrecreated: vi.fn(),openLink: openLinkA,- discardPrecreated: discardA,+ cancelPrecreated: discardA,isSessionClaimed: isSessionClaimedA,sleep: sleepA,isCurrent: () => currentOwner === ACCOUNT,@@ -655,8 +773,9 @@ describe('precreated worktree recovery ledger', () => {const discardB = vi.fn(async () => ({ discarded: true }));await expect(recoverPendingPrecreatedWorktrees(accountB, {+ discardPrecreated: vi.fn(),openLink: vi.fn(async () => undefined),- discardPrecreated: discardB,+ cancelPrecreated: discardB,isSessionClaimed: vi.fn(async () => false),sleep: async () => undefined,isCurrent: () => currentOwner === accountB,diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.tsindex ed49274d78..d3d015ae72 100644--- a/apps/mobile/src/device-link/mobileMakerTransport.ts+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts@@ -664,6 +664,13 @@ export interface MobileMakerTransport {| { sessionId: string; path: string; recoveryKey?: never }| { sessionId: string; recoveryKey: string; path?: never },): Promise<{ discarded: true; branchDeleted?: boolean }>;+ /** New hosts seal the creation id before discarding; never fall back to+ * discardPrecreated once a session-create request may have been sent. */+ cancelPrecreated?(+ input:+ | { sessionId: string; path: string; recoveryKey?: never }+ | { sessionId: string; recoveryKey: string; path?: never },+ ): Promise<{ discarded: true; branchDeleted?: boolean }>;};listAgentCommands(agentKind: MobileAgentKind,@@ -1257,6 +1264,8 @@ export function createMobileMakerTransport({create: (req) => call("worktree:create", [req]),discardPrecreated: (input) =>call("worktree:discard-precreated", [input]),+ cancelPrecreated: (input) =>+ call("worktree:cancel-precreated", [input]),},listAgentCommands: (agentKind, opts) =>call("maker:list-agent-commands", opts ? [agentKind, opts] : [agentKind]),diff --git a/apps/mobile/src/session/MobileOutboxBridge.tsx b/apps/mobile/src/session/MobileOutboxBridge.tsxindex c690c31928..ba7320bce0 100644--- a/apps/mobile/src/session/MobileOutboxBridge.tsx+++ b/apps/mobile/src/session/MobileOutboxBridge.tsx@@ -39,7 +39,7 @@ import {import { buildQueuedTextMessage } from "./inputProjection";import { outboxItemAttachments } from "./sessionOutbox";import { sessionFromCreateResult } from "./newSession";-import { getNewSessionCreationTask } from "./newSessionCreation";+import { dismissRecoveredPrecreatedSession, getNewSessionCreationTask } from "./newSessionCreation";import {MobileSessionReferenceError,prepareMobileQueuedSessionReferences,@@ -127,6 +127,10 @@ export function MobileOutboxBridge() {const keys = new Set<string>();for (const record of mobileDurableOutbox.getSnapshot()) {if (isDurableOutboxSettled(record)) continue;+ if (record.creation?.cancelled) {+ dismissRecoveredPrecreatedSession({ sessionId: record.item.sessionId, deviceId: record.deviceId });+ continue;+ }if (record.creation &&!remoteSessionStore@@ -169,7 +173,7 @@ export function MobileOutboxBridge() {AppState.currentState !== "background" &&AppState.currentState !== "inactive" &&(isDurableOutboxSettled(r) ||- (!r.suspended &&+ (!r.suspended && !r.creation?.cancelled &&!isDurableOutboxCreationHeld(r.item.sessionId) &&latest.current.link.status === "online" &&latest.current.link.getPresenceAvailability(r.deviceId) !== false &&diff --git a/apps/mobile/src/session/cancelledCreationDraft.ts b/apps/mobile/src/session/cancelledCreationDraft.tsnew file mode 100644index 0000000000..01d3437312--- /dev/null+++ b/apps/mobile/src/session/cancelledCreationDraft.ts@@ -0,0 +1,29 @@+import { managedWorktreeBaseRepo } from '@cindy/maker-shared/worktree-paths';+import type { DurableOutboxRecord } from './durableOutbox';++/** Called only after the host has fenced this session ID and acknowledged cleanup. */+export function cancelledCreationDraft(record: DurableOutboxRecord): DurableOutboxRecord {+ if (!record.creation || record.prepared || record.enqueueStarted || record.sendAtMs !== undefined) {+ throw new Error('OUTBOX_CREATION_OWNERSHIP_UNRESOLVED');+ }+ const creation = record.creation;+ // Pre-field records used Cindy's managed worktree layout. Never restore its deleted directory.+ const originalWorkingDir = creation.originalWorkingDir+ ?? managedWorktreeBaseRepo(creation.draft.workingDir)+ ?? '';+ return {+ ...record, suspended: true, state: 'failed',+ creation: {+ ...creation, cancelled: true, originalWorkingDir,+ draft: { ...creation.draft, workingDir: originalWorkingDir },+ },+ };+}++/** Preserve the one durable key and attachment directory; only the remote identity rotates. */+export function outboxCreationRetryIdentity(record: DurableOutboxRecord, newSessionId: () => string) {+ return {+ sessionId: record.creation?.cancelled ? newSessionId() : record.item.sessionId,+ storageSessionId: record.storageSessionId ?? record.item.sessionId,+ };+}diff --git a/apps/mobile/src/session/completePrecreatedWorktreeRecovery.ts b/apps/mobile/src/session/completePrecreatedWorktreeRecovery.tsnew file mode 100644index 0000000000..f60c1d032c--- /dev/null+++ b/apps/mobile/src/session/completePrecreatedWorktreeRecovery.ts@@ -0,0 +1,9 @@+import { persistCancelledCreationDraft } from './mobileDurableOutbox';+import { dismissRecoveredPrecreatedSession } from './newSessionCreation';+import type { PendingPrecreatedWorktree } from './precreatedWorktreeRecovery';++/** Keep the recovery ledger until its matching draft is durably safe to resubmit. */+export async function completePrecreatedWorktreeRecovery(record: PendingPrecreatedWorktree): Promise<void> {+ await persistCancelledCreationDraft(record);+ dismissRecoveredPrecreatedSession(record);+}diff --git a/apps/mobile/src/session/durableOutbox.ts b/apps/mobile/src/session/durableOutbox.tsindex 6876c7c5a2..aa6a57faa8 100644--- a/apps/mobile/src/session/durableOutbox.ts+++ b/apps/mobile/src/session/durableOutbox.ts@@ -21,6 +21,8 @@ export interface DurableOutboxRecord {/** Canonical realm-qualified auth accountKey; unqualified pre-release rows are never claimed. */accountId: string;deviceId: string;+ /** Stable disk/file identity when a cancelled creation is retried with a fresh session ID. */+ storageSessionId?: string;item: MobileOutboxItem;createdAt: number;state: "queued" | "sending" | "confirming" | "host-owned" | "failed";@@ -42,6 +44,8 @@ export interface DurableOutboxRecord {refreshUploads?: boolean;creation?: {draft: NewSessionDraft;+ originalWorkingDir?: string;+ cancelled?: true;deviceName: string;planModeArm: boolean;restorePermissionMode: string | null;@@ -79,10 +83,10 @@ export const DURABLE_OUTBOX_PREFIX = "cindy.mobile.outbox.v1.";const PREFIX = DURABLE_OUTBOX_PREFIX;const EMPTY: readonly DurableOutboxRecord[] = Object.freeze([]);const keyFor = (- r: Pick<DurableOutboxRecord, "accountId" | "deviceId" | "item">,+ r: Pick<DurableOutboxRecord, "accountId" | "deviceId" | "item" | "storageSessionId">,) =>PREFIX +- [r.accountId, r.deviceId, r.item.sessionId, r.item.clientId]+ [r.accountId, r.deviceId, r.storageSessionId ?? r.item.sessionId, r.item.clientId].map(encodeURIComponent).join("/");@@ -121,6 +125,11 @@ export function createDurableOutbox(storage: OutboxStorage, reconcileDraft?: (const current = records.find((r) => keyFor(r) === keyFor(record));if (adding ? current !== undefined : current !== record)throw new Error("OUTBOX_STALE_WRITE");+ if (next && keyFor(next) !== keyFor(record)) throw new Error("OUTBOX_IDENTITY_CHANGED");+ if (next && next.item.sessionId !== record.item.sessionId+ && (!record.creation?.cancelled || !next.creation || record.prepared)) {+ throw new Error('OUTBOX_CREATION_OWNERSHIP_UNRESOLVED');+ }if (next) await storage.setItem(keyFor(record), JSON.stringify(next));else await storage.removeItem(keyFor(record));// The disk write is already committed, even if logout raced its completion.@@ -240,6 +249,8 @@ function isLoadableOutboxRecord(&& !!row.deviceId&& !!row.item?.sessionId&& !!row.item.clientId+ && (row.storageSessionId === undefined+ || (typeof row.storageSessionId === 'string' && row.storageSessionId.length > 0))&& keyFor(row) === key&& Array.isArray(row.uploads)&& (row.cleanupOutcome === undefineddiff --git a/apps/mobile/src/session/durableOutboxFiles.ts b/apps/mobile/src/session/durableOutboxFiles.tsindex 0794f10e9c..bc1a21e710 100644--- a/apps/mobile/src/session/durableOutboxFiles.ts+++ b/apps/mobile/src/session/durableOutboxFiles.ts@@ -16,11 +16,11 @@ function segment(value: string): string {return encodeURIComponent(value).replace(/\./g, "%2E");}export function durableOutboxDirectory(- record: Pick<DurableOutboxRecord, "accountId" | "deviceId" | "item">,+ record: Pick<DurableOutboxRecord, "accountId" | "deviceId" | "item" | "storageSessionId">,): string {if (!FileSystem.documentDirectory)throw new Error("OUTBOX_STORAGE_UNAVAILABLE");- return `${FileSystem.documentDirectory}message-outbox/${[record.accountId, record.deviceId, record.item.sessionId, record.item.clientId].map(segment).join("/")}/`;+ return `${FileSystem.documentDirectory}message-outbox/${[record.accountId, record.deviceId, record.storageSessionId ?? record.item.sessionId, record.item.clientId].map(segment).join("/")}/`;}export function durableOutboxUploadUri(record: DurableOutboxRecord,@@ -109,7 +109,10 @@ export function initializeOutboxFiles(): Promise<void> {if (!info.exists || !info.isDirectory) return;for (const name of await FileSystem.readDirectoryAsync(directory)) {if (!name || name === '.' || name === '..' || /[\\/]/.test(name)) continue;- const uri = directory + name;+ // Native listings return decoded names, while the ledger contains URI-encoded+ // segments. Re-encode before comparison or a realm-qualified account's retained+ // files look unreferenced after restart. Keep the same encoding as the writer.+ const uri = directory + (depth < 4 ? segment(name) : encodeURIComponent(name));if (depth < 4) await visit(uri + '/', depth + 1);else if (/^slot-\d+(?:-[a-z0-9]+)?\.[a-z0-9]{1,12}$/.test(name) && !retained.has(uri)) {await FileSystem.deleteAsync(uri, { idempotent: true });diff --git a/apps/mobile/src/session/mobileDurableOutbox.ts b/apps/mobile/src/session/mobileDurableOutbox.tsindex a9726063b6..93f74c77c2 100644--- a/apps/mobile/src/session/mobileDurableOutbox.ts+++ b/apps/mobile/src/session/mobileDurableOutbox.ts@@ -8,6 +8,7 @@ import type { RemoteSerializedAttachment } from "./types";import { reconcileCommittedComposerDraft } from './composerDraftStore';import { withAsyncStorageFullRecovery } from './asyncStorageFull';import { migrateLegacySessionMessageCache } from './mobileSessionMessageCache';+import { cancelledCreationDraft } from './cancelledCreationDraft';const outboxStorage = withAsyncStorageFullRecovery(AsyncStorage, migrateLegacySessionMessageCache);export const mobileDurableOutbox = createDurableOutbox(outboxStorage, async (record, guard) => {@@ -21,6 +22,27 @@ export const mobileDurableOutbox = createDurableOutbox(outboxStorage, async (rec};await reconcileCommittedComposerDraft(record.item.sessionId, record.draftHandoff, check);});++/** Host ACK must be followed by this durable write before the recovery ledger is removed. */+export async function persistCancelledCreationDraft(record: { sessionId: string; deviceId: string; originalWorkingDir?: string }): Promise<void> {+ const owner = getMobileAuthOwner();+ const guard = () => {+ if (!owner.accountKey || !isMobileAuthOwnerCurrent(owner)) throw new Error('OUTBOX_OWNER_CHANGED');+ };+ guard();+ await mobileDurableOutbox.activate(owner.accountKey);+ guard();+ const drafts = mobileDurableOutbox.getSnapshot().filter((r) =>+ r.deviceId === record.deviceId && r.item.sessionId === record.sessionId && r.creation);+ for (const draft of drafts) {+ guard();+ const next = record.originalWorkingDir !== undefined+ ? { ...draft, creation: { ...draft.creation!, originalWorkingDir: record.originalWorkingDir } }+ : draft;+ await mobileDurableOutbox.update(draft, cancelledCreationDraft(next));+ }+ guard();+}export async function reconcileMobileOutboxDrafts(sessionId: string): Promise<void> {const owner = getMobileAuthOwner();if (!owner.accountKey) return;diff --git a/apps/mobile/src/session/newSessionCreation.ts b/apps/mobile/src/session/newSessionCreation.tsindex 9edebccd64..a3f4a7838f 100644--- a/apps/mobile/src/session/newSessionCreation.ts+++ b/apps/mobile/src/session/newSessionCreation.ts@@ -49,6 +49,7 @@ import {} from '@/session/newSession';import type { DeviceProvidersPayload } from '@/device-link/deviceProvidersCache';import { remoteSessionStore } from '@/session/remoteSessionStore';+import { persistCancelledCreationDraft } from './mobileDurableOutbox';import {forgetPendingPrecreatedWorktree,parseDiscardPrecreatedAck,@@ -327,7 +328,8 @@ export function retryNewSessionCreation(sessionId: string): void {// Once createSession may have run against a managed path, retrying can create// another wrong-id session that shares it. Recovery must first prove the// exact pre-generated id was claimed; unknown/NOT_FOUND stays retain-only.- if (task.precreatedWorktreeSessionCreateStarted) return;+ // A retry may reconcile an exact-id success, but must never resend an+ // uncertain managed create (see createSessionIdempotent).if (!isTaskOwnerCurrent(task)) {cancelStaleOwnerTask(task);return;@@ -436,7 +438,10 @@ export async function prepareNewSessionCreationForEdit(}const precreated = task.precreatedWorktree;if (precreated) {- if (task.precreatedWorktreeSessionCreateStarted) {+ const discard = task.precreatedWorktreeSessionCreateStarted+ ? task.params.transport.maker.worktree.cancelPrecreated+ : task.params.transport.maker.worktree.discardPrecreated;+ if (!discard) {throw new Error(i18n.t('session.new.worktreeCleanupPending'));}try {@@ -444,7 +449,7 @@ export async function prepareNewSessionCreationForEdit(assertTaskOwnerCurrent(task);await task.params.transport.openLink(task.deviceId);assertTaskOwnerCurrent(task);- const discardResult = await task.params.transport.maker.worktree.discardPrecreated({+ const discardResult = await discard({sessionId,recoveryKey: precreated.recoveryKey,});@@ -465,6 +470,9 @@ export async function prepareNewSessionCreationForEdit(}throw err;}+ assertTaskOwnerCurrent(task);+ await persistCancelledCreationDraft({ sessionId, deviceId: task.params.deviceId,+ originalWorkingDir: precreated.originalWorkingDir });const accountId = task.params.precreatedWorktreeAccountId?.trim();if (accountId) {assertTaskOwnerCurrent(task);@@ -484,6 +492,19 @@ export function getNewSessionCreationTask(sessionId: string): NewSessionCreationreturn tasks.get(sessionId) ?? null;}+/** Host cancellation ACK is authoritative; keep the durable outbox draft for editing. */+export function dismissRecoveredPrecreatedSession(record: { sessionId: string; deviceId: string }): void {+ if (tasks.has(record.sessionId)) return;+ if (remoteSessionStore.getSessionDeviceId(record.sessionId) !== record.deviceId) return;+ const row = remoteSessionStore.getSessions().find((session) => session.id === record.sessionId);+ // The host cancellation ACK proves this identity cannot become a live task.+ // Cold outbox hydration and cached rows need not carry pendingLocalCreation.+ if (!row) return;+ remoteSessionStore.applySessionPatch(record.deviceId, record.sessionId, { status: 'deleted' });+ remoteSessionStore.setInputProjectionOptimistically(record.sessionId, null);+ remoteSessionStore.clearPendingTitlePreview(record.sessionId);+}+/*** 会话页 syncSession 守卫:running(被控端可能还没有这个会话,getSession 会* NOT_FOUND 报错横幅)与 create-failed(确定不存在)都要跳过同步;@@ -672,9 +693,16 @@ async function createSessionIdempotent(};if (task.precreatedWorktree) {+ if (task.precreatedWorktreeSessionCreateStarted) {+ assertTaskOwnerCurrent(task);+ const existing = exactSessionFromProbe(await maker.getSession(task.sessionId), task.sessionId);+ assertTaskOwnerCurrent(task);+ if (existing) return { workDir: existing.workingDir ?? null, finalDraft: effectiveDraft };+ throw new Error(i18n.t('session.new.worktreeCleanupPending'));+ }// Persist the retain-only phase before the first createSession side effect.- // From here on, only an exact-id session may clear the ledger; NOT_FOUND,- // malformed replies, wrong ids, and transport errors must never authorize+ // From here on, only an exact-id session or a fenced cancellation ACK may+ // clear the ledger; malformed replies, wrong ids, and transport errors never authorize// retrying or discarding the managed directory.await persistPrecreatedSessionCreateStarted(task);assertTaskOwnerCurrent(task);@@ -765,7 +793,7 @@ async function createSessionIdempotent(} catch (probeError) {if (isStaleNewSessionOwnerError(probeError)) throw probeError;}- throw new Error(i18n.t('session.new.worktreeCleanupPending'));+ throw new Error(`${formatRemoteError(error)}\n${i18n.t('session.new.worktreeCleanupPending')}`);}}diff --git a/apps/mobile/src/session/precreatedWorktreeRecovery.ts b/apps/mobile/src/session/precreatedWorktreeRecovery.tsindex 5f66a9e91d..de2a8015f0 100644--- a/apps/mobile/src/session/precreatedWorktreeRecovery.ts+++ b/apps/mobile/src/session/precreatedWorktreeRecovery.ts@@ -29,9 +29,8 @@ interface PendingPrecreatedWorktreeBase {deviceId: string;createdAt: number;/**- * Destructive cleanup is allowed only while createSession is known not to- * have started. Missing legacy values are normalized to- * session-create-started (retain-only).+ * Every phase may have an in-flight create request. Recovery always requires+ * the host cancellation fence, including reservations without a create ACK.*/phase: 'reserved' | 'precreated' | 'session-create-started';}@@ -62,6 +61,8 @@ export interface PrecreatedWorktreeRecoveryDeps {| { sessionId: string; path: string; recoveryKey?: never }| { sessionId: string; recoveryKey: string; path?: never },) => Promise<unknown>;+ cancelPrecreated?: PrecreatedWorktreeRecoveryDeps['discardPrecreated'];+ onDiscarded?: (record: PendingPrecreatedWorktree) => void | Promise<void>;/*** PRECONDITION_FAILED 既可能表示会话已经认领 worktree,也可能表示* worktree 有改动/保留标记。调用方用权威 get-session 区分二者,只有前者@@ -565,16 +566,17 @@ export async function recoverPendingPrecreatedWorktrees(return;}if (!isRecoveryCurrent(deps)) return;- if (record.phase !== 'reserved' && record.phase !== 'precreated') {+ const discard = deps.cancelPrecreated;+ if (!discard) {throw new Error('Pre-created worktree session ownership is unresolved');}const discardResult = typeof record.recoveryKey === 'string'- ? await deps.discardPrecreated(record.deviceId, {+ ? await discard(record.deviceId, {sessionId: record.sessionId,recoveryKey: record.recoveryKey,}): typeof record.path === 'string'- ? await deps.discardPrecreated(record.deviceId, {+ ? await discard(record.deviceId, {sessionId: record.sessionId,path: record.path,})@@ -582,6 +584,8 @@ export async function recoverPendingPrecreatedWorktrees(if (!parseDiscardPrecreatedAck(discardResult)) {throw new Error('Invalid pre-created worktree discard acknowledgement');}+ // Persist the draft's cancellation before forgetting its recovery ledger.+ if (isRecoveryCurrent(deps)) await deps.onDiscarded?.(record);},{maxAttempts: 2,diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.mdindex 427700c16b..711dd10774 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -141,6 +141,8 @@ Claude.ai 登录,也不得收集、存储或中转订阅凭证。Cindy 因此| 数据性质 | 正确位置 ||---|---|| Cindy 管理的持久数据 | Desktop 使用 `app.getPath('userData')`,共享 package 由宿主注入等价根目录 |+| 预创建 worktree 的取消标记 | `userData/worktree-cancelled-creations/<sessionId 的 SHA-256>`,空文件原子排他创建;不含路径、草稿或关联密钥。保留以拒绝重启后迟到的创建请求,不按超时删除。只在核实未被任务认领后写入。同路径加 `.lock` 是可释放的跨进程操作锁,复用既有锁协议;同一 profile、同一任务的创建登记与取消回收串行,拿不到锁不得确认回收完成。异步创建完成后、登记前再次核对取消标记 |+| Mobile 已取消创建的草稿 | 复用账号隔离的 durable outbox;持久创建流程先保存草稿、原项目目录和附件,再登记 reservation 和发送远端 worktree 创建;创建回包前暂停发件箱投递。回收确认后,`creation.cancelled` 与原项目目录先持久写入,再忘记回收账本。重建使用新远端 ID,`storageSessionId` 保持原 AsyncStorage 键和附件目录,通过单次记录写入提交;写入失败时原草稿仍可读。编辑页恢复目录时重新探测资格,不沿用旧 worktree 的资格或分支偏好 || 可丢弃的临时数据 | `app.getPath('temp')` 或 `os.tmpdir()` 下的任务专属目录 || 测试生成物 | `os.tmpdir()` 下通过 `mkdtemp` 创建的独立目录,并在测试结束时清理 || Skill 卸载清理回执 | `app.getPath('userData')/skillhub/uninstall-cleanups/<token>.json`,记录操作 owner、旧文件/注册/偏好身份与完成阶段;跨窗口和重启保留,当前 owner 重试完成后删除,不作为授权凭据 |diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex f7c0686ef3..1c82316856 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -11,6 +11,22 @@ Agent 会话的事件流与 prompt 组装中枢,这里的改动会在用户无[`electron-security-and-process-boundaries.md`](electron-security-and-process-boundaries.md),Orca 多 Agent 协同另见 [`orca-team-architecture.md`](orca-team-architecture.md)。+## 启动失败与工作目录占用++Claude Code、Codex、Pi 共用 Maker 的启动失败清理契约:只有明确未启动进程或已确认+进程退出时,adapter 才返回 `AgentStartupStoppedError`;Maker 释放本次启动的目录租约,+并向调用方还原原始错误。准备环境失败也必须进入该契约,不能把尚未启动的任务永久+记为可能仍占用目录。鉴权失败保留原 `AgentNotAuthenticatedError` 类型。++本地 SDK 已接收启动调用、已观察到进程创建、或远端启动请求已发出后,普通异常不是+退出证明。Pi 在 transport 已创建而 RPC 包装器构造失败时,也必须关闭已取得的+transport;关闭未确认时复用原有隔离清理记录和 `AgentStartupCleanupPendingError`,+保留运行期文件与目录保护,重试确认退出后才释放。旧隔离进程的清理失败不能被新一轮+“尚未启动”的状态覆盖。此恢复只影响失败任务,不重置设备连接或其他任务,不自动重放消息。++回归见 `claude-code/__tests__/startup-cleanup.test.ts`、+`pi/__tests__/pi-startsession-cleanup.test.ts` 与 `maker.test.ts`。+## 工具循环与无响应的分工工具持续返回但反复原地搜索时,复用diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 890c35d9e8..ae152db952 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -609,6 +609,20 @@ X 快照有请求正文时,按原始 triggerMessageId 排除引用列表中的- 不要重新引入预装/播种机制或私有种子 submodule;需要推荐插件时走 SkillHub 的分发与用户主动安装流程。+## 预创建 worktree 的终止确认++同账号设备互联新增 `worktree:cancel-precreated`,参数仍为 `sessionId` 加 `path` 或+`recoveryKey` 二选一,成功回执沿用严格的 `{ discarded: true, branchDeleted?: boolean }`。+主机在与创建共用的任务锁内检查任务归属,再按创建 ID 持久标记取消、回收未认领目录。+迟到的 worktree 创建和任务启动均检查该标记;有内容改动、运行时占用或真实任务时仍保留。++Mobile 对所有预创建恢复记录(含未收到创建回包的 `reserved`)只接受此终止确认,不用一次 `NOT_FOUND` 授权+旧式删除。旧主机拒绝未知 channel 时保留记录,不回退 `discard-precreated`;旧控制端+继续使用原 channel。完全恢复需要两端均更新,服务端与 Mobile 原生配置无需改动。+恢复仅作用于该任务 ID,不重启 peer 或共享 relay,也不将创建请求加入自动重放。+终止确认后先持久保存草稿的取消状态和原项目目录,再删除回收账本;再次提交使用新任务 ID。+手机发件箱保留原持久键与附件目录,只原子替换记录中的远端任务 ID,写入失败仍可恢复原草稿。+## 3. Ghost manifest 与 Cindy 专属界面能力- `ghost.json` 的跨消费者字段、v2 兼容映射与枚举属于 Ghost manifest 协议,客户端正本位于diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.tsindex f48a0a3457..03b1b77d01 100644--- a/packages/device-link/src/__tests__/allowlist.test.ts+++ b/packages/device-link/src/__tests__/allowlist.test.ts@@ -273,6 +273,7 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {'worktree:suggest-name','worktree:create','worktree:discard-precreated',+ 'worktree:cancel-precreated','worktree:removal-preview',]) {expect(REMOTE_INVOKE_ALLOWLIST.has(ch)).toBe(true);@@ -467,6 +468,7 @@ describe('INVOKE_TIMEOUT_OVERRIDES_MS', () => {it('worktree:discard-precreated 可等待同 session 创建锁且不沿用默认 30s', () => {expect(INVOKE_TIMEOUT_OVERRIDES_MS['worktree:discard-precreated']).toBeGreaterThan(30_000);+ expect(INVOKE_TIMEOUT_OVERRIDES_MS['worktree:cancel-precreated']).toBeGreaterThan(30_000);});it('maker:compact-session 隧道超时必须大于 pi 压缩执行预算(10min + 回程余量,不 30s 截断)', () => {diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex e0276bea9d..33373077b4 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -594,6 +594,7 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = ['worktree:suggest-name','worktree:create','worktree:discard-precreated',+ 'worktree:cancel-precreated','worktree:removal-preview',// —— 个人 Telegram bot 跨设备上下线(准入论证见上方 DL_TELEGRAM_* 常量注释)——// 两条都由被控端 dispatch 拦截执行, 不是 ipcMain handler。@@ -768,6 +769,7 @@ export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {'worktree:create': 60_000,// 可能先等待同 sessionId 的晚到 create 释放互斥锁,再执行 git worktree remove。'worktree:discard-precreated': 60_000,+ 'worktree:cancel-precreated': 60_000,// pi 手动压缩调 LLM 生成摘要,大上下文 + 网关排队可达分钟级(core 侧// PI_COMPACT_TIMEOUT_MS = 10min);默认 30s 隧道超时会截断远程压缩请求,// 用户在控制端看到的就是「无反馈失败」。给足执行预算 + 回程余量:diff --git a/packages/maker-core/src/agents/claude-code/__tests__/startup-cleanup.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/startup-cleanup.test.tsnew file mode 100644index 0000000000..4a0707341c--- /dev/null+++ b/packages/maker-core/src/agents/claude-code/__tests__/startup-cleanup.test.ts@@ -0,0 +1,143 @@+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { AgentNotAuthenticatedError, AgentStartupCleanupPendingError, AgentStartupStoppedError, type AgentDeps } from '../../base-agent.js';+import type { Logger } from '../../../interfaces/logger.js';+import type { SessionMeta, SessionStorage } from '../../../interfaces/session-storage.js';+import { Maker, type CreateSessionOptions } from '../../../maker.js';+import { createAsyncQueue } from '../../shared/async-queue.js';++const sdk = vi.hoisted(() => ({ query: vi.fn() }));+vi.mock('@anthropic-ai/claude-agent-sdk', () => ({ query: sdk.query, forkSession: vi.fn() }));+import { ClaudeCodeAgent } from '../index.js';++const logger: Logger = {+ trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {},+ child: () => logger,+};++describe('Claude startup exit evidence', () => {+ let workingDir: string;+ beforeEach(async () => {+ workingDir = await mkdtemp(path.join(tmpdir(), 'claude-startup-cleanup-'));+ sdk.query.mockReset();+ });+ afterEach(async () => { await rm(workingDir, { recursive: true, force: true }); });++ function deps(): AgentDeps {+ return {+ binaryPath: process.execPath, runtimeConfig: {}, logger,+ auth: {+ getState: vi.fn(async () => ({ authenticated: true })),+ getAuthEnv: vi.fn(async () => ({})),+ triggerLogin: async () => ({ authenticated: true }), logout: async () => {},+ },+ };+ }++ it.each(['getState', 'getAuthEnv'] as const)('proves %s failures happened before any SDK dispatch', async (hook) => {+ const dependencies = deps();+ const error = new TypeError('preparation failed');+ vi.mocked(dependencies.auth[hook]).mockRejectedValueOnce(error);+ const agent = new ClaudeCodeAgent(dependencies);+ const failure = await agent.startSession({ sessionId: 'failed', workingDir, model: 'claude-sonnet-4-6' }).catch((e: unknown) => e);+ expect(failure).toBeInstanceOf(AgentStartupStoppedError);+ expect(failure).toMatchObject({ cause: error });+ expect(sdk.query).not.toHaveBeenCalled();++ // A later attempt reaches the SDK; its unknown exit is kept distinct from+ // the proven pre-spawn failure so Maker cannot release a live writer.+ const dispatchedError = new Error('SDK exit unconfirmed');+ sdk.query.mockImplementationOnce(() => { throw dispatchedError; });+ await expect(agent.startSession({ sessionId: 'fresh', workingDir, model: 'claude-sonnet-4-6' })).rejects.toBe(dispatchedError);+ expect(sdk.query).toHaveBeenCalledOnce();+ });++ it('preserves the authentication error class used by callers', async () => {+ const dependencies = deps();+ vi.mocked(dependencies.auth.getState).mockResolvedValueOnce({ authenticated: false });+ await expect(new ClaudeCodeAgent(dependencies).startSession({ workingDir, model: 'claude-sonnet-4-6' }))+ .rejects.toBeInstanceOf(AgentNotAuthenticatedError);+ expect(sdk.query).not.toHaveBeenCalled();+ });++ it('retains protection when the remote factory rejects without proving exit', async () => {+ const dependencies = deps();+ const error = new Error('remote startup reply lost');+ dependencies.remoteCcQueryFactory = vi.fn().mockRejectedValueOnce(error);+ await expect(new ClaudeCodeAgent(dependencies).startSession({+ workingDir, model: 'claude-sonnet-4-6', sessionId: 'remote-failure', remoteHostId: 'remote-1',+ })).rejects.toBe(error);+ expect(dependencies.remoteCcQueryFactory).toHaveBeenCalledOnce();+ expect(sdk.query).not.toHaveBeenCalled();+ });++ it('releases the failed attempt through Maker and creates a replacement without releasing another task', async () => {+ const dependencies = deps();+ const error = new Error('environment failed before CLI startup');+ vi.mocked(dependencies.auth.getAuthEnv).mockRejectedValueOnce(error);+ const rows = new Map<string, SessionMeta>();+ const storage: SessionStorage = {+ async create(meta) {+ const row = { ...meta, createdAt: Date.now(), updatedAt: Date.now() };+ rows.set(row.id, row);+ return row;+ },+ async get(id) { return rows.get(id) ?? null; },+ async list() { return [...rows.values()]; },+ async update(id, patch) {+ const row = rows.get(id);+ if (!row) throw new Error('missing test task');+ const next = { ...row, ...patch, updatedAt: Date.now() };+ rows.set(id, next);+ return next;+ },+ async compareAndClearSdkSessionId() { return false; },+ async delete(id) { rows.delete(id); },+ };+ const other = {} as CreateSessionOptions;+ const leases = new Set<CreateSessionOptions>([other]);+ const maker = new Maker({+ agents: { 'claude-code': new ClaudeCodeAgent(dependencies) }, storage, logger,+ lifecycleHooks: {+ prepareStartOptions: (_id, options) => { leases.add(options); },+ onStartFailed: ({ options, runtimeMayBeAlive }) => { if (!runtimeMayBeAlive) leases.delete(options); },+ onClose: (_id, options) => { leases.delete(options); },+ },+ });+ const options = { agentKind: 'claude-code' as const, workingDir, model: 'claude-sonnet-4-6' };+ await expect(maker.createSession({ ...options, id: 'failed' })).rejects.toBe(error);+ expect(leases).toEqual(new Set([other]));+ expect(rows.has('failed')).toBe(false);++ sdk.query.mockImplementationOnce(({ options: sdkOptions }) => {+ const queue = createAsyncQueue<never>();+ sdkOptions.abortController.signal.addEventListener('abort', () => queue.end(), { once: true });+ return queue;+ });+ const replacement = await maker.createSession({ ...options, id: 'replacement' });+ expect(maker.getSession('replacement')).toBe(replacement);+ expect(rows.has('replacement')).toBe(true);+ expect(leases.size).toBe(2);+ await replacement.close();+ await vi.waitFor(() => expect(leases).toEqual(new Set([other])));+ });++ it('does not nest explicit stopped errors from pre-spawn validation', async () => {+ const dependencies = deps();+ const error = new AgentStartupStoppedError(new Error('already confirmed'));+ vi.mocked(dependencies.auth.getState).mockRejectedValueOnce(error);+ await expect(new ClaudeCodeAgent(dependencies).startSession({ workingDir, model: 'claude-sonnet-4-6' })).rejects.toBe(error);+ });++ it('does not turn pending cleanup evidence into a stopped error', async () => {+ const dependencies = deps();+ const error = new AgentStartupCleanupPendingError('cleanup unconfirmed', {+ cause: new Error('preparation helper failed'), whenStopped: new Promise(() => {}),+ });+ vi.mocked(dependencies.auth.getState).mockRejectedValueOnce(error);+ await expect(new ClaudeCodeAgent(dependencies).startSession({ workingDir, model: 'claude-sonnet-4-6' }))+ .rejects.toBe(error);+ });+});diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 512ff27ba1..9931f82738 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -62,6 +62,7 @@ import {OneShotError,AgentNotAuthenticatedError,AgentStartupStoppedError,+ AgentStartupCleanupPendingError,TurnPermissionPolicyUnsupportedError,PINNED_SKILL_INVOCATION,type AgentSessionHandle,@@ -1331,6 +1332,27 @@ export class ClaudeCodeAgent extends BaseAgent {}async startSession(opts: StartSessionOptions): Promise<AgentSessionHandle> {+ let runtimeStartAttempted = false;+ try {+ return await this.startSessionInternal(opts, () => { runtimeStartAttempted = true; });+ } catch (error) {+ // Preparation failures cannot leave a CLI writer behind. Once a local SDK+ // query or remote start is dispatched, only explicit exit evidence can+ // release the workdir; a rejected factory alone does not prove termination.+ if (!runtimeStartAttempted+ && !(error instanceof AgentNotAuthenticatedError)+ && !(error instanceof AgentStartupCleanupPendingError)+ && !(error instanceof AgentStartupStoppedError)) {+ throw new AgentStartupStoppedError(error);+ }+ throw error;+ }+ }++ private async startSessionInternal(+ opts: StartSessionOptions,+ onRuntimeStartAttempted: () => void,+ ): Promise<AgentSessionHandle> {// scope 带完整 s:<sessionId> 前缀 → host logger 落盘时提取 business sessionId,// 路由到 sessions/<id>/<date>.ndjson (logger.ts extractSessionId / sessionAgentSlot)。const sid = opts.sessionId ?? '';@@ -3610,6 +3632,7 @@ export class ClaudeCodeAgent extends BaseAgent {},};+ onRuntimeStartAttempted();const remoteQuery = await this.deps.remoteCcQueryFactory({remoteHostId: opts.remoteHostId,botSession: !reviewMode && !!opts.botRuntimeProfile,@@ -4221,6 +4244,7 @@ export class ClaudeCodeAgent extends BaseAgent {if (managedPlugins && querySignal.aborted) throw new Error('Claude session closed before skill plugins were loaded');const queryArgs = createLocalQueryArgs();if (newSdkSessionId) sdkSessionId = newSdkSessionId;+ onRuntimeStartAttempted();query = sdkQuery(queryArgs);} catch (error) {if (sdkSessionId === newSdkSessionId) sdkSessionId = previousSdkSessionId;diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex f4ad65d8e2..87c714afdc 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -21,6 +21,7 @@ import {PINNED_SKILL_INVOCATION,CodexResumePreparationBlockedError,AgentNotAuthenticatedError,+ AgentStartupStoppedError,type AgentDeps,type AgentSessionHandle,type TurnPermissionPolicy,@@ -35143,14 +35144,16 @@ describe('CodexAgent custom provider context window override', () => {await agent.dispose();});- it('retires the isolated custom-context app-server when initialize fails', async () => {+ it.each(['account', 'custom-context'])('reports confirmed %s host exit after initialize fails', async (kind) => {MockCodexTransport.onCreate = (transport) => {transport.setMockResponse(Method.Initialize, {error: { code: -32_000, message: 'initialize boom' },});};const agent = new CodexAgent(createDeps({}, {- resolveCodexThreadContextWindow: () => 700_000,+ ...(kind === 'account'+ ? { isCodexAccountProvider: (id?: string | null) => id === 'mygpt' }+ : { resolveCodexThreadContextWindow: () => 700_000 }),prepareCodexExtraSpawnConfig: async () => ({ extraArgs: [], extraEnv: {} }),}));@@ -35159,13 +35162,60 @@ describe('CodexAgent custom provider context window override', () => {model: 'gpt-5.6-sol',providerId: 'mygpt',workingDir: '/repo',- })).rejects.toThrow('initialize boom');+ })).rejects.toMatchObject({+ name: 'AgentStartupStoppedError',+ cause: expect.objectContaining({ message: expect.stringContaining('initialize boom') }),+ });expect(createdTransports[0]?.closed).toBe(true);expect((agent as unknown as { hosts: Map<string, unknown> }).hosts.size).toBe(0);await agent.dispose();});+ it.each([+ ['account', Method.Initialize], ['custom-context', Method.Initialize],+ ['account', Method.ThreadStart], ['custom-context', Method.ThreadStart],+ ])('never reports stopped when the %s startup transport fails to retire after %s fails', async (kind, method) => {+ MockCodexTransport.onCreate = (transport) => {+ transport.setMockResponse(method, {+ error: { code: -32_000, message: 'startup boom' },+ });+ };+ MockCodexTransport.closeError = new Error('shutdown unconfirmed');+ const agent = new CodexAgent(createDeps({}, {+ ...(kind === 'account'+ ? { isCodexAccountProvider: (id?: string | null) => id === 'account-a' }+ : { resolveCodexThreadContextWindow: () => 700_000 }),+ prepareCodexExtraSpawnConfig: async () => ({ extraArgs: [], extraEnv: {} }),+ }));+ const failure = await agent.startSession({+ sessionId: 'failed-isolated-start', providerId: 'account-a', model: 'gpt-5.4', workingDir: '/repo',+ }).catch((error) => error);+ expect(failure).toBeInstanceOf(Error);+ expect(failure).toBe(MockCodexTransport.closeError);+ expect(failure).not.toBeInstanceOf(AgentStartupStoppedError);+ expect((agent as unknown as { retiringHosts: Map<string, unknown> }).retiringHosts.size).toBe(1);+ MockCodexTransport.closeError = null;+ await agent.dispose();+ expect(createdTransports[0]?.closed).toBe(true);+ expect((agent as unknown as { retiringHosts: Map<string, unknown> }).retiringHosts.size).toBe(0);+ });++ it('releases the failed account startup without interrupting another live host', async () => {+ const agent = new CodexAgent(createDeps({}, { isCodexAccountProvider: () => true }));+ const live = await agent.startSession({ sessionId: 'unrelated-live', providerId: 'account-b', model: 'gpt-5.4', workingDir: '/other' });+ MockCodexTransport.onCreate = (transport) => {+ transport.setMockResponse(Method.Initialize, { error: { code: -32_000, message: 'initialize boom' } });+ };+ await expect(agent.startSession({ sessionId: 'failed-start', providerId: 'account-a', model: 'gpt-5.4', workingDir: '/repo' }))+ .rejects.toBeInstanceOf(AgentStartupStoppedError);+ expect(createdTransports[0].closed).toBe(false);+ expect(createdTransports[1].closed).toBe(true);+ await live.send({ type: 'user', content: 'still available' });+ await live.close();+ await agent.dispose();+ });+it('retires the isolated custom-context app-server when capability preparation fails', async () => {const agent = new CodexAgent(createDeps({}, {resolveCodexThreadContextWindow: () => 700_000,diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 88864da612..943dfd216a 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -3601,7 +3601,13 @@ assertRouteCurrent();if (!signal.aborted && error instanceof CodexRouteSelectionChangedError && error.retryable && attempt < 7) continue;throw new AgentStartupStoppedError(signal.aborted ? signal.reason : error);}- await startup.customContext?.();+ if (startup.customContext) {+ await startup.customContext();+ // Retirement of this isolated local host proves the failed startup+ // cannot keep using its workdir. Propagate that proof to Maker so its+ // onStartFailed hook releases the directory lease.+ if (!opts.remoteHostId) throw new AgentStartupStoppedError(error);+ }throw error;}}@@ -5136,7 +5142,7 @@ assertRouteCurrent();})();const hostGeneration = this.hostGenerations.get(currentHostKey) ?? 0;const capturedHostWasRegistered = this.hosts.get(currentHostKey) === host;- const retireSingleSessionHost = async (): Promise<void> => {+ const retireSingleSessionHost = async (throwOnShutdownFailure = accountSessionHost): Promise<void> => {if (!reviewMode && !usesCustomContextHost && !accountSessionHost && !sessionSqliteHome) return;const purpose = reviewMode ? 'Review' : accountSessionHost ? 'account' : 'custom context';const reason = `Cindy ${purpose} host is single-session`;@@ -5145,9 +5151,9 @@ assertRouteCurrent();logPrefix: `codex ${purpose.toLowerCase()} host cleanup`,...(capturedHostWasRegistered ? { expectedHost: host } : {}),expectedGeneration: hostGeneration,- throwOnShutdownFailure: accountSessionHost,+ throwOnShutdownFailure,}).catch((error) => {- if (accountSessionHost) throw error;+ if (throwOnShutdownFailure) throw error;log.warn(`${purpose} host retire failed`, {error: error instanceof Error ? error.message : String(error),});@@ -5156,7 +5162,11 @@ assertRouteCurrent();if (usesCustomContextHost || accountSessionHost) {registerFailedCustomContextStartupCleanup(async () => {releaseHostBindingLeaseIfNeeded();- await retireSingleSessionHost();+ await retireSingleSessionHost(true);+ // retireHostKey may skip an already-replaced generation, or preserve a+ // shutdown error for retry. Only confirmed retirement of our captured+ // host may authorize releasing this startup's workdir guard.+ await host.retire('Codex isolated startup failed', { throwOnTransportError: true });});}startup.cleanup = async () => {diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.tsindex dae2dc4439..19cf99c8c4 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts@@ -156,6 +156,7 @@ vi.mock("../rpc-client.js", () => ({import { buildPiSettingsJsonContent, PiAgent } from "../index.js";import type { AgentDeps, AgentSessionHandle } from "../../base-agent.js";+import { AgentStartupStoppedError } from "../../base-agent.js";import type { Logger } from "../../../interfaces/logger.js";const noopLogger: Logger = {@@ -472,8 +473,10 @@ describe("PiAgent native auto-compaction ownership", () => {return originalSymlink(target, link, type);});}- await expect(new PiAgent(deps).startSession({ sessionId: 'failed-skill', workingDir: cwd, model: 'm' }))- .rejects.toBe(failure);+ const startupFailure = await new PiAgent(deps).startSession({ sessionId: 'failed-skill', workingDir: cwd, model: 'm' })+ .catch((error: unknown) => error);+ expect(startupFailure).toBeInstanceOf(AgentStartupStoppedError);+ expect((startupFailure as AgentStartupStoppedError).cause).toBe(failure);expect(failedPath).not.toBe('');expect(disposeSessionCtx).toHaveBeenCalledTimes(1);expect(knobs.spawnArgs).toEqual([]);diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.tsindex 7970c35e35..66b2bbcdf5 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts@@ -2769,13 +2769,13 @@ describe("Pi provider-aware model routing", () => {);for (const [index, model] of ["grok-4.6", "xai/grok-4.6"].entries()) {- await expect(- agent.startSession({+ const startupFailure = await agent.startSession({sessionId: `providerless-grok-proxy-not-ready-${index}`,workingDir: cwd,model,- }),- ).rejects.toBe(proxyNotReady);+ }).catch((error: unknown) => error);+ expect(startupFailure).toMatchObject({ name: 'AgentStartupStoppedError' });+ expect((startupFailure as Error).cause).toBe(proxyNotReady);}expect(captured.args).toEqual([]);});diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.tsindex 7cfe5d1f32..db7cb1bc79 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts@@ -32,6 +32,10 @@ import type { AutoReviewRequest } from '../../shared/auto-review-decision.js';// hoisted 控制旋钮:vi.mock 工厂被提升到 import 之上,不能闭包引用普通 let。const knobs = vi.hoisted(() => ({ctorThrows: false,+ rpcCtorThrows: false,+ transportThrowsAfterSpawn: false,+ transportCloseRejects: false,+ transportCloseCount: 0,getStateRejects: false,abortRejects: false,getStateGate: null as Promise<void> | null,@@ -59,12 +63,16 @@ vi.mock('../transport.js', () => ({knobs.spawnedArgs.push([...(opts.args ?? [])]);if (knobs.ctorThrows) throw new Error('spawn failed (mock)');opts.onProcessSpawned?.(1234);+ if (knobs.transportThrowsAfterSpawn) throw new Error('transport failed after spawn (mock)');return {writeLine: async () => {},onLine: () => () => {},onStderr: () => () => {},onClose: () => () => {},- close: async () => {},+ close: async () => {+ knobs.transportCloseCount++;+ if (knobs.transportCloseRejects) throw new Error('transport close unconfirmed (mock)');+ },pid: 1234,isClosed: () => false,};@@ -76,6 +84,7 @@ vi.mock('../rpc-client.js', () => ({PiRpcProcess: class {isClosed = false;constructor(opts: unknown) {+ if (knobs.rpcCtorThrows) throw new Error('RPC constructor failed (mock)');// 捕获 onExit 以便单测模拟进程异常退出(crash)。const o = opts as| {@@ -153,6 +162,10 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {beforeEach(() => {knobs.ctorThrows = false;+ knobs.rpcCtorThrows = false;+ knobs.transportThrowsAfterSpawn = false;+ knobs.transportCloseRejects = false;+ knobs.transportCloseCount = 0;knobs.getStateRejects = false;knobs.abortRejects = false;knobs.getStateGate = null;@@ -379,12 +392,97 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {it('disposes ctx (and does not close a nonexistent proc) when the process constructor throws synchronously', async () => {knobs.ctorThrows = true;const agent = new PiAgent(buildDeps());- await expect(agent.startSession(opts())).rejects.toThrow(/spawn failed/);+ const failure = await agent.startSession(opts()).catch((error: unknown) => error);+ expect(failure).toBeInstanceOf(AgentStartupStoppedError);+ expect(failure).toMatchObject({ cause: new Error('spawn failed (mock)') });expect(disposed).toBe(1);expect(proxyDisposed).toBe(2);expect(knobs.closeCount).toBe(0); // 构造失败没有 proc 可关});+ it('confirms a preparation failure before transport creation and permits a fresh attempt', async () => {+ const error = new Error('environment unavailable');+ const deps = buildDeps();+ vi.spyOn(deps.auth, 'getState').mockRejectedValueOnce(error);+ const agent = new PiAgent(deps);+ await expect(agent.startSession(opts())).rejects.toMatchObject({+ name: 'AgentStartupStoppedError', cause: error,+ });+ expect(knobs.spawnedEnvs).toHaveLength(0);+ const handle = await agent.startSession({ ...opts(), sessionId: 'fresh-after-preparation' });+ expect(knobs.spawnedEnvs).toHaveLength(1);+ await handle.close();+ });++ it('confirms that a start refused after disposal never acquired a new process', async () => {+ const agent = new PiAgent(buildDeps());+ await agent.dispose();+ await expect(agent.startSession(opts())).rejects.toMatchObject({+ name: 'AgentStartupStoppedError', cause: new Error('Pi agent is disposing; refusing to start a new session'),+ });+ expect(knobs.spawnedEnvs).toHaveLength(0);+ });++ it('closes an acquired transport if its RPC wrapper cannot be constructed', async () => {+ knobs.rpcCtorThrows = true;+ const agent = new PiAgent(buildDeps());+ await expect(agent.startSession(opts())).rejects.toMatchObject({+ name: 'AgentStartupStoppedError', cause: new Error('RPC constructor failed (mock)'),+ });+ expect(knobs.transportCloseCount).toBe(1);+ expect(knobs.closeCount).toBe(0);+ knobs.rpcCtorThrows = false;+ const handle = await agent.startSession(opts());+ await handle.close();+ });++ it('retains protection when remote transport creation loses the startup reply', async () => {+ const error = new Error('remote startup reply lost');+ const transport = vi.fn().mockRejectedValueOnce(error);+ const agent = new PiAgent(buildDeps({+ runtimeConfig: { endpoint: 'http://127.0.0.1:9', remoteEndpoint: 'https://gateway.invalid' },+ resolveRemotePiBinaryPath: async () => '/remote/pi',+ getRemotePiTransport: transport,+ getRemotePiFileOps: () => ({+ mkdirp: async () => {}, writeFile: async () => {}, rm: async () => {},+ stat: async () => ({ isFile: true }), listDir: async () => [],+ readFile: async () => { throw new Error('no existing remote fixture'); },+ sha256File: async () => { throw new Error('no existing remote fixture'); },+ }),+ }));+ await expect(agent.startSession({ ...opts(), remoteHostId: 'remote-1' })).rejects.toBe(error);+ expect(transport).toHaveBeenCalledOnce();+ });++ it('keeps protection and runtime files when a local spawn loses its transport handle', async () => {+ knobs.transportThrowsAfterSpawn = true;+ const failure = await new PiAgent(buildDeps()).startSession(opts()).catch((error: unknown) => error);+ expect(failure).toEqual(new Error('transport failed after spawn (mock)'));+ expect(failure).not.toBeInstanceOf(AgentStartupStoppedError);+ expect(knobs.transportCloseCount).toBe(0);+ expect(existsSync(knobs.spawnedEnvs[0]!.PI_CODING_AGENT_DIR!)).toBe(true);+ });++ it('quarantines a transport whose RPC wrapper and close both fail', async () => {+ knobs.rpcCtorThrows = true;+ knobs.transportCloseRejects = true;+ const agent = new PiAgent(buildDeps());+ const failure = await agent.startSession(opts()).catch((error: unknown) => error);+ expect(failure).toBeInstanceOf(AgentStartupCleanupPendingError);+ if (!(failure instanceof AgentStartupCleanupPendingError)) throw new Error('missing cleanup evidence');+ const stopped = vi.fn();+ void failure.whenStopped.then(stopped);+ await expect(agent.startSession(opts())).rejects.toThrow('transport close unconfirmed');+ expect(knobs.spawnedEnvs).toHaveLength(1);+ expect(stopped).not.toHaveBeenCalled();+ knobs.transportCloseRejects = false;+ knobs.rpcCtorThrows = false;+ const handle = await agent.startSession(opts());+ expect(stopped).toHaveBeenCalledOnce();+ expect(knobs.spawnedEnvs).toHaveLength(2);+ await handle.close();+ });+it('reports confirmed startup cleanup only after the proc closes, preserving the RPC error', async () => {knobs.getStateRejects = true;let confirmStopped!: () => void;diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 621cd49e81..b69f153116 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -1629,7 +1629,7 @@ function piExtraDirsPrompt(readOnlyDirs: readonly string[], writableDirs: readon}interface FailedPiStartupCleanup {- proc: PiRpcProcess;+ proc: Pick<PiRpcProcess, 'close'>;promise: Promise<void> | null;cleanupLocal?: () => void;confirmStopped: () => void;@@ -2474,7 +2474,7 @@ export class PiAgent extends BaseAgent {override async startSession(opts: StartSessionOptions): Promise<AgentSessionHandle> {if (this.disposeStarted) {- throw new Error('Pi agent is disposing; refusing to start a new session');+ throw new AgentStartupStoppedError(new Error('Pi agent is disposing; refusing to start a new session'));}const startup = this.startSessionWhileRunning(opts);this.inFlightStartups.add(startup);@@ -2486,11 +2486,32 @@ export class PiAgent extends BaseAgent {}private async startSessionWhileRunning(opts: StartSessionOptions): Promise<AgentSessionHandle> {- const startupTraceId = randomBytes(8).toString('hex');const startupCleanupKey = opts.sessionId ?? '<anonymous>';// A previous pre-publication Pi process for this business session must be// confirmed dead before another spawn can begin.await this.retryFailedStartupCleanup(startupCleanupKey);+ let runtimeStartAttempted = false;+ try {+ return await this.startSessionPrepared(opts, () => { runtimeStartAttempted = true; });+ } catch (error) {+ // Keep a previous quarantined process outside this boundary. Only this+ // attempt's pre-spawn failures are proof that it has no workdir writer.+ if (!runtimeStartAttempted+ && !(error instanceof AgentNotAuthenticatedError)+ && !(error instanceof AgentStartupCleanupPendingError)+ && !(error instanceof AgentStartupStoppedError)) {+ throw new AgentStartupStoppedError(error);+ }+ throw error;+ }+ }++ private async startSessionPrepared(+ opts: StartSessionOptions,+ onRuntimeStartAttempted: () => void,+ ): Promise<AgentSessionHandle> {+ const startupTraceId = randomBytes(8).toString('hex');+ const startupCleanupKey = opts.sessionId ?? '<anonymous>';// 轮 22 LOW-6:空串 remoteHostId 规范化 —— Boolean('') 是 false 会让会话// 被判定本地但后续仍把 '' 传给 resolvePiNativeProviders 等, 行为分裂。if (opts.remoteHostId === '') opts.remoteHostId = undefined;@@ -4885,6 +4906,7 @@ export class PiAgent extends BaseAgent {const runPiCompact = (instructions?: string): Promise<ManualCompactResult> =>runExclusivePiRpc(() => requestPiCompact(instructions));let sessionTransport: PiTransport | undefined;+ let localProcessSpawned = false;let runtimeCapabilityManifest: PiRuntimeCapabilityManifest | undefined;let runtimeCapabilityGeneration = 0;let piAgentLifecycleSequence = 0;@@ -5328,6 +5350,9 @@ export class PiAgent extends BaseAgent {const initialHostProxyForward = nativeProviderById.get(initialProvider)?.hostProxyForward;companionEnvironment?.assertCurrent?.();piSpawnStartedAt = Date.now();+ // A remote rejection may lose the reply after spawning. Local spawning is+ // synchronous and its process observer marks the boundary before returning.+ if (remote) onRuntimeStartAttempted();const { transport } = await this.createTransport({args,@@ -5336,16 +5361,20 @@ export class PiAgent extends BaseAgent {sessionId: opts.sessionId,hostProxyForwards: initialHostProxyForward ? [initialHostProxyForward] : [],},- (pid) =>- this.deps.registerLocalAgentProcess?.({+ (pid) => {+ localProcessSpawned = true;+ onRuntimeStartAttempted();+ return this.deps.registerLocalAgentProcess?.({pid,kind: 'pi',role: 'task-host',- }),+ });+ },opts.remoteHostId,effectivePiBinaryPath,);sessionTransport = transport;+ onRuntimeStartAttempted();proc = new PiRpcProcess({transport,logger: this.deps.logger,@@ -5600,12 +5629,44 @@ export class PiAgent extends BaseAgent {} catch {/* best-effort:注销失败不掩盖原始构造错误 */}+ // The transport can exist even if constructing its RPC wrapper throws.+ // Reuse the same quarantine as RPC startup failures until close is proven.+ if (sessionTransport) {+ const transport = sessionTransport;+ const cleanup = { close: async () => {+ try { await transport.killRemoteSession?.(); }+ finally { await transport.close(); }+ } };+ try {+ await cleanup.close();+ } catch (closeError) {+ if (!remote) configHomeCleanupDeferredToQuarantine = true;+ let confirmStopped!: () => void;+ const whenStopped = new Promise<void>((resolve) => { confirmStopped = resolve; });+ this.failedStartupCleanups.set(startupCleanupKey, {+ proc: cleanup, promise: null, confirmStopped,+ ...(!remote ? { cleanupLocal: () => {+ void cleanupConfigHome();+ cleanupRuntimeFiles();+ } } : {}),+ });+ throw new AgentStartupCleanupPendingError(+ `pi startup failed and transport cleanup remains unconfirmed: ${String(closeError)}`,+ { cause: err, whenStopped },+ );+ }+ } else if (remote || localProcessSpawned) {+ // No handle after dispatch/spawn is not proof of exit. Keep runtime+ // files too: an unpublished local writer may still be reading them.+ if (!remote) configHomeCleanupDeferredToQuarantine = true;+ throw err;+ }// 轮 42 P1:远端失败也不清理 runtime 文件(可能与并发存活会话共享/复用)。if (!remote) {await cleanupConfigHome();cleanupRuntimeFiles();}- throw err;+ throw new AgentStartupStoppedError(err);}let localSessionScanCache:diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex 02f65f22b0..42007452b5 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -1768,16 +1768,20 @@ describe('Maker start-option lifecycle hooks', () => {expect(onStartCleanupSucceeded).not.toHaveBeenCalled();});- it.each([new TypeError('startup RPC failed'), 'non-Error startup failure'])(- 'releases only the confirmed-stopped startup and preserves its original error: %s', async (startupError) => {+ it.each((['codex', 'claude-code', 'pi'] as const).flatMap((kind) =>+ [new TypeError('startup RPC failed'), 'non-Error startup failure'].map((error) => ({ kind, error }))))(+ 'releases only the confirmed-stopped $kind startup and permits a fresh task: $error', async ({ kind, error: startupError }) => {const otherStartup = {} as CreateSessionOptions;const leased = new Set<CreateSessionOptions>([otherStartup]);const onStartFailed = vi.fn(({ options, runtimeMayBeAlive }: SessionStartFailureContext) => {if (!runtimeMayBeAlive) leased.delete(options);});const onStartCleanupSucceeded = vi.fn();+ const startSession = vi.fn()+ .mockRejectedValueOnce(new AgentStartupStoppedError(startupError))+ .mockResolvedValueOnce(createHandle({ id: 'fresh-sdk-session' }));const maker = new Maker({- agents: { pi: createAgent(vi.fn().mockRejectedValue(new AgentStartupStoppedError(startupError)), 'pi') },+ agents: { [kind]: createAgent(startSession, kind) },storage: createStorage(), logger: createLogger(),lifecycleHooks: {prepareStartOptions: (_id, options) => { leased.add(options); },@@ -1785,7 +1789,7 @@ describe('Maker start-option lifecycle hooks', () => {},});await expect(maker.createSession({- id: 'confirmed-exit', agentKind: 'pi', workingDir: '/repo', model: 'pi-model',+ id: 'confirmed-exit', agentKind: kind, workingDir: '/repo', model: 'test-model',})).rejects.toBe(startupError);expect(onStartFailed).toHaveBeenCalledOnce();expect(onStartFailed).toHaveBeenCalledWith(expect.objectContaining({@@ -1793,6 +1797,12 @@ describe('Maker start-option lifecycle hooks', () => {}));expect(leased).toEqual(new Set([otherStartup]));expect(onStartCleanupSucceeded).not.toHaveBeenCalled();+ const replacement = await maker.createSession({+ id: 'fresh-task', agentKind: kind, workingDir: '/repo', model: 'test-model',+ });+ expect(maker.getSession('fresh-task')).toBe(replacement);+ expect(startSession).toHaveBeenCalledTimes(2);+ await replacement.close();},);diff --git a/packages/maker-shared/src/__tests__/brandIdentity.test.ts b/packages/maker-shared/src/__tests__/brandIdentity.test.tsindex 18262a549b..8245200f2e 100644--- a/packages/maker-shared/src/__tests__/brandIdentity.test.ts+++ b/packages/maker-shared/src/__tests__/brandIdentity.test.ts@@ -182,7 +182,7 @@ describe('派生 helper', () => {...BRAND_IDENTITY,primaryScheme: 'xdt-maker',legacySchemes: [],- userDataDirNameByRegion: { cn: 'xdt-maker', global: 'xdt-maker' },+ userDataDirNameByRegion: { cn: 'xdt-maker', global: 'xdt-maker', dev: 'xdt-maker' },legacyUserDataDirNames: [],legacyUserDataDirNamesByRegion: { cn: [], global: [], dev: [] },legacyDialogueUserDataDirNamesByRegion: { cn: [], global: [], dev: [] },diff --git a/packages/maker-shared/src/__tests__/composerPalette.test.ts b/packages/maker-shared/src/__tests__/composerPalette.test.tsindex da9a815c27..606328e9bb 100644--- a/packages/maker-shared/src/__tests__/composerPalette.test.ts+++ b/packages/maker-shared/src/__tests__/composerPalette.test.ts@@ -98,11 +98,11 @@ describe('shared composer palette model', () => {});it('serializes directory and quoted @ references like the desktop composer expects', () => {- expect(serializeAtResource({ type: 'dir', name: 'routes', relPath: 'apps/server/src/routes' }))+ expect(serializeAtResource({ type: 'dir', relPath: 'apps/server/src/routes' })).toBe('@apps/server/src/routes/');- expect(serializeAtResource({ type: 'agent', name: 'reviewer', relPath: '.claude/agents/reviewer.md' }))+ expect(serializeAtResource({ type: 'agent', relPath: '.claude/agents/reviewer.md' })).toBe('@.claude/agents/reviewer.md');- expect(serializeAtResource({ type: 'file', name: 'design notes.md', relPath: 'docs/design notes.md' }))+ expect(serializeAtResource({ type: 'file', relPath: 'docs/design notes.md' })).toBe('@"docs/design notes.md"');});diff --git a/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts b/packages/maker-shared/src/__tests__/deviceLinkContract.test.tsindex 8f95533819..9c8f7f92de 100644--- a/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts+++ b/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts@@ -50,6 +50,7 @@ describe('device-link shared contract', () => {expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('maker:apply-new-maker-worktree-branch-pref');expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('worktree:list-branches');expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('worktree:discard-precreated');+ expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('worktree:cancel-precreated');expect(MOBILE_REMOTE_INVOKE_CHANNELS).not.toContain(DEVICE_LINK_VOICE_CREDENTIAL_SYNC_CHANNEL);expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain(DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL);expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('text-file:read-preview');diff --git a/packages/maker-shared/src/__tests__/historyView.test.ts b/packages/maker-shared/src/__tests__/historyView.test.tsindex 4b874abd55..87125bd7ef 100644--- a/packages/maker-shared/src/__tests__/historyView.test.ts+++ b/packages/maker-shared/src/__tests__/historyView.test.ts@@ -408,8 +408,9 @@ describe('shared history view lifecycle', () => {const detail = snapshot.details.get(key)!;// A refreshed subrange can temporarily reuse a wider cache. Both endpoints// must still clip correctly after the live rows acquire persistent IDs.- snapshot.details.set(key, { ...detail, messages: [row(0, 'thinking', 'before'), ...persisted, row(3, 'thinking', 'after')] });- const rendered = renderHistoryView({ view, snapshot, liveMessages: [], streaming: true,+ const details = new Map(snapshot.details);+ details.set(key, { ...detail, messages: [row(0, 'thinking', 'before'), ...persisted, row(3, 'thinking', 'after')] });+ const rendered = renderHistoryView({ view, snapshot: { ...snapshot, details }, liveMessages: [], streaming: true,build: messages => messages.map(message => message.content), structure: ungroupedStructure });if (mode === 'stored') expect(rendered).not.toContain('first');else expect(rendered).toEqual(['first', 'last']);diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.tsindex 3a4143671b..b85a1bd52e 100644--- a/packages/maker-shared/src/deviceLinkContract.ts+++ b/packages/maker-shared/src/deviceLinkContract.ts@@ -420,6 +420,7 @@ export const MOBILE_REMOTE_INVOKE_CHANNELS = ['worktree:suggest-name','worktree:create','worktree:discard-precreated',+ 'worktree:cancel-precreated','text-file:read-preview',// 完整文件浏览(网格/预览/缩略图/大文件导出)走桌面同款聚合通道,// op 分发与响应形状见 apps/desktop/src/main/file-browser/device-op.ts。diff --git a/packages/maker-shared/src/workRunGrouping.ts b/packages/maker-shared/src/workRunGrouping.tsindex ad22d0a631..bb759ff7af 100644--- a/packages/maker-shared/src/workRunGrouping.ts+++ b/packages/maker-shared/src/workRunGrouping.ts@@ -48,9 +48,13 @@ export function groupWorkRuns<TItem, TChild extends TItem>(if (activeTail && isSessionStreaming) {// A new run's status can arrive before its user row. A durable done seal still// closes the loaded work before it; only subsequent content may stay active.- const completedIndex = turn.findLastIndex(- (item) => adapter.isAnswer(item) && adapter.isSealedAnswer(item),- );+ let completedIndex = -1;+ for (let index = turn.length - 1; index >= 0; index--) {+ if (adapter.isAnswer(turn[index]) && adapter.isSealedAnswer(turn[index])) {+ completedIndex = index;+ break;+ }+ }const activeStart =completedIndex >= 0? adapter.boundaryTimestamp(turn[completedIndex])