Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): harden task cleanup and media ownership

JiangJiahaof3e79542fd26
diff --git a/apps/desktop/src/main/__tests__/imageCacheStoreLifecycle.test.ts b/apps/desktop/src/main/__tests__/imageCacheStoreLifecycle.test.ts
index bf49321d67..148e2abf5f 100644
--- a/apps/desktop/src/main/__tests__/imageCacheStoreLifecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/imageCacheStoreLifecycle.test.ts
@@ -150,4 +150,14 @@ describe('imageCacheStore lifecycle metadata', () => {
expect(urls).toEqual(['xdt-image://session-a/a.png', 'xdt-image://session-b/c.webp']);
});
+
+ it('keeps the legacy session cleanup IPC out of the cindy-media ledger', async () => {
+ const source = await fs.readFile(new URL('../bootstrap-electron.ts', import.meta.url), 'utf8');
+ const start = source.indexOf("'image-cache:cleanup-session'");
+ const end = source.indexOf('// F7: cleanup a list of files', start);
+ const handler = source.slice(start, end);
+
+ expect(handler).toContain('imageCacheStore.removeSession(sessionId)');
+ expect(handler).not.toContain('removeSessionMediaRefs');
+ });
});
diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
index 711f710291..848f3a1792 100644
--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
@@ -16,12 +16,13 @@ const h = vi.hoisted(() => ({
tapWindowBroadcast: vi.fn(),
webContentsSend: vi.fn(),
closeSession: vi.fn(),
- withSendToSessionLock: vi.fn(
- async (_sessionId: string, task: () => Promise<unknown>) => task(),
- ),
+ withSendToSessionLock: vi.fn(async (_sessionId: string, task: () => Promise<unknown>) => task()),
isSessionStillRemovable: vi.fn(),
cancelSessionOperations: vi.fn(),
+ removeSessionRefs: vi.fn(),
recycleWorktreeForRemovedSession: vi.fn(),
+ isOwnerScopeCurrent: vi.fn(),
+ drizzle: {},
userDataPath: '',
agentIslandService: {
handleSessionMetadataPatch: vi.fn(),
@@ -38,14 +39,19 @@ vi.mock('electron', () => ({
vi.mock('../logger', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
-vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ tx: h.tx }) }));
+vi.mock('../localDb/client/current', () => ({
+ getDbClient: () => ({ tx: h.tx, drizzle: h.drizzle }),
+}));
+vi.mock('../cindy-media/ledger', () => ({
+ removeSessionRefsIfDeleted: h.removeSessionRefs,
+}));
vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));
vi.mock('../git-context/prRefsStore', () => ({ recomputePrRefsForSession: vi.fn() }));
vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn() }));
vi.mock('../device-link/broadcast-tap', () => ({
captureDataOwnerBroadcastScope: vi.fn(() => null),
getSafeDataOwnerPushStamp: vi.fn(() => undefined),
- isDataOwnerBroadcastScopeCurrent: vi.fn(() => true),
+ isDataOwnerBroadcastScopeCurrent: h.isOwnerScopeCurrent,
tapWindowBroadcast: h.tapWindowBroadcast,
}));
vi.mock('../agent-island/service.js', () => ({
@@ -67,6 +73,7 @@ import {
setSessionRemovalCancelOperations,
setSessionsStatusInDb,
} from '../localDb/ipc/sessions.js';
+import { setSessionRouteLockImplementation } from '../localDb/sessionRouteLock.js';
beforeEach(() => {
vi.clearAllMocks();
@@ -74,39 +81,55 @@ beforeEach(() => {
h.closeSession.mockResolvedValue(undefined);
h.isSessionStillRemovable.mockResolvedValue(true);
h.cancelSessionOperations.mockResolvedValue(undefined);
+ h.removeSessionRefs.mockResolvedValue(0);
h.recycleWorktreeForRemovedSession.mockResolvedValue(undefined);
+ h.isOwnerScopeCurrent.mockReturnValue(true);
setSessionRemovalCancelOperations(h.cancelSessionOperations);
+ setSessionRouteLockImplementation(h.withSendToSessionLock);
});
afterEach(() => {
setSessionRemovalCancelOperations(null);
+ setSessionRouteLockImplementation(null);
fs.rmSync(h.userDataPath, { recursive: true, force: true });
});
describe('setSessionsStatusInDb', () => {
it('runs one sessions.setStatus tx and broadcasts per session after commit', async () => {
h.tx.mockResolvedValueOnce([
- { sessionId: 's1', title: 'T1', workingDir: '/repo', workspaceKind: 'project', status: 'archived' },
- { sessionId: 's2', title: 'T2', workingDir: null, workspaceKind: 'dialogue', status: 'archived' },
+ {
+ sessionId: 's1',
+ title: 'T1',
+ workingDir: '/repo',
+ workspaceKind: 'project',
+ status: 'active',
+ },
+ {
+ sessionId: 's2',
+ title: 'T2',
+ workingDir: null,
+ workspaceKind: 'dialogue',
+ status: 'active',
+ },
]);
- const result = await setSessionsStatusInDb(['s1', 's2'], 'archived');
+ const result = await setSessionsStatusInDb(['s1', 's2'], 'active');
expect(h.tx).toHaveBeenCalledWith('sessions.setStatus', {
sessionIds: ['s1', 's2'],
- status: 'archived',
+ status: 'active',
});
// 提交后逐个广播
expect(h.tapWindowBroadcast).toHaveBeenCalledTimes(2);
expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {
sessionId: 's1',
- patch: { status: 'archived' },
+ patch: { status: 'active' },
});
expect(h.webContentsSend).toHaveBeenCalledTimes(2);
// 返回值是精简后的行(不含 workspaceKind)
expect(result).toEqual([
- { sessionId: 's1', title: 'T1', workingDir: '/repo', status: 'archived' },
- { sessionId: 's2', title: 'T2', workingDir: null, status: 'archived' },
+ { sessionId: 's1', title: 'T1', workingDir: '/repo', status: 'active' },
+ { sessionId: 's2', title: 'T2', workingDir: null, status: 'active' },
]);
});
@@ -129,7 +152,13 @@ describe('setSessionsStatusInDb', () => {
it('does not schedule recycle when batch restores sessions to active', async () => {
h.tx.mockResolvedValueOnce([
- { sessionId: 's1', title: 'T1', workingDir: '/repo', workspaceKind: 'project', status: 'active' },
+ {
+ sessionId: 's1',
+ title: 'T1',
+ workingDir: '/repo',
+ workspaceKind: 'project',
+ status: 'active',
+ },
]);
await setSessionsStatusInDb(['s1'], 'active');
@@ -138,18 +167,42 @@ describe('setSessionsStatusInDb', () => {
expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();
});
+ it('acquires overlapping batch route locks once in stable order', async () => {
+ h.tx.mockResolvedValueOnce([]);
+
+ await setSessionsStatusInDb(['s2', 's1', 's2'], 'active');
+
+ expect(h.withSendToSessionLock.mock.calls.map(([sessionId]) => sessionId)).toEqual([
+ 's1',
+ 's2',
+ ]);
+ expect(h.tx).toHaveBeenCalledWith('sessions.setStatus', {
+ sessionIds: ['s2', 's1', 's2'],
+ status: 'active',
+ });
+ });
+
it('rechecks current status before closing a session from a delayed archive task', async () => {
h.tx.mockResolvedValueOnce([
- { sessionId: 's1', title: 'T1', workingDir: '/repo', workspaceKind: 'project', status: 'archived' },
+ {
+ sessionId: 's1',
+ title: 'T1',
+ workingDir: '/repo',
+ workspaceKind: 'project',
+ status: 'archived',
+ },
]);
h.isSessionStillRemovable.mockResolvedValueOnce(false);
await setSessionsStatusInDb(['s1'], 'archived');
await vi.waitFor(() => {
- expect(h.isSessionStillRemovable).toHaveBeenCalledWith('s1');
+ expect(h.isSessionStillRemovable).toHaveBeenCalledWith('s1', h.drizzle);
});
- expect(h.withSendToSessionLock).not.toHaveBeenCalled();
+ // The status transaction itself is serialized; the delayed cleanup exits
+ // before acquiring a second lock because the task is no longer removable.
+ expect(h.withSendToSessionLock).toHaveBeenCalledTimes(1);
+ expect(h.withSendToSessionLock).toHaveBeenCalledWith('s1', expect.any(Function));
expect(h.cancelSessionOperations).not.toHaveBeenCalled();
expect(h.closeSession).not.toHaveBeenCalled();
expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();
@@ -157,7 +210,13 @@ describe('setSessionsStatusInDb', () => {
it('serializes archive-driven close with the session route lock', async () => {
h.tx.mockResolvedValueOnce([
- { sessionId: 's1', title: 'T1', workingDir: '/repo', workspaceKind: 'project', status: 'archived' },
+ {
+ sessionId: 's1',
+ title: 'T1',
+ workingDir: '/repo',
+ workspaceKind: 'project',
+ status: 'archived',
+ },
]);
await setSessionsStatusInDb(['s1'], 'archived');
@@ -166,16 +225,25 @@ describe('setSessionsStatusInDb', () => {
});
expect(h.withSendToSessionLock).toHaveBeenCalledWith('s1', expect.any(Function));
- expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(3);
+ expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(4);
expect(h.cancelSessionOperations).toHaveBeenCalledWith('s1');
- expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith('s1');
+ expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith(
+ 's1',
+ expect.objectContaining({ db: h.drizzle, isOwnerCurrent: expect.any(Function) }),
+ );
});
it('broadcasts worktree:changed only after the recycle chain finishes', async () => {
// renderer 的 WorktreeContext 靠这条推送才能拿到回收后的快照 —— 回收是异步链,
// 状态 IPC 返回时 store 条目还在,归档动作里那次「顺手 refresh」必然是旧的。
h.tx.mockResolvedValueOnce([
- { sessionId: 's1', title: 'T1', workingDir: '/repo', workspaceKind: 'project', status: 'archived' },
+ {
+ sessionId: 's1',
+ title: 'T1',
+ workingDir: '/repo',
+ workspaceKind: 'project',
+ status: 'archived',
+ },
]);
let finishRecycle!: () => void;
h.recycleWorktreeForRemovedSession.mockImplementationOnce(
@@ -187,7 +255,10 @@ describe('setSessionsStatusInDb', () => {
await setSessionsStatusInDb(['s1'], 'archived');
await vi.waitFor(() => {
- expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith('s1');
+ expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith(
+ 's1',
+ expect.objectContaining({ db: h.drizzle, isOwnerCurrent: expect.any(Function) }),
+ );
});
// 回收还没结束 —— 此时只该有 sessions:patched,不能提前报 worktree 已变。
@@ -202,9 +273,17 @@ describe('setSessionsStatusInDb', () => {
it('still broadcasts worktree:changed when the recycle chain fails', async () => {
// 回收失败/跳过时条目仍在 store 里,重拉拿到「徽标还在」也是真实状态。
h.tx.mockResolvedValueOnce([
- { sessionId: 's1', title: 'T1', workingDir: '/repo', workspaceKind: 'project', status: 'archived' },
+ {
+ sessionId: 's1',
+ title: 'T1',
+ workingDir: '/repo',
+ workspaceKind: 'project',
+ status: 'archived',
+ },
]);
- h.recycleWorktreeForRemovedSession.mockRejectedValueOnce(new Error('git worktree remove failed'));
+ h.recycleWorktreeForRemovedSession.mockRejectedValueOnce(
+ new Error('git worktree remove failed'),
+ );
await setSessionsStatusInDb(['s1'], 'archived');
@@ -215,7 +294,13 @@ describe('setSessionsStatusInDb', () => {
it('does not broadcast worktree:changed when restoring to active', async () => {
h.tx.mockResolvedValueOnce([
- { sessionId: 's1', title: 'T1', workingDir: '/repo', workspaceKind: 'project', status: 'active' },
+ {
+ sessionId: 's1',
+ title: 'T1',
+ workingDir: '/repo',
+ workspaceKind: 'project',
+ status: 'active',
+ },
]);
await setSessionsStatusInDb(['s1'], 'active');
@@ -224,27 +309,72 @@ describe('setSessionsStatusInDb', () => {
});
it('keeps batch archived status wired to worktree recycle scheduling', () => {
- const source = fs.readFileSync(
- new URL('../localDb/ipc/sessions.ts', import.meta.url),
- 'utf8',
- );
+ const source = fs.readFileSync(new URL('../localDb/ipc/sessions.ts', import.meta.url), 'utf8');
const batchBody = source.match(
/export async function setSessionsStatusInDb[\s\S]*return applied\.map/,
)?.[0];
- expect(batchBody).toContain('scheduleWorktreeRecycleForStatusChange(item.sessionId, item.status)');
+ expect(batchBody).toContain(
+ 'scheduleWorktreeRecycleForStatusChange(item.sessionId, item.status, {',
+ );
+ expect(batchBody).toContain('ownerScope,');
+ expect(batchBody).toContain('mediaDb: dbClient.drizzle,');
});
});
describe('recycleSessionWorktreeForStatusChange', () => {
it('awaits the shared close and worktree recycle chain for deleted sessions', async () => {
+ const order: string[] = [];
+ h.cancelSessionOperations.mockImplementationOnce(async () => {
+ order.push('cancel');
+ });
+ h.removeSessionRefs.mockImplementationOnce(async () => {
+ order.push('remove-media-refs');
+ return 1;
+ });
+ h.recycleWorktreeForRemovedSession.mockImplementationOnce(async () => {
+ order.push('recycle-worktree');
+ });
+
await recycleSessionWorktreeForStatusChange('s1', 'deleted');
expect(h.withSendToSessionLock).toHaveBeenCalledWith('s1', expect.any(Function));
- expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(3);
+ expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(4);
expect(h.cancelSessionOperations).toHaveBeenCalledWith('s1');
expect(h.closeSession).toHaveBeenCalledWith('s1');
- expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith('s1');
+ expect(h.removeSessionRefs).toHaveBeenCalledWith('s1', h.drizzle);
+ expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith(
+ 's1',
+ expect.objectContaining({ db: h.drizzle, isOwnerCurrent: expect.any(Function) }),
+ );
expect(h.webContentsSend).toHaveBeenCalledWith('worktree:changed', { sessionId: 's1' });
+ expect(order).toEqual(['cancel', 'remove-media-refs', 'recycle-worktree']);
+ });
+
+ it('keeps media and worktree deletion inside the task route lock', async () => {
+ let lockHeld = false;
+ h.withSendToSessionLock.mockImplementationOnce(
+ async (_sessionId: string, task: () => Promise<unknown>) => {
+ lockHeld = true;
+ try {
+ return await task();
+ } finally {
+ lockHeld = false;
+ }
+ },
+ );
+ h.removeSessionRefs.mockImplementationOnce(async () => {
+ expect(lockHeld).toBe(true);
+ return 1;
+ });
+ h.recycleWorktreeForRemovedSession.mockImplementationOnce(async () => {
+ expect(lockHeld).toBe(true);
+ });
+
+ await recycleSessionWorktreeForStatusChange('s1', 'deleted');
+
+ expect(lockHeld).toBe(false);
+ expect(h.removeSessionRefs).toHaveBeenCalledWith('s1', h.drizzle);
+ expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledOnce();
});
it('does not touch the runtime or worktree for active sessions', async () => {
@@ -271,4 +401,34 @@ describe('recycleSessionWorktreeForStatusChange', () => {
const source = fs.readFileSync(new URL('../localDb/ipc/sessions.ts', import.meta.url), 'utf8');
expect(source).not.toContain("import('../../mcp-integrations/ios-simulator.js')");
});
+
+ it('does not let a stale status write clean the next owner database', async () => {
+ h.isOwnerScopeCurrent.mockReturnValue(false);
+
+ await recycleSessionWorktreeForStatusChange('shared-session-id', 'deleted', {
+ ownerScope: { ownerStamp: 'old-owner' } as never,
+ mediaDb: h.drizzle as never,
+ });
+
+ expect(h.isSessionStillRemovable).not.toHaveBeenCalled();
+ expect(h.cancelSessionOperations).not.toHaveBeenCalled();
+ expect(h.removeSessionRefs).not.toHaveBeenCalled();
+ expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();
+ });
+
+ it('stops after Agent close when the captured owner changes mid-cleanup', async () => {
+ h.closeSession.mockImplementationOnce(async () => {
+ h.isOwnerScopeCurrent.mockReturnValue(false);
+ });
+
+ await recycleSessionWorktreeForStatusChange('shared-session-id', 'deleted', {
+ ownerScope: { ownerStamp: 'old-owner' } as never,
+ mediaDb: h.drizzle as never,
+ });
+
+ expect(h.cancelSessionOperations).toHaveBeenCalledWith('shared-session-id');
+ expect(h.closeSession).toHaveBeenCalledWith('shared-session-id');
+ expect(h.removeSessionRefs).not.toHaveBeenCalled();
+ expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts b/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts
index 3bd4c34fc4..69220e33b7 100644
--- a/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts
@@ -53,6 +53,16 @@ function makeMeta(sessionId: string, ephemeral = false): WorktreeMeta {
};
}
+function dbFor(rows: Array<{ id: string; status: string | null }>) {
+ return {
+ select: () => ({
+ from: () => ({
+ where: () => rows,
+ }),
+ }),
+ };
+}
+
describe('sessionRemovalRecycle', () => {
let mod: typeof import('../worktree/sessionRemovalRecycle');
@@ -120,6 +130,27 @@ describe('sessionRemovalRecycle', () => {
expect(removeMock).not.toHaveBeenCalled();
});
+
+ it('uses the captured owner database and stops its live guard after owner switch', async () => {
+ storeMap.set('shared-session-id', makeMeta('shared-session-id'));
+ sessionRows.push({ id: 'shared-session-id', status: 'active' });
+ const capturedRows = [{ id: 'shared-session-id', status: 'deleted' as string | null }];
+ let ownerCurrent = true;
+ removeMock.mockImplementationOnce(
+ async (_sessionId: string, options: { canRemove: () => Promise<boolean> }) => {
+ await expect(options.canRemove()).resolves.toBe(true);
+ ownerCurrent = false;
+ await expect(options.canRemove()).resolves.toBe(false);
+ },
+ );
+
+ await mod.recycleWorktreeForRemovedSession('shared-session-id', {
+ db: dbFor(capturedRows) as never,
+ isOwnerCurrent: () => ownerCurrent,
+ });
+
+ expect(removeMock).toHaveBeenCalledOnce();
+ });
});
describe('isSessionStillRemovable', () => {
@@ -135,6 +166,15 @@ describe('sessionRemovalRecycle', () => {
sessionLookupError = new Error('db closed');
await expect(mod.isSessionStillRemovable('s1')).resolves.toBe(false);
});
+
+ it('uses an explicitly captured database instead of the current global owner', async () => {
+ sessionRows.push({ id: 'shared-session-id', status: 'active' });
+ const capturedDb = dbFor([{ id: 'shared-session-id', status: 'archived' }]);
+
+ await expect(
+ mod.isSessionStillRemovable('shared-session-id', capturedDb as never),
+ ).resolves.toBe(true);
+ });
});
describe('reconcileWorktreesForDeletedSessions', () => {
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index dd2d0067b0..9076b4d154 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -243,7 +243,6 @@ import {
} from './cindy-media/cindyMediaProtocol';
import * as cindyMediaBlobStore from './cindy-media/blobStore';
import * as cindyChatAttachments from './cindy-media/chatAttachments';
-import { removeSessionRefs as removeSessionMediaRefs } from './cindy-media/ledger';
import { createStorageIpcHandlers } from './cindy-media/storageIpc';
import {
getAllRegisteredDraftUrls,
@@ -491,6 +490,7 @@ import {
setGoalIdleObserver,
setGoalStopObserver,
setGoalAskAnswerObserver,
+ withSendToSessionLock,
} from './maker-ipc/register.js';
import { MAKER_INVOKE as MAKER_IPC_INVOKE, MAKER_PUSH } from './maker-ipc/channels.js';
import {
@@ -5461,7 +5461,8 @@ const registerIpcHandlers = () => {
'reg.exe',
['query', keyPath, ...args],
{ windowsHide: true, timeout: 5000, encoding: 'buffer' },
- (err, stdout) => resolve(err ? '' : decodeRegOutput(stdout ?? Buffer.alloc(0), codepage)),
+ (err, stdout) =>
+ resolve(err ? '' : decodeRegOutput(stdout ?? Buffer.alloc(0), codepage)),
);
});
},
@@ -6014,17 +6015,9 @@ const registerIpcHandlers = () => {
'image-cache:cleanup-session',
async (_event: Electron.IpcMainInvokeEvent, sessionId: string): Promise<void> => {
await imageCacheStore.removeSession(sessionId);
- // 媒体总仓对应清理:删本会话名下的媒体引用行(附件/导入/
- // 消息出生引用;画廊等持久引用不动)。失败只警告——引用行残留是
- // 无害的保守方向(blob 多活一阵),由对账工具兜底,不阻塞会话删除。
- try {
- await removeSessionMediaRefs(sessionId);
- } catch (err) {
- createLogger('image-cache').warn('session media ref cleanup failed', {
- sessionId,
- error: err instanceof Error ? err.message : String(err),
- });
- }
+ // cindy-media refs are removed only by the Main-owned, quiesced session
+ // deletion chain. This legacy IPC intentionally cleans xdt-image files
+ // only; deleting ledger refs here could race a late Simulator ingest.
},
);
@@ -6382,6 +6375,7 @@ app.on('ready', async () => {
registerLegacyMigrationIpc();
registerLocalDbIpc({
cancelSessionOperations: cancelIOSSimulatorSessionOperations,
+ withSessionLock: withSendToSessionLock,
isOwnerCurrent: (userId) =>
isLocalDbOwnerCurrent(authManager.getAuthState(), userId, isAppSessionBoundaryPending()),
discardStaleOwner: (userId) =>
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index ad585b64e6..68211e6d8f 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -301,6 +301,7 @@ import { createGatewayImageClient } from '../cindy-proxy-media/api/gatewayImageC
import * as blobStore from '../cindy-media/blobStore.js';
import * as ledger from '../cindy-media/ledger.js';
import { ingestMedia, supportedMime } from '../cindy-media/ingest.js';
+import { captureMediaRefCompensationScope } from '../cindy-media/refCompensationJournal.js';
import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';
import { recordGhostCallMedia } from './ghostMediaLedger.js';
import { MAKER_PUSH } from '../maker-ipc/channels.js';
@@ -3133,6 +3134,7 @@ export function getGhostCindySlot(): GhostCindySlot {
},
],
assertStillValid: assertOwnerScopeCurrent,
+ refCompensationScope: captureMediaRefCompensationScope(ownerScopeKey),
},
db,
);
diff --git a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
index ea2e8648de..f71b29205d 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
@@ -14,15 +14,28 @@ import os from 'node:os';
import path from 'node:path';
import { createHash } from 'node:crypto';
import type { LedgerDb } from '../ledger';
+import type { MediaRefCompensationScope } from '../refCompensationJournal';
let tmpUserData = '';
+const OWNER_ID = 'owner-a';
+const OWNER_KEY = 'a'.repeat(20);
+const OWNER_SCOPE_KEY = 'cloud:owner-a:1';
vi.mock('electron', () => ({
app: { getPath: () => tmpUserData },
}));
+vi.mock('../../appSessionState', () => ({
+ activeOwnerScopeKey: () => OWNER_SCOPE_KEY,
+ dataOwnerStorageKey: () => OWNER_KEY,
+ getActiveAppSession: () => ({ mode: 'cloud', dataOwnerId: OWNER_ID, generation: 1 }),
+ isAppSessionBoundaryPending: () => false,
+}));
+
const schema = await import('../../localDb/schema');
+const ledger = await import('../ledger');
const ingest = await import('../ingest');
+const refCompensation = await import('../refCompensationJournal');
const MIGRATION_0070 = path.resolve(__dirname, '../../../../drizzle/0070_woozy_harpoon.sql');
// eslint-disable-next-line @typescript-eslint/no-require-imports
@@ -57,8 +70,16 @@ afterAll(() => {
beforeEach(() => {
db = freshDb();
+ fs.rmSync(path.join(tmpUserData, 'owners', OWNER_KEY, 'cindy-media', 'ref-compensation-v1'), {
+ recursive: true,
+ force: true,
+ });
});
+function compensationScope(): MediaRefCompensationScope {
+ return refCompensation.captureMediaRefCompensationScope(OWNER_SCOPE_KEY);
+}
+
function blobPathOf(hash: string, ext: string): string {
return path.join(tmpUserData, 'cindy-media', 'blobs', hash.slice(0, 2), `${hash}${ext}`);
}
@@ -126,26 +147,44 @@ describe('ingestMedia(主路径)', () => {
describe('ingestMedia(全局去重)', () => {
it('cache 先入、非 cache 后到:去重命中时 isCache 降为 false(只降不升)', async () => {
- await ingest.ingestMedia({ buffer: PNG_BYTES, mimeType: 'image/png', isCache: true, refs: [] }, db);
+ await ingest.ingestMedia(
+ { buffer: PNG_BYTES, mimeType: 'image/png', isCache: true, refs: [] },
+ db,
+ );
expect(db.select().from(schema.mediaBlobs).all()[0].isCache).toBe(true);
// 同字节被聊天附件(非 cache)引用 → 必须降级,否则 cache 回收器会清掉用户附件
await ingest.ingestMedia(
- { buffer: PNG_BYTES, mimeType: 'image/png', refs: [{ refKind: 'session-attachment', refId: 's-1' }] },
+ {
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [{ refKind: 'session-attachment', refId: 's-1' }],
+ },
db,
);
expect(db.select().from(schema.mediaBlobs).all()[0].isCache).toBe(false);
// 反向不升:后续再有 cache 写入,非 cache 粘性保持
- await ingest.ingestMedia({ buffer: PNG_BYTES, mimeType: 'image/png', isCache: true, refs: [] }, db);
+ await ingest.ingestMedia(
+ { buffer: PNG_BYTES, mimeType: 'image/png', isCache: true, refs: [] },
+ db,
+ );
expect(db.select().from(schema.mediaBlobs).all()[0].isCache).toBe(false);
});
it('同内容第二次入库:一个文件、一行 blob、引用行累加', async () => {
await ingest.ingestMedia(
- { buffer: PNG_BYTES, mimeType: 'image/png', refs: [{ refKind: 'session-attachment', refId: 's-1' }] },
+ {
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [{ refKind: 'session-attachment', refId: 's-1' }],
+ },
db,
);
const again = await ingest.ingestMedia(
- { buffer: PNG_BYTES, mimeType: 'image/png', refs: [{ refKind: 'session-attachment', refId: 's-2' }] },
+ {
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [{ refKind: 'session-attachment', refId: 's-2' }],
+ },
db,
);
expect(again.deduplicated).toBe(true);
@@ -181,6 +220,7 @@ describe('ingestMedia(崩溃语义:先字节后记账)', () => {
checks += 1;
if (checks === 3) throw new Error('owner scope changed');
},
+ refCompensationScope: compensationScope(),
},
db,
),
@@ -190,6 +230,214 @@ describe('ingestMedia(崩溃语义:先字节后记账)', () => {
expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
});
+ it('作用域在 addRef 返回后失效时精确回滚本次引用', async () => {
+ let checks = 0;
+ await expect(
+ ingest.ingestMedia(
+ {
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [{ refKind: 'session-attachment', refId: 'deleted-session' }],
+ assertStillValid: () => {
+ checks += 1;
+ if (checks === 4) throw new Error('session was deleted');
+ },
+ refCompensationScope: compensationScope(),
+ },
+ db,
+ ),
+ ).rejects.toThrow('session was deleted');
+
+ expect(db.select().from(schema.mediaBlobs).all()).toHaveLength(1);
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
+ });
+
+ it('addRef 已提交但回执丢失时仍用预留 id 精确回滚引用', async () => {
+ const realAddRef = ledger.addRef;
+ const addRef = vi.spyOn(ledger, 'addRef').mockImplementationOnce(async (params, targetDb) => {
+ await realAddRef(params, targetDb);
+ throw new Error('worker acknowledgement lost');
+ });
+ try {
+ await expect(
+ ingest.ingestMedia(
+ {
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [{ refKind: 'session-attachment', refId: 'deleted-session' }],
+ refCompensationScope: compensationScope(),
+ },
+ db,
+ ),
+ ).rejects.toThrow('worker acknowledgement lost');
+
+ expect(addRef).toHaveBeenCalledWith(
+ expect.objectContaining({ id: expect.any(String), refId: 'deleted-session' }),
+ db,
+ );
+ expect(db.select().from(schema.mediaBlobs).all()).toHaveLength(1);
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
+ } finally {
+ addRef.mockRestore();
+ }
+ });
+
+ it('worker 在 INSERT 后丢失 ACK 且即时回滚不可用时由同 owner 下次就绪补偿', async () => {
+ const realAddRef = ledger.addRef;
+ const addRef = vi.spyOn(ledger, 'addRef').mockImplementationOnce(async (params, targetDb) => {
+ await realAddRef(params, targetDb);
+ throw new Error('worker acknowledgement lost');
+ });
+ const removeRefById = vi
+ .spyOn(ledger, 'removeRefById')
+ .mockRejectedValueOnce(new Error('worker disposed'));
+ try {
+ await expect(
+ ingest.ingestMedia(
+ {
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [{ refKind: 'session-attachment', refId: 'deleted-session' }],
+ refCompensationScope: compensationScope(),
+ },
+ db,
+ ),
+ ).rejects.toThrow('worker acknowledgement lost');
+
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(1);
+ const journalDir = compensationScope().journalDir;
+ expect(
+ fs.readdirSync(journalDir).filter((name) => name.endsWith('.pending.json')),
+ ).toHaveLength(1);
+
+ addRef.mockRestore();
+ removeRefById.mockRestore();
+ await expect(
+ refCompensation.reconcileMediaRefCompensationsForOwner({
+ ownerId: OWNER_ID,
+ db,
+ isOwnerCurrent: () => true,
+ }),
+ ).resolves.toMatchObject({ recoveredPending: 1 });
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
+ expect(fs.readdirSync(journalDir).filter((name) => name.endsWith('.json'))).toHaveLength(0);
+ } finally {
+ addRef.mockRestore();
+ removeRefById.mockRestore();
+ }
+ });
+
+ it('补偿日志无法可靠落盘时不执行任何 addRef', async () => {
+ const blockedJournalPath = path.join(tmpUserData, 'blocked-ref-journal');
+ fs.writeFileSync(blockedJournalPath, 'not a directory');
+ const addRef = vi.spyOn(ledger, 'addRef');
+ try {
+ await expect(
+ ingest.ingestMedia(
+ {
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [{ refKind: 'session-attachment', refId: 'session-a' }],
+ refCompensationScope: {
+ journalDir: blockedJournalPath,
+ ownerStorageKey: OWNER_KEY,
+ assertStillValid: () => undefined,
+ },
+ },
+ db,
+ ),
+ ).rejects.toThrow();
+ expect(addRef).not.toHaveBeenCalled();
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
+ } finally {
+ addRef.mockRestore();
+ fs.rmSync(blockedJournalPath, { force: true });
+ }
+ });
+
+ it('startup 只回收 committed marker,不删除已经提交的引用', async () => {
+ const operationId = '11111111-1111-4111-8111-111111111111';
+ const refId = '22222222-2222-4222-8222-222222222222';
+ await ledger.recordBlob(
+ { hash: PNG_HASH, ext: '.png', mimeType: 'image/png', bytes: PNG_BYTES.length },
+ db,
+ );
+ await ledger.addRef(
+ {
+ id: refId,
+ hash: PNG_HASH,
+ refKind: 'session-attachment',
+ refId: 'session-a',
+ },
+ db,
+ );
+ const journalDir = compensationScope().journalDir;
+ fs.mkdirSync(journalDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(journalDir, `${operationId}.committed.json`),
+ JSON.stringify({
+ version: 1,
+ operationId,
+ ownerStorageKey: OWNER_KEY,
+ createdAt: Date.now(),
+ refIds: [refId],
+ }),
+ );
+
+ await expect(
+ refCompensation.reconcileMediaRefCompensationsForOwner({
+ ownerId: OWNER_ID,
+ db,
+ isOwnerCurrent: () => true,
+ }),
+ ).resolves.toMatchObject({ removedCommitted: 1, recoveredPending: 0 });
+ expect(db.select().from(schema.mediaRefs).all()).toEqual([
+ expect.objectContaining({ id: refId }),
+ ]);
+ expect(fs.readdirSync(journalDir).filter((name) => name.endsWith('.json'))).toHaveLength(0);
+ });
+
+ it('startup 补偿目录提交不确定且即时回滚失败的 committed 引用', async () => {
+ const operationId = '33333333-3333-4333-8333-333333333333';
+ const refId = '44444444-4444-4444-8444-444444444444';
+ await ledger.recordBlob(
+ { hash: PNG_HASH, ext: '.png', mimeType: 'image/png', bytes: PNG_BYTES.length },
+ db,
+ );
+ await ledger.addRef(
+ {
+ id: refId,
+ hash: PNG_HASH,
+ refKind: 'session-attachment',
+ refId: 'session-a',
+ },
+ db,
+ );
+ const journalDir = compensationScope().journalDir;
+ fs.mkdirSync(journalDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(journalDir, `${operationId}.committed.json`),
+ JSON.stringify({
+ version: 1,
+ operationId,
+ ownerStorageKey: OWNER_KEY,
+ createdAt: Date.now(),
+ refIds: [refId],
+ rollbackRequired: true,
+ }),
+ );
+
+ await expect(
+ refCompensation.reconcileMediaRefCompensationsForOwner({
+ ownerId: OWNER_ID,
+ db,
+ isOwnerCurrent: () => true,
+ }),
+ ).resolves.toMatchObject({ recoveredPending: 1, removedCommitted: 0 });
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
+ expect(fs.readdirSync(journalDir).filter((name) => name.endsWith('.json'))).toHaveLength(0);
+ });
+
it('启用作用域断言时必须显式捕获数据库句柄', async () => {
await expect(
ingest.ingestMedia({
@@ -200,6 +448,21 @@ describe('ingestMedia(崩溃语义:先字节后记账)', () => {
}),
).rejects.toThrow('requires an explicit database');
});
+
+ it('会挂引用的 guarded ingest 必须显式捕获 owner 补偿日志', async () => {
+ await expect(
+ ingest.ingestMedia(
+ {
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [{ refKind: 'session-attachment', refId: 'session-a' }],
+ assertStillValid: () => undefined,
+ },
+ db,
+ ),
+ ).rejects.toThrow('requires a reference compensation scope');
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
+ });
});
describe('ingestMedia(白名单外拒绝)', () => {
diff --git a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
index 0804850d66..769532b027 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
@@ -9,6 +9,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
+import { eq, sql } from 'drizzle-orm';
import fs from 'node:fs';
import path from 'node:path';
import type { LedgerDb } from '../ledger';
@@ -19,7 +20,9 @@ vi.mock('electron', () => ({
const schema = await import('../../localDb/schema');
const ledger = await import('../ledger');
+const sessionCleanup = await import('../sessionCleanup');
+const MIGRATION_0000 = path.resolve(__dirname, '../../../../drizzle/0000_init.sql');
const MIGRATION_0070 = path.resolve(__dirname, '../../../../drizzle/0070_woozy_harpoon.sql');
// 0071 的加列在配套脚本里(SQL 是占位),与生产同源经 CommonJS require 加载。
// eslint-disable-next-line @typescript-eslint/no-require-imports
@@ -33,10 +36,12 @@ const HASH_B = 'b'.repeat(64);
function freshDb(): LedgerDb {
const raw = new Database(':memory:');
raw.pragma('foreign_keys = ON');
- const sqlText = fs.readFileSync(MIGRATION_0070, 'utf8');
- for (const stmt of sqlText.split('--> statement-breakpoint')) {
- const trimmed = stmt.trim();
- if (trimmed) raw.exec(trimmed);
+ for (const migrationPath of [MIGRATION_0000, MIGRATION_0070]) {
+ const sqlText = fs.readFileSync(migrationPath, 'utf8');
+ for (const stmt of sqlText.split('--> statement-breakpoint')) {
+ const trimmed = stmt.trim();
+ if (trimmed) raw.exec(trimmed);
+ }
}
migration0071.run(raw);
return drizzle(raw, { schema }) as unknown as LedgerDb;
@@ -52,6 +57,13 @@ async function seedBlob(hash: string, isCache = false): Promise<void> {
await ledger.recordBlob({ hash, ext: '.png', mimeType: 'image/png', bytes: 8, isCache }, db);
}
+async function seedSession(id: string, status: 'active' | 'archived' | 'deleted'): Promise<void> {
+ await db.run(sql`
+ insert into sessions (id, status, created_at, updated_at)
+ values (${id}, ${status}, 1, 1)
+ `);
+}
+
describe('recordBlob(幂等入账)', () => {
it('首次入账写全量字段,重复入账不炸只刷 lastAccess', async () => {
await seedBlob(HASH_A);
@@ -66,13 +78,37 @@ describe('recordBlob(幂等入账)', () => {
describe('addRef / removeRefs(引用增删)', () => {
it('未入账的指纹加引用被 FK 拒绝(先记 blob 后记 ref 的顺序由类型层保证)', async () => {
await expect(
- ledger.addRef({ hash: HASH_A, refKind: 'message', refId: 'msg-1', originSessionId: 'sess-1' }, db),
+ ledger.addRef(
+ { hash: HASH_A, refKind: 'message', refId: 'msg-1', originSessionId: 'sess-1' },
+ db,
+ ),
).rejects.toThrow();
});
+ it('允许 staged writer 预留稳定 id 以便提交回执丢失后精确补偿', async () => {
+ await seedBlob(HASH_A);
+ await expect(
+ ledger.addRef(
+ {
+ id: 'staged-ref-id',
+ hash: HASH_A,
+ refKind: 'session-attachment',
+ refId: 'session-a',
+ },
+ db,
+ ),
+ ).resolves.toBe('staged-ref-id');
+ expect(db.select().from(schema.mediaRefs).all()).toEqual([
+ expect.objectContaining({ id: 'staged-ref-id', refId: 'session-a' }),
+ ]);
+ });
+
it('removeRefs 只删指定引用方名下的行,返回删除数', async () => {
await seedBlob(HASH_A);
- await ledger.addRef({ hash: HASH_A, refKind: 'message', refId: 'msg-1', originSessionId: 'sess-1' }, db);
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'message', refId: 'msg-1', originSessionId: 'sess-1' },
+ db,
+ );
await ledger.addRef({ hash: HASH_A, refKind: 'ghost-gallery', refId: 'art' }, db);
await expect(ledger.removeRefs({ refKind: 'message', refId: 'msg-1' }, db)).resolves.toBe(1);
const left = db.select().from(schema.mediaRefs).all();
@@ -89,7 +125,10 @@ describe('addRef / removeRefs(引用增删)', () => {
it('删除 blob 行时引用级联清空(回收器删文件后账面自洽)', async () => {
await seedBlob(HASH_A);
- await ledger.addRef({ hash: HASH_A, refKind: 'message', refId: 'msg-1', originSessionId: 'sess-1' }, db);
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'message', refId: 'msg-1', originSessionId: 'sess-1' },
+ db,
+ );
db.delete(schema.mediaBlobs).run();
expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
});
@@ -105,20 +144,26 @@ describe('addRef / removeRefs(引用增删)', () => {
ledger.hasRef({ hash: HASH_A, refKind: 'ghost-grant', refId: 'art' }, db),
).resolves.toBe(true);
await expect(
- ledger.hasRef({
- hash: HASH_A,
- refKind: 'ghost-grant',
- refId: 'art',
- originKind: 'user',
- }, db),
+ ledger.hasRef(
+ {
+ hash: HASH_A,
+ refKind: 'ghost-grant',
+ refId: 'art',
+ originKind: 'user',
+ },
+ db,
+ ),
).resolves.toBe(false);
await expect(
- ledger.hasRef({
- hash: HASH_A,
- refKind: 'ghost-grant',
- refId: 'art',
- originKind: 'tool',
- }, db),
+ ledger.hasRef(
+ {
+ hash: HASH_A,
+ refKind: 'ghost-grant',
+ refId: 'art',
+ originKind: 'tool',
+ },
+ db,
+ ),
).resolves.toBe(true);
await ledger.addRef(
@@ -126,45 +171,48 @@ describe('addRef / removeRefs(引用增删)', () => {
db,
);
await expect(
- ledger.hasRef({
- hash: HASH_A,
- refKind: 'ghost-grant',
- refId: 'art',
- originKind: 'user',
- }, db),
+ ledger.hasRef(
+ {
+ hash: HASH_A,
+ refKind: 'ghost-grant',
+ refId: 'art',
+ originKind: 'user',
+ },
+ db,
+ ),
).resolves.toBe(true);
});
it('hasGhostToolGrant 兼容旧 ghost-grant/tool,但不把 user provenance 当工具交接', async () => {
await seedBlob(HASH_A);
- await expect(
- ledger.hasGhostToolGrant({ hash: HASH_A, ghostId: 'art' }, db),
- ).resolves.toBe(false);
+ await expect(ledger.hasGhostToolGrant({ hash: HASH_A, ghostId: 'art' }, db)).resolves.toBe(
+ false,
+ );
await ledger.addRef(
{ hash: HASH_A, refKind: 'ghost-grant', refId: 'art', originKind: 'user' },
db,
);
- await expect(
- ledger.hasGhostToolGrant({ hash: HASH_A, ghostId: 'art' }, db),
- ).resolves.toBe(false);
+ await expect(ledger.hasGhostToolGrant({ hash: HASH_A, ghostId: 'art' }, db)).resolves.toBe(
+ false,
+ );
await ledger.addRef(
{ hash: HASH_A, refKind: 'ghost-grant', refId: 'art', originKind: 'tool' },
db,
);
- await expect(
- ledger.hasGhostToolGrant({ hash: HASH_A, ghostId: 'art' }, db),
- ).resolves.toBe(true);
+ await expect(ledger.hasGhostToolGrant({ hash: HASH_A, ghostId: 'art' }, db)).resolves.toBe(
+ true,
+ );
await seedBlob(HASH_B);
await ledger.addRef(
{ hash: HASH_B, refKind: 'ghost-tool-grant', refId: 'art', originKind: 'tool' },
db,
);
- await expect(
- ledger.hasGhostToolGrant({ hash: HASH_B, ghostId: 'art' }, db),
- ).resolves.toBe(true);
+ await expect(ledger.hasGhostToolGrant({ hash: HASH_B, ghostId: 'art' }, db)).resolves.toBe(
+ true,
+ );
});
it('新版工具交接可取件,但旧版 ghost-grant shortcut 看不到它(回退 fail closed)', async () => {
@@ -192,14 +240,26 @@ describe('removeRefsExceptHash(替换型引用清理:个人头像换图)', () =>
await seedBlob(HASH_A);
await seedBlob(HASH_B);
// user-1 换头像:旧图 HASH_A、新图 HASH_B 均已挂 profile-avatar 引用
- await ledger.addRef({ hash: HASH_A, refKind: 'profile-avatar', refId: 'user-1', originKind: 'user' }, db);
- await ledger.addRef({ hash: HASH_B, refKind: 'profile-avatar', refId: 'user-1', originKind: 'user' }, db);
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'profile-avatar', refId: 'user-1', originKind: 'user' },
+ db,
+ );
+ await ledger.addRef(
+ { hash: HASH_B, refKind: 'profile-avatar', refId: 'user-1', originKind: 'user' },
+ db,
+ );
// 同指纹的其它业务引用与别的用户头像都必须幸存
await ledger.addRef({ hash: HASH_A, refKind: 'ghost-gallery', refId: 'art' }, db);
- await ledger.addRef({ hash: HASH_A, refKind: 'profile-avatar', refId: 'user-2', originKind: 'user' }, db);
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'profile-avatar', refId: 'user-2', originKind: 'user' },
+ db,
+ );
await expect(
- ledger.removeRefsExceptHash({ refKind: 'profile-avatar', refId: 'user-1', keepHash: HASH_B }, db),
+ ledger.removeRefsExceptHash(
+ { refKind: 'profile-avatar', refId: 'user-1', keepHash: HASH_B },
+ db,
+ ),
).resolves.toBe(1);
const left = db.select().from(schema.mediaRefs).all();
@@ -211,10 +271,19 @@ describe('removeRefsExceptHash(替换型引用清理:个人头像换图)', () =>
it('同指纹重复保存(去重命中)时不删 keepHash 的任何行', async () => {
await seedBlob(HASH_A);
- await ledger.addRef({ hash: HASH_A, refKind: 'profile-avatar', refId: 'user-1', originKind: 'user' }, db);
- await ledger.addRef({ hash: HASH_A, refKind: 'profile-avatar', refId: 'user-1', originKind: 'user' }, db);
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'profile-avatar', refId: 'user-1', originKind: 'user' },
+ db,
+ );
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'profile-avatar', refId: 'user-1', originKind: 'user' },
+ db,
+ );
await expect(
- ledger.removeRefsExceptHash({ refKind: 'profile-avatar', refId: 'user-1', keepHash: HASH_A }, db),
+ ledger.removeRefsExceptHash(
+ { refKind: 'profile-avatar', refId: 'user-1', keepHash: HASH_A },
+ db,
+ ),
).resolves.toBe(0);
expect(db.select().from(schema.mediaRefs).all()).toHaveLength(2);
});
@@ -226,9 +295,24 @@ describe('removeSessionRefs(会话删除钩子)', () => {
await seedBlob(HASH_B);
// 会话 sess-1 名下:附件 ref + 导入 ref + 出生消息 ref
await ledger.addRef({ hash: HASH_A, refKind: 'session-attachment', refId: 'sess-1' }, db);
+ await ledger.addRef(
+ {
+ hash: HASH_A,
+ refKind: 'session-attachment',
+ refId: 'ios-simulator:legacy-capture',
+ originSessionId: 'sess-1',
+ },
+ db,
+ );
await ledger.addRef({ hash: HASH_A, refKind: 'import', refId: 'sess-1' }, db);
await ledger.addRef(
- { hash: HASH_A, refKind: 'message', refId: 'msg-1', originSessionId: 'sess-1', originKind: 'tool' },
+ {
+ hash: HASH_A,
+ refKind: 'message',
+ refId: 'msg-1',
+ originSessionId: 'sess-1',
+ originKind: 'tool',
+ },
db,
);
// 免死引用:同一指纹挂了画廊 + 引渡(跨会话持久,删会话不动)。
@@ -239,7 +323,13 @@ describe('removeSessionRefs(会话删除钩子)', () => {
db,
);
await ledger.addRef(
- { hash: HASH_A, refKind: 'ghost-grant', refId: 'art', originKind: 'user', originSessionId: 'sess-1' },
+ {
+ hash: HASH_A,
+ refKind: 'ghost-grant',
+ refId: 'art',
+ originKind: 'user',
+ originSessionId: 'sess-1',
+ },
db,
);
// 无关会话 sess-2 的引用
@@ -249,7 +339,7 @@ describe('removeSessionRefs(会话删除钩子)', () => {
db,
);
- await expect(ledger.removeSessionRefs('sess-1', db)).resolves.toBe(3);
+ await expect(ledger.removeSessionRefs('sess-1', db)).resolves.toBe(4);
const left = db.select().from(schema.mediaRefs).all();
expect(left.map((r) => r.refKind).sort()).toEqual([
@@ -269,6 +359,152 @@ describe('removeSessionRefs(会话删除钩子)', () => {
});
});
+describe('removeSessionRefsIfDeleted(软删墓碑原子门禁)', () => {
+ it('只在任务仍为 deleted 时删除会话引用并保留持久引用', async () => {
+ await seedSession('sess-1', 'deleted');
+ await seedBlob(HASH_A);
+ await ledger.addRef({ hash: HASH_A, refKind: 'session-attachment', refId: 'sess-1' }, db);
+ await ledger.addRef(
+ {
+ hash: HASH_A,
+ refKind: 'session-attachment',
+ refId: 'ios-simulator:legacy-recording',
+ originSessionId: 'sess-1',
+ },
+ db,
+ );
+ await ledger.addRef({ hash: HASH_A, refKind: 'import', refId: 'sess-1' }, db);
+ await ledger.addRef(
+ {
+ hash: HASH_A,
+ refKind: 'message',
+ refId: 'msg-1',
+ originSessionId: 'sess-1',
+ },
+ db,
+ );
+ await ledger.addRef(
+ {
+ hash: HASH_A,
+ refKind: 'ghost-gallery',
+ refId: 'art-1',
+ originSessionId: 'sess-1',
+ },
+ db,
+ );
+
+ await expect(ledger.removeSessionRefsIfDeleted('sess-1', db)).resolves.toBe(4);
+ expect(db.select().from(schema.mediaRefs).all()).toMatchObject([
+ { refKind: 'ghost-gallery', refId: 'art-1' },
+ ]);
+ });
+
+ it.each(['active', 'archived', 'missing'] as const)(
+ 'does not delete refs when the final task state is %s',
+ async (status) => {
+ if (status !== 'missing') {
+ await seedSession('sess-1', status);
+ }
+ await seedBlob(HASH_A);
+ await ledger.addRef({ hash: HASH_A, refKind: 'session-attachment', refId: 'sess-1' }, db);
+
+ await expect(ledger.removeSessionRefsIfDeleted('sess-1', db)).resolves.toBe(0);
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(1);
+ },
+ );
+});
+
+describe('reconcileSessionMediaRefsForDeletedSessions(持久重试)', () => {
+ it('只重试 deleted 任务并且重复运行幂等', async () => {
+ await seedSession('deleted-1', 'deleted');
+ await seedSession('archived-1', 'archived');
+ await seedBlob(HASH_A);
+ await ledger.addRef({ hash: HASH_A, refKind: 'session-attachment', refId: 'deleted-1' }, db);
+ await ledger.addRef({ hash: HASH_A, refKind: 'session-attachment', refId: 'archived-1' }, db);
+
+ await expect(
+ sessionCleanup.reconcileSessionMediaRefsForDeletedSessions({
+ db,
+ isOwnerCurrent: () => true,
+ withSessionLock: async (_sessionId, task) => task(),
+ quiesceSession: async () => undefined,
+ }),
+ ).resolves.toMatchObject({ scanned: 1, removed: 1, failed: 0 });
+ await expect(
+ sessionCleanup.reconcileSessionMediaRefsForDeletedSessions({
+ db,
+ isOwnerCurrent: () => true,
+ withSessionLock: async (_sessionId, task) => task(),
+ quiesceSession: async () => undefined,
+ }),
+ ).resolves.toMatchObject({ scanned: 1, removed: 0, failed: 0 });
+ expect(db.select().from(schema.mediaRefs).all()).toMatchObject([{ refId: 'archived-1' }]);
+ });
+
+ it('continues after one task fails and stops when the captured owner changes', async () => {
+ await seedSession('deleted-a', 'deleted');
+ await seedSession('deleted-b', 'deleted');
+ const removeRefsIfDeleted = vi.fn(async (sessionId: string) => {
+ if (sessionId === 'deleted-a') throw new Error('busy');
+ return 2;
+ });
+
+ await expect(
+ sessionCleanup.reconcileSessionMediaRefsForDeletedSessions({
+ db,
+ isOwnerCurrent: () => true,
+ withSessionLock: async (_sessionId, task) => task(),
+ quiesceSession: async () => undefined,
+ removeRefsIfDeleted,
+ }),
+ ).resolves.toMatchObject({ scanned: 2, removed: 2, failed: 1, ownerChanged: false });
+
+ let ownerChecks = 0;
+ await expect(
+ sessionCleanup.reconcileSessionMediaRefsForDeletedSessions({
+ db,
+ isOwnerCurrent: () => ++ownerChecks === 1,
+ withSessionLock: async (_sessionId, task) => task(),
+ quiesceSession: async () => undefined,
+ removeRefsIfDeleted,
+ }),
+ ).resolves.toMatchObject({ scanned: 0, removed: 0, ownerChanged: true });
+ });
+
+ it('rechecks a deleted tombstone under the task lock before cancelling runtime', async () => {
+ await seedSession('restored-before-lock', 'deleted');
+ await seedBlob(HASH_A);
+ await ledger.addRef(
+ {
+ hash: HASH_A,
+ refKind: 'session-attachment',
+ refId: 'restored-before-lock',
+ },
+ db,
+ );
+ const quiesceSession = vi.fn(async () => undefined);
+
+ await expect(
+ sessionCleanup.reconcileSessionMediaRefsForDeletedSessions({
+ db,
+ isOwnerCurrent: () => true,
+ withSessionLock: async (sessionId, task) => {
+ await db
+ .update(schema.sessions)
+ .set({ status: 'active' })
+ .where(eq(schema.sessions.id, sessionId))
+ .run();
+ return task();
+ },
+ quiesceSession,
+ }),
+ ).resolves.toMatchObject({ scanned: 1, removed: 0, failed: 0 });
+
+ expect(quiesceSession).not.toHaveBeenCalled();
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(1);
+ });
+});
+
describe('ghostCanRead(供图归属校验)', () => {
it('出生自本意识 → 放行', async () => {
await seedBlob(HASH_A);
@@ -311,12 +547,15 @@ describe('ghostCanRead(供图归属校验)', () => {
await expect(ledger.ghostCanRead(HASH_A, 'art', db)).resolves.toBe(true);
await expect(ledger.ghostCanRead(HASH_A, 'other-ghost', db)).resolves.toBe(false);
await expect(
- ledger.hasRef({
- hash: HASH_A,
- refKind: 'ghost-grant',
- refId: 'art',
- originKind: 'user',
- }, db),
+ ledger.hasRef(
+ {
+ hash: HASH_A,
+ refKind: 'ghost-grant',
+ refId: 'art',
+ originKind: 'user',
+ },
+ db,
+ ),
).resolves.toBe(false);
});
@@ -334,7 +573,14 @@ describe('ghostCanRead(供图归属校验)', () => {
it('别的意识 / 未知指纹一律拒(不区分不存在与不属于你)', async () => {
await seedBlob(HASH_A);
await ledger.addRef(
- { hash: HASH_A, refKind: 'message', refId: 'msg-1', originSessionId: 'sess-1', originKind: 'ghost', originId: 'art' },
+ {
+ hash: HASH_A,
+ refKind: 'message',
+ refId: 'msg-1',
+ originSessionId: 'sess-1',
+ originKind: 'ghost',
+ originId: 'art',
+ },
db,
);
await expect(ledger.ghostCanRead(HASH_A, 'other-ghost', db)).resolves.toBe(false);
@@ -345,7 +591,14 @@ describe('ghostCanRead(供图归属校验)', () => {
await seedBlob(HASH_A);
// originKind 不是 ghost:即使 originId 恰好等于某意识 id 也不算它的出生。
await ledger.addRef(
- { hash: HASH_A, refKind: 'message', refId: 'msg-1', originSessionId: 'sess-1', originKind: 'tool', originId: 'art' },
+ {
+ hash: HASH_A,
+ refKind: 'message',
+ refId: 'msg-1',
+ originSessionId: 'sess-1',
+ originKind: 'tool',
+ originId: 'art',
+ },
db,
);
await expect(ledger.ghostCanRead(HASH_A, 'art', db)).resolves.toBe(false);
@@ -396,7 +649,14 @@ describe('listGhostGallery(画廊清单:重启回放数据源)', () => {
await seedBlob(HASH_B);
await ledger.addRef({ hash: HASH_A, refKind: 'ghost-gallery', refId: 'other-ghost' }, db);
await ledger.addRef(
- { hash: HASH_B, refKind: 'message', refId: 'msg-1', originSessionId: 'sess-1', originKind: 'ghost', originId: 'art' },
+ {
+ hash: HASH_B,
+ refKind: 'message',
+ refId: 'msg-1',
+ originSessionId: 'sess-1',
+ originKind: 'ghost',
+ originId: 'art',
+ },
db,
);
await expect(ledger.listGhostGallery('art', db)).resolves.toEqual([]);
@@ -449,11 +709,17 @@ describe('寄存计量与释放(ghostDepositUsageBytes / removeGhostDepositRef,#
db,
);
- await expect(ledger.removeGhostDepositRef({ hash: HASH_A, ghostId: 'art' }, db)).resolves.toBe(true);
+ await expect(ledger.removeGhostDepositRef({ hash: HASH_A, ghostId: 'art' }, db)).resolves.toBe(
+ true,
+ );
await expect(ledger.ghostDepositUsageBytes('art', db)).resolves.toBe(0);
// 别人的寄存、自己的画廊、聊天消息都还在(字节不会被连带清掉)。
await expect(ledger.ghostDepositUsageBytes('other-ghost', db)).resolves.toBe(100);
- const kinds = db.select().from(schema.mediaRefs).all().map((r) => `${r.refKind}:${r.refId}`);
+ const kinds = db
+ .select()
+ .from(schema.mediaRefs)
+ .all()
+ .map((r) => `${r.refKind}:${r.refId}`);
expect(kinds.sort()).toEqual([
'ghost-deposit:other-ghost',
'ghost-gallery:art',
@@ -465,7 +731,9 @@ describe('寄存计量与释放(ghostDepositUsageBytes / removeGhostDepositRef,#
it('撤回不存在的寄存引用 → false(幂等,不报错)', async () => {
await seedBlob(HASH_A);
- await expect(ledger.removeGhostDepositRef({ hash: HASH_A, ghostId: 'art' }, db)).resolves.toBe(false);
+ await expect(ledger.removeGhostDepositRef({ hash: HASH_A, ghostId: 'art' }, db)).resolves.toBe(
+ false,
+ );
});
it('卸载意识时按 refKind 清空自己的寄存物(removeRefs 口)', async () => {
@@ -504,7 +772,11 @@ describe('touchBlob(惰性刷新,读路径永不被拖垮)', () => {
});
it('账本抛错时静默(不影响媒体读取)', async () => {
- const broken = { update: () => { throw new Error('db down'); } } as unknown as LedgerDb;
+ const broken = {
+ update: () => {
+ throw new Error('db down');
+ },
+ } as unknown as LedgerDb;
await expect(ledger.touchBlob(HASH_A, broken)).resolves.toBeUndefined();
});
});
diff --git a/apps/desktop/src/main/cindy-media/ingest.ts b/apps/desktop/src/main/cindy-media/ingest.ts
index 5dcf4f4987..d02988c7dd 100644
--- a/apps/desktop/src/main/cindy-media/ingest.ts
+++ b/apps/desktop/src/main/cindy-media/ingest.ts
@@ -18,9 +18,15 @@
* 所有函数接受可注入 db(规则 14),生产默认走 DbClient 的 drizzle 代理。
*/
+import { randomUUID } from 'node:crypto';
+
import * as blobStore from './blobStore';
import * as ledger from './ledger';
import type { LedgerDb, MediaRefKind, MediaOriginKind } from './ledger';
+import { withMediaRefCompensation, type MediaRefCompensationScope } from './refCompensationJournal';
+import { createLogger } from '../logger';
+
+const log = createLogger('cindy-media-ingest');
/** 一条待挂的引用(字段语义见 ledger.AddRefParams / schema.ts mediaRefs)。 */
export interface IngestRef {
@@ -50,6 +56,12 @@ export interface IngestMediaParams {
* 启用时必须同时显式传入在稳定作用域下捕获的 db,禁止每次记账现取新作用域。
*/
assertStillValid?: () => void;
+ /**
+ * Stable owner-scoped durable journal captured with the explicit db. Guarded
+ * ingests that create refs require it so a committed INSERT can still be
+ * compensated after the DbClient worker disappears before its ACK.
+ */
+ refCompensationScope?: MediaRefCompensationScope;
}
export interface IngestedMedia {
@@ -78,6 +90,9 @@ export async function ingestMedia(
if (params.assertStillValid && !db) {
throw new Error('cindy-media: guarded ingest requires an explicit database');
}
+ if (params.assertStillValid && params.refs.length > 0 && !params.refCompensationScope) {
+ throw new Error('cindy-media: guarded ingest requires a reference compensation scope');
+ }
params.assertStillValid?.();
const written = await blobStore.writeBlob({
buffer: params.buffer,
@@ -95,10 +110,43 @@ export async function ingestMedia(
db,
);
params.assertStillValid?.();
- const refIds: string[] = [];
- for (const ref of params.refs) {
- refIds.push(await ledger.addRef({ hash: written.hash, ...ref }, db));
- params.assertStillValid?.();
+ // Reserve every id before the first INSERT. A committed INSERT whose worker
+ // acknowledgement is lost can then be deleted by exact id without touching
+ // refs from another concurrent ingest.
+ const refIds = params.refs.map(() => randomUUID());
+ const addRefs = async (): Promise<void> => {
+ for (const [index, ref] of params.refs.entries()) {
+ await ledger.addRef({ id: refIds[index], hash: written.hash, ...ref }, db);
+ params.assertStillValid?.();
+ }
+ };
+
+ if (refIds.length > 0 && params.refCompensationScope) {
+ await withMediaRefCompensation({
+ scope: params.refCompensationScope,
+ refIds,
+ perform: addRefs,
+ compensate: (id) => ledger.removeRefById(id, db),
+ });
+ } else {
+ try {
+ await addRefs();
+ } catch (error) {
+ // Unguarded legacy callers still get best-effort in-process rollback.
+ // Guarded owner/session writers take the durable journal path above.
+ const rollbackResults = await Promise.allSettled(
+ refIds.map((id) => ledger.removeRefById(id, db)),
+ );
+ rollbackResults.forEach((result, index) => {
+ if (result.status === 'rejected') {
+ log.warn('Failed to roll back a staged media reference', {
+ refId: refIds[index],
+ error: String(result.reason),
+ });
+ }
+ });
+ throw error;
+ }
}
return { ...written, refIds };
}
diff --git a/apps/desktop/src/main/cindy-media/ledger.ts b/apps/desktop/src/main/cindy-media/ledger.ts
index b64393138e..92db2c8e46 100644
--- a/apps/desktop/src/main/cindy-media/ledger.ts
+++ b/apps/desktop/src/main/cindy-media/ledger.ts
@@ -17,7 +17,7 @@
*/
import { randomUUID } from 'node:crypto';
-import { and, asc, desc, eq, lt, ne, or, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, exists, lt, ne, or, sql } from 'drizzle-orm';
import type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
import { getDbClient } from '../localDb/client/current';
@@ -83,6 +83,8 @@ export interface RecordBlobParams {
}
export interface AddRefParams {
+ /** Stable row id supplied by staged writers so a lost commit acknowledgement can be rolled back. */
+ id?: string;
hash: string;
refKind: MediaRefKind;
refId: string;
@@ -100,10 +102,14 @@ export interface AddRefParams {
* 用户附件的 blob 当可再生缓存清掉(review P1);反向(false→true)不升,
* 已有非 cache 引用的内容不因后来的缓存写入而变得可清。
*/
-export async function recordBlob(params: RecordBlobParams, db: LedgerDb = defaultDb()): Promise<void> {
+export async function recordBlob(
+ params: RecordBlobParams,
+ db: LedgerDb = defaultDb(),
+): Promise<void> {
const now = Date.now();
const isCache = params.isCache ?? false;
- await db.insert(mediaBlobs)
+ await db
+ .insert(mediaBlobs)
.values({
hash: params.hash,
ext: params.ext,
@@ -142,8 +148,9 @@ export async function addRef(params: AddRefParams, db: LedgerDb = defaultDb()):
if (params.refKind === 'message' && !params.originSessionId) {
throw new Error('cindy-media: message ref requires originSessionId');
}
- const id = randomUUID();
- await db.insert(mediaRefs)
+ const id = params.id ?? randomUUID();
+ await db
+ .insert(mediaRefs)
.values({
id,
hash: params.hash,
@@ -230,10 +237,7 @@ export async function hasGhostToolGrant(
eq(mediaRefs.hash, params.hash),
eq(mediaRefs.refId, params.ghostId),
eq(mediaRefs.originKind, 'tool'),
- or(
- eq(mediaRefs.refKind, 'ghost-tool-grant'),
- eq(mediaRefs.refKind, 'ghost-grant'),
- ),
+ or(eq(mediaRefs.refKind, 'ghost-tool-grant'), eq(mediaRefs.refKind, 'ghost-grant')),
),
)
.limit(1)
@@ -243,7 +247,9 @@ export async function hasGhostToolGrant(
/**
* 删会话的引用清理(会话删除钩子唯一入口):
- * - session-attachment / import:refId 就是会话 id,直接删;
+ * - session-attachment:新格式 refId 就是会话 id;兼容旧 Simulator
+ * 复合 refId,额外按 originSessionId 连坐删;
+ * - import:refId 就是会话 id,直接删;
* - message:refId 是消息 id,按出生会话(originSessionId)连坐删——
* 会话没了,它名下消息的引用自然一起走;
* - **绝不**碰 ghost-gallery / ghost-grant / ghost-tool-grant /
@@ -252,19 +258,41 @@ export async function hasGhostToolGrant(
* (寄存物同理:画布上的图不该因为删了某个会话就变得不能改)。
* 引用删完后引用归零的 blob 交回收器,本函数不动字节仓。
*/
+function sessionOwnedRefCondition(sessionId: string) {
+ return or(
+ and(
+ eq(mediaRefs.refKind, 'session-attachment'),
+ or(eq(mediaRefs.refId, sessionId), eq(mediaRefs.originSessionId, sessionId)),
+ ),
+ and(eq(mediaRefs.refKind, 'import'), eq(mediaRefs.refId, sessionId)),
+ and(eq(mediaRefs.refKind, 'message'), eq(mediaRefs.originSessionId, sessionId)),
+ );
+}
+
export async function removeSessionRefs(
sessionId: string,
db: LedgerDb = defaultDb(),
): Promise<number> {
+ const result = await db.delete(mediaRefs).where(sessionOwnedRefCondition(sessionId)).run();
+ return result.changes;
+}
+
+/**
+ * Delete session-owned refs only while the same stable DB still records the
+ * task as deleted. The EXISTS guard and DELETE share one SQLite statement, so
+ * restore/archive cannot race a separate status read and lose valid media.
+ */
+export async function removeSessionRefsIfDeleted(
+ sessionId: string,
+ db: LedgerDb = defaultDb(),
+): Promise<number> {
+ const deletedSession = db
+ .select({ id: schema.sessions.id })
+ .from(schema.sessions)
+ .where(and(eq(schema.sessions.id, sessionId), eq(schema.sessions.status, 'deleted')));
const result = await db
.delete(mediaRefs)
- .where(
- or(
- and(eq(mediaRefs.refKind, 'session-attachment'), eq(mediaRefs.refId, sessionId)),
- and(eq(mediaRefs.refKind, 'import'), eq(mediaRefs.refId, sessionId)),
- and(eq(mediaRefs.refKind, 'message'), eq(mediaRefs.originSessionId, sessionId)),
- ),
- )
+ .where(and(sessionOwnedRefCondition(sessionId), exists(deletedSession)))
.run();
return result.changes;
}
@@ -464,7 +492,9 @@ export async function listZeroRefBlobs(
lastAccessAt: mediaBlobs.lastAccessAt,
})
.from(mediaBlobs)
- .where(and(lt(mediaBlobs.createdAt, cutoffMs), lt(mediaBlobs.lastAccessAt, cutoffMs), noRefsExist()))
+ .where(
+ and(lt(mediaBlobs.createdAt, cutoffMs), lt(mediaBlobs.lastAccessAt, cutoffMs), noRefsExist()),
+ )
.all();
}
diff --git a/apps/desktop/src/main/cindy-media/refCompensationJournal.ts b/apps/desktop/src/main/cindy-media/refCompensationJournal.ts
new file mode 100644
index 0000000000..8fb4ecfeee
--- /dev/null
+++ b/apps/desktop/src/main/cindy-media/refCompensationJournal.ts
@@ -0,0 +1,509 @@
+/**
+ * Durable compensation journal for staged cindy-media references.
+ *
+ * A DbClient worker can commit an INSERT and disappear before its RPC ACK is
+ * delivered. The caller then knows the reserved reference id, but an immediate
+ * DELETE through the same disposed worker can fail as well. A small owner-scoped
+ * file journal keeps those exact ids outside the worker lifecycle so the next
+ * ready DbClient for the same owner can finish the idempotent compensation.
+ *
+ * The journal deliberately stores no media hashes, paths, labels or raw owner
+ * ids. `.pending` means the ids must be removed; ordinary `.committed` means
+ * the ingest completed and only the marker itself may be collected. A
+ * committed record carrying `rollbackRequired` is compensated like pending.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { app } from 'electron';
+import { constants } from 'node:fs';
+import { lstat, mkdir, open, readdir, rename, rm } from 'node:fs/promises';
+import path from 'node:path';
+
+import {
+ activeOwnerScopeKey,
+ dataOwnerStorageKey,
+ getActiveAppSession,
+ isAppSessionBoundaryPending,
+} from '../appSessionState.js';
+import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
+import { createLogger } from '../logger.js';
+import * as ledger from './ledger.js';
+import type { LedgerDb } from './ledger.js';
+
+const log = createLogger('cindy-media-ref-compensation');
+
+const JOURNAL_VERSION = 1 as const;
+const JOURNAL_DIRECTORY = 'ref-compensation-v1';
+const MAX_JOURNAL_BYTES = 64 * 1024;
+const MAX_REF_IDS = 256;
+const MAX_SCAN_ENTRIES = 1_024;
+const JOURNAL_LOCK_WAIT_MS = 50;
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+const OWNER_KEY_PATTERN = /^[0-9a-f]{20}$/;
+
+type JournalState = 'pending' | 'committed';
+
+interface RefCompensationRecord {
+ version: typeof JOURNAL_VERSION;
+ operationId: string;
+ ownerStorageKey: string;
+ createdAt: number;
+ refIds: string[];
+ rollbackRequired?: true;
+}
+
+export interface MediaRefCompensationScope {
+ readonly journalDir: string;
+ readonly ownerStorageKey: string;
+ assertStillValid(): void;
+}
+
+export interface MediaRefCompensationReconcileResult {
+ recoveredPending: number;
+ removedCommitted: number;
+ busy: number;
+ skipped: number;
+}
+
+interface JournalPaths {
+ operationId: string;
+ pending: string;
+ committed: string;
+ lock: string;
+}
+
+function ownerJournalDir(ownerStorageKey: string): string {
+ return path.join(
+ app.getPath('userData'),
+ 'owners',
+ ownerStorageKey,
+ 'cindy-media',
+ JOURNAL_DIRECTORY,
+ );
+}
+
+/** Capture the owner identity and path synchronously before any async ingest work. */
+export function captureMediaRefCompensationScope(
+ expectedOwnerScopeKey: string = activeOwnerScopeKey(),
+): MediaRefCompensationScope {
+ const session = getActiveAppSession();
+ const ownerId = session.dataOwnerId;
+ if (
+ !ownerId ||
+ isAppSessionBoundaryPending() ||
+ activeOwnerScopeKey() !== expectedOwnerScopeKey
+ ) {
+ throw new Error('cindy-media: cannot capture compensation journal outside a stable owner');
+ }
+ const ownerStorageKey = dataOwnerStorageKey(ownerId);
+ return {
+ journalDir: ownerJournalDir(ownerStorageKey),
+ ownerStorageKey,
+ assertStillValid(): void {
+ const current = getActiveAppSession();
+ if (
+ isAppSessionBoundaryPending() ||
+ activeOwnerScopeKey() !== expectedOwnerScopeKey ||
+ current.dataOwnerId !== ownerId
+ ) {
+ throw new Error('cindy-media: data owner changed during reference ingest');
+ }
+ },
+ };
+}
+
+function pathsFor(journalDir: string, operationId: string): JournalPaths {
+ return {
+ operationId,
+ pending: path.join(journalDir, `${operationId}.pending.json`),
+ committed: path.join(journalDir, `${operationId}.committed.json`),
+ lock: path.join(journalDir, `${operationId}.lock`),
+ };
+}
+
+async function assertSafeJournalDirectory(journalDir: string): Promise<void> {
+ const info = await lstat(journalDir);
+ if (!info.isDirectory() || info.isSymbolicLink()) {
+ throw new Error('cindy-media: reference compensation path is not a safe directory');
+ }
+}
+
+async function syncDirectory(journalDir: string): Promise<void> {
+ // Windows does not support opening directories for fsync. The simulator
+ // producer is macOS-only, while other guarded media paths remain portable.
+ if (process.platform === 'win32') return;
+ const directory = await open(journalDir, 'r');
+ try {
+ await directory.sync();
+ } finally {
+ await directory.close();
+ }
+}
+
+async function writePendingRecord(
+ scope: MediaRefCompensationScope,
+ paths: JournalPaths,
+ refIds: readonly string[],
+): Promise<RefCompensationRecord> {
+ await mkdir(scope.journalDir, { recursive: true, mode: 0o700 });
+ await assertSafeJournalDirectory(scope.journalDir);
+ scope.assertStillValid();
+
+ const record: RefCompensationRecord = {
+ version: JOURNAL_VERSION,
+ operationId: paths.operationId,
+ ownerStorageKey: scope.ownerStorageKey,
+ createdAt: Date.now(),
+ refIds: [...refIds],
+ };
+ const temporary = path.join(
+ scope.journalDir,
+ `.${paths.operationId}.${process.pid}.${randomUUID()}.tmp`,
+ );
+ const handle = await open(temporary, 'wx', 0o600);
+ try {
+ await handle.writeFile(`${JSON.stringify(record)}\n`, 'utf8');
+ await handle.sync();
+ } catch (error) {
+ await handle.close().catch(() => undefined);
+ await rm(temporary, { force: true }).catch(() => undefined);
+ throw error;
+ }
+ await handle.close();
+ try {
+ await rename(temporary, paths.pending);
+ await syncDirectory(scope.journalDir);
+ } catch (error) {
+ await rm(temporary, { force: true }).catch(() => undefined);
+ throw error;
+ }
+ return record;
+}
+
+async function removeMarker(markerPath: string, journalDir: string): Promise<void> {
+ await rm(markerPath, { force: true });
+ await syncDirectory(journalDir);
+}
+
+async function markRollbackRequired(
+ paths: JournalPaths,
+ record: RefCompensationRecord,
+): Promise<void> {
+ const handle = await open(paths.committed, 'w', 0o600);
+ try {
+ await handle.writeFile(`${JSON.stringify({ ...record, rollbackRequired: true })}\n`, 'utf8');
+ await handle.sync();
+ } finally {
+ await handle.close();
+ }
+}
+
+async function removeOperationMarkers(paths: JournalPaths, journalDir: string): Promise<void> {
+ await Promise.all([rm(paths.pending, { force: true }), rm(paths.committed, { force: true })]);
+ await syncDirectory(journalDir);
+}
+
+async function commitRecord(
+ scope: MediaRefCompensationScope,
+ paths: JournalPaths,
+ record: RefCompensationRecord,
+): Promise<void> {
+ await rename(paths.pending, paths.committed);
+
+ // The rename is not a crash-durable commit until the parent directory is
+ // synced. If durability cannot be confirmed, fail the ingest so the caller's
+ // exact-id compensation runs; returning success could later resurrect the
+ // pre-rename `.pending` state after a power loss and make startup delete a ref
+ // already handed to the caller. Keep the visible `.committed` marker as a
+ // harmless GC marker while propagating the uncertainty.
+ try {
+ await syncDirectory(scope.journalDir);
+ } catch (error) {
+ log.warn('Failed to sync a committed media reference journal', {
+ operationId: paths.operationId,
+ error: String(error),
+ });
+ // If recovery sees the old name it is already pending. If it sees the new
+ // name, this fsynced inode flag makes committed compensate as well.
+ await markRollbackRequired(paths, record).catch((markError) => {
+ log.warn('Failed to mark an uncertain media reference commit for rollback', {
+ operationId: paths.operationId,
+ error: String(markError),
+ });
+ });
+ throw Object.assign(
+ new Error('cindy-media: reference journal commit durability is uncertain'),
+ { code: 'REF_JOURNAL_COMMIT_UNCERTAIN', cause: error },
+ );
+ }
+ await removeMarker(paths.committed, scope.journalDir).catch((error) => {
+ log.warn('Failed to collect a committed media reference journal', {
+ operationId: paths.operationId,
+ error: String(error),
+ });
+ });
+}
+
+/**
+ * Run staged ref INSERTs behind a durable pending marker. `compensate` must be
+ * idempotent and delete only the supplied reserved id.
+ */
+export async function withMediaRefCompensation<T>(params: {
+ scope: MediaRefCompensationScope;
+ refIds: readonly string[];
+ perform: () => Promise<T>;
+ compensate: (refId: string) => Promise<unknown>;
+}): Promise<T> {
+ if (params.refIds.length === 0 || params.refIds.length > MAX_REF_IDS) {
+ throw new Error('cindy-media: invalid reference compensation batch size');
+ }
+ if (!params.refIds.every((id) => UUID_PATTERN.test(id))) {
+ throw new Error('cindy-media: invalid staged reference id');
+ }
+ if (!OWNER_KEY_PATTERN.test(params.scope.ownerStorageKey)) {
+ throw new Error('cindy-media: invalid compensation owner namespace');
+ }
+
+ params.scope.assertStillValid();
+ await mkdir(params.scope.journalDir, { recursive: true, mode: 0o700 });
+ await assertSafeJournalDirectory(params.scope.journalDir);
+ const paths = pathsFor(params.scope.journalDir, randomUUID());
+
+ return withCrossProcessLock(
+ paths.lock,
+ { label: 'cindy-media-ref-compensation', waitMs: JOURNAL_LOCK_WAIT_MS },
+ async (status) => {
+ if (!status.held) {
+ throw new Error('cindy-media: reference compensation journal lock unavailable');
+ }
+
+ const record = await writePendingRecord(params.scope, paths, params.refIds);
+ try {
+ params.scope.assertStillValid();
+ const result = await params.perform();
+ params.scope.assertStillValid();
+ await commitRecord(params.scope, paths, record);
+ return result;
+ } catch (error) {
+ const rollback = await Promise.allSettled(params.refIds.map(params.compensate));
+ const rollbackFailed = rollback.some((result) => result.status === 'rejected');
+ rollback.forEach((result, index) => {
+ if (result.status === 'rejected') {
+ log.warn('Failed to compensate a staged media reference', {
+ operationId: paths.operationId,
+ refId: params.refIds[index],
+ error: String(result.reason),
+ });
+ }
+ });
+ if (!rollbackFailed) {
+ await removeOperationMarkers(paths, params.scope.journalDir).catch((cleanupError) => {
+ // Keeping a pending marker is safe: startup will repeat idempotent
+ // exact-id deletes. Never replace the original ingest error.
+ log.warn('Failed to collect a compensated media reference journal', {
+ operationId: paths.operationId,
+ error: String(cleanupError),
+ });
+ });
+ }
+ throw error;
+ }
+ },
+ );
+}
+
+function parseJournalRecord(
+ raw: string,
+ operationId: string,
+ ownerStorageKey: string,
+): RefCompensationRecord | null {
+ let candidate: unknown;
+ try {
+ candidate = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ if (!candidate || typeof candidate !== 'object') return null;
+ const record = candidate as Partial<RefCompensationRecord>;
+ if (
+ record.version !== JOURNAL_VERSION ||
+ record.operationId !== operationId ||
+ record.ownerStorageKey !== ownerStorageKey ||
+ !Number.isSafeInteger(record.createdAt) ||
+ (record.createdAt ?? 0) <= 0 ||
+ !Array.isArray(record.refIds) ||
+ record.refIds.length === 0 ||
+ record.refIds.length > MAX_REF_IDS ||
+ !record.refIds.every((id) => typeof id === 'string' && UUID_PATTERN.test(id)) ||
+ new Set(record.refIds).size !== record.refIds.length ||
+ (record.rollbackRequired !== undefined && record.rollbackRequired !== true)
+ ) {
+ return null;
+ }
+ return record as RefCompensationRecord;
+}
+
+async function readJournalRecord(
+ filePath: string,
+ operationId: string,
+ ownerStorageKey: string,
+): Promise<RefCompensationRecord | null> {
+ const before = await lstat(filePath);
+ if (!before.isFile() || before.isSymbolicLink() || before.size > MAX_JOURNAL_BYTES) return null;
+ const flags = constants.O_RDONLY | (process.platform === 'win32' ? 0 : constants.O_NOFOLLOW);
+ const handle = await open(filePath, flags);
+ let raw: string;
+ let opened: Awaited<ReturnType<typeof handle.stat>>;
+ try {
+ opened = await handle.stat();
+ if (
+ !opened.isFile() ||
+ before.dev !== opened.dev ||
+ before.ino !== opened.ino ||
+ opened.size > MAX_JOURNAL_BYTES
+ ) {
+ return null;
+ }
+ raw = await handle.readFile('utf8');
+ } finally {
+ await handle.close();
+ }
+ if (Buffer.byteLength(raw, 'utf8') > MAX_JOURNAL_BYTES) return null;
+ return parseJournalRecord(raw, operationId, ownerStorageKey);
+}
+
+function parseJournalName(name: string): { operationId: string; state: JournalState } | null {
+ const match = /^([0-9a-f-]+)\.(pending|committed)\.json$/i.exec(name);
+ if (!match || !UUID_PATTERN.test(match[1])) return null;
+ return { operationId: match[1], state: match[2] as JournalState };
+}
+
+/** Replay journals only for the explicitly supplied, currently ready owner DB. */
+export async function reconcileMediaRefCompensationsForOwner(params: {
+ ownerId: string;
+ db: LedgerDb;
+ isOwnerCurrent: () => boolean;
+}): Promise<MediaRefCompensationReconcileResult> {
+ const ownerStorageKey = dataOwnerStorageKey(params.ownerId);
+ const journalDir = ownerJournalDir(ownerStorageKey);
+ const result: MediaRefCompensationReconcileResult = {
+ recoveredPending: 0,
+ removedCommitted: 0,
+ busy: 0,
+ skipped: 0,
+ };
+
+ if (!params.isOwnerCurrent()) return result;
+ const entries = await (async () => {
+ try {
+ return await readdir(journalDir, { withFileTypes: true, encoding: 'utf8' });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+ })();
+ if (!entries) return result;
+ if (!params.isOwnerCurrent()) return result;
+
+ const candidates = entries
+ .map((entry) => ({ entry, parsed: parseJournalName(entry.name) }))
+ .filter(
+ (
+ candidate,
+ ): candidate is {
+ entry: (typeof entries)[number];
+ parsed: NonNullable<ReturnType<typeof parseJournalName>>;
+ } => candidate.parsed !== null,
+ );
+ const stateCountByOperation = new Map<string, number>();
+ for (const { parsed } of candidates) {
+ stateCountByOperation.set(
+ parsed.operationId,
+ (stateCountByOperation.get(parsed.operationId) ?? 0) + 1,
+ );
+ }
+
+ for (const { entry, parsed } of candidates.slice(0, MAX_SCAN_ENTRIES)) {
+ if ((stateCountByOperation.get(parsed.operationId) ?? 0) !== 1) {
+ // A valid atomic rename can never leave both states. Preserve both
+ // instead of guessing and potentially deleting refs from a committed op.
+ result.skipped += 1;
+ continue;
+ }
+ if (!entry.isFile() || entry.isSymbolicLink()) {
+ result.skipped += 1;
+ continue;
+ }
+ if (!params.isOwnerCurrent()) break;
+ const paths = pathsFor(journalDir, parsed.operationId);
+ const markerPath = parsed.state === 'pending' ? paths.pending : paths.committed;
+ await withCrossProcessLock(
+ paths.lock,
+ { label: 'cindy-media-ref-compensation-reconcile', waitMs: JOURNAL_LOCK_WAIT_MS },
+ async (status) => {
+ if (!status.held) {
+ result.busy += 1;
+ return;
+ }
+ if (!params.isOwnerCurrent()) return;
+ let record: RefCompensationRecord | null;
+ try {
+ record = await readJournalRecord(markerPath, parsed.operationId, ownerStorageKey);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ log.warn('Failed to read a media reference compensation journal', {
+ operationId: parsed.operationId,
+ state: parsed.state,
+ error: String(error),
+ });
+ result.skipped += 1;
+ return;
+ }
+ if (!record) {
+ log.warn('Refusing malformed media reference compensation journal', {
+ operationId: parsed.operationId,
+ state: parsed.state,
+ });
+ result.skipped += 1;
+ return;
+ }
+
+ if (parsed.state === 'committed' && record.rollbackRequired !== true) {
+ await removeMarker(markerPath, journalDir);
+ result.removedCommitted += 1;
+ return;
+ }
+
+ try {
+ for (const refId of record.refIds) {
+ if (!params.isOwnerCurrent()) {
+ throw new Error('data owner changed during media reference compensation');
+ }
+ await ledger.removeRefById(refId, params.db);
+ if (!params.isOwnerCurrent()) {
+ throw new Error('data owner changed during media reference compensation');
+ }
+ }
+ await removeMarker(markerPath, journalDir);
+ result.recoveredPending += 1;
+ } catch (error) {
+ // Exact-id deletes are idempotent. Preserve the pending marker so a
+ // later ready DbClient for this owner can repeat the entire batch.
+ log.warn('Media reference compensation remains pending', {
+ operationId: parsed.operationId,
+ error: String(error),
+ });
+ result.skipped += 1;
+ }
+ },
+ );
+ }
+ if (candidates.length > MAX_SCAN_ENTRIES) {
+ log.warn('Media reference compensation scan was capped', {
+ ownerStorageKey,
+ entries: candidates.length,
+ cap: MAX_SCAN_ENTRIES,
+ });
+ }
+ return result;
+}
diff --git a/apps/desktop/src/main/cindy-media/sessionCleanup.ts b/apps/desktop/src/main/cindy-media/sessionCleanup.ts
new file mode 100644
index 0000000000..c0e243ee14
--- /dev/null
+++ b/apps/desktop/src/main/cindy-media/sessionCleanup.ts
@@ -0,0 +1,93 @@
+import { eq } from 'drizzle-orm';
+
+import { sessions } from '../localDb/schema.js';
+import { createLogger } from '../logger.js';
+import { removeSessionRefsIfDeleted, type LedgerDb } from './ledger.js';
+
+const log = createLogger('cindy-media-session-cleanup');
+
+export interface ReconcileDeletedSessionMediaOptions {
+ db: LedgerDb;
+ isOwnerCurrent(): boolean;
+ withSessionLock<T>(sessionId: string, task: () => Promise<T>): Promise<T>;
+ quiesceSession(sessionId: string): Promise<void>;
+ removeRefsIfDeleted?: (sessionId: string, db: LedgerDb) => Promise<number>;
+}
+
+export interface ReconcileDeletedSessionMediaResult {
+ scanned: number;
+ removed: number;
+ failed: number;
+ ownerChanged: boolean;
+}
+
+/**
+ * Retry session-ref cleanup from durable soft-delete tombstones. A process
+ * restart guarantees old media producers are gone; the atomic ledger guard
+ * still preserves refs if a task was restored before this pass reaches it.
+ */
+export async function reconcileSessionMediaRefsForDeletedSessions(
+ options: ReconcileDeletedSessionMediaOptions,
+): Promise<ReconcileDeletedSessionMediaResult> {
+ const result: ReconcileDeletedSessionMediaResult = {
+ scanned: 0,
+ removed: 0,
+ failed: 0,
+ ownerChanged: false,
+ };
+ if (!options.isOwnerCurrent()) {
+ result.ownerChanged = true;
+ return result;
+ }
+
+ let rows: Array<{ id: string }>;
+ try {
+ rows = await options.db
+ .select({ id: sessions.id })
+ .from(sessions)
+ .where(eq(sessions.status, 'deleted'))
+ .all();
+ } catch (error) {
+ log.warn('deleted task media reconcile query failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ result.failed = 1;
+ return result;
+ }
+
+ const removeRefs = options.removeRefsIfDeleted ?? removeSessionRefsIfDeleted;
+ for (const row of rows) {
+ if (!options.isOwnerCurrent()) {
+ result.ownerChanged = true;
+ break;
+ }
+ result.scanned += 1;
+ try {
+ const removed = await options.withSessionLock(row.id, async () => {
+ if (!options.isOwnerCurrent()) return null;
+ const [current] = await options.db
+ .select({ status: sessions.status })
+ .from(sessions)
+ .where(eq(sessions.id, row.id))
+ .limit(1)
+ .all();
+ if (!options.isOwnerCurrent() || current?.status !== 'deleted') return null;
+ await options.quiesceSession(row.id);
+ if (!options.isOwnerCurrent()) return null;
+ return removeRefs(row.id, options.db);
+ });
+ if (!options.isOwnerCurrent()) {
+ result.ownerChanged = true;
+ break;
+ }
+ result.removed += removed ?? 0;
+ } catch (error) {
+ result.failed += 1;
+ log.warn('deleted task media reconcile item failed', {
+ sessionId: row.id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ return result;
+}
diff --git a/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts b/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts
index 8fbeb4ff01..8c9dab6e8c 100644
--- a/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts
@@ -8,7 +8,7 @@
* - createSession 的 INSERT 带 onConflictDoUpdate 兜并发竞态,冲突时只翻
* status 不碰上下文列。
*/
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => {
const updateWhere = vi.fn(async (_where: unknown) => {});
@@ -75,8 +75,21 @@ vi.mock('../../defaultSessionSettings', () => ({
}));
import { createImSessionRepo, type ImSessionRow } from '../sessionRepo';
+import { setSessionRouteLockImplementation } from '../../../localDb/sessionRouteLock';
import type { ImOrchestratorConfig, ImSessionNamespace } from '../types';
+const routeLock = vi.fn(async (_sessionId: string, task: () => Promise<unknown>) => task());
+
+beforeEach(() => {
+ routeLock.mockClear();
+ routeLock.mockImplementation(async (_sessionId, task) => task());
+ setSessionRouteLockImplementation(routeLock);
+});
+
+afterEach(() => {
+ setSessionRouteLockImplementation(null);
+});
+
const ns: ImSessionNamespace = {
source: 'feishu',
sessionIdFor: (bot: string, user: string) => `feishu_${bot}_${user}`,
@@ -149,6 +162,7 @@ describe('sessionRepo.findActiveSession 软删行复活(#748)', () => {
expect(mocks.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:created', {
sessionId: 'feishu_bot_user',
});
+ expect(routeLock).toHaveBeenCalledWith('feishu_bot_user', expect.any(Function));
},
);
@@ -193,6 +207,7 @@ describe('sessionRepo.createSession upsert 兜竞态(#748)', () => {
await makeRepo().createSession('bot', 'user', undefined, preparedDefaults);
expect(mocks.insertValues).toHaveBeenCalledTimes(1);
+ expect(routeLock).toHaveBeenCalledWith('feishu_bot_user', expect.any(Function));
expect(mocks.insertConflict).toHaveBeenCalledTimes(1);
const conflictArg = mocks.insertConflict.mock.calls[0][0] as {
target: unknown;
@@ -234,10 +249,7 @@ describe('sessionRepo workspaceKind(渠道声明 dialogue 归组时)', () => {
const dialogueNs = { ...ns, workspaceKind: 'dialogue' } as unknown as ImSessionNamespace;
function makeDialogueRepo() {
- return createImSessionRepo(
- { agentKind: 'claude-code' } as ImOrchestratorConfig,
- dialogueNs,
- );
+ return createImSessionRepo({ agentKind: 'claude-code' } as ImOrchestratorConfig, dialogueNs);
}
beforeEach(() => {
diff --git a/apps/desktop/src/main/im/shared/sessionRepo.ts b/apps/desktop/src/main/im/shared/sessionRepo.ts
index 6d27b4e636..ff8cec2e1f 100644
--- a/apps/desktop/src/main/im/shared/sessionRepo.ts
+++ b/apps/desktop/src/main/im/shared/sessionRepo.ts
@@ -19,6 +19,7 @@ import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';
import { getDbClient } from '../../localDb/client/current';
import { normalizeDbAgentKind } from '../../../shared/agentKindConversion';
import { sessions } from '../../localDb/schema';
+import { withSessionRouteLock } from '../../localDb/sessionRouteLock';
import { createLogger, maskPath } from '../../logger';
import { setSessionProvider } from '../../maker-host/session-provider-store';
import {
@@ -118,10 +119,12 @@ export function createImSessionRepo(
async findActiveSession(botContextId, userId, scopeKey) {
const id = ns.sessionIdFor(botContextId, userId, scopeKey);
const db = getDbClient().drizzle;
- const rows = await db.select().from(sessions).where(eq(sessions.id, id)).limit(1);
- const row = rows[0];
- if (!row) return null;
- if (row.status !== 'active') {
+ const result = await withSessionRouteLock(id, async () => {
+ const rows = await db.select().from(sessions).where(eq(sessions.id, id)).limit(1);
+ const row = rows[0];
+ if (!row) return { row: null, revivedFrom: null };
+ if (row.status === 'active') return { row, revivedFrom: null };
+
// 复活由用户 IM 消息触发,一并 bump userSendAt:广播 created 后 renderer
// 立即重拉,而稍后 turnRunner 的 touchUserSent 不再广播 patched,不在这里
// 写的话 sidebar 会按旧活跃时间排序/分组,直到下次整页刷新。
@@ -136,7 +139,14 @@ export function createImSessionRepo(
...(ns.workspaceKind ? { workspaceKind: ns.workspaceKind } : {}),
})
.where(eq(sessions.id, id));
- log.info(`revived soft-deleted ${ns.source} session id=${row.id} (was ${row.status})`);
+ return { row, revivedFrom: row.status };
+ });
+ const row = result.row;
+ if (!row) return null;
+ if (result.revivedFrom) {
+ log.info(
+ `revived soft-deleted ${ns.source} session id=${row.id} (was ${result.revivedFrom})`,
+ );
// 软删行已从 sidebar 消失,patched 增量对不存在的行无效;
// created 触发 renderer 重拉列表,让会话重新出现。
broadcastSessionCreated(row.id);
@@ -181,48 +191,50 @@ export function createImSessionRepo(
const db = getDbClient().drizzle;
const row = prepared ?? (await this.prepareNewSession(botContextId, userId, scopeKey));
const now = Date.now();
- await db
- .insert(sessions)
- .values({
- id: row.id,
- title: ns.defaultTitle(userId),
- ...(ns.workspaceKind ? { workspaceKind: ns.workspaceKind } : {}),
- workingDir: row.workingDir,
- model: row.model,
- effort: row.effort,
- permissionMode: row.permissionMode,
- fastMode: row.fastMode,
- status: 'active',
- agentKind: toDbAgentKind(row.agentKind),
- providerId: row.providerId,
- source: ns.source,
- ...ns.extraInsertColumns(botContextId, userId),
- createdAt: now,
- updatedAt: now,
- // IM 会话由用户消息触发创建,插入时即设 userSendAt,
- // 避免广播后 renderer 重拉到 userSendAt=null 的行被误判为草稿。
- userSendAt: now,
- })
- .onConflictDoUpdate({
- target: sessions.id,
- set: {
+ const persisted = await withSessionRouteLock(row.id, async () => {
+ await db
+ .insert(sessions)
+ .values({
+ id: row.id,
+ title: ns.defaultTitle(userId),
+ ...(ns.workspaceKind ? { workspaceKind: ns.workspaceKind } : {}),
+ workingDir: row.workingDir,
+ model: row.model,
+ effort: row.effort,
+ permissionMode: row.permissionMode,
+ fastMode: row.fastMode,
status: 'active',
+ agentKind: toDbAgentKind(row.agentKind),
+ providerId: row.providerId,
source: ns.source,
- ...(ns.workspaceKind ? { workspaceKind: ns.workspaceKind } : {}),
...ns.extraInsertColumns(botContextId, userId),
+ createdAt: now,
updatedAt: now,
+ // IM 会话由用户消息触发创建,插入时即设 userSendAt,
+ // 避免广播后 renderer 重拉到 userSendAt=null 的行被误判为草稿。
userSendAt: now,
- },
- });
- // upsert 可能走冲突分支(残留行的 sdkSessionId / 模型 / 权限被刻意保留),
- // 返回值必须以 DB 持久化结果为准——直接返回 prepared 默认值会让 turn 拿
- // sdkSessionId=null 新开对话,而 DB 里旧上下文仍标记 active,两边失配。
- const persistedRows = await db
- .select()
- .from(sessions)
- .where(eq(sessions.id, row.id))
- .limit(1);
- const persisted = persistedRows[0];
+ })
+ .onConflictDoUpdate({
+ target: sessions.id,
+ set: {
+ status: 'active',
+ source: ns.source,
+ ...(ns.workspaceKind ? { workspaceKind: ns.workspaceKind } : {}),
+ ...ns.extraInsertColumns(botContextId, userId),
+ updatedAt: now,
+ userSendAt: now,
+ },
+ });
+ // upsert 可能走冲突分支(残留行的 sdkSessionId / 模型 / 权限被刻意保留),
+ // 返回值必须以 DB 持久化结果为准——直接返回 prepared 默认值会让 turn 拿
+ // sdkSessionId=null 新开对话,而 DB 里旧上下文仍标记 active,两边失配。
+ const persistedRows = await db
+ .select()
+ .from(sessions)
+ .where(eq(sessions.id, row.id))
+ .limit(1);
+ return persistedRows[0];
+ });
const result: ImSessionRow = persisted
? {
id: persisted.id,
diff --git a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
index 4ef425e7ca..b9b7487d4f 100644
--- a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import type { DbClient } from '../client/DbClient.js';
import { clearCurrentDbClient, setCurrentDbClient } from '../client/current.js';
+import { tx as runInprocTx } from '../worker/opHandlers/tx.js';
import * as schema from '../schema.js';
const h = vi.hoisted(() => ({
@@ -105,6 +106,55 @@ describe('orcaTeamStore', () => {
});
});
+ it('never archives or broadcasts a worker task that is already deleted', async () => {
+ const { archiveWorkersByTeam } = await import('../orcaTeamStore.js');
+ const client = createTestDbClient();
+ setCurrentDbClient(client, 'test-user');
+
+ await seedOrcaWorkers(client);
+ await client.exec('UPDATE sessions SET status = ? WHERE id = ?', [
+ 'deleted',
+ 'worker-session-2',
+ ]);
+
+ await expect(archiveWorkersByTeam('team-1')).resolves.toEqual(['worker-session-1']);
+ await expect(
+ client.queryOne<{ status: string }>('SELECT status FROM sessions WHERE id = ?', [
+ 'worker-session-2',
+ ]),
+ ).resolves.toEqual({ status: 'deleted' });
+ expect(h.tapWindowBroadcast).not.toHaveBeenCalledWith('local-db:sessions:patched', {
+ sessionId: 'worker-session-2',
+ patch: { status: 'archived' },
+ });
+ });
+
+ it('reconciles only still-active workers from inactive teams', async () => {
+ const { reconcileInactiveTeamWorkersForLead } = await import('../orcaTeamStore.js');
+ const client = createTestDbClient();
+ setCurrentDbClient(client, 'test-user');
+
+ await seedOrcaWorkers(client);
+ await client.exec('UPDATE orca_teams SET status = ? WHERE id = ?', ['completed', 'team-1']);
+ await client.exec('UPDATE sessions SET status = ? WHERE id = ?', [
+ 'deleted',
+ 'worker-session-2',
+ ]);
+
+ await expect(reconcileInactiveTeamWorkersForLead('lead-session-1')).resolves.toEqual([
+ 'worker-session-1',
+ ]);
+ await expect(
+ client.query<{ id: string; status: string }>(
+ 'SELECT id, status FROM sessions WHERE id IN (?, ?) ORDER BY id',
+ ['worker-session-1', 'worker-session-2'],
+ ),
+ ).resolves.toEqual([
+ { id: 'worker-session-1', status: 'archived' },
+ { id: 'worker-session-2', status: 'deleted' },
+ ]);
+ });
+
it('preserves Pi worker identity in Orca projections', async () => {
const { listWorkersByLead } = await import('../orcaTeamStore.js');
const client = createTestDbClient();
@@ -113,8 +163,9 @@ describe('orcaTeamStore', () => {
await seedOrcaWorkers(client);
const workers = await listWorkersByLead('lead-session-1');
- expect(workers.find((worker) => worker.sessionId === 'worker-session-2')?.session.agentKind)
- .toBe('pi');
+ expect(
+ workers.find((worker) => worker.sessionId === 'worker-session-2')?.session.agentKind,
+ ).toBe('pi');
});
it('returns complete active worker projections grouped by lead in one batch', async () => {
@@ -255,9 +306,8 @@ describe('orcaTeamStore', () => {
queryOne: async <T = unknown>(sql: string, params: unknown[] = []) =>
dbHandle.prepare(sql).get(...params) as T | undefined,
exec: async (sql, params = []) => dbHandle.prepare(sql).run(...params),
- tx: async () => {
- throw new Error('tx is not used by this test');
- },
+ tx: (async (name: string, args: unknown) =>
+ runInprocTx(dbHandle, { name, args })) as DbClient['tx'],
drizzle: db,
vecAvailable: false,
dispose: async () => {},
diff --git a/apps/desktop/src/main/localDb/client/DbTransport.ts b/apps/desktop/src/main/localDb/client/DbTransport.ts
index 4c02bd682c..c65a5d25c4 100644
--- a/apps/desktop/src/main/localDb/client/DbTransport.ts
+++ b/apps/desktop/src/main/localDb/client/DbTransport.ts
@@ -9,6 +9,31 @@ export interface DbTransport {
close(): Promise<void>;
}
+export const DB_TRANSPORT_NOT_SENT = 'DB_TRANSPORT_NOT_SENT' as const;
+export const DB_TRANSPORT_OUTCOME_UNKNOWN = 'DB_TRANSPORT_OUTCOME_UNKNOWN' as const;
+
+export type DbTransportErrorCode =
+ typeof DB_TRANSPORT_NOT_SENT | typeof DB_TRANSPORT_OUTCOME_UNKNOWN;
+
+export function createDbTransportError(
+ code: DbTransportErrorCode,
+ message: string,
+ cause?: unknown,
+): Error & { code: DbTransportErrorCode; cause?: unknown } {
+ return Object.assign(new Error(message), {
+ code,
+ ...(cause === undefined ? {} : { cause }),
+ });
+}
+
+export function isDbTransportOutcomeUnknown(error: unknown): boolean {
+ return (
+ typeof error === 'object' &&
+ error !== null &&
+ (error as { code?: unknown }).code === DB_TRANSPORT_OUTCOME_UNKNOWN
+ );
+}
+
export interface DbTransportTerminationInfo {
code: number | null;
signal: string | null;
@@ -26,8 +51,7 @@ export type RpcResponse =
| { id: number; ok: false; error: { code: string; message: string; stack?: string } };
export type WorkerEvent =
- | { event: 'log'; payload: LogEvent }
- | { event: 'vec-status'; payload: VecStatusEvent };
+ { event: 'log'; payload: LogEvent } | { event: 'vec-status'; payload: VecStatusEvent };
export type WorkerMessage = RpcResponse | WorkerEvent;
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
index 81417d874d..931d115d04 100644
--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
@@ -2,13 +2,16 @@ import fs from 'node:fs';
import path from 'node:path';
import { Worker } from 'node:worker_threads';
-import type {
- DbTransport,
- DbTransportTerminationInfo,
- LogEvent,
- RpcRequest,
- VecStatusEvent,
- WorkerMessage,
+import {
+ createDbTransportError,
+ DB_TRANSPORT_NOT_SENT,
+ DB_TRANSPORT_OUTCOME_UNKNOWN,
+ type DbTransport,
+ type DbTransportTerminationInfo,
+ type LogEvent,
+ type RpcRequest,
+ type VecStatusEvent,
+ type WorkerMessage,
} from './DbTransport.js';
const WORKER_CODE = `
@@ -300,6 +303,10 @@ function dispatchTx(readyDb, payload) {
return orcaRemoveWorker(readyDb, request.args);
case 'orca.cancelStaleTeams':
return orcaCancelStaleTeams(readyDb, request.args);
+ case 'orca.archiveWorkersByTeam':
+ return orcaArchiveWorkersByTeam(readyDb, request.args);
+ case 'orca.reconcileInactiveTeamWorkersForLead':
+ return orcaReconcileInactiveTeamWorkersForLead(readyDb, request.args);
case 'sessions.renameTitles':
return sessionsRenameTitles(readyDb, request.args);
case 'sessions.setStatus':
@@ -555,7 +562,7 @@ function sessionsSetStatus(readyDb, args) {
throw Object.assign(new Error('invalid status: ' + status), { code: 'INVALID_ARGS' });
}
const selectSession = readyDb.prepare(
- 'SELECT id, title, working_dir AS workingDir, workspace_kind AS workspaceKind FROM sessions WHERE id = ? LIMIT 1',
+ 'SELECT id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, status FROM sessions WHERE id = ? LIMIT 1',
);
const updateSession = readyDb.prepare(
'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind',
@@ -566,6 +573,11 @@ function sessionsSetStatus(readyDb, args) {
for (const sessionId of sessionIds) {
const existing = selectSession.get(sessionId);
if (!existing) throw Object.assign(new Error('Session 不存在: ' + sessionId), { code: 'NOT_FOUND' });
+ if (existing.status === 'deleted') {
+ throw Object.assign(new Error('已删除的任务不能恢复或归档: ' + sessionId), {
+ code: 'PRECONDITION_FAILED',
+ });
+ }
const updated = updateSession.get(status, now, sessionId);
if (!updated) throw Object.assign(new Error('Session 不存在: ' + sessionId), { code: 'NOT_FOUND' });
applied.push({
@@ -732,13 +744,13 @@ function orcaRemoveWorker(readyDb, args) {
const now = expectNumber(payload.now, 'now');
const selectWorker = readyDb.prepare('SELECT session_id AS sessionId FROM orca_workers WHERE id = ? LIMIT 1');
const deleteWorker = readyDb.prepare('DELETE FROM orca_workers WHERE id = ?');
- const archiveSession = readyDb.prepare("UPDATE sessions SET status = 'archived', orca_role = NULL, updated_at = ? WHERE id = ?");
+ const archiveSession = readyDb.prepare("UPDATE sessions SET status = 'archived', orca_role = NULL, updated_at = ? WHERE id = ? AND status != 'deleted'");
return readyDb.transaction(() => {
const row = selectWorker.get(workerId);
if (!row) return null;
deleteWorker.run(workerId);
- archiveSession.run(now, row.sessionId);
- return row.sessionId;
+ const archived = archiveSession.run(now, row.sessionId);
+ return archived.changes > 0 ? row.sessionId : null;
})();
}
@@ -753,6 +765,50 @@ function orcaCancelStaleTeams(readyDb, args) {
})();
}
+function orcaArchiveWorkersByTeam(readyDb, args) {
+ const payload = asRecord(args, 'orca.archiveWorkersByTeam args');
+ const teamId = expectString(payload.teamId, 'teamId');
+ const now = expectNumber(payload.now, 'now');
+ const selectCandidates = readyDb.prepare(
+ "SELECT sessions.id FROM orca_workers INNER JOIN sessions ON orca_workers.session_id = sessions.id WHERE orca_workers.team_id = ? AND sessions.status = 'active' ORDER BY sessions.id",
+ );
+ const archiveSession = readyDb.prepare(
+ "UPDATE sessions SET status = 'archived', updated_at = ? WHERE id = ? AND status = 'active'",
+ );
+ return readyDb.transaction(() => {
+ const candidates = selectCandidates.all(teamId);
+ const updatedIds = [];
+ for (const { id } of candidates) {
+ if (archiveSession.run(now, id).changes > 0) updatedIds.push(id);
+ }
+ return updatedIds;
+ })();
+}
+
+function orcaReconcileInactiveTeamWorkersForLead(readyDb, args) {
+ const payload = asRecord(args, 'orca.reconcileInactiveTeamWorkersForLead args');
+ const leadSessionId = expectString(payload.leadSessionId, 'leadSessionId');
+ const now = expectNumber(payload.now, 'now');
+ const selectCandidates = readyDb.prepare(
+ "SELECT sessions.id FROM orca_workers INNER JOIN orca_teams ON orca_workers.team_id = orca_teams.id INNER JOIN sessions ON orca_workers.session_id = sessions.id WHERE orca_teams.lead_session_id = ? AND orca_teams.status != 'active' AND sessions.status = 'active' ORDER BY sessions.id",
+ );
+ const finishWorkers = readyDb.prepare(
+ "UPDATE orca_workers SET status = 'done', updated_at = ? WHERE team_id IN (SELECT id FROM orca_teams WHERE lead_session_id = ? AND status != 'active')",
+ );
+ const archiveSession = readyDb.prepare(
+ "UPDATE sessions SET status = 'archived', updated_at = ? WHERE id = ? AND status = 'active'",
+ );
+ return readyDb.transaction(() => {
+ const candidates = selectCandidates.all(leadSessionId);
+ finishWorkers.run(now, leadSessionId);
+ const updatedIds = [];
+ for (const { id } of candidates) {
+ if (archiveSession.run(now, id).changes > 0) updatedIds.push(id);
+ }
+ return updatedIds;
+ })();
+}
+
function orcaUpsertWorker(readyDb, args) {
const payload = asRecord(args, 'orca.upsertWorker args');
const id = expectString(payload.id, 'id');
@@ -1802,7 +1858,12 @@ export class WorkerThreadTransport implements DbTransport {
send<R = unknown>(op: string, args?: unknown, transferList?: unknown[]): Promise<R> {
if (this.closed || this.closing) {
- return Promise.reject(new Error('db worker transport is closed'));
+ return Promise.reject(
+ createDbTransportError(
+ DB_TRANSPORT_NOT_SENT,
+ 'db worker transport is closed',
+ ),
+ );
}
const id = this.nextId++;
const req: RpcRequest = { id, op, args };
@@ -1820,7 +1881,8 @@ export class WorkerThreadTransport implements DbTransport {
}
if (this.queued.length >= this.maxQueuedRpcs) {
reject(
- new Error(
+ createDbTransportError(
+ DB_TRANSPORT_NOT_SENT,
`db worker RPC queue overloaded: op="${op}" inFlight=${this.pending.size}` +
` queued=${this.queued.length}`,
),
@@ -1862,7 +1924,13 @@ export class WorkerThreadTransport implements DbTransport {
// Worker may already be down; terminate below still releases resources.
} finally {
this.closed = true;
- this.rejectAllPending(new Error('db worker transport closed'));
+ this.rejectAllPending(
+ createDbTransportError(
+ DB_TRANSPORT_OUTCOME_UNKNOWN,
+ 'db worker transport closed',
+ ),
+ createDbTransportError(DB_TRANSPORT_NOT_SENT, 'db worker transport closed'),
+ );
await this.worker.terminate();
}
}
@@ -1903,7 +1971,8 @@ export class WorkerThreadTransport implements DbTransport {
}
this.queued.splice(index, 1);
item.reject(
- new Error(
+ createDbTransportError(
+ DB_TRANSPORT_NOT_SENT,
`db worker RPC queue timeout: op="${item.req.op}" id=${item.req.id}` +
` exceeded ${this.rpcTimeoutMs / 1000}s total budget`,
),
@@ -1937,7 +2006,8 @@ export class WorkerThreadTransport implements DbTransport {
}
this.pending.delete(id);
pending.reject(
- new Error(
+ createDbTransportError(
+ DB_TRANSPORT_OUTCOME_UNKNOWN,
`db worker RPC timeout: op="${op}" id=${id} exceeded ${this.rpcTimeoutMs / 1000}s` +
` wallElapsedMs=${verdict.wallElapsedMs}`,
),
@@ -1961,7 +2031,13 @@ export class WorkerThreadTransport implements DbTransport {
} catch (err) {
clearTimeout(timeout);
this.pending.delete(id);
- item.reject(toError(err));
+ item.reject(
+ createDbTransportError(
+ DB_TRANSPORT_NOT_SENT,
+ toError(err).message,
+ err,
+ ),
+ );
this.drainQueue();
}
}
@@ -1982,14 +2058,20 @@ export class WorkerThreadTransport implements DbTransport {
if (workerTerminated) return;
workerTerminated = true;
const error = toError(err);
- this.rejectAllPending(error);
+ this.rejectAllPending(
+ createDbTransportError(DB_TRANSPORT_OUTCOME_UNKNOWN, error.message, error),
+ createDbTransportError(DB_TRANSPORT_NOT_SENT, error.message, error),
+ );
this.emitTerminated({ code: null, signal: null, error });
});
worker.on('exit', (code) => {
if (workerTerminated) return;
workerTerminated = true;
const err = new Error(`db worker exited with code ${code}`);
- this.rejectAllPending(err);
+ this.rejectAllPending(
+ createDbTransportError(DB_TRANSPORT_OUTCOME_UNKNOWN, err.message, err),
+ createDbTransportError(DB_TRANSPORT_NOT_SENT, err.message, err),
+ );
this.emitTerminated({ code, signal: null });
});
return worker;
@@ -2058,15 +2140,15 @@ export class WorkerThreadTransport implements DbTransport {
for (const cb of listeners) cb(event);
}
- private rejectAllPending(err: Error): void {
+ private rejectAllPending(pendingError: Error, queuedError: Error = pendingError): void {
for (const pending of this.pending.values()) {
clearTimeout(pending.timeout);
- pending.reject(err);
+ pending.reject(pendingError);
}
this.pending.clear();
for (const queued of this.queued.splice(0)) {
if (queued.queueTimeout) clearTimeout(queued.queueTimeout);
- queued.reject(err);
+ queued.reject(queuedError);
}
}
diff --git a/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts b/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts
index bd4e85877a..f7dec5446f 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts
@@ -4,7 +4,12 @@ import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { buildDbWorkerBundle, createMigratedSmokeDb } from '../../__tests__/dbWorkerTestUtils.js';
-import type { LogEvent, VecStatusEvent } from '../DbTransport.js';
+import {
+ DB_TRANSPORT_NOT_SENT,
+ DB_TRANSPORT_OUTCOME_UNKNOWN,
+ type LogEvent,
+ type VecStatusEvent,
+} from '../DbTransport.js';
import { WorkerThreadTransport } from '../WorkerThreadTransport.js';
describe('WorkerThreadTransport', () => {
@@ -32,7 +37,10 @@ describe('WorkerThreadTransport', () => {
const transport = new WorkerThreadTransport({ useInlineWorker: true });
const pending = transport.send('sleep', { ms: 1_000 });
await transport.terminateForTest();
- await expect(pending).rejects.toThrow(/db worker exited|terminated/i);
+ await expect(pending).rejects.toMatchObject({
+ code: DB_TRANSPORT_OUTCOME_UNKNOWN,
+ message: expect.stringMatching(/db worker exited|terminated/i),
+ });
});
it('applies bounded backpressure before posting more RPCs to the worker', async () => {
@@ -85,13 +93,28 @@ describe('WorkerThreadTransport', () => {
});
const active = transport.send('sleep', { ms: 1_000 });
const queued = transport.send('query', { sql: 'SELECT 1' });
- const activeRejection = expect(active).rejects.toThrow(/transport closed/);
- const queuedRejection = expect(queued).rejects.toThrow(/transport closed/);
+ const activeRejection = expect(active).rejects.toMatchObject({
+ code: DB_TRANSPORT_OUTCOME_UNKNOWN,
+ message: expect.stringMatching(/transport closed/),
+ });
+ const queuedRejection = expect(queued).rejects.toMatchObject({
+ code: DB_TRANSPORT_NOT_SENT,
+ message: expect.stringMatching(/transport closed/),
+ });
await expect(transport.close()).resolves.toBeUndefined();
await Promise.all([activeRejection, queuedRejection]);
});
+ it('marks requests rejected before dispatch as definitely not sent', async () => {
+ const transport = new WorkerThreadTransport({ useInlineWorker: true });
+ await transport.close();
+
+ await expect(transport.send('query', { sql: 'SELECT 1' })).rejects.toMatchObject({
+ code: DB_TRANSPORT_NOT_SENT,
+ });
+ });
+
it('transfers ArrayBuffer ownership through postMessage transferList', async () => {
const transport = new WorkerThreadTransport({ useInlineWorker: true });
try {
diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
index 8c67d4b0c9..bb0d585699 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
@@ -1728,6 +1728,79 @@ describe('db worker tx handlers', () => {
});
});
+ it.each([
+ { label: 'bundled worker', useInlineWorker: false },
+ { label: 'inline worker', useInlineWorker: true },
+ ])('returns exact Orca archive ids through the $label tx path', async ({ useInlineWorker }) => {
+ await withClient(
+ async (client) => {
+ await seedSession(client, 'lead');
+ await seedSession(client, 'active-worker', { orcaRole: 'worker' });
+ await seedSession(client, 'archived-worker', {
+ orcaRole: 'worker',
+ status: 'archived',
+ });
+ await seedSession(client, 'deleted-worker', {
+ orcaRole: 'worker',
+ status: 'deleted',
+ });
+ await seedSession(client, 'orphan-worker', { orcaRole: 'worker' });
+ await client.exec(
+ 'INSERT INTO orca_teams (id, lead_session_id, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
+ ['active-team', 'lead', 'active', 1, 1],
+ );
+ await client.exec(
+ 'INSERT INTO orca_teams (id, lead_session_id, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
+ ['inactive-team', 'lead', 'completed', 1, 1],
+ );
+ for (const [id, teamId, sessionId] of [
+ ['active-link', 'active-team', 'active-worker'],
+ ['archived-link', 'active-team', 'archived-worker'],
+ ['deleted-link', 'active-team', 'deleted-worker'],
+ ['orphan-link', 'inactive-team', 'orphan-worker'],
+ ]) {
+ await client.exec(
+ 'INSERT INTO orca_workers (id, team_id, session_id, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)',
+ [id, teamId, sessionId, 'idle', 1, 1],
+ );
+ }
+
+ await expect(
+ client.tx('orca.archiveWorkersByTeam', { teamId: 'active-team', now: 100 }),
+ ).resolves.toEqual(['active-worker']);
+ await expect(
+ client.tx('orca.reconcileInactiveTeamWorkersForLead', {
+ leadSessionId: 'lead',
+ now: 200,
+ }),
+ ).resolves.toEqual(['orphan-worker']);
+
+ await expect(
+ client.query<{ id: string; status: string; updated_at: number }>(
+ 'SELECT id, status, updated_at FROM sessions WHERE id != ? ORDER BY id',
+ ['lead'],
+ ),
+ ).resolves.toEqual([
+ { id: 'active-worker', status: 'archived', updated_at: 100 },
+ { id: 'archived-worker', status: 'archived', updated_at: 1 },
+ { id: 'deleted-worker', status: 'deleted', updated_at: 1 },
+ { id: 'orphan-worker', status: 'archived', updated_at: 200 },
+ ]);
+ await expect(
+ client.query<{ id: string; status: string; updated_at: number }>(
+ 'SELECT id, status, updated_at FROM orca_workers ORDER BY id',
+ ),
+ ).resolves.toEqual([
+ { id: 'active-link', status: 'idle', updated_at: 1 },
+ { id: 'archived-link', status: 'idle', updated_at: 1 },
+ { id: 'deleted-link', status: 'idle', updated_at: 1 },
+ { id: 'orphan-link', status: 'done', updated_at: 200 },
+ ]);
+ },
+ { useInlineWorker },
+ );
+ });
+
it('serializes the same worker label across independent database workers', async () => {
await withTwoClients(async ([first, second]) => {
await seedSession(first, 'lead');
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index 9ca6308231..41a4fbb364 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -15,6 +15,8 @@ export type DbTxName =
| 'orca.setWorkerFocus'
| 'orca.removeWorker'
| 'orca.cancelStaleTeams'
+ | 'orca.archiveWorkersByTeam'
+ | 'orca.reconcileInactiveTeamWorkersForLead'
| 'sessions.renameTitles'
| 'sessions.setStatus'
| 'session.agentSwitchFallback'
@@ -255,6 +257,18 @@ export interface OrcaCancelStaleTeamsArgs {
now: number;
}
+/** Archive every still-active worker session linked to one team. */
+export interface OrcaArchiveWorkersByTeamArgs {
+ teamId: string;
+ now: number;
+}
+
+/** Repair active worker sessions left behind under a lead's inactive teams. */
+export interface OrcaReconcileInactiveTeamWorkersForLeadArgs {
+ leadSessionId: string;
+ now: number;
+}
+
export interface SessionsRenameTitleChange {
sessionId: string;
title: string;
@@ -729,6 +743,8 @@ export type DbTxArgsByName = {
'orca.setWorkerFocus': OrcaSetWorkerFocusArgs;
'orca.removeWorker': OrcaRemoveWorkerArgs;
'orca.cancelStaleTeams': OrcaCancelStaleTeamsArgs;
+ 'orca.archiveWorkersByTeam': OrcaArchiveWorkersByTeamArgs;
+ 'orca.reconcileInactiveTeamWorkersForLead': OrcaReconcileInactiveTeamWorkersForLeadArgs;
'sessions.renameTitles': SessionsRenameTitlesArgs;
'sessions.setStatus': SessionsSetStatusArgs;
'session.agentSwitchFallback': SessionAgentSwitchFallbackArgs;
@@ -772,6 +788,8 @@ export type DbTxResultByName = {
'orca.setWorkerFocus': undefined;
'orca.removeWorker': string | null;
'orca.cancelStaleTeams': undefined;
+ 'orca.archiveWorkersByTeam': string[];
+ 'orca.reconcileInactiveTeamWorkersForLead': string[];
'sessions.renameTitles': SessionsRenameTitleResult[];
'sessions.setStatus': SessionsSetStatusResultItem[];
'session.agentSwitchFallback': undefined;
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts
index 117fc4135f..6c5930b7b4 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
import { createOwnerEnsureCoordinator } from '../ownerEnsureCoordinator.js';
@@ -18,7 +19,7 @@ describe('createOwnerEnsureCoordinator', () => {
const discard = vi.fn();
const run = createOwnerEnsureCoordinator({
isOwnerCurrent: (ownerId) => ownerId === activeOwner,
- beforeEnsureReady: (ownerId) => ownerId === 'cloud-a' ? preflightA.promise : undefined,
+ beforeEnsureReady: (ownerId) => (ownerId === 'cloud-a' ? preflightA.promise : undefined),
ensureReady: ensure,
discardReadyOwner: discard,
});
@@ -58,11 +59,7 @@ describe('createOwnerEnsureCoordinator', () => {
await expect(stale).resolves.toMatchObject({ ready: false });
await expect(local).resolves.toEqual({ ready: true });
- expect(events).toEqual([
- 'ensure:cloud-a',
- 'discard:cloud-a',
- 'ensure:local-v1',
- ]);
+ expect(events).toEqual(['ensure:cloud-a', 'discard:cloud-a', 'ensure:local-v1']);
});
it('discards an owner superseded while its ready callback is pending', async () => {
@@ -117,3 +114,20 @@ describe('createOwnerEnsureCoordinator', () => {
expect(discard).toHaveBeenCalledWith('local-v1');
});
});
+
+describe('registerLocalDbIpc ready-hook composition', () => {
+ it('lets the lifecycle hook install DbClient before scheduling media reconcile', () => {
+ const source = fs.readFileSync(new URL('../registerAll.ts', import.meta.url), 'utf8');
+ const start = source.indexOf('onReady: async (userId) => {');
+ const end = source.indexOf('onReadyError:', start);
+ const hook = source.slice(start, end);
+
+ expect(hook.indexOf('await opts.onReady?.(userId)')).toBeLessThan(
+ hook.indexOf('tryGetDbClient()'),
+ );
+ expect(hook).toContain('if (');
+ expect(hook).toContain('!client');
+ expect(hook).toContain('!withSessionLock');
+ expect(hook).toContain('withSessionLock,');
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemovalOperations.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemovalOperations.test.ts
index d0c031e01b..edb4a6b974 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemovalOperations.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemovalOperations.test.ts
@@ -18,12 +18,13 @@ describe('quiesceSessionBeforeWorktreeRecycle', () => {
await expect(
quiesceSessionBeforeWorktreeRecycle('session-a', {
+ isOwnerCurrent: () => true,
isSessionStillRemovable,
cancelSessionOperations,
closeSession,
}),
).resolves.toBe(true);
- expect(order).toEqual(['check', 'cancel', 'check', 'close']);
+ expect(order).toEqual(['check', 'cancel', 'check', 'close', 'check']);
});
it('does not close or recycle a task restored while cancellation settles', async () => {
@@ -36,6 +37,7 @@ describe('quiesceSessionBeforeWorktreeRecycle', () => {
await expect(
quiesceSessionBeforeWorktreeRecycle('session-a', {
+ isOwnerCurrent: () => true,
isSessionStillRemovable,
cancelSessionOperations,
closeSession,
@@ -44,4 +46,45 @@ describe('quiesceSessionBeforeWorktreeRecycle', () => {
expect(cancelSessionOperations).toHaveBeenCalledWith('session-a');
expect(closeSession).not.toHaveBeenCalled();
});
+
+ it('does not recycle a task restored while Agent close settles', async () => {
+ const isSessionStillRemovable = vi
+ .fn<() => Promise<boolean>>()
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(false);
+ const cancelSessionOperations = vi.fn(async () => undefined);
+ const closeSession = vi.fn(async () => undefined);
+
+ await expect(
+ quiesceSessionBeforeWorktreeRecycle('session-a', {
+ isOwnerCurrent: () => true,
+ isSessionStillRemovable,
+ cancelSessionOperations,
+ closeSession,
+ }),
+ ).resolves.toBe(false);
+ expect(closeSession).toHaveBeenCalledWith('session-a');
+ });
+
+ it('stops before each side effect when the captured owner changes', async () => {
+ let current = true;
+ const isSessionStillRemovable = vi.fn(async () => {
+ current = false;
+ return true;
+ });
+ const cancelSessionOperations = vi.fn(async () => undefined);
+ const closeSession = vi.fn(async () => undefined);
+
+ await expect(
+ quiesceSessionBeforeWorktreeRecycle('shared-session-id', {
+ isOwnerCurrent: () => current,
+ isSessionStillRemovable,
+ cancelSessionOperations,
+ closeSession,
+ }),
+ ).resolves.toBe(false);
+ expect(cancelSessionOperations).not.toHaveBeenCalled();
+ expect(closeSession).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
index 468177c642..17c9f7ef5c 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
@@ -6,7 +6,7 @@
*/
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { messages, sessions } from '../../schema';
@@ -15,6 +15,7 @@ const h = vi.hoisted(() => ({
sqlite: null as InstanceType<typeof import('better-sqlite3')> | null,
handlers: new Map<string, (...args: unknown[]) => unknown>(),
tapWindowBroadcast: vi.fn(),
+ routeLock: vi.fn(async (_sessionId: string, task: () => Promise<unknown>) => task()),
}));
vi.mock('electron', () => ({
@@ -46,6 +47,7 @@ vi.mock('../../../messagePersistBroadcaster', () => ({ noteSessionClearBoundary:
vi.mock('../../../sessionIds', () => ({ resolveBusinessSessionId: (id: string) => id }));
import { registerSessionIpc } from '../sessions';
+import { setSessionRouteLockImplementation } from '../../sessionRouteLock';
type ExpectedIdentity = {
workingDir: string | null;
@@ -146,11 +148,17 @@ function readStatus(): string {
beforeEach(() => {
vi.clearAllMocks();
+ h.routeLock.mockImplementation(async (_sessionId, task) => task());
h.handlers.clear();
createDb();
+ setSessionRouteLockImplementation(h.routeLock);
registerSessionIpc();
});
+afterEach(() => {
+ setSessionRouteLockImplementation(null);
+});
+
describe('local-db:sessions:restore-if-archived', () => {
it('restores when archived status and the full project identity still match', async () => {
const updated = (await restore()) as { id: string; status: string };
@@ -163,6 +171,30 @@ describe('local-db:sessions:restore-if-archived', () => {
});
});
+ it('waits for the shared task route lock before restoring', async () => {
+ let markWaiting!: () => void;
+ const waiting = new Promise<void>((resolve) => {
+ markWaiting = resolve;
+ });
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ h.routeLock.mockImplementationOnce(async (_sessionId, task) => {
+ markWaiting();
+ await gate;
+ return task();
+ });
+
+ const restoring = restore();
+ await waiting;
+ expect(readStatus()).toBe('archived');
+ release();
+
+ await expect(restoring).resolves.toMatchObject({ status: 'active' });
+ expect(h.routeLock).toHaveBeenCalledWith('target', expect.any(Function));
+ });
+
it.each(['active', 'deleted'])('does not overwrite a newer %s status', async (status) => {
h.sqlite!.prepare('UPDATE sessions SET status = ? WHERE id = ?').run(status, 'target');
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index cca6af6d2b..87a7503932 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -10,7 +10,7 @@
*/
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { messages, sessions } from '../../schema';
@@ -23,6 +23,7 @@ const h = vi.hoisted(() => ({
})),
tapWindowBroadcast: vi.fn(),
summarizeSession: vi.fn(async () => undefined),
+ routeLock: vi.fn(async (_sessionId: string, task: () => Promise<unknown>) => task()),
}));
vi.mock('electron', () => ({
@@ -60,6 +61,7 @@ vi.mock('../../../maker-host/claude-transcript-relocation.js', () => ({
}));
import { registerSessionIpc } from '../sessions';
+import { setSessionRouteLockImplementation } from '../../sessionRouteLock';
function createDb(): void {
const sqlite = new Database(':memory:');
@@ -142,12 +144,33 @@ async function invokeUpdate(id: string, patch: Record<string, unknown>): Promise
beforeEach(() => {
vi.clearAllMocks();
h.relocate.mockImplementation(async () => ({ persistedSdkSessionId: null }));
+ h.routeLock.mockImplementation(async (_sessionId, task) => task());
h.handlers.clear();
createDb();
+ setSessionRouteLockImplementation(h.routeLock);
registerSessionIpc();
});
+afterEach(() => {
+ setSessionRouteLockImplementation(null);
+});
+
describe('local-db:sessions:update handler wiring', () => {
+ it('does not resurrect a deleted task through the generic status writer', async () => {
+ h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('codex-local');
+
+ await expect(invokeUpdate('codex-local', { status: 'active' })).rejects.toThrow(
+ '[PRECONDITION_FAILED]',
+ );
+
+ const persisted = h
+ .sqlite!.prepare('SELECT status FROM sessions WHERE id = ?')
+ .get('codex-local') as { status: string };
+ expect(persisted.status).toBe('deleted');
+ expect(h.tapWindowBroadcast).not.toHaveBeenCalled();
+ expect(h.routeLock).toHaveBeenCalledWith('codex-local', expect.any(Function));
+ });
+
it('persists and broadcasts title-only patches to device-link subscribers', async () => {
await invokeUpdate('codex-local', { title: '排查远程标题同步' });
diff --git a/apps/desktop/src/main/localDb/ipc/registerAll.ts b/apps/desktop/src/main/localDb/ipc/registerAll.ts
index 4ace59e2a1..732477f8a9 100644
--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts
+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts
@@ -10,7 +10,7 @@
import { ipcMain } from 'electron';
import { closeDb, ensureReady, getCurrentUserId } from '../index';
-import { getCurrentDbClientUserId } from '../client/current';
+import { getCurrentDbClientUserId, tryGetDbClient } from '../client/current';
import { registerSessionIpc, setSessionRemovalCancelOperations } from './sessions';
import { registerMessageIpc } from './messages';
import { registerOrcaWorkflowIpc } from './orcaTeams';
@@ -26,8 +26,43 @@ import { registerRemoteHistoryIpc } from './history';
import { createLogger } from '../../logger';
import { recordDesktopDevLocalDbStartupResult } from '../../devStartupStatus';
import { createOwnerEnsureCoordinator } from './ownerEnsureCoordinator';
+import { reconcileSessionMediaRefsForDeletedSessions } from '../../cindy-media/sessionCleanup';
+import { reconcileMediaRefCompensationsForOwner } from '../../cindy-media/refCompensationJournal';
+import { setSessionRouteLockImplementation } from '../sessionRouteLock';
const log = createLogger('registerAll');
+const MEDIA_REF_COMPENSATION_BUSY_RETRY_MS = 12_000;
+
+function startMediaRefCompensationReconcile(
+ userId: string,
+ client: NonNullable<ReturnType<typeof tryGetDbClient>>,
+ isOwnerCurrent: () => boolean,
+): void {
+ const run = async (allowBusyRetry: boolean): Promise<void> => {
+ if (!isOwnerCurrent()) return;
+ const result = await reconcileMediaRefCompensationsForOwner({
+ ownerId: userId,
+ db: client.drizzle,
+ isOwnerCurrent,
+ });
+ if (!allowBusyRetry || result.busy === 0 || !isOwnerCurrent()) return;
+ const retry = setTimeout(() => {
+ void run(false).catch((error) => {
+ log.warn('delayed media reference compensation reconcile failed', {
+ userId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }, MEDIA_REF_COMPENSATION_BUSY_RETRY_MS);
+ retry.unref?.();
+ };
+ void run(true).catch((error) => {
+ log.warn('media reference compensation reconcile failed', {
+ userId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+}
export interface RegisterLocalDbIpcOpts {
/** Current stable app-session owner. False makes queued/in-flight work stale. */
@@ -38,6 +73,8 @@ export interface RegisterLocalDbIpcOpts {
beforeEnsureReady?: (userId: string) => void | Promise<void>;
/** Stop Host-owned session operations before an archived/deleted worktree is recycled. */
cancelSessionOperations?: (sessionId: string) => Promise<void>;
+ /** Serialize startup tombstone cleanup with task restore/start/send operations. */
+ withSessionLock?: <T>(sessionId: string, task: () => Promise<T>) => Promise<T>;
/**
* 可选回调:localDb.ensureReady 成功(含已就绪复用路径)后触发。
* 用途:启动依赖 localDb 的 host 单例(如 scheduler-host)。失败时协调器会
@@ -53,11 +90,43 @@ export interface RegisterLocalDbIpcOpts {
export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {
setSessionRemovalCancelOperations(opts.cancelSessionOperations ?? null);
+ setSessionRouteLockImplementation(opts.withSessionLock ?? null);
const runEnsureReady = createOwnerEnsureCoordinator({
isOwnerCurrent: opts.isOwnerCurrent ?? (() => true),
beforeEnsureReady: opts.beforeEnsureReady,
ensureReady,
- onReady: opts.onReady,
+ onReady: async (userId) => {
+ await opts.onReady?.(userId);
+ const client = tryGetDbClient();
+ if (
+ !client ||
+ getCurrentDbClientUserId() !== userId ||
+ !(opts.isOwnerCurrent?.(userId) ?? true)
+ ) {
+ return;
+ }
+ const isReadyOwnerCurrent = (): boolean =>
+ tryGetDbClient() === client &&
+ getCurrentDbClientUserId() === userId &&
+ (opts.isOwnerCurrent?.(userId) ?? true);
+ startMediaRefCompensationReconcile(userId, client, isReadyOwnerCurrent);
+
+ const cancelSessionOperations = opts.cancelSessionOperations;
+ const withSessionLock = opts.withSessionLock;
+ if (!cancelSessionOperations || !withSessionLock) return;
+ const db = client.drizzle;
+ void reconcileSessionMediaRefsForDeletedSessions({
+ db,
+ isOwnerCurrent: isReadyOwnerCurrent,
+ withSessionLock,
+ quiesceSession: cancelSessionOperations,
+ }).catch((error) => {
+ log.warn('deleted task media reconcile failed', {
+ userId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ },
onReadyError: (userId, err) => {
log.warn(
JSON.stringify({
@@ -101,11 +170,13 @@ export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {
result = await runEnsureReady(userId);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
- log.error(JSON.stringify({
- event: 'localDb.ipc.ensure-ready.failed',
- userId,
- error: message,
- }));
+ log.error(
+ JSON.stringify({
+ event: 'localDb.ipc.ensure-ready.failed',
+ userId,
+ error: message,
+ }),
+ );
result = {
ready: false,
error: { code: 'DB_INIT_FAILED', message },
diff --git a/apps/desktop/src/main/localDb/ipc/session-share.ts b/apps/desktop/src/main/localDb/ipc/session-share.ts
index 1d214ec993..8f61524aad 100644
--- a/apps/desktop/src/main/localDb/ipc/session-share.ts
+++ b/apps/desktop/src/main/localDb/ipc/session-share.ts
@@ -23,10 +23,7 @@ import {
exportSessionShare,
type SessionShareExportOutcome,
} from '../../session-share/sessionShareExport.js';
-import {
- SHARE_FILE_EXT,
- SHARE_FILE_EXTENSIONS,
-} from '../../session-share/xdtshareFormat.pure.js';
+import { SHARE_FILE_EXT, SHARE_FILE_EXTENSIONS } from '../../session-share/xdtshareFormat.pure.js';
import {
cancelShareDraft,
cleanupReplacedSessionMediaRefs,
@@ -38,9 +35,12 @@ import {
type SharePreview,
type ShareImportDraftPrefs,
} from '../../session-share/sessionShareImport.js';
-import { getDbClient } from '../client/current.js';
+import { getDbClient, tryGetDbClient } from '../client/current.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../appSessionState.js';
+import { captureMediaRefCompensationScope } from '../../cindy-media/refCompensationJournal.js';
import {
broadcastSessionPatched,
+ captureSessionRecycleScope,
recycleSessionWorktreeForStatusChange,
} from './sessions.js';
@@ -57,7 +57,10 @@ export type SessionShareExportResponse = SessionShareExportOutcome | { status: '
export type SessionShareInspectResponse = InspectResult | { status: 'canceled' };
/** 统一错误出口:业务码原样透传,未知错误按 fallbackCode 抛。 */
-function rethrowIpc(err: unknown, fallbackCode: 'SHARE_EXPORT_FAILED' | 'SHARE_IMPORT_FAILED'): never {
+function rethrowIpc(
+ err: unknown,
+ fallbackCode: 'SHARE_EXPORT_FAILED' | 'SHARE_IMPORT_FAILED',
+): never {
const code = (err as { code?: unknown }).code;
const message = err instanceof Error ? err.message : String(err);
if (isIpcErrorCode(code)) throwIpcError(code, message);
@@ -170,17 +173,37 @@ export function registerSessionShareIpc(): void {
const overwrite = payload.overwrite === true;
const useWorktree = payload.useWorktree === true;
try {
- const result = await commitShareImport({ draftId, workingDir, draftPrefs, overwrite, useWorktree });
+ const ownerScopeKey = activeOwnerScopeKey();
+ const importDbClient = getDbClient();
+ const recycleScope = captureSessionRecycleScope(importDbClient);
+ const refCompensationScope = captureMediaRefCompensationScope(ownerScopeKey);
+ const isStillCurrent = (): boolean =>
+ !isAppSessionBoundaryPending() &&
+ activeOwnerScopeKey() === ownerScopeKey &&
+ tryGetDbClient() === importDbClient;
+ const assertStillValid = (): void => {
+ refCompensationScope.assertStillValid();
+ if (!isStillCurrent()) {
+ throw new Error('Session share import owner changed before commit');
+ }
+ };
+ const result = await commitShareImport(
+ { draftId, workingDir, draftPrefs, overwrite, useWorktree },
+ { dbClient: importDbClient, assertStillValid, refCompensationScope },
+ );
// 覆盖事务成功后再执行不可随 SQLite 回滚的运行时/UI/资源收尾:
// - 广播 patched 让 sidebar/会话视图立即移除旧任务;
// - 经统一回收链在 route lock 下复验 deleted,关闭 runtime 并回收旧 worktree;
// - 删除旧 session 名下的媒体引用,引用归零的共享 blob 交 recycler 回收。
// 不直接删除转录或媒体字节:同 resume id/内容的新任务可能复用它们。
for (const replaced of result.replacedSessions) {
- broadcastSessionPatched(replaced.id, { status: 'deleted' });
- await recycleSessionWorktreeForStatusChange(replaced.id, 'deleted');
+ if (!isStillCurrent()) break;
+ broadcastSessionPatched(replaced.id, { status: 'deleted' }, recycleScope.ownerScope);
+ await recycleSessionWorktreeForStatusChange(replaced.id, 'deleted', recycleScope);
+ }
+ if (isStillCurrent()) {
+ await cleanupReplacedSessionMediaRefs(result.replacedSessions, importDbClient.drizzle);
}
- await cleanupReplacedSessionMediaRefs(result.replacedSessions);
// replacedSessions 是 main 内部收尾信息,不暴露给 renderer/preload 契约。
const publicResult: CommitShareImportResult = {
sessionId: result.sessionId,
@@ -190,7 +213,9 @@ export function registerSessionShareIpc(): void {
};
// 在此补发(fire-and-forget;workdir 由通知内部的资格查询回填)——否则订阅
// 了 session 的意识对导入会话只见 switched/archived 不见 created(review P2)。
- notifyGhostSessionEvent('created', { sessionId: result.sessionId });
+ if (isStillCurrent()) {
+ notifyGhostSessionEvent('created', { sessionId: result.sessionId });
+ }
return publicResult;
} catch (err) {
log.warn('session share commit failed', {
@@ -212,7 +237,10 @@ export function registerSessionShareIpc(): void {
// 会话(PR4);其它忽略。放本模块因为分享文件识别是它的域;目录分支为通用能力。
ipcMain.handle(
'local-db:session-share:classify-path',
- async (_e, request?: { path?: unknown }): Promise<{ kind: 'share' | 'directory' | 'other' }> => {
+ async (
+ _e,
+ request?: { path?: unknown },
+ ): Promise<{ kind: 'share' | 'directory' | 'other' }> => {
const raw = typeof request?.path === 'string' ? request.path : '';
if (!raw) return { kind: 'other' };
const stat = await fsp.stat(raw).catch(() => null);
@@ -240,8 +268,7 @@ function sanitizeDraftPrefs(raw: unknown): ShareImportDraftPrefs | null {
permissionMode: typeof r.permissionMode === 'string' ? r.permissionMode : undefined,
planMode: r.planMode === true,
fastMode: r.fastMode === true,
- providerId:
- typeof r.providerId === 'string' && r.providerId.length > 0 ? r.providerId : null,
+ providerId: typeof r.providerId === 'string' && r.providerId.length > 0 ? r.providerId : null,
};
}
diff --git a/apps/desktop/src/main/localDb/ipc/sessionRemovalOperations.ts b/apps/desktop/src/main/localDb/ipc/sessionRemovalOperations.ts
index 4d0a299c74..070a2b9594 100644
--- a/apps/desktop/src/main/localDb/ipc/sessionRemovalOperations.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessionRemovalOperations.ts
@@ -1,4 +1,5 @@
export interface SessionRemovalOperationDeps {
+ isOwnerCurrent(): boolean;
isSessionStillRemovable(sessionId: string): Promise<boolean>;
cancelSessionOperations(sessionId: string): Promise<void>;
closeSession(sessionId: string): Promise<void>;
@@ -13,9 +14,14 @@ export async function quiesceSessionBeforeWorktreeRecycle(
sessionId: string,
deps: SessionRemovalOperationDeps,
): Promise<boolean> {
+ if (!deps.isOwnerCurrent()) return false;
if (!(await deps.isSessionStillRemovable(sessionId))) return false;
+ if (!deps.isOwnerCurrent()) return false;
await deps.cancelSessionOperations(sessionId);
+ if (!deps.isOwnerCurrent()) return false;
if (!(await deps.isSessionStillRemovable(sessionId))) return false;
+ if (!deps.isOwnerCurrent()) return false;
await deps.closeSession(sessionId);
- return true;
+ if (!deps.isOwnerCurrent()) return false;
+ return deps.isSessionStillRemovable(sessionId);
}
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 0be0523a2e..f855b53cef 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -31,7 +31,7 @@ import { recomputePrRefsForSession } from '../../git-context/prRefsStore';
import { ensureProjectGitInitialized } from '../../git-snapshot/projectGitBootstrap';
import { readGitSafetySettings } from '../../maker-host/git-safety-settings-store';
import * as imageCacheStore from '../../imageCacheStore';
-import { removeSessionRefs as removeSessionMediaRefs } from '../../cindy-media/ledger';
+import { removeSessionRefsIfDeleted as removeDeletedSessionMediaRefs } from '../../cindy-media/ledger';
import { removeWechatSessionAttachmentDir } from '../../im/wechat/mediaStaging';
import { upsertRecentWorkdir } from './recentWorkdirs';
import { createLogger } from '../../logger';
@@ -50,13 +50,11 @@ import {
listInterruptedPendingSessionIds,
setOnSessionTurnEndedPersisted,
} from '../sessionActiveTurn';
-import {
- dismissErrorMessage,
- rebroadcastAgentSwitchBoundary,
-} from './messages';
+import { dismissErrorMessage, rebroadcastAgentSwitchBoundary } from './messages';
import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer.js';
import { removeTurnChangeSetsForSession } from '../../turn-change-set/store.js';
import { quiesceSessionBeforeWorktreeRecycle } from './sessionRemovalOperations.js';
+import { withSessionRouteLock, withSessionRouteLocks } from '../sessionRouteLock.js';
const log = createLogger('sessions');
const REMOTE_EDITABLE_META = new Set(['status', 'title', 'pinnedAt']);
@@ -64,6 +62,10 @@ const initialSessionListLogged = new Set<string>();
const SLOW_SESSION_LIST_MS = 250;
type OwnerScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null;
type SessionRemovalCancelOperations = (sessionId: string) => Promise<void>;
+export interface SessionRecycleScope {
+ ownerScope: OwnerScope;
+ mediaDb: DbClient['drizzle'];
+}
let sessionRemovalCancelOperations: SessionRemovalCancelOperations | null = null;
@@ -94,6 +96,50 @@ function isOwnerScopeCurrent(scope: OwnerScope): boolean {
}
}
+async function withStatusWriteLock<T>(
+ sessionId: string,
+ status: unknown,
+ task: () => Promise<T>,
+): Promise<T> {
+ if (status === undefined) return task();
+ return withSessionRouteLock(sessionId, task);
+}
+
+async function writeSessionPatch(
+ db: DbClient['drizzle'],
+ sessionId: string,
+ setObj: ReturnType<typeof sessionPatchToRow>,
+ status: unknown,
+): Promise<void> {
+ const deletedIsTerminal = status === 'active' || status === 'archived';
+ const result = await db
+ .update(sessions)
+ .set(setObj)
+ .where(
+ deletedIsTerminal
+ ? and(eq(sessions.id, sessionId), ne(sessions.status, 'deleted'))
+ : eq(sessions.id, sessionId),
+ )
+ .run();
+ if (!deletedIsTerminal || result.changes > 0) return;
+
+ const [existing] = await db
+ .select({ id: sessions.id })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId));
+ if (!existing) throwIpcError('NOT_FOUND', 'Session 不存在');
+ throwIpcError('PRECONDITION_FAILED', '已删除的任务不能恢复或归档');
+}
+
+export function captureSessionRecycleScope(
+ dbClient: DbClient = getDbClient(),
+): SessionRecycleScope {
+ return {
+ ownerScope: captureOwnerScope(),
+ mediaDb: dbClient.drizzle,
+ };
+}
+
function getSafeOwnerPushStamp(): ReturnType<typeof broadcastTap.getSafeDataOwnerPushStamp> {
try {
return broadcastTap.getSafeDataOwnerPushStamp?.();
@@ -169,22 +215,31 @@ function broadcastWorktreeChanged(sessionId: string): void {
export async function recycleSessionWorktreeForStatusChange(
sessionId: string,
status: unknown,
+ capturedScope?: SessionRecycleScope,
): Promise<void> {
if (status !== 'deleted' && status !== 'archived') return;
try {
+ // Callers that already crossed an async status write pass the owner/DB
+ // captured at operation entry. The fallback is only for direct callers.
+ const ownerScope = capturedScope?.ownerScope ?? captureOwnerScope();
+ const mediaDb = capturedScope?.mediaDb ?? getDbClient().drizzle;
+ if (!isOwnerScopeCurrent(ownerScope)) return;
const cancelOperations = sessionRemovalCancelOperations;
if (!cancelOperations) {
throw new Error('iOS Simulator session cleanup is not configured');
}
- const [mh, recycle, routeLock] = await Promise.all([
+ const [mh, recycle] = await Promise.all([
import('../../maker-host/index.js'),
import('../../worktree/sessionRemovalRecycle.js'),
- import('../../maker-ipc/register.js'),
]);
- if (!(await recycle.isSessionStillRemovable(sessionId))) return;
- const shouldRecycle = await routeLock.withSendToSessionLock(sessionId, async () =>
- quiesceSessionBeforeWorktreeRecycle(sessionId, {
- isSessionStillRemovable: recycle.isSessionStillRemovable,
+ const ownerIsCurrent = (): boolean => isOwnerScopeCurrent(ownerScope);
+ const isStillRemovable = async (id: string): Promise<boolean> =>
+ ownerIsCurrent() && recycle.isSessionStillRemovable(id, mediaDb);
+ if (!(await isStillRemovable(sessionId))) return;
+ await withSessionRouteLock(sessionId, async () => {
+ const shouldRecycle = await quiesceSessionBeforeWorktreeRecycle(sessionId, {
+ isOwnerCurrent: ownerIsCurrent,
+ isSessionStillRemovable: isStillRemovable,
cancelSessionOperations: cancelOperations,
closeSession: async (id) => {
await mh
@@ -192,10 +247,28 @@ export async function recycleSessionWorktreeForStatusChange(
?.closeSession(id)
.catch(() => undefined);
},
- }),
- );
- if (!shouldRecycle) return;
- await recycle.recycleWorktreeForRemovedSession(sessionId);
+ });
+ if (!shouldRecycle || !ownerIsCurrent()) return;
+
+ // Keep irreversible cleanup under the same task route lock as the final
+ // status check. A concurrent restore/start/send must not slip between
+ // quiescence and ref/worktree deletion.
+ await removeDeletedSessionMediaRefs(sessionId, mediaDb)
+ .then((count) => {
+ if (count > 0) log.info('session media refs removed', { sessionId, count });
+ })
+ .catch((err) => {
+ log.warn('session media ref cleanup failed', {
+ sessionId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ });
+ if (!ownerIsCurrent()) return;
+ await recycle.recycleWorktreeForRemovedSession(sessionId, {
+ db: mediaDb,
+ isOwnerCurrent: ownerIsCurrent,
+ });
+ });
} catch (err) {
log.warn('worktree recycle after session status change failed', {
sessionId,
@@ -206,8 +279,12 @@ export async function recycleSessionWorktreeForStatusChange(
}
}
-function scheduleWorktreeRecycleForStatusChange(sessionId: string, status: unknown): void {
- void recycleSessionWorktreeForStatusChange(sessionId, status);
+function scheduleWorktreeRecycleForStatusChange(
+ sessionId: string,
+ status: unknown,
+ capturedScope?: SessionRecycleScope,
+): void {
+ void recycleSessionWorktreeForStatusChange(sessionId, status, capturedScope);
}
// shadow savepoint 链(refs/cindy/savepoints/<sid>)刻意**不**挂 status 变化
@@ -1183,38 +1260,42 @@ export function registerSessionIpc(
}
const db = getDbClient().drizzle;
- // 显式 .run() 才能从生产 DbClient.drizzle proxy 拿到 changes;隐式 await
- // 会丢弃写结果。CAS 是否命中必须以该原子 UPDATE 的 changes 判定。
- const writeResult = await db
- .update(sessions)
- .set(sessionPatchToRow({ status: 'active' }))
- .where(
- and(
- eq(sessions.id, sid),
- eq(sessions.status, 'archived'),
- expectedWorkingDir === null
- ? isNull(sessions.workingDir)
- : eq(sessions.workingDir, expectedWorkingDir),
- eq(sessions.workspaceKind, expectedWorkspaceKind),
- expectedRemoteHostId === null
- ? isNull(sessions.remoteHostId)
- : eq(sessions.remoteHostId, expectedRemoteHostId),
- ),
- )
- .run();
-
- if (writeResult.changes === 0) {
- const [existing] = await db
- .select({ id: sessions.id })
- .from(sessions)
- .where(eq(sessions.id, sid));
- if (!existing) throwIpcError('NOT_FOUND', 'Session 不存在');
- return null;
- }
-
- const row = await selectSessionWithCount(db, sid);
- if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');
- const updated = sessionToCamel(row);
+ const updated = await withSessionRouteLock(sid, async () => {
+ if (!isOwnerScopeCurrent(ownerScope)) return null;
+ // 显式 .run() 才能从生产 DbClient.drizzle proxy 拿到 changes;隐式 await
+ // 会丢弃写结果。CAS 是否命中必须以该原子 UPDATE 的 changes 判定。
+ const writeResult = await db
+ .update(sessions)
+ .set(sessionPatchToRow({ status: 'active' }))
+ .where(
+ and(
+ eq(sessions.id, sid),
+ eq(sessions.status, 'archived'),
+ expectedWorkingDir === null
+ ? isNull(sessions.workingDir)
+ : eq(sessions.workingDir, expectedWorkingDir),
+ eq(sessions.workspaceKind, expectedWorkspaceKind),
+ expectedRemoteHostId === null
+ ? isNull(sessions.remoteHostId)
+ : eq(sessions.remoteHostId, expectedRemoteHostId),
+ ),
+ )
+ .run();
+
+ if (writeResult.changes === 0) {
+ const [existing] = await db
+ .select({ id: sessions.id })
+ .from(sessions)
+ .where(eq(sessions.id, sid));
+ if (!existing) throwIpcError('NOT_FOUND', 'Session 不存在');
+ return null;
+ }
+
+ const row = await selectSessionWithCount(db, sid);
+ if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');
+ return sessionToCamel(row);
+ });
+ if (!updated) return null;
notifyAgentIslandSessionPatch(updated.id, {
status: updated.status,
title: updated.title,
@@ -1296,7 +1377,7 @@ export function registerSessionIpc(
// 先记号后写库,代价只是写库失败时该会话本进程内不再自动起名 —— 用户毕竟确实
// 按下过保存,这个方向的偏差是安全的。
if (typeof p.title === 'string') noteUserTitleWritten(sid);
- await db.update(sessions).set(setObj).where(eq(sessions.id, sid));
+ await withStatusWriteLock(sid, p.status, () => writeSessionPatch(db, sid, setObj, p.status));
// session-git-pr-context:/clear 经此处写 clearedAt——边界之前的消息对用户
// 不可见,PR 引用同步重算(fire-and-forget,内部按 clearedAt/rewindAt 过滤)。
if (p.clearedAt !== undefined) {
@@ -1378,7 +1459,7 @@ export function registerSessionIpc(
workingDir: updated.workingDir,
workspaceKind: updated.workspaceKind,
});
- scheduleWorktreeRecycleForStatusChange(sid, p.status);
+ scheduleWorktreeRecycleForStatusChange(sid, p.status, { ownerScope, mediaDb: db });
notifyGhostSessionStatusChange(sid, p.status, updated.workingDir);
removeHookAttachmentDir(sid, p.status);
return updated;
@@ -1445,10 +1526,12 @@ export async function patchSessionMetaInDb(
const setObj = sessionPatchToRow(patch, { bumpUpdatedAt: false });
// 控制端远程改名走这条,与本机改名同口径(同样先记号后写库)。
if (patch.title !== undefined) noteUserTitleWritten(sessionId);
- await db.update(sessions).set(setObj).where(eq(sessions.id, sessionId));
- const row = await selectSessionWithCount(db, sessionId);
- if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');
- const updated = sessionToCamel(row);
+ const updated = await withStatusWriteLock(sessionId, patch.status, async () => {
+ await writeSessionPatch(db, sessionId, setObj, patch.status);
+ const row = await selectSessionWithCount(db, sessionId);
+ if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');
+ return sessionToCamel(row);
+ });
notifyAgentIslandSessionPatch(updated.id, {
status: updated.status,
title: updated.title,
@@ -1462,19 +1545,6 @@ export async function patchSessionMetaInDb(
err: err instanceof Error ? err.message : String(err),
});
});
- // 媒体总仓对应清理:删本会话名下的媒体引用行(附件/导入/
- // 消息出生引用;画廊等持久引用不动),引用归零的 blob 交回收器。
- // fire-and-forget 与历史目录清理同语义:失败只警告,不阻塞删除。
- void removeSessionMediaRefs(sessionId)
- .then((n) => {
- if (n > 0) log.info('session media refs removed', { sessionId, count: n });
- })
- .catch((err) => {
- log.warn('session media ref cleanup failed', {
- sessionId,
- err: err instanceof Error ? err.message : String(err),
- });
- });
void removeWechatSessionAttachmentDir(sessionId).catch((err) => {
log.warn('WeChat session attachment cleanup failed', {
sessionId,
@@ -1483,7 +1553,7 @@ export async function patchSessionMetaInDb(
});
}
removeHookAttachmentDir(sessionId, patch.status);
- scheduleWorktreeRecycleForStatusChange(sessionId, patch.status);
+ scheduleWorktreeRecycleForStatusChange(sessionId, patch.status, { ownerScope, mediaDb: db });
notifyGhostSessionStatusChange(sessionId, patch.status, updated.workingDir);
// 远程 / MCP 改动绕过 renderer 乐观更新,故主动广播 sessions:patched:
// - sessionsStore.onPatched → patchLocal,即时反映到 sidebar(删/归档移出 active 桶、改名/置顶刷新);
@@ -1602,16 +1672,17 @@ export async function setSessionsStatusInDb(
): Promise<SessionStatusChangeRow[]> {
if (sessionIds.length === 0) return [];
const ownerScope = captureOwnerScope();
- const applied = await getDbClient()
- .tx('sessions.setStatus', { sessionIds, status })
- .catch((err) => {
+ const dbClient = getDbClient();
+ const applied = await withSessionRouteLocks(sessionIds, () =>
+ dbClient.tx('sessions.setStatus', { sessionIds, status }).catch((err) => {
const code = (err as { code?: string }).code;
const message = err instanceof Error ? err.message : String(err);
- if (code === 'NOT_FOUND' || code === 'INVALID_PARAMS') {
+ if (code === 'NOT_FOUND' || code === 'INVALID_PARAMS' || code === 'PRECONDITION_FAILED') {
throwIpcError(code, message);
}
throw err;
- });
+ }),
+ );
if (!isOwnerScopeCurrent(ownerScope))
return applied.map((item) => ({
sessionId: item.sessionId,
@@ -1627,7 +1698,10 @@ export async function setSessionsStatusInDb(
workspaceKind: item.workspaceKind,
});
broadcastSessionPatched(item.sessionId, { status: item.status }, ownerScope);
- scheduleWorktreeRecycleForStatusChange(item.sessionId, item.status);
+ scheduleWorktreeRecycleForStatusChange(item.sessionId, item.status, {
+ ownerScope,
+ mediaDb: dbClient.drizzle,
+ });
notifyGhostSessionStatusChange(item.sessionId, item.status, item.workingDir);
removeHookAttachmentDir(item.sessionId, item.status);
}
@@ -1646,13 +1720,12 @@ export async function setSessionsStatusInDb(
function removeHookAttachmentDir(sessionId: string, status: unknown): void {
if (status !== 'deleted' && status !== 'archived') return;
if (status === 'deleted') {
- void removeTurnChangeSetsForSession(sessionId)
- .catch((err) => {
- log.warn('turn change-set cleanup failed', {
- sessionId,
- err: err instanceof Error ? err.message : String(err),
- });
+ void removeTurnChangeSetsForSession(sessionId).catch((err) => {
+ log.warn('turn change-set cleanup failed', {
+ sessionId,
+ err: err instanceof Error ? err.message : String(err),
});
+ });
}
const attachRoot = path.join(app.getPath('userData'), 'hook-attachments');
const attachDir = path.join(attachRoot, sessionId);
diff --git a/apps/desktop/src/main/localDb/orcaTeamStore.ts b/apps/desktop/src/main/localDb/orcaTeamStore.ts
index 98d26d2d3b..ee4beee359 100644
--- a/apps/desktop/src/main/localDb/orcaTeamStore.ts
+++ b/apps/desktop/src/main/localDb/orcaTeamStore.ts
@@ -1,5 +1,5 @@
import { BrowserWindow } from 'electron';
-import { and, desc, eq, inArray, ne, sql } from 'drizzle-orm';
+import { and, desc, eq, inArray, ne } from 'drizzle-orm';
import { createId } from '@paralleldrive/cuid2';
import { getDbClient } from './client/current.js';
@@ -246,20 +246,12 @@ export async function markTeamEnded(
* orca_role 字段保留 'worker' 不动 — 历史上下文识别需要它。
*/
export async function archiveWorkersByTeam(teamId: string): Promise<string[]> {
- const db = getDbClient().drizzle;
- const rows = await db
- .select({ sessionId: orcaWorkers.sessionId })
- .from(orcaWorkers)
- .where(eq(orcaWorkers.teamId, teamId));
- const ids = rows.map((r) => r.sessionId);
- if (ids.length === 0) return [];
- const now = Date.now();
- await db
- .update(sessions)
- .set({ status: 'archived', updatedAt: now })
- .where(sql`${sessions.id} IN (${sql.join(ids.map((id) => sql`${id}`), sql`, `)})`);
- for (const id of ids) broadcastSessionPatch(id, { status: 'archived' });
- return ids;
+ const updatedIds = await getDbClient().tx('orca.archiveWorkersByTeam', {
+ teamId,
+ now: Date.now(),
+ });
+ for (const id of updatedIds) broadcastSessionPatch(id, { status: 'archived' });
+ return updatedIds;
}
/**
@@ -291,37 +283,12 @@ export async function markWorkersStatusByTeam(
export async function reconcileInactiveTeamWorkersForLead(
leadSessionId: string,
): Promise<string[]> {
- const db = getDbClient().drizzle;
- const teamRows = await db
- .select({ id: orcaTeams.id })
- .from(orcaTeams)
- .where(and(eq(orcaTeams.leadSessionId, leadSessionId), ne(orcaTeams.status, 'active')));
- const teamIds = teamRows.map((r) => r.id);
- if (teamIds.length === 0) return [];
-
- // 这些非 active team 下仍 active 的孤儿 worker session。只取 status='active':已 archived 的
- // 无需再动,已被用户软删除的 status='deleted' 必须原样保留(不能借 reconcile 复活)。
- const workerRows = await db
- .select({ sessionId: orcaWorkers.sessionId })
- .from(orcaWorkers)
- .innerJoin(sessions, eq(orcaWorkers.sessionId, sessions.id))
- .where(and(inArray(orcaWorkers.teamId, teamIds), eq(sessions.status, 'active')));
- const ids = workerRows.map((r) => r.sessionId);
-
- const now = Date.now();
- // orca_workers 收敛 done(对齐 markWorkersStatusByTeam;已 done 的重写无副作用)。
- await db
- .update(orcaWorkers)
- .set({ status: 'done', updatedAt: now })
- .where(inArray(orcaWorkers.teamId, teamIds));
-
- if (ids.length === 0) return [];
- await db
- .update(sessions)
- .set({ status: 'archived', updatedAt: now })
- .where(inArray(sessions.id, ids));
- for (const id of ids) broadcastSessionPatch(id, { status: 'archived' });
- return ids;
+ const updatedIds = await getDbClient().tx('orca.reconcileInactiveTeamWorkersForLead', {
+ leadSessionId,
+ now: Date.now(),
+ });
+ for (const id of updatedIds) broadcastSessionPatch(id, { status: 'archived' });
+ return updatedIds;
}
export async function getTeamByWorkerSession(
@@ -545,8 +512,12 @@ export async function setWorkerFocus(teamId: string, workerId: string): Promise<
export async function archiveSingleWorkerSession(sessionId: string): Promise<void> {
const db = getDbClient().drizzle;
const now = Date.now();
- await db.update(sessions).set({ status: 'archived', updatedAt: now }).where(eq(sessions.id, sessionId));
- broadcastSessionPatch(sessionId, { status: 'archived' });
+ const result = await db
+ .update(sessions)
+ .set({ status: 'archived', updatedAt: now })
+ .where(and(eq(sessions.id, sessionId), ne(sessions.status, 'deleted')))
+ .run();
+ if (result.changes > 0) broadcastSessionPatch(sessionId, { status: 'archived' });
}
export async function setSessionOrcaRole(
diff --git a/apps/desktop/src/main/localDb/sessionRouteLock.ts b/apps/desktop/src/main/localDb/sessionRouteLock.ts
new file mode 100644
index 0000000000..631b6ab35c
--- /dev/null
+++ b/apps/desktop/src/main/localDb/sessionRouteLock.ts
@@ -0,0 +1,35 @@
+/**
+ * Shared bridge to the Host's per-task send/route lock.
+ *
+ * The lock itself remains owned by maker-ipc. Local DB status writers and
+ * destructive task cleanup use this injected bridge so a restore/status change
+ * cannot cross the final removable check and irreversible media/worktree
+ * cleanup. Tests and DB-only tools fall back to direct execution.
+ */
+
+export type SessionRouteLock = <T>(sessionId: string, task: () => Promise<T>) => Promise<T>;
+
+const passthroughLock: SessionRouteLock = async (_sessionId, task) => task();
+let routeLock: SessionRouteLock = passthroughLock;
+
+export function setSessionRouteLockImplementation(lock: SessionRouteLock | null): void {
+ routeLock = lock ?? passthroughLock;
+}
+
+export function withSessionRouteLock<T>(sessionId: string, task: () => Promise<T>): Promise<T> {
+ return routeLock(sessionId, task);
+}
+
+/** Acquire a batch in stable order so reversed overlapping batches cannot deadlock. */
+export function withSessionRouteLocks<T>(
+ sessionIds: readonly string[],
+ task: () => Promise<T>,
+): Promise<T> {
+ const ordered = [...new Set(sessionIds)].sort();
+ const acquire = (index: number): Promise<T> => {
+ const sessionId = ordered[index];
+ if (sessionId === undefined) return task();
+ return routeLock(sessionId, () => acquire(index + 1));
+ };
+ return acquire(0);
+}
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 467e77c697..b6d8c8ea17 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -67,6 +67,10 @@ export function tx(db: Database.Database, args: unknown): unknown {
return orcaRemoveWorker(db, txArgs);
case 'orca.cancelStaleTeams':
return orcaCancelStaleTeams(db, txArgs);
+ case 'orca.archiveWorkersByTeam':
+ return orcaArchiveWorkersByTeam(db, txArgs);
+ case 'orca.reconcileInactiveTeamWorkersForLead':
+ return orcaReconcileInactiveTeamWorkersForLead(db, txArgs);
case 'sessions.renameTitles':
return sessionsRenameTitles(db, txArgs);
case 'sessions.setStatus':
@@ -405,7 +409,7 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{
throw invalidArgs(`invalid status: ${status}`);
}
const selectSession = db.prepare(
- 'SELECT id, title, working_dir AS workingDir, workspace_kind AS workspaceKind FROM sessions WHERE id = ? LIMIT 1',
+ 'SELECT id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, status FROM sessions WHERE id = ? LIMIT 1',
);
const updateSession = db.prepare(
'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind',
@@ -424,6 +428,11 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{
if (!existing) {
throw Object.assign(new Error(`Session 不存在: ${sessionId}`), { code: 'NOT_FOUND' });
}
+ if ((existing as { status?: unknown }).status === 'deleted') {
+ throw Object.assign(new Error(`已删除的任务不能恢复或归档: ${sessionId}`), {
+ code: 'PRECONDITION_FAILED',
+ });
+ }
const updated = updateSession.get(status, now, sessionId) as
| { id: string; title: string | null; workingDir: string | null; workspaceKind: string | null }
| undefined;
@@ -1332,13 +1341,13 @@ function orcaRemoveWorker(db: Database.Database, args: unknown): string | null {
const now = expectNumber(payload.now, 'now');
const selectWorker = db.prepare('SELECT session_id AS sessionId FROM orca_workers WHERE id = ? LIMIT 1');
const deleteWorker = db.prepare('DELETE FROM orca_workers WHERE id = ?');
- const archiveSession = db.prepare("UPDATE sessions SET status = 'archived', orca_role = NULL, updated_at = ? WHERE id = ?");
+ const archiveSession = db.prepare("UPDATE sessions SET status = 'archived', orca_role = NULL, updated_at = ? WHERE id = ? AND status != 'deleted'");
const transaction = db.transaction(() => {
const row = selectWorker.get(workerId) as { sessionId: string } | undefined;
if (!row) return null;
deleteWorker.run(workerId);
- archiveSession.run(now, row.sessionId);
- return row.sessionId;
+ const archived = archiveSession.run(now, row.sessionId);
+ return archived.changes > 0 ? row.sessionId : null;
});
return transaction() as string | null;
}
@@ -1354,6 +1363,71 @@ function orcaCancelStaleTeams(db: Database.Database, args: unknown): void {
})();
}
+function orcaArchiveWorkersByTeam(db: Database.Database, args: unknown): string[] {
+ const payload = asRecord(args, 'orca.archiveWorkersByTeam args');
+ const teamId = expectString(payload.teamId, 'teamId');
+ const now = expectNumber(payload.now, 'now');
+ const selectCandidates = db.prepare(
+ `SELECT sessions.id
+ FROM orca_workers
+ INNER JOIN sessions ON orca_workers.session_id = sessions.id
+ WHERE orca_workers.team_id = ? AND sessions.status = 'active'
+ ORDER BY sessions.id`,
+ );
+ const archiveSession = db.prepare(
+ "UPDATE sessions SET status = 'archived', updated_at = ? WHERE id = ? AND status = 'active'",
+ );
+ const transaction = db.transaction(() => {
+ const candidates = selectCandidates.all(teamId) as Array<{ id: string }>;
+ const updatedIds: string[] = [];
+ for (const { id } of candidates) {
+ if (archiveSession.run(now, id).changes > 0) updatedIds.push(id);
+ }
+ return updatedIds;
+ });
+ return transaction() as string[];
+}
+
+function orcaReconcileInactiveTeamWorkersForLead(
+ db: Database.Database,
+ args: unknown,
+): string[] {
+ const payload = asRecord(args, 'orca.reconcileInactiveTeamWorkersForLead args');
+ const leadSessionId = expectString(payload.leadSessionId, 'leadSessionId');
+ const now = expectNumber(payload.now, 'now');
+ const selectCandidates = db.prepare(
+ `SELECT sessions.id
+ FROM orca_workers
+ INNER JOIN orca_teams ON orca_workers.team_id = orca_teams.id
+ INNER JOIN sessions ON orca_workers.session_id = sessions.id
+ WHERE orca_teams.lead_session_id = ?
+ AND orca_teams.status != 'active'
+ AND sessions.status = 'active'
+ ORDER BY sessions.id`,
+ );
+ const finishWorkers = db.prepare(
+ `UPDATE orca_workers
+ SET status = 'done', updated_at = ?
+ WHERE team_id IN (
+ SELECT id FROM orca_teams
+ WHERE lead_session_id = ? AND status != 'active'
+ )`,
+ );
+ const archiveSession = db.prepare(
+ "UPDATE sessions SET status = 'archived', updated_at = ? WHERE id = ? AND status = 'active'",
+ );
+ const transaction = db.transaction(() => {
+ const candidates = selectCandidates.all(leadSessionId) as Array<{ id: string }>;
+ finishWorkers.run(now, leadSessionId);
+ const updatedIds: string[] = [];
+ for (const { id } of candidates) {
+ if (archiveSession.run(now, id).changes > 0) updatedIds.push(id);
+ }
+ return updatedIds;
+ });
+ return transaction() as string[];
+}
+
function orcaUpsertWorker(db: Database.Database, args: unknown): void {
const payload = asRecord(args, 'orca.upsertWorker args');
const id = expectString(payload.id, 'id');
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
index 2377f16c24..781ec9d522 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
@@ -1,4 +1,4 @@
-import { mkdir, stat, truncate, writeFile } from 'node:fs/promises';
+import { mkdir, rm, stat, truncate, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -44,12 +44,184 @@ describe('IOSSimulatorMediaCapture', () => {
expect.objectContaining({
mimeType: 'image/png',
refs: [
- expect.objectContaining({ refKind: 'session-attachment', originSessionId: 'session-a' }),
+ expect.objectContaining({
+ refKind: 'session-attachment',
+ refId: 'session-a',
+ originSessionId: 'session-a',
+ }),
],
}),
);
});
+ it('does not ingest a screenshot after its data owner changes during capture', async () => {
+ let ownerScopeKey = 'owner-a';
+ const ingest = vi.fn();
+ const run = vi.fn(async (_command: string, args: readonly string[]) => {
+ const output = args.at(-1)!;
+ await mkdir(path.dirname(output), { recursive: true });
+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1]));
+ ownerScopeKey = 'owner-b';
+ return { stdout: '', stderr: '', exitCode: 0 };
+ });
+ const capture = new IOSSimulatorMediaCapture({
+ commandRunner: { run },
+ ingest,
+ getOwnerScopeKey: () => ownerScopeKey,
+ isOwnerScopeCurrent: (expected) => ownerScopeKey === expected,
+ });
+
+ await expect(
+ capture.takeScreenshot({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ source: 'agent',
+ }),
+ ).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });
+ expect(ingest).not.toHaveBeenCalled();
+ });
+
+ it('quiesces a screenshot before task cleanup and prevents a late session reference', async () => {
+ let markCaptureStarted: () => void = () => undefined;
+ let markCaptureFinished: () => void = () => undefined;
+ let releaseCapture: () => void = () => undefined;
+ const captureStarted = new Promise<void>((resolve) => {
+ markCaptureStarted = resolve;
+ });
+ const captureGate = new Promise<void>((resolve) => {
+ releaseCapture = resolve;
+ });
+ const captureFinished = new Promise<void>((resolve) => {
+ markCaptureFinished = resolve;
+ });
+ const ingest = vi.fn();
+ const run = vi.fn(async (_command: string, args: readonly string[]) => {
+ markCaptureStarted();
+ await captureGate;
+ const output = args.at(-1)!;
+ await mkdir(path.dirname(output), { recursive: true });
+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1]));
+ markCaptureFinished();
+ return { stdout: '', stderr: '', exitCode: 0 };
+ });
+ const capture = new IOSSimulatorMediaCapture({ commandRunner: { run }, ingest });
+
+ const screenshot = capture.takeScreenshot({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ source: 'agent',
+ });
+ await captureStarted;
+ await expect(capture.discardSession('session-a')).resolves.toBeUndefined();
+ await expect(screenshot).rejects.toMatchObject({ code: 'MUTATION_CANCELLED' });
+
+ releaseCapture();
+ await captureFinished;
+ await Promise.resolve();
+ expect(ingest).not.toHaveBeenCalled();
+ });
+
+ it('does not poison media storage while screenshot capture itself is slow', async () => {
+ let releaseFirstCapture: () => void = () => undefined;
+ let markFirstCaptureStarted: () => void = () => undefined;
+ const firstCaptureStarted = new Promise<void>((resolve) => {
+ markFirstCaptureStarted = resolve;
+ });
+ const firstCaptureGate = new Promise<void>((resolve) => {
+ releaseFirstCapture = resolve;
+ });
+ let captureCount = 0;
+ const run = vi.fn(async (_command: string, args: readonly string[]) => {
+ captureCount += 1;
+ if (captureCount === 1) {
+ markFirstCaptureStarted();
+ await firstCaptureGate;
+ }
+ const output = args.at(-1)!;
+ await mkdir(path.dirname(output), { recursive: true });
+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, captureCount]));
+ return { stdout: '', stderr: '', exitCode: 0 };
+ });
+ const ingest = vi.fn(async (params) => ({
+ hash: 'f'.repeat(64),
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: params.buffer.length,
+ url: `cindy-media://blobs/${'f'.repeat(64)}.png`,
+ deduplicated: false,
+ refIds: ['ref-screenshot'],
+ }));
+ const capture = new IOSSimulatorMediaCapture({ commandRunner: { run }, ingest });
+
+ vi.useFakeTimers();
+ const first = capture.takeScreenshot({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ source: 'agent',
+ });
+ await firstCaptureStarted;
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(ingest).not.toHaveBeenCalled();
+
+ releaseFirstCapture();
+ await expect(first).resolves.toMatchObject({ refIds: ['ref-screenshot'] });
+ await expect(
+ capture.takeScreenshot({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-b',
+ instanceId: 'instance-b',
+ source: 'user',
+ }),
+ ).resolves.toMatchObject({ refIds: ['ref-screenshot'] });
+ expect(run).toHaveBeenCalledTimes(2);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('bounds only screenshot ingest and poisons later media when storage never settles', async () => {
+ const run = vi.fn(async (_command: string, args: readonly string[]) => {
+ const output = args.at(-1)!;
+ await mkdir(path.dirname(output), { recursive: true });
+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1]));
+ return { stdout: '', stderr: '', exitCode: 0 };
+ });
+ const ingest = vi.fn(() => new Promise<never>(() => undefined));
+ const launch = vi.fn();
+ const capture = new IOSSimulatorMediaCapture({
+ commandRunner: { run },
+ ingest,
+ recordingLauncher: { launch },
+ });
+
+ vi.useFakeTimers();
+ const screenshot = capture.takeScreenshot({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ source: 'agent',
+ });
+ const screenshotFailure = expect(screenshot).rejects.toMatchObject({
+ code: 'SCREENSHOT_CAPTURE_FAILED',
+ });
+ await vi.waitFor(() => expect(ingest).toHaveBeenCalledOnce());
+ await vi.advanceTimersByTimeAsync(30_000);
+
+ await screenshotFailure;
+ await expect(
+ capture.startRecording({
+ simulatorUdid: 'EXACT-UDID-2',
+ sessionId: 'session-b',
+ instanceId: 'instance-b',
+ generation: 1,
+ source: 'agent',
+ }),
+ ).rejects.toMatchObject({ code: 'RECORDING_FAILED' });
+ expect(launch).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
it('records an exact UDID and ingests the finalized MOV through cindy-media', async () => {
const ingest = vi.fn(async (params) => ({
hash: 'b'.repeat(64),
@@ -104,12 +276,138 @@ describe('IOSSimulatorMediaCapture', () => {
expect(ingest).toHaveBeenCalledWith(
expect.objectContaining({
mimeType: 'video/quicktime',
- refs: [expect.objectContaining({ refKind: 'session-attachment', originKind: 'user' })],
+ refs: [
+ expect.objectContaining({
+ refKind: 'session-attachment',
+ refId: 'session-a',
+ originKind: 'user',
+ }),
+ ],
}),
);
await expect(stat(path.dirname(launchArgs.at(-1)!))).rejects.toMatchObject({ code: 'ENOENT' });
});
+ it('does not ingest a recording after its data owner changes during finalization', async () => {
+ let ownerScopeKey = 'owner-a';
+ let videoPath = '';
+ let resolveExit: () => void = () => undefined;
+ const ingest = vi.fn();
+ const capture = new IOSSimulatorMediaCapture({
+ ingest,
+ getOwnerScopeKey: () => ownerScopeKey,
+ isOwnerScopeCurrent: (expected) => ownerScopeKey === expected,
+ recordingLauncher: {
+ launch: vi.fn((args: readonly string[]) => {
+ videoPath = args.at(-1)!;
+ return {
+ exited: new Promise<void>((resolve) => {
+ resolveExit = resolve;
+ }),
+ kill: vi.fn(async (signal: NodeJS.Signals) => {
+ if (signal !== 'SIGINT') return;
+ ownerScopeKey = 'owner-b';
+ await writeFile(videoPath, Buffer.from('mov-bytes'));
+ resolveExit();
+ }),
+ };
+ }),
+ },
+ });
+ const started = await capture.startRecording({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ source: 'agent',
+ });
+
+ await expect(
+ capture.stopRecording({
+ recordingId: started.recordingId,
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ }),
+ ).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });
+ expect(ingest).not.toHaveBeenCalled();
+ });
+
+ it('does not launch a queued recording after its data owner changes', async () => {
+ let ownerScopeKey = 'owner-a';
+ let firstVideoPath = '';
+ let resolveFirstExit: () => void = () => undefined;
+ let markIngestStarted: () => void = () => undefined;
+ let releaseIngest: () => void = () => undefined;
+ const ingestStarted = new Promise<void>((resolve) => {
+ markIngestStarted = resolve;
+ });
+ const ingestGate = new Promise<void>((resolve) => {
+ releaseIngest = resolve;
+ });
+ const ingest = vi.fn(async (params) => {
+ markIngestStarted();
+ await ingestGate;
+ params.assertStillValid?.();
+ return {
+ hash: 'c'.repeat(64),
+ ext: '.mov',
+ mimeType: 'video/quicktime',
+ bytes: params.buffer.length,
+ url: `cindy-media://blobs/${'c'.repeat(64)}.mov`,
+ deduplicated: false,
+ refIds: ['ref-video'],
+ };
+ });
+ const launch = vi.fn((args: readonly string[]) => {
+ firstVideoPath ||= args.at(-1)!;
+ return {
+ exited: new Promise<void>((resolve) => {
+ resolveFirstExit = resolve;
+ }),
+ kill: vi.fn(async (signal: NodeJS.Signals) => {
+ if (signal !== 'SIGINT') return;
+ await writeFile(firstVideoPath, Buffer.from('mov-bytes'));
+ resolveFirstExit();
+ }),
+ };
+ });
+ const capture = new IOSSimulatorMediaCapture({
+ ingest,
+ getOwnerScopeKey: () => ownerScopeKey,
+ isOwnerScopeCurrent: (expected) => ownerScopeKey === expected,
+ recordingLauncher: { launch },
+ });
+ const first = await capture.startRecording({
+ simulatorUdid: 'UDID-A',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ source: 'agent',
+ });
+ const stopping = capture.stopRecording({
+ recordingId: first.recordingId,
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ });
+ await ingestStarted;
+ const queuedStart = capture.startRecording({
+ simulatorUdid: 'UDID-B',
+ sessionId: 'session-a',
+ instanceId: 'instance-b',
+ generation: 1,
+ source: 'agent',
+ });
+
+ ownerScopeKey = 'owner-b';
+ releaseIngest();
+
+ await expect(stopping).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });
+ await expect(queuedStart).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });
+ expect(launch).toHaveBeenCalledOnce();
+ });
+
it('rejects oversized recordings before buffering them in Electron Main', async () => {
const ingest = vi.fn();
let videoPath = '';
@@ -195,7 +493,258 @@ describe('IOSSimulatorMediaCapture', () => {
).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });
});
- it('bounds cleanup when a discarded recording does not confirm SIGKILL', async () => {
+ it('discards every active recording owned by one session without touching another task', async () => {
+ const videoPaths: string[] = [];
+ const kills: Array<ReturnType<typeof vi.fn>> = [];
+ const capture = new IOSSimulatorMediaCapture({
+ recordingLauncher: {
+ launch: vi.fn((args: readonly string[]) => {
+ videoPaths.push(args.at(-1)!);
+ let resolveExit: () => void = () => undefined;
+ const exited = new Promise<void>((resolve) => {
+ resolveExit = resolve;
+ });
+ const kill = vi.fn((signal: NodeJS.Signals) => {
+ if (signal === 'SIGKILL') resolveExit();
+ });
+ kills.push(kill);
+ return { exited, kill };
+ }),
+ },
+ });
+ await capture.startRecording({
+ simulatorUdid: 'SESSION-A-UDID-1',
+ sessionId: 'session-a',
+ instanceId: 'instance-a-1',
+ generation: 1,
+ source: 'agent',
+ });
+ await capture.startRecording({
+ simulatorUdid: 'SESSION-B-UDID',
+ sessionId: 'session-b',
+ instanceId: 'instance-b',
+ generation: 1,
+ source: 'user',
+ });
+ await capture.startRecording({
+ simulatorUdid: 'SESSION-A-UDID-2',
+ sessionId: 'session-a',
+ instanceId: 'instance-a-2',
+ generation: 1,
+ source: 'user',
+ });
+
+ await capture.discardSession('session-a');
+
+ expect(kills[0]).toHaveBeenCalledWith('SIGKILL');
+ expect(kills[1]).not.toHaveBeenCalled();
+ expect(kills[2]).toHaveBeenCalledWith('SIGKILL');
+ await expect(stat(path.dirname(videoPaths[0]!))).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(stat(path.dirname(videoPaths[1]!))).resolves.toMatchObject({
+ isDirectory: expect.any(Function),
+ });
+ await expect(stat(path.dirname(videoPaths[2]!))).rejects.toMatchObject({ code: 'ENOENT' });
+
+ await capture.discardSession('session-b');
+ expect(kills[1]).toHaveBeenCalledWith('SIGKILL');
+ await expect(stat(path.dirname(videoPaths[1]!))).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('does not let another task pending ingest block session cleanup', async () => {
+ let videoPath = '';
+ let resolveExit: () => void = () => undefined;
+ let markIngestStarted: () => void = () => undefined;
+ let releaseIngest: () => void = () => undefined;
+ const ingestStarted = new Promise<void>((resolve) => {
+ markIngestStarted = resolve;
+ });
+ const ingestGate = new Promise<void>((resolve) => {
+ releaseIngest = resolve;
+ });
+ const ingest = vi.fn(async (params) => {
+ markIngestStarted();
+ await ingestGate;
+ params.assertStillValid?.();
+ return {
+ hash: 'd'.repeat(64),
+ ext: '.mov',
+ mimeType: 'video/quicktime',
+ bytes: params.buffer.length,
+ url: `cindy-media://blobs/${'d'.repeat(64)}.mov`,
+ deduplicated: false,
+ refIds: ['ref-video'],
+ };
+ });
+ const capture = new IOSSimulatorMediaCapture({
+ ingest,
+ recordingLauncher: {
+ launch: vi.fn((args: readonly string[]) => {
+ videoPath = args.at(-1)!;
+ return {
+ exited: new Promise<void>((resolve) => {
+ resolveExit = resolve;
+ }),
+ kill: vi.fn(async (signal: NodeJS.Signals) => {
+ if (signal !== 'SIGINT') return;
+ await writeFile(videoPath, Buffer.from('mov-bytes'));
+ resolveExit();
+ }),
+ };
+ }),
+ },
+ });
+ const started = await capture.startRecording({
+ simulatorUdid: 'SESSION-B-UDID',
+ sessionId: 'session-b',
+ instanceId: 'instance-b',
+ generation: 1,
+ source: 'agent',
+ });
+ const stopping = capture.stopRecording({
+ recordingId: started.recordingId,
+ sessionId: 'session-b',
+ instanceId: 'instance-b',
+ generation: 1,
+ });
+ await ingestStarted;
+
+ await expect(capture.discardSession('session-a')).resolves.toBeUndefined();
+
+ releaseIngest();
+ await expect(stopping).resolves.toMatchObject({ refIds: ['ref-video'] });
+ });
+
+ it('invalidates pending ingest without making session cleanup wait for it', async () => {
+ let videoPath = '';
+ let resolveExit: () => void = () => undefined;
+ let markIngestStarted: () => void = () => undefined;
+ let releaseIngest: () => void = () => undefined;
+ const ingestStarted = new Promise<void>((resolve) => {
+ markIngestStarted = resolve;
+ });
+ const ingestGate = new Promise<void>((resolve) => {
+ releaseIngest = resolve;
+ });
+ const ingest = vi.fn(async (params) => {
+ markIngestStarted();
+ await ingestGate;
+ params.assertStillValid?.();
+ return {
+ hash: 'e'.repeat(64),
+ ext: '.mov',
+ mimeType: 'video/quicktime',
+ bytes: params.buffer.length,
+ url: `cindy-media://blobs/${'e'.repeat(64)}.mov`,
+ deduplicated: false,
+ refIds: ['late-ref'],
+ };
+ });
+ const capture = new IOSSimulatorMediaCapture({
+ ingest,
+ recordingLauncher: {
+ launch: vi.fn((args: readonly string[]) => {
+ videoPath = args.at(-1)!;
+ return {
+ exited: new Promise<void>((resolve) => {
+ resolveExit = resolve;
+ }),
+ kill: vi.fn(async (signal: NodeJS.Signals) => {
+ if (signal !== 'SIGINT') return;
+ await writeFile(videoPath, Buffer.from('mov-bytes'));
+ resolveExit();
+ }),
+ };
+ }),
+ },
+ });
+ const started = await capture.startRecording({
+ simulatorUdid: 'SESSION-A-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ source: 'agent',
+ });
+ const stopping = capture.stopRecording({
+ recordingId: started.recordingId,
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ });
+ await ingestStarted;
+
+ const discarding = capture.discardSession('session-a');
+ let cleanupSettled = false;
+ void discarding.then(
+ () => {
+ cleanupSettled = true;
+ },
+ () => {
+ cleanupSettled = true;
+ },
+ );
+ await expect(stopping).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });
+ await Promise.resolve();
+ expect(cleanupSettled).toBe(false);
+
+ releaseIngest();
+ await expect(discarding).resolves.toBeUndefined();
+ expect(ingest).toHaveBeenCalledTimes(1);
+ });
+
+ it('bounds recording ingest even when storage never settles', async () => {
+ let videoPath = '';
+ const ingest = vi.fn(() => new Promise<never>(() => undefined));
+ const launch = vi.fn((args: readonly string[]) => {
+ videoPath = args.at(-1)!;
+ return {
+ exited: Promise.resolve(),
+ isAlive: () => false,
+ kill: vi.fn(),
+ };
+ });
+ const capture = new IOSSimulatorMediaCapture({
+ ingest,
+ recordingLauncher: { launch },
+ });
+ const started = await capture.startRecording({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ source: 'agent',
+ });
+ await writeFile(videoPath, Buffer.from('mov-bytes'));
+
+ vi.useFakeTimers();
+ const stopping = capture.stopRecording({
+ recordingId: started.recordingId,
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ });
+ await vi.waitFor(() => expect(ingest).toHaveBeenCalledTimes(1));
+ await vi.advanceTimersByTimeAsync(30_000);
+
+ await expect(stopping).rejects.toMatchObject({ code: 'RECORDING_FAILED' });
+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });
+ const cleanup = capture.discardSession('session-a');
+ const cleanupFailure = expect(cleanup).rejects.toMatchObject({ code: 'RECORDING_FAILED' });
+ await vi.advanceTimersByTimeAsync(30_000);
+ await cleanupFailure;
+ await expect(
+ capture.startRecording({
+ simulatorUdid: 'EXACT-UDID-2',
+ sessionId: 'session-b',
+ instanceId: 'instance-b',
+ generation: 1,
+ source: 'agent',
+ }),
+ ).rejects.toMatchObject({ code: 'RECORDING_FAILED' });
+ expect(launch).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('reports incomplete cleanup and retains tracking when SIGKILL is not confirmed', async () => {
let videoPath = '';
const kill = vi.fn();
const capture = new IOSSimulatorMediaCapture({
@@ -216,11 +765,19 @@ describe('IOSSimulatorMediaCapture', () => {
vi.useFakeTimers();
const discarded = capture.discardInstance('instance-a');
+ const rejection = expect(discarded).rejects.toMatchObject({ code: 'RECORDING_FAILED' });
await vi.advanceTimersByTimeAsync(500);
- await discarded;
+ await rejection;
expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGKILL']);
- await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(stat(path.dirname(videoPath))).resolves.toBeDefined();
+
+ const retry = capture.discardInstance('instance-a');
+ const retryRejection = expect(retry).rejects.toMatchObject({ code: 'RECORDING_FAILED' });
+ await vi.advanceTimersByTimeAsync(500);
+ await retryRejection;
+ expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGKILL', 'SIGKILL']);
+ await rm(path.dirname(videoPath), { recursive: true, force: true });
expect(vi.getTimerCount()).toBe(0);
});
@@ -261,7 +818,17 @@ describe('IOSSimulatorMediaCapture', () => {
expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGINT', 'SIGTERM', 'SIGKILL']);
expect(ingest).not.toHaveBeenCalled();
- await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(stat(path.dirname(videoPath))).resolves.toBeDefined();
+ await expect(
+ capture.startRecording({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 3,
+ source: 'agent',
+ }),
+ ).rejects.toMatchObject({ code: 'RECORDING_ALREADY_ACTIVE' });
+ await rm(path.dirname(videoPath), { recursive: true, force: true });
expect(vi.getTimerCount()).toBe(0);
});
@@ -339,6 +906,26 @@ describe('IOSSimulatorMediaCapture', () => {
expect(launch).not.toHaveBeenCalled();
});
+ it('rejects a queued recording start when session cleanup wins before registration', async () => {
+ const launch = vi.fn();
+ const capture = new IOSSimulatorMediaCapture({
+ recordingLauncher: { launch },
+ });
+
+ const starting = capture.startRecording({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ source: 'agent',
+ });
+ const discarding = capture.discardSession('session-a');
+
+ await expect(starting).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });
+ await expect(discarding).resolves.toBeUndefined();
+ expect(launch).not.toHaveBeenCalled();
+ });
+
it('synchronously kills active recorders on force-exit and rejects later starts', async () => {
let resolveExit: () => void = () => undefined;
let videoPath = '';
@@ -427,6 +1014,68 @@ describe('IOSSimulatorMediaCapture', () => {
expect(vi.getTimerCount()).toBe(0);
});
+ it('cleans active recorders before reporting a hung ingest during dispose', async () => {
+ const paths = new Map<string, string>();
+ const kills = new Map<string, ReturnType<typeof vi.fn>>();
+ const ingest = vi.fn(() => new Promise<never>(() => undefined));
+ const capture = new IOSSimulatorMediaCapture({
+ ingest,
+ recordingLauncher: {
+ launch: vi.fn((args: readonly string[]) => {
+ const instanceId = args[2] === 'UDID-A' ? 'instance-a' : 'instance-b';
+ paths.set(instanceId, args.at(-1)!);
+ const kill = vi.fn();
+ kills.set(instanceId, kill);
+ return {
+ exited: Promise.resolve(),
+ isAlive: () => false,
+ kill,
+ };
+ }),
+ },
+ });
+ const first = await capture.startRecording({
+ simulatorUdid: 'UDID-A',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ source: 'agent',
+ });
+ await writeFile(paths.get('instance-a')!, Buffer.from('mov-bytes'));
+ await capture.startRecording({
+ simulatorUdid: 'UDID-B',
+ sessionId: 'session-b',
+ instanceId: 'instance-b',
+ generation: 1,
+ source: 'agent',
+ });
+
+ vi.useFakeTimers();
+ const stopping = capture.stopRecording({
+ recordingId: first.recordingId,
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ });
+ await vi.waitFor(() => expect(ingest).toHaveBeenCalledTimes(1));
+ const disposing = capture.dispose();
+ const disposeFailure = expect(disposing).rejects.toMatchObject({ code: 'RECORDING_FAILED' });
+
+ await expect(stopping).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });
+ await vi.advanceTimersByTimeAsync(30_000);
+ await disposeFailure;
+
+ expect(kills.get('instance-a')).toHaveBeenCalledWith('SIGKILL');
+ expect(kills.get('instance-b')).toHaveBeenCalledWith('SIGKILL');
+ await expect(stat(path.dirname(paths.get('instance-a')!))).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+ await expect(stat(path.dirname(paths.get('instance-b')!))).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
it('regular dispose immediately kills both finalizing and active recorders', async () => {
const exits = new Map<string, () => void>();
const kills = new Map<string, ReturnType<typeof vi.fn>>();
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index 99bdcb0381..2b269c1425 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
@@ -895,11 +895,7 @@ describe('iOS Simulator host', () => {
const shutdownExact = vi
.fn<() => Promise<void>>()
.mockRejectedValueOnce(
- new IOSSimulatorInstanceError(
- 'SIMULATOR_SHUTDOWN_FAILED',
- 'simctl shutdown failed',
- true,
- ),
+ new IOSSimulatorInstanceError('SIMULATOR_SHUTDOWN_FAILED', 'simctl shutdown failed', true),
)
.mockResolvedValue(undefined);
const lifecycle: IOSSimulatorSimctlLifecycle = {
@@ -1870,15 +1866,7 @@ describe('iOS Simulator host', () => {
);
await vi.waitFor(() => expect(staleViewportDeferred.resolve).not.toBeNull());
await expect(
- host.setViewerVisibility(
- 'session-a',
- route,
- true,
- 'h264',
- undefined,
- 88,
- 'viewer-e-current',
- ),
+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 88, 'viewer-e-current'),
).resolves.toMatchObject({ ok: true });
staleViewportDeferred.resolve?.({ width: 393, height: 852 });
await expect(staleRemount).resolves.toMatchObject({
@@ -1886,15 +1874,7 @@ describe('iOS Simulator host', () => {
errorCode: 'INSTANCE_NOT_OWNED',
});
await expect(
- host.setViewerVisibility(
- 'session-a',
- route,
- false,
- 'h264',
- undefined,
- 88,
- 'viewer-d-stale',
- ),
+ host.setViewerVisibility('session-a', route, false, 'h264', undefined, 88, 'viewer-d-stale'),
).resolves.toMatchObject({ ok: true, data: { ignored: true } });
await expect(
@@ -3381,12 +3361,17 @@ describe('iOS Simulator host', () => {
return snapshot;
});
const build = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>();
+ const discardSession = vi.fn(async () => undefined);
const host = createIOSSimulatorHost({
actor,
lifecycle,
runtime: { inspect: vi.fn(async () => READY_REPORT) },
getSession,
projectBuilder: { build },
+ mediaCapture: {
+ discardSession,
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
});
await host.reconcileOwnership();
@@ -3404,6 +3389,8 @@ describe('iOS Simulator host', () => {
);
await finalReadStarted;
await host.cancelSessionOperations('session-a');
+ expect(discardSession).toHaveBeenCalledOnce();
+ expect(discardSession).toHaveBeenCalledWith('session-a');
resolveFinalRead();
await expect(buildPromise).resolves.toMatchObject({
@@ -3414,6 +3401,395 @@ describe('iOS Simulator host', () => {
await host.dispose();
});
+ it('does not register a recording after its task cancellation has completed', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ bootProvenance: 'preexisting',
+ });
+ let armed = false;
+ let armedReadCount = 0;
+ let signalFinalRead!: () => void;
+ const finalReadStarted = new Promise<void>((resolve) => {
+ signalFinalRead = resolve;
+ });
+ let resolveFinalRead!: () => void;
+ const getSession = vi.fn(async (id: string) => {
+ const snapshot = { ...localSession(id), status: 'active' as const };
+ if (armed && ++armedReadCount === 2) {
+ signalFinalRead();
+ await new Promise<void>((resolve) => {
+ resolveFinalRead = resolve;
+ });
+ }
+ return snapshot;
+ });
+ const startRecording = vi.fn(async () => ({
+ recordingId: 'late-recording',
+ startedAt: new Date().toISOString(),
+ }));
+ const discardSession = vi.fn(async () => undefined);
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession,
+ mediaCapture: {
+ startRecording,
+ discardSession,
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ });
+
+ await host.reconcileOwnership();
+ const instance = actor.list('session-a')[0]!;
+ armed = true;
+ const recordingPromise = host.callTool(
+ 'start_recording',
+ {
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ },
+ { sessionId: 'session-a', origin: 'user' },
+ );
+ await finalReadStarted;
+ await host.cancelSessionOperations('session-a');
+ resolveFinalRead();
+
+ await expect(recordingPromise).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ expect(startRecording).not.toHaveBeenCalled();
+ expect(discardSession).toHaveBeenCalledOnce();
+ await host.dispose();
+ });
+
+ it('does not capture a screenshot after its task cancellation has completed', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ bootProvenance: 'preexisting',
+ });
+ let armed = false;
+ let armedReadCount = 0;
+ let signalFinalRead!: () => void;
+ const finalReadStarted = new Promise<void>((resolve) => {
+ signalFinalRead = resolve;
+ });
+ let resolveFinalRead!: () => void;
+ const getSession = vi.fn(async (id: string) => {
+ const snapshot = { ...localSession(id), status: 'active' as const };
+ if (armed && ++armedReadCount === 2) {
+ signalFinalRead();
+ await new Promise<void>((resolve) => {
+ resolveFinalRead = resolve;
+ });
+ }
+ return snapshot;
+ });
+ const takeScreenshot = vi.fn(async () => ({
+ hash: 'a'.repeat(64),
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: 8,
+ url: `cindy-media://blobs/${'a'.repeat(64)}.png`,
+ deduplicated: false,
+ refIds: ['ref-a'],
+ }));
+ const discardSession = vi.fn(async () => undefined);
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession,
+ mediaCapture: {
+ takeScreenshot,
+ discardSession,
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ });
+
+ await host.reconcileOwnership();
+ const instance = actor.list('session-a')[0]!;
+ armed = true;
+ const screenshotPromise = host.callTool(
+ 'take_screenshot',
+ {
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ },
+ { sessionId: 'session-a', origin: 'user' },
+ );
+ await finalReadStarted;
+ await host.cancelSessionOperations('session-a');
+ resolveFinalRead();
+
+ await expect(screenshotPromise).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ expect(takeScreenshot).not.toHaveBeenCalled();
+ expect(discardSession).toHaveBeenCalledOnce();
+ await host.dispose();
+ });
+
+ it('does not block task removal when recording cleanup fails', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ const discardSession = vi.fn(async () => {
+ throw new Error('recording process did not exit');
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ mediaCapture: {
+ discardSession,
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ });
+
+ await expect(host.cancelSessionOperations('session-a')).resolves.toBeUndefined();
+ expect(discardSession).toHaveBeenCalledWith('session-a');
+ await host.dispose();
+ });
+
+ it('rejects queued screenshot and recording registration after instance teardown begins', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ bootProvenance: 'preexisting',
+ });
+ let markActiveStarted: () => void = () => undefined;
+ let releaseActive: () => void = () => undefined;
+ const activeStarted = new Promise<void>((resolve) => {
+ markActiveStarted = resolve;
+ });
+ const activeGate = new Promise<void>((resolve) => {
+ releaseActive = resolve;
+ });
+ let markDiscardStarted: () => void = () => undefined;
+ let releaseDiscard: () => void = () => undefined;
+ const discardStarted = new Promise<void>((resolve) => {
+ markDiscardStarted = resolve;
+ });
+ const discardGate = new Promise<void>((resolve) => {
+ releaseDiscard = resolve;
+ });
+ let discardCalls = 0;
+ const discardInstance = vi.fn(async () => {
+ discardCalls += 1;
+ if (discardCalls !== 1) return;
+ markDiscardStarted();
+ await discardGate;
+ });
+ const takeScreenshot = vi.fn(async () => ({
+ hash: 'a'.repeat(64),
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: 8,
+ url: `cindy-media://blobs/${'a'.repeat(64)}.png`,
+ deduplicated: false,
+ refIds: ['ref-a'],
+ }));
+ const startRecording = vi.fn(async () => ({
+ recordingId: 'late-recording',
+ startedAt: new Date().toISOString(),
+ }));
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ driverManager: {
+ get: vi.fn(() => null),
+ start: vi.fn(),
+ stop: vi.fn(async () => undefined),
+ },
+ mediaCapture: {
+ takeScreenshot,
+ startRecording,
+ discardInstance,
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ });
+
+ await host.reconcileOwnership();
+ const instance = actor.list('session-a')[0]!;
+ const route = {
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ };
+ await expect(
+ host.setAgentControlGrant('session-a', instance.instanceId, 'allowed'),
+ ).resolves.toMatchObject({ ok: true });
+ const active = actor.runMutation(
+ { sessionId: 'session-a', ...route },
+ async () => {
+ markActiveStarted();
+ await activeGate;
+ },
+ 'agent',
+ );
+ await activeStarted;
+
+ const screenshot = host.callTool('take_screenshot', route, {
+ sessionId: 'session-a',
+ origin: 'agent',
+ });
+ const recording = host.callTool('start_recording', route, {
+ sessionId: 'session-a',
+ origin: 'agent',
+ });
+ await vi.waitFor(() =>
+ expect(actor.mutationState(instance.instanceId)).toMatchObject({ queuedAgentMutations: 2 }),
+ );
+
+ const stopping = host.callTool('stop_instance', route, {
+ sessionId: 'session-a',
+ origin: 'user',
+ });
+ await discardStarted;
+ releaseActive();
+
+ await expect(screenshot).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ await expect(recording).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ expect(takeScreenshot).not.toHaveBeenCalled();
+ expect(startRecording).not.toHaveBeenCalled();
+
+ releaseDiscard();
+ await expect(stopping).resolves.toMatchObject({ ok: true });
+ await expect(active).resolves.toBeUndefined();
+ await host.dispose();
+ });
+
+ it.each(['stop_instance', 'detach_device'] as const)(
+ 'completes %s even when pending media cleanup times out',
+ async (toolName) => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => READY_REPORT.devices[0]!),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ const instance = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ bootProvenance: 'preexisting',
+ });
+ const discardInstance = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('raw media ingest did not become idle'))
+ .mockResolvedValue(undefined);
+ const stopDriver = vi.fn(async () => undefined);
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ driverManager: {
+ get: vi.fn(() => null),
+ start: vi.fn(),
+ stop: stopDriver,
+ },
+ mediaCapture: {
+ discardInstance,
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ });
+ await host.reconcileOwnership();
+ const current = actor.getOwned('session-a', instance.instanceId);
+ const route = {
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ };
+
+ await expect(
+ host.callTool(toolName, route, { sessionId: 'session-a', origin: 'user' }),
+ ).resolves.toMatchObject({
+ ok: true,
+ data: {
+ mediaCleanupWarning: { code: 'MEDIA_CLEANUP_INCOMPLETE' },
+ },
+ });
+ expect(discardInstance).toHaveBeenCalledWith(instance.instanceId);
+ expect(stopDriver).toHaveBeenCalledWith(instance.instanceId);
+ if (toolName === 'stop_instance') {
+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(instance.simulatorUdid);
+ expect(actor.list('session-a')[0]).toMatchObject({ lifecycleState: 'stopped' });
+ } else {
+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();
+ expect(actor.list('session-a')).toEqual([]);
+ }
+ await host.dispose();
+ },
+ );
+
it('shares exact attachment and lifecycle state while rejecting another session', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
index 046f66060c..f2d217ab9b 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
@@ -15,7 +15,11 @@ import {
type IOSSimulatorCommandRunner,
} from '@cindy/ios-simulator-runtime';
-import { ingestMedia, type IngestedMedia } from '../cindy-media/ingest.js';
+import { ingestMedia, type IngestedMedia, type IngestMediaParams } from '../cindy-media/ingest.js';
+import type { LedgerDb } from '../cindy-media/ledger.js';
+import { captureMediaRefCompensationScope } from '../cindy-media/refCompensationJournal.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
+import { tryGetDbClient } from '../localDb/client/current.js';
const MAX_SCREENSHOT_BYTES = 32 * 1024 * 1024;
// cindy-media currently ingests buffers. Keep the recording ceiling bounded to
@@ -26,11 +30,16 @@ const RECORDING_STOP_TIMEOUT_MS = 5_000;
const RECORDING_TERM_TIMEOUT_MS = 1_000;
const RECORDING_KILL_TIMEOUT_MS = 500;
const RECORDING_DISCARD_KILL_TIMEOUT_MS = 500;
+const RECORDING_INGEST_TIMEOUT_MS = 30_000;
+
+type IOSSimulatorMediaIngest = (params: IngestMediaParams) => Promise<IngestedMedia>;
export interface IOSSimulatorMediaCaptureOptions {
commandRunner?: IOSSimulatorCommandRunner;
- ingest?: typeof ingestMedia;
+ ingest?: IOSSimulatorMediaIngest;
recordingLauncher?: IOSSimulatorRecordingLauncher;
+ getOwnerScopeKey?: () => string;
+ isOwnerScopeCurrent?: (ownerScopeKey: string) => boolean;
}
export interface IOSSimulatorRecordingProcess {
@@ -64,6 +73,27 @@ interface ActiveRecording {
phase: 'active' | 'finalizing';
discardRequested: boolean;
discardSignalSent: boolean;
+ discarded: Promise<void>;
+ resolveDiscarded(): void;
+ sessionEpoch: number;
+ instanceEpoch: number;
+ ownerScopeKey: string;
+ ingestDb: LedgerDb | null;
+}
+
+interface IOSSimulatorMediaOwnerScope {
+ ownerScopeKey: string;
+ ingestDb: LedgerDb | null;
+}
+
+interface ActiveScreenshotRequest {
+ sessionId: string;
+ instanceId: string;
+ sessionEpoch: number;
+ ownerScope: IOSSimulatorMediaOwnerScope;
+ cancelled: boolean;
+ cancelledSignal: Promise<void>;
+ resolveCancelled(): void;
}
function isProcessGroupAlive(pid: number, leaderClosed: boolean): boolean {
@@ -193,31 +223,332 @@ async function terminateRecordingProcess(
/** Explicit simulator media capture. Transient stream frames never enter this path. */
export class IOSSimulatorMediaCapture {
readonly #runner: IOSSimulatorCommandRunner;
- readonly #ingest: typeof ingestMedia;
+ readonly #customIngest: IOSSimulatorMediaIngest | null;
+ readonly #getOwnerScopeKey: () => string;
+ readonly #isOwnerScopeCurrent: (ownerScopeKey: string) => boolean;
readonly #recordingLauncher: IOSSimulatorRecordingLauncher;
readonly #recordings = new Map<string, ActiveRecording>();
- #recordingOperationTail: Promise<void> = Promise.resolve();
+ readonly #recordingOperationTails = new Map<string, Promise<void>>();
+ readonly #screenshotRequestsBySession = new Map<string, Set<ActiveScreenshotRequest>>();
+ readonly #rawIngestsBySession = new Map<string, Set<Promise<void>>>();
+ readonly #rawIngestsByInstance = new Map<string, Set<Promise<void>>>();
+ readonly #instanceSessions = new Map<string, string>();
+ readonly #sessionEpochs = new Map<string, number>();
+ readonly #instanceEpochs = new Map<string, number>();
+ #ingestPoisoned = false;
#closed = false;
constructor(options: IOSSimulatorMediaCaptureOptions = {}) {
this.#runner = options.commandRunner ?? createNodeIOSSimulatorCommandRunner();
- this.#ingest = options.ingest ?? ingestMedia;
+ this.#customIngest = options.ingest ?? null;
+ this.#getOwnerScopeKey = options.getOwnerScopeKey ?? activeOwnerScopeKey;
+ this.#isOwnerScopeCurrent =
+ options.isOwnerScopeCurrent ??
+ ((ownerScopeKey) =>
+ !isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScopeKey);
this.#recordingLauncher = options.recordingLauncher ?? createRecordingLauncher();
}
- #serializeRecordingOperation<T>(operation: () => Promise<T>): Promise<T> {
- const result = this.#recordingOperationTail.then(operation, operation);
- this.#recordingOperationTail = result.then(
+ #captureOwnerScope(): IOSSimulatorMediaOwnerScope {
+ return {
+ ownerScopeKey: this.#getOwnerScopeKey(),
+ ingestDb: this.#customIngest ? null : (tryGetDbClient()?.drizzle ?? null),
+ };
+ }
+
+ #assertOwnerScopeCurrent(scope: IOSSimulatorMediaOwnerScope): void {
+ if (!this.#isOwnerScopeCurrent(scope.ownerScopeKey)) {
+ throw new IOSSimulatorInstanceError(
+ 'RECORDING_NOT_FOUND',
+ 'The simulator media request was cancelled because its data owner changed.',
+ true,
+ );
+ }
+ }
+
+ #assertScreenshotCurrent(request: ActiveScreenshotRequest): void {
+ if (
+ this.#closed ||
+ this.#ingestPoisoned ||
+ request.cancelled ||
+ this.#epoch(this.#sessionEpochs, request.sessionId) !== request.sessionEpoch
+ ) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The simulator screenshot was cancelled while its task was closing.',
+ true,
+ );
+ }
+ this.#assertOwnerScopeCurrent(request.ownerScope);
+ }
+
+ #ingestMedia(
+ params: IngestMediaParams,
+ scope: IOSSimulatorMediaOwnerScope,
+ ): Promise<IngestedMedia> {
+ const callerGuard = params.assertStillValid;
+ const guardedParams: IngestMediaParams = {
+ ...params,
+ assertStillValid: () => {
+ this.#assertOwnerScopeCurrent(scope);
+ callerGuard?.();
+ },
+ };
+ guardedParams.assertStillValid?.();
+ if (this.#customIngest) return this.#customIngest(guardedParams);
+ if (!scope.ingestDb) {
+ throw new IOSSimulatorInstanceError(
+ 'RECORDING_FAILED',
+ 'The simulator media database is not ready.',
+ true,
+ );
+ }
+ return ingestMedia(
+ {
+ ...guardedParams,
+ refCompensationScope: captureMediaRefCompensationScope(scope.ownerScopeKey),
+ },
+ scope.ingestDb,
+ );
+ }
+
+ #serializeRecordingOperation<T>(sessionId: string, operation: () => Promise<T>): Promise<T> {
+ const previous = this.#recordingOperationTails.get(sessionId) ?? Promise.resolve();
+ const result = previous.then(operation, operation);
+ const tail = result.then(
() => undefined,
() => undefined,
);
+ this.#recordingOperationTails.set(sessionId, tail);
+ void tail.then(() => {
+ if (this.#recordingOperationTails.get(sessionId) === tail) {
+ this.#recordingOperationTails.delete(sessionId);
+ }
+ });
return result;
}
- #requestDiscard(instanceId?: string): void {
- for (const recording of this.#recordings.values()) {
- if (instanceId && recording.instanceId !== instanceId) continue;
+ #epoch(epochs: Map<string, number>, key: string): number {
+ return epochs.get(key) ?? 0;
+ }
+
+ #advanceEpoch(epochs: Map<string, number>, key: string): void {
+ epochs.set(key, this.#epoch(epochs, key) + 1);
+ }
+
+ #assertRecordingCurrent(recording: ActiveRecording): void {
+ if (
+ this.#closed ||
+ this.#ingestPoisoned ||
+ recording.discardRequested ||
+ this.#epoch(this.#sessionEpochs, recording.sessionId) !== recording.sessionEpoch ||
+ this.#epoch(this.#instanceEpochs, recording.instanceId) !== recording.instanceEpoch ||
+ !this.#isOwnerScopeCurrent(recording.ownerScopeKey)
+ ) {
+ throw new IOSSimulatorInstanceError(
+ 'RECORDING_NOT_FOUND',
+ 'The simulator recording was discarded while its task or instance was closing.',
+ true,
+ );
+ }
+ }
+
+ #markDiscardRequested(recording: ActiveRecording): void {
+ if (!recording.discardRequested) {
recording.discardRequested = true;
+ recording.resolveDiscarded();
+ }
+ }
+
+ #awaitRecordingIngest(
+ recording: ActiveRecording,
+ operation: Promise<IngestedMedia>,
+ ): Promise<IngestedMedia> {
+ return new Promise<IngestedMedia>((resolve, reject) => {
+ let settled = false;
+ const finish = (callback: () => void): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ callback();
+ };
+ const timer = setTimeout(() => {
+ this.#ingestPoisoned = true;
+ this.#markDiscardRequested(recording);
+ finish(() =>
+ reject(
+ new IOSSimulatorInstanceError(
+ 'RECORDING_FAILED',
+ 'The simulator recording could not be saved before the bounded timeout.',
+ true,
+ ),
+ ),
+ );
+ }, RECORDING_INGEST_TIMEOUT_MS);
+ void recording.discarded.then(() => {
+ finish(() => {
+ try {
+ this.#assertRecordingCurrent(recording);
+ } catch (error) {
+ reject(error);
+ }
+ });
+ });
+ void operation.then(
+ (result) => finish(() => resolve(result)),
+ (error) => finish(() => reject(error)),
+ );
+ });
+ }
+
+ #trackRawIngest(
+ sessionId: string,
+ instanceId: string,
+ operation: Promise<IngestedMedia>,
+ ): Promise<IngestedMedia> {
+ const completion = operation.then(
+ () => undefined,
+ () => undefined,
+ );
+ const sessionSet = this.#rawIngestsBySession.get(sessionId) ?? new Set();
+ const instanceSet = this.#rawIngestsByInstance.get(instanceId) ?? new Set();
+ sessionSet.add(completion);
+ instanceSet.add(completion);
+ this.#rawIngestsBySession.set(sessionId, sessionSet);
+ this.#rawIngestsByInstance.set(instanceId, instanceSet);
+ void completion.then(() => {
+ sessionSet.delete(completion);
+ instanceSet.delete(completion);
+ if (sessionSet.size === 0) this.#rawIngestsBySession.delete(sessionId);
+ if (instanceSet.size === 0) this.#rawIngestsByInstance.delete(instanceId);
+ });
+ return operation;
+ }
+
+ #awaitScreenshotRequest(
+ request: ActiveScreenshotRequest,
+ operation: Promise<IngestedMedia>,
+ ): Promise<IngestedMedia> {
+ return new Promise<IngestedMedia>((resolve, reject) => {
+ let settled = false;
+ const finish = (callback: () => void): void => {
+ if (settled) return;
+ settled = true;
+ callback();
+ };
+ void request.cancelledSignal.then(() => {
+ finish(() => {
+ try {
+ this.#assertScreenshotCurrent(request);
+ } catch (error) {
+ reject(error);
+ }
+ });
+ });
+ void operation.then(
+ (result) =>
+ finish(() => {
+ try {
+ this.#assertScreenshotCurrent(request);
+ resolve(result);
+ } catch (error) {
+ reject(error);
+ }
+ }),
+ (error) => finish(() => reject(error)),
+ );
+ });
+ }
+
+ #awaitScreenshotIngest(
+ request: ActiveScreenshotRequest,
+ operation: Promise<IngestedMedia>,
+ ): Promise<IngestedMedia> {
+ return new Promise<IngestedMedia>((resolve, reject) => {
+ let settled = false;
+ const finish = (callback: () => void): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ callback();
+ };
+ const timer = setTimeout(() => {
+ this.#ingestPoisoned = true;
+ request.cancelled = true;
+ finish(() =>
+ reject(
+ new IOSSimulatorInstanceError(
+ 'SCREENSHOT_CAPTURE_FAILED',
+ 'The simulator screenshot could not be saved before the bounded timeout.',
+ true,
+ ),
+ ),
+ );
+ }, RECORDING_INGEST_TIMEOUT_MS);
+ void request.cancelledSignal.then(() => {
+ finish(() => {
+ try {
+ this.#assertScreenshotCurrent(request);
+ } catch (error) {
+ reject(error);
+ }
+ });
+ });
+ void operation.then(
+ (result) => finish(() => resolve(result)),
+ (error) => finish(() => reject(error)),
+ );
+ });
+ }
+
+ #requestScreenshotDiscard(
+ matches: (request: ActiveScreenshotRequest) => boolean = () => true,
+ ): ActiveScreenshotRequest[] {
+ const requests = Array.from(this.#screenshotRequestsBySession.values())
+ .flatMap((items) => [...items])
+ .filter(matches);
+ for (const request of requests) {
+ if (request.cancelled) continue;
+ request.cancelled = true;
+ request.resolveCancelled();
+ }
+ return requests;
+ }
+
+ #awaitRawIngestQuiescence(operations: Iterable<Promise<void>>, scope: string): Promise<void> {
+ const pending = [...operations];
+ if (pending.length === 0) return Promise.resolve();
+ return new Promise<void>((resolve, reject) => {
+ let settled = false;
+ const finish = (callback: () => void): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ callback();
+ };
+ const timer = setTimeout(() => {
+ this.#ingestPoisoned = true;
+ finish(() =>
+ reject(
+ new IOSSimulatorInstanceError(
+ 'RECORDING_FAILED',
+ `The simulator recording store did not become idle before ${scope} cleanup timed out.`,
+ true,
+ ),
+ ),
+ );
+ }, RECORDING_INGEST_TIMEOUT_MS);
+ void Promise.all(pending).then(
+ () => finish(resolve),
+ (error) => finish(() => reject(error)),
+ );
+ });
+ }
+
+ #requestDiscard(matches: (recording: ActiveRecording) => boolean = () => true): void {
+ for (const recording of this.#recordings.values()) {
+ if (!matches(recording)) continue;
+ this.#markDiscardRequested(recording);
if (!recording.discardSignalSent) {
recording.discardSignalSent = true;
// Discard never preserves the MOV. Kill immediately so one finalizing
@@ -227,24 +558,36 @@ export class IOSSimulatorMediaCapture {
}
}
- async #discardMatching(instanceId?: string): Promise<void> {
- const recordings = Array.from(this.#recordings.values()).filter(
- (recording) => !instanceId || recording.instanceId === instanceId,
- );
+ async #discardMatching(
+ matches: (recording: ActiveRecording) => boolean = () => true,
+ ): Promise<void> {
+ const recordings = Array.from(this.#recordings.values()).filter(matches);
+ const stuckRecordingIds: string[] = [];
await Promise.all(
recordings.map(async (recording) => {
- try {
- if (recording.discardSignalSent) {
- await waitForRecordingExit(recording.process, RECORDING_KILL_TIMEOUT_MS);
- } else {
- await terminateRecordingProcess(recording.process, 'discard');
- }
- } finally {
- this.#recordings.delete(recording.recordingId);
- await rm(recording.tempRoot, { recursive: true, force: true });
+ const exited = recording.discardSignalSent
+ ? await waitForRecordingExit(recording.process, RECORDING_KILL_TIMEOUT_MS)
+ : (await terminateRecordingProcess(recording.process, 'discard')) !== 'stuck';
+ if (!exited) {
+ // Keep the process and temp path tracked so a later lifecycle pass can
+ // retry SIGKILL. Clearing the signal latch lets #requestDiscard send
+ // another kill instead of treating the first unconfirmed signal as
+ // completed cleanup.
+ recording.discardSignalSent = false;
+ stuckRecordingIds.push(recording.recordingId);
+ return;
}
+ this.#recordings.delete(recording.recordingId);
+ await rm(recording.tempRoot, { recursive: true, force: true });
}),
);
+ if (stuckRecordingIds.length > 0) {
+ throw new IOSSimulatorInstanceError(
+ 'RECORDING_FAILED',
+ 'One or more simulator recording processes did not confirm exit after SIGKILL.',
+ true,
+ );
+ }
}
async captureScreenshotBytes(
@@ -286,21 +629,58 @@ export class IOSSimulatorMediaCapture {
}
async takeScreenshot(input: IOSSimulatorScreenshotInput): Promise<IngestedMedia> {
- const buffer = await this.captureScreenshotBytes(input);
- return this.#ingest({
- buffer,
- mimeType: 'image/png',
- refs: [
- {
- refKind: 'session-attachment',
- refId: `ios-simulator:${input.instanceId}:${randomUUID()}`,
- originSessionId: input.sessionId,
- originKind: input.source === 'agent' ? 'tool' : 'user',
- originId: input.instanceId,
- label: 'iOS Simulator screenshot',
- },
- ],
- });
+ const ownerScope = this.#captureOwnerScope();
+ let resolveCancelled: () => void = () => undefined;
+ const request: ActiveScreenshotRequest = {
+ sessionId: input.sessionId,
+ instanceId: input.instanceId,
+ sessionEpoch: this.#epoch(this.#sessionEpochs, input.sessionId),
+ ownerScope,
+ cancelled: false,
+ cancelledSignal: new Promise<void>((resolve) => {
+ resolveCancelled = resolve;
+ }),
+ resolveCancelled: () => resolveCancelled(),
+ };
+ const requests = this.#screenshotRequestsBySession.get(input.sessionId) ?? new Set();
+ requests.add(request);
+ this.#screenshotRequestsBySession.set(input.sessionId, requests);
+ const operation = (async (): Promise<IngestedMedia> => {
+ this.#assertScreenshotCurrent(request);
+ const buffer = await this.captureScreenshotBytes(input);
+ this.#assertScreenshotCurrent(request);
+ const ingestOperation = this.#trackRawIngest(
+ input.sessionId,
+ input.instanceId,
+ this.#ingestMedia(
+ {
+ buffer,
+ mimeType: 'image/png',
+ refs: [
+ {
+ refKind: 'session-attachment',
+ refId: input.sessionId,
+ originSessionId: input.sessionId,
+ originKind: input.source === 'agent' ? 'tool' : 'user',
+ originId: input.instanceId,
+ label: 'iOS Simulator screenshot',
+ },
+ ],
+ assertStillValid: () => this.#assertScreenshotCurrent(request),
+ },
+ ownerScope,
+ ),
+ );
+ const ingested = await this.#awaitScreenshotIngest(request, ingestOperation);
+ this.#assertScreenshotCurrent(request);
+ return ingested;
+ })();
+ try {
+ return await this.#awaitScreenshotRequest(request, operation);
+ } finally {
+ requests.delete(request);
+ if (requests.size === 0) this.#screenshotRequestsBySession.delete(input.sessionId);
+ }
}
async startRecording(input: {
@@ -310,14 +690,37 @@ export class IOSSimulatorMediaCapture {
generation: number;
source: 'agent' | 'user';
}): Promise<{ recordingId: string; startedAt: string }> {
- return this.#serializeRecordingOperation(async () => {
- if (this.#closed) {
+ if (this.#ingestPoisoned) {
+ throw new IOSSimulatorInstanceError(
+ 'RECORDING_FAILED',
+ 'The simulator media store is unavailable until Cindy restarts.',
+ true,
+ );
+ }
+ const ownerScope = this.#captureOwnerScope();
+ this.#assertOwnerScopeCurrent(ownerScope);
+ const sessionEpoch = this.#epoch(this.#sessionEpochs, input.sessionId);
+ const instanceEpoch = this.#epoch(this.#instanceEpochs, input.instanceId);
+ this.#instanceSessions.set(input.instanceId, input.sessionId);
+ return this.#serializeRecordingOperation(input.sessionId, async () => {
+ if (this.#closed || this.#ingestPoisoned) {
throw new IOSSimulatorInstanceError(
'RECORDING_FAILED',
'The simulator media service is shutting down.',
true,
);
}
+ this.#assertOwnerScopeCurrent(ownerScope);
+ if (
+ this.#epoch(this.#sessionEpochs, input.sessionId) !== sessionEpoch ||
+ this.#epoch(this.#instanceEpochs, input.instanceId) !== instanceEpoch
+ ) {
+ throw new IOSSimulatorInstanceError(
+ 'RECORDING_NOT_FOUND',
+ 'The simulator recording request was cancelled while its task or instance was closing.',
+ true,
+ );
+ }
if (
Array.from(this.#recordings.values()).some((item) => item.instanceId === input.instanceId)
) {
@@ -330,13 +733,23 @@ export class IOSSimulatorMediaCapture {
const videoPath = path.join(tempRoot, 'recording.mov');
const recordingId = randomUUID();
try {
- if (this.#closed) {
+ if (
+ this.#closed ||
+ this.#ingestPoisoned ||
+ this.#epoch(this.#sessionEpochs, input.sessionId) !== sessionEpoch ||
+ this.#epoch(this.#instanceEpochs, input.instanceId) !== instanceEpoch
+ ) {
throw new IOSSimulatorInstanceError(
- 'RECORDING_FAILED',
- 'The simulator media service is shutting down.',
+ 'RECORDING_NOT_FOUND',
+ 'The simulator recording request was cancelled while its task or instance was closing.',
true,
);
}
+ this.#assertOwnerScopeCurrent(ownerScope);
+ let resolveDiscarded: () => void = () => undefined;
+ const discarded = new Promise<void>((resolve) => {
+ resolveDiscarded = resolve;
+ });
const process = this.#recordingLauncher.launch([
'simctl',
'io',
@@ -354,6 +767,12 @@ export class IOSSimulatorMediaCapture {
phase: 'active',
discardRequested: false,
discardSignalSent: false,
+ discarded,
+ resolveDiscarded,
+ sessionEpoch,
+ instanceEpoch,
+ ownerScopeKey: ownerScope.ownerScopeKey,
+ ingestDb: ownerScope.ingestDb,
});
return { recordingId, startedAt: new Date().toISOString() };
} catch (error) {
@@ -369,7 +788,7 @@ export class IOSSimulatorMediaCapture {
instanceId: string;
generation: number;
}): Promise<IngestedMedia> {
- return this.#serializeRecordingOperation(async () => {
+ return this.#serializeRecordingOperation(input.sessionId, async () => {
const recording = this.#recordings.get(input.recordingId);
if (
!recording ||
@@ -383,8 +802,10 @@ export class IOSSimulatorMediaCapture {
);
}
recording.phase = 'finalizing';
+ let processExitConfirmed = false;
try {
const termination = await terminateRecordingProcess(recording.process, 'finalize');
+ processExitConfirmed = termination !== 'stuck';
if (termination !== 'finalized') {
throw new IOSSimulatorInstanceError(
'RECORDING_FAILED',
@@ -394,13 +815,7 @@ export class IOSSimulatorMediaCapture {
true,
);
}
- if (recording.discardRequested || this.#closed) {
- throw new IOSSimulatorInstanceError(
- 'RECORDING_NOT_FOUND',
- 'The simulator recording was discarded while its instance was closing.',
- true,
- );
- }
+ this.#assertRecordingCurrent(recording);
const info = await stat(recording.videoPath);
if (!info.isFile() || info.size <= 0 || info.size > MAX_BUFFERED_RECORDING_BYTES) {
throw new IOSSimulatorInstanceError(
@@ -409,44 +824,113 @@ export class IOSSimulatorMediaCapture {
);
}
const buffer = await readFile(recording.videoPath);
- return await this.#ingest({
- buffer,
- mimeType: 'video/quicktime',
- refs: [
+ this.#assertRecordingCurrent(recording);
+ const ingestOperation = this.#trackRawIngest(
+ recording.sessionId,
+ recording.instanceId,
+ this.#ingestMedia(
{
- refKind: 'session-attachment',
- refId: `ios-simulator:${recording.instanceId}:${recording.recordingId}`,
- originSessionId: recording.sessionId,
- originKind: recording.source === 'agent' ? 'tool' : 'user',
- originId: recording.instanceId,
- label: 'iOS Simulator recording',
+ buffer,
+ mimeType: 'video/quicktime',
+ refs: [
+ {
+ refKind: 'session-attachment',
+ refId: recording.sessionId,
+ originSessionId: recording.sessionId,
+ originKind: recording.source === 'agent' ? 'tool' : 'user',
+ originId: recording.instanceId,
+ label: 'iOS Simulator recording',
+ },
+ ],
+ assertStillValid: () => this.#assertRecordingCurrent(recording),
},
- ],
- });
+ {
+ ownerScopeKey: recording.ownerScopeKey,
+ ingestDb: recording.ingestDb,
+ },
+ ),
+ );
+ return await this.#awaitRecordingIngest(recording, ingestOperation);
} finally {
- this.#recordings.delete(recording.recordingId);
- await rm(recording.tempRoot, { recursive: true, force: true });
+ if (processExitConfirmed) {
+ this.#recordings.delete(recording.recordingId);
+ await rm(recording.tempRoot, { recursive: true, force: true });
+ }
}
});
}
async discardInstance(instanceId: string): Promise<void> {
- this.#requestDiscard(instanceId);
- return this.#serializeRecordingOperation(() => this.#discardMatching(instanceId));
+ const matches = (recording: ActiveRecording) => recording.instanceId === instanceId;
+ let sessionId = this.#instanceSessions.get(instanceId);
+ this.#advanceEpoch(this.#instanceEpochs, instanceId);
+ const screenshotRequests = this.#requestScreenshotDiscard(
+ (request) => request.instanceId === instanceId,
+ );
+ sessionId ??= screenshotRequests[0]?.sessionId;
+ this.#requestDiscard(matches);
+ if (!sessionId) {
+ await this.#discardMatching(matches);
+ await this.#awaitRawIngestQuiescence(
+ this.#rawIngestsByInstance.get(instanceId) ?? [],
+ 'instance',
+ );
+ return;
+ }
+ return this.#serializeRecordingOperation(sessionId, async () => {
+ await this.#discardMatching(matches);
+ await this.#awaitRawIngestQuiescence(
+ this.#rawIngestsByInstance.get(instanceId) ?? [],
+ 'instance',
+ );
+ this.#instanceSessions.delete(instanceId);
+ });
+ }
+
+ async discardSession(sessionId: string): Promise<void> {
+ const matches = (recording: ActiveRecording) => recording.sessionId === sessionId;
+ this.#advanceEpoch(this.#sessionEpochs, sessionId);
+ this.#requestScreenshotDiscard((request) => request.sessionId === sessionId);
+ this.#requestDiscard(matches);
+ return this.#serializeRecordingOperation(sessionId, async () => {
+ await this.#discardMatching(matches);
+ await this.#awaitRawIngestQuiescence(this.#rawIngestsBySession.get(sessionId) ?? [], 'task');
+ for (const [instanceId, boundSessionId] of this.#instanceSessions) {
+ if (boundSessionId === sessionId) this.#instanceSessions.delete(instanceId);
+ }
+ });
}
/** Graceful Host teardown closes the gate before waiting for in-flight starts. */
async dispose(): Promise<void> {
this.#closed = true;
+ this.#requestScreenshotDiscard();
this.#requestDiscard();
- return this.#serializeRecordingOperation(() => this.#discardMatching());
+ await Promise.all([...this.#recordingOperationTails.values()]);
+ const rawIngestQuiescence = this.#awaitRawIngestQuiescence(
+ Array.from(this.#rawIngestsBySession.values()).flatMap((operations) => [...operations]),
+ 'host',
+ ).then(
+ () => null,
+ (error: unknown) => error,
+ );
+ let firstError: unknown = null;
+ try {
+ await this.#discardMatching();
+ } catch (error) {
+ firstError = error;
+ }
+ firstError ??= await rawIngestQuiescence;
+ this.#instanceSessions.clear();
+ if (firstError) throw firstError;
}
/** Updater force-quit cannot await cleanup, so synchronously kill every group. */
abortOperationsForExit(): void {
this.#closed = true;
+ this.#requestScreenshotDiscard();
for (const recording of this.#recordings.values()) {
- recording.discardRequested = true;
+ this.#markDiscardRequested(recording);
if (!recording.discardSignalSent) {
recording.discardSignalSent = true;
signalRecordingProcess(recording.process, 'SIGKILL');
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 14d9ebc20b..34c2592876 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -150,6 +150,7 @@ export type IOSSimulatorMediaCaptureAdapter = Pick<
| 'startRecording'
| 'stopRecording'
| 'discardInstance'
+ | 'discardSession'
> &
Partial<Pick<IOSSimulatorMediaCapture, 'dispose' | 'abortOperationsForExit'>>;
@@ -814,12 +815,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
resolveSettled: () => void;
};
const activeBuilds = new Map<string, ActiveBuild>();
- const sessionBuildAdmissionEpochs = new Map<string, number>();
+ const sessionOperationAdmissionEpochs = new Map<string, number>();
const blockedBuildInstances = new Set<string>();
- const instanceLifecycleBarriers = new Map<
- string,
- { epoch: number; pendingTeardowns: number }
- >();
+ const instanceLifecycleBarriers = new Map<string, { epoch: number; pendingTeardowns: number }>();
const mediaCapture = options.mediaCapture ?? new IOSSimulatorMediaCapture();
const visualBaselines = new Map<
string,
@@ -890,15 +888,21 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
errorCode: 'IOS_SIMULATOR_HOST_ERROR',
message: 'The iOS Simulator host is shutting down.',
});
+ function assertSessionOperationAdmission(
+ sessionId: string,
+ expectedEpoch: number,
+ operation: 'app build' | 'screenshot' | 'screen recording',
+ ): void {
+ if ((sessionOperationAdmissionEpochs.get(sessionId) ?? 0) === expectedEpoch) return;
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ `The ${operation} was cancelled because its Cindy task lifecycle changed.`,
+ true,
+ );
+ }
function beginBuild(instance: IOSSimulatorInstance, expectedSessionEpoch: number): ActiveBuild {
if (disposePromise) throw new IOSSimulatorHostDisposedError();
- if ((sessionBuildAdmissionEpochs.get(instance.sessionId) ?? 0) !== expectedSessionEpoch) {
- throw new IOSSimulatorInstanceError(
- 'MUTATION_CANCELLED',
- 'The app build was cancelled because its Cindy task lifecycle changed.',
- true,
- );
- }
+ assertSessionOperationAdmission(instance.sessionId, expectedSessionEpoch, 'app build');
if (blockedBuildInstances.has(instance.instanceId)) {
throw new IOSSimulatorInstanceError(
'MUTATION_CANCELLED',
@@ -936,14 +940,29 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
build.controller.abort();
await build.settled;
}
- async function cancelSessionBuilds(sessionId: string): Promise<void> {
- sessionBuildAdmissionEpochs.set(
+ async function cancelSessionBuildsAndRecordings(sessionId: string): Promise<void> {
+ sessionOperationAdmissionEpochs.set(
sessionId,
- (sessionBuildAdmissionEpochs.get(sessionId) ?? 0) + 1,
+ (sessionOperationAdmissionEpochs.get(sessionId) ?? 0) + 1,
);
const builds = [...activeBuilds.entries()].filter(([, build]) => build.sessionId === sessionId);
for (const [, build] of builds) build.controller.abort();
- await Promise.all(builds.map(([, build]) => build.settled));
+ const results = await Promise.allSettled([
+ ...builds.map(([, build]) => build.settled),
+ mediaCapture.discardSession(sessionId),
+ ]);
+ // Admission is already closed above, so a recorder cleanup failure must not
+ // strand the whole task archive/delete (or an Orca shutdown) halfway through.
+ // The media adapter keeps its own failed process state for later lifecycle
+ // reconciliation; here we only wait for every build/cleanup attempt to settle
+ // and surface diagnostics without reopening task-owned mutations.
+ for (const result of results) {
+ if (result.status !== 'rejected') continue;
+ logger.warn('iOS Simulator task-owned operation cleanup failed', {
+ sessionId,
+ error: result.reason instanceof Error ? result.reason.message : String(result.reason),
+ });
+ }
}
function lifecycleBarrier(instanceId: string): { epoch: number; pendingTeardowns: number } {
return instanceLifecycleBarriers.get(instanceId) ?? { epoch: 0, pendingTeardowns: 0 };
@@ -975,6 +994,31 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
return current.epoch;
}
+ function captureInstanceOperationAdmission(instanceId: string, operation: string): number {
+ const current = lifecycleBarrier(instanceId);
+ if (current.pendingTeardowns > 0) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ `The simulator ${operation} was cancelled because its lifecycle is changing.`,
+ true,
+ );
+ }
+ return current.epoch;
+ }
+ function assertInstanceOperationAdmission(
+ instanceId: string,
+ expectedEpoch: number,
+ operation: string,
+ ): void {
+ const current = lifecycleBarrier(instanceId);
+ if (current.epoch !== expectedEpoch || current.pendingTeardowns > 0) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ `The simulator ${operation} was cancelled because its lifecycle changed.`,
+ true,
+ );
+ }
+ }
function completeInstanceActivation(instance: IOSSimulatorInstance, expectedEpoch: number): void {
const current = lifecycleBarrier(instance.instanceId);
if (current.epoch !== expectedEpoch || current.pendingTeardowns > 0) {
@@ -1921,10 +1965,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
if (session.remoteHostId || !device) {
const runtimeReleased = await releaseInstanceRuntime(instance);
- if (
- runtimeReleased &&
- (!device || device.state.trim().toLowerCase() === 'shutdown')
- ) {
+ if (runtimeReleased && (!device || device.state.trim().toLowerCase() === 'shutdown')) {
resourceScheduler.markStopped(instance.instanceId);
}
actor.reconcile(
@@ -2638,6 +2679,27 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
);
}
+ async function discardInstanceMediaForLifecycle(
+ instanceId: string,
+ operation: 'stop' | 'detach',
+ ): Promise<{ code: 'MEDIA_CLEANUP_INCOMPLETE'; message: string } | null> {
+ try {
+ await mediaCapture.discardInstance(instanceId);
+ return null;
+ } catch (error) {
+ logger.warn('iOS Simulator media cleanup did not finish before lifecycle teardown', {
+ instanceId,
+ operation,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return {
+ code: 'MEDIA_CLEANUP_INCOMPLETE',
+ message:
+ 'The simulator lifecycle completed, but pending media cleanup did not finish. Restart Cindy before capturing more simulator media.',
+ };
+ }
+ }
+
function requireArtifact(
instance: IOSSimulatorInstance,
artifactId: string,
@@ -2964,7 +3026,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
revokeRendererViewer(sessionId, viewerWebContentsId) {
let revoked = 0;
for (const [instanceId, viewer] of [...viewerSessions]) {
- if (viewer.sessionId !== sessionId || viewer.webContentsId !== viewerWebContentsId) continue;
+ if (viewer.sessionId !== sessionId || viewer.webContentsId !== viewerWebContentsId)
+ continue;
revoked += 1;
try {
stopViewerMedia(actor.getOwned(sessionId, instanceId));
@@ -3546,7 +3609,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
try {
await cancelBuild(route.instanceId);
cancelIdleRecycle(route.instanceId);
- await mediaCapture.discardInstance(route.instanceId);
+ const mediaCleanupWarning = await discardInstanceMediaForLifecycle(
+ route.instanceId,
+ 'stop',
+ );
clearVisualBaselines(route.instanceId);
await getDriverManager().stop(route.instanceId);
screenMaps.clear(route.instanceId);
@@ -3562,7 +3628,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
publishRouteStatusForInstance(stopped, null);
return {
ok: true,
- data: instanceData(stopped),
+ data: {
+ ...instanceData(stopped),
+ ...(mediaCleanupWarning ? { mediaCleanupWarning } : {}),
+ },
};
} finally {
finishInstanceTeardown(route.instanceId);
@@ -3576,7 +3645,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
try {
await cancelBuild(route.instanceId);
cancelIdleRecycle(route.instanceId);
- await mediaCapture.discardInstance(route.instanceId);
+ const mediaCleanupWarning = await discardInstanceMediaForLifecycle(
+ route.instanceId,
+ 'detach',
+ );
clearVisualBaselines(route.instanceId);
await getDriverManager().stop(route.instanceId);
screenMaps.clear(route.instanceId);
@@ -3590,9 +3662,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
agentControlLeases.delete(route.instanceId);
return {
ok: true,
- data: instanceData(
- await actor.detach(route, () => resourceScheduler.markStopped(route.instanceId)),
- ),
+ data: {
+ ...instanceData(
+ await actor.detach(route, () => resourceScheduler.markStopped(route.instanceId)),
+ ),
+ ...(mediaCleanupWarning ? { mediaCleanupWarning } : {}),
+ },
};
} finally {
finishInstanceTeardown(route.instanceId);
@@ -4468,7 +4543,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
// between this check and beginBuild: if archival wins first this
// call fails closed; if beginBuild wins first archival observes and
// cancels the registered operation.
- const buildAdmissionEpoch = sessionBuildAdmissionEpochs.get(sessionId) ?? 0;
+ const buildAdmissionEpoch = sessionOperationAdmissionEpochs.get(sessionId) ?? 0;
const buildSession = await resolveSession(sessionId);
if (!buildSession.ok) return buildSession;
assertHostActive();
@@ -4719,9 +4794,27 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return { ok: true, data: { opened: true } };
}
if (name === 'take_screenshot') {
- const route = readMutationRoute(sessionId, args);
+ const screenshotAdmissionEpoch = sessionOperationAdmissionEpochs.get(sessionId) ?? 0;
+ const screenshotSession = await resolveSession(sessionId);
+ if (!screenshotSession.ok) return screenshotSession;
+ assertHostActive();
+ const route = readMutationRoute(screenshotSession.sessionId, args);
+ const screenshotInstanceEpoch = captureInstanceOperationAdmission(
+ route.instanceId,
+ 'screenshot',
+ );
const captured = await runHostMutation(route, context, async (instance) => {
requireControlGrant(instance, context);
+ assertSessionOperationAdmission(
+ instance.sessionId,
+ screenshotAdmissionEpoch,
+ 'screenshot',
+ );
+ assertInstanceOperationAdmission(
+ instance.instanceId,
+ screenshotInstanceEpoch,
+ 'screenshot',
+ );
return mediaCapture.takeScreenshot({
simulatorUdid: instance.simulatorUdid,
sessionId: instance.sessionId,
@@ -4881,9 +4974,31 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return { ok: true, data: { diagnostics: entry } };
}
if (name === 'start_recording') {
- const route = readMutationRoute(sessionId, args);
+ // Revalidate immediately before the actor queue, then check the
+ // task lifecycle epoch again at the synchronous media-registration
+ // boundary. If cancellation wins first, registration is denied; if
+ // registration wins first, discardSession is queued behind it.
+ const recordingAdmissionEpoch = sessionOperationAdmissionEpochs.get(sessionId) ?? 0;
+ const recordingSession = await resolveSession(sessionId);
+ if (!recordingSession.ok) return recordingSession;
+ assertHostActive();
+ const route = readMutationRoute(recordingSession.sessionId, args);
+ const recordingInstanceEpoch = captureInstanceOperationAdmission(
+ route.instanceId,
+ 'screen recording',
+ );
const recording = await runHostMutation(route, context, async (instance) => {
requireControlGrant(instance, context);
+ assertSessionOperationAdmission(
+ instance.sessionId,
+ recordingAdmissionEpoch,
+ 'screen recording',
+ );
+ assertInstanceOperationAdmission(
+ instance.instanceId,
+ recordingInstanceEpoch,
+ 'screen recording',
+ );
return mediaCapture.startRecording({
simulatorUdid: instance.simulatorUdid,
sessionId: instance.sessionId,
@@ -5077,7 +5192,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
},
cancelSessionOperations(sessionId) {
- return cancelSessionBuilds(sessionId.trim());
+ return cancelSessionBuildsAndRecordings(sessionId.trim());
},
abortOperationsForExit() {
for (const build of activeBuilds.values()) build.controller.abort();
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 147f10d75e..1e8186a2dc 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -293,7 +293,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (isIpcError(err) && err.code === 'NOT_FOUND') {
- return { ok: false, errorCode: 'NOT_FOUND', message };
+ return { ok: false, errorCode: err.code, message };
}
return { ok: false, errorCode: 'INTERNAL', message };
}
@@ -327,8 +327,10 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
return { ok: true, changed };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
- if (isIpcError(err) && err.code === 'NOT_FOUND') {
- return { ok: false, errorCode: 'NOT_FOUND', message };
+ if (isIpcError(err)) {
+ if (err.code === 'NOT_FOUND' || err.code === 'PRECONDITION_FAILED') {
+ return { ok: false, errorCode: err.code, message };
+ }
}
return { ok: false, errorCode: 'INTERNAL', message };
}
diff --git a/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts b/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts
index 930d442793..49ac549208 100644
--- a/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts
+++ b/apps/desktop/src/main/session-share/__tests__/sessionShareImport.test.ts
@@ -13,6 +13,8 @@ import path from 'node:path';
import JSZip from 'jszip';
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DB_TRANSPORT_OUTCOME_UNKNOWN } from '../../localDb/client/DbTransport.js';
+
const tmpRoot = mkdtempSync(path.join(os.tmpdir(), 'xdtshare-import-test-'));
const projectsRoot = path.join(tmpRoot, 'claude-home', 'projects');
const newWorkdir = path.join(tmpRoot, 'their-proj');
@@ -27,6 +29,7 @@ const dbMock = vi.hoisted(() => ({
queryCalls: [] as Array<{ sql: string; params: unknown[] }>,
txCalls: [] as Array<{ name: string; args: unknown }>,
txError: null as Error | null,
+ drizzle: { scope: 'stable-import-db' },
}));
const codexMock = vi.hoisted(() => ({
importCalls: [] as unknown[],
@@ -45,6 +48,7 @@ const codexMock = vi.hoisted(() => ({
const cindyMediaMock = vi.hoisted(() => ({
ingestCalls: [] as Array<{ buffer: Buffer; mimeType: string; refs: Array<Record<string, unknown>> }>,
removeSessionRefsCalls: [] as string[],
+ removeSessionRefsIfDeletedCalls: [] as string[],
removeSessionRefsErrorFor: null as string | null,
/** 置为 Error 让 ingest 全部失败(测回落老目录路径)。 */
ingestError: null as Error | null,
@@ -58,6 +62,7 @@ vi.mock('electron', () => ({
}));
vi.mock('../../localDb/client/current.js', () => ({
getDbClient: () => ({
+ drizzle: dbMock.drizzle,
queryOne: async (sql: string, params: unknown[]) => {
dbMock.queryCalls.push({ sql, params });
if (dbMock.conflictForResumeId != null) {
@@ -165,6 +170,13 @@ vi.mock('../../cindy-media/ledger.js', () => ({
}
return 0;
},
+ removeSessionRefsIfDeleted: async (sessionId: string) => {
+ cindyMediaMock.removeSessionRefsIfDeletedCalls.push(sessionId);
+ if (cindyMediaMock.removeSessionRefsErrorFor === sessionId) {
+ throw new Error('media cleanup failed');
+ }
+ return 0;
+ },
}));
const worktreeMock = vi.hoisted(() => ({
detect: null as
@@ -186,13 +198,25 @@ vi.mock('../../worktree/WorktreeManager.js', () => ({
worktreeMock.removeCalls.push(sessionId);
},
}));
+const sessionShareImportModule = await import('../sessionShareImport.js');
const {
inspectShareFile,
unlockShareDraft,
- commitShareImport,
cancelShareDraft,
cleanupReplacedSessionMediaRefs,
-} = await import('../sessionShareImport.js');
+} = sessionShareImportModule;
+const mockedDbClientModule = await import('../../localDb/client/current.js');
+const rawCommitShareImport = sessionShareImportModule.commitShareImport;
+const commitShareImport = (opts: Parameters<typeof rawCommitShareImport>[0]) =>
+ rawCommitShareImport(opts, {
+ dbClient: mockedDbClientModule.getDbClient(),
+ assertStillValid: () => undefined,
+ refCompensationScope: {
+ journalDir: path.join(tmpRoot, 'ref-compensation'),
+ ownerStorageKey: 'a'.repeat(20),
+ assertStillValid: () => undefined,
+ },
+ });
const { buildLooseUrl } = await import('../mediaUrlRewrite.pure.js');
const { buildPlainFile, sealPayload } = await import('../xdtshareCrypto.js');
@@ -421,6 +445,7 @@ describe('sessionShareImport', () => {
};
cindyMediaMock.ingestCalls = [];
cindyMediaMock.removeSessionRefsCalls = [];
+ cindyMediaMock.removeSessionRefsIfDeletedCalls = [];
cindyMediaMock.removeSessionRefsErrorFor = null;
cindyMediaMock.ingestError = null;
legacyImageMock.removeSessionCalls = [];
@@ -627,6 +652,33 @@ describe('sessionShareImport', () => {
expect(cindyMediaMock.removeSessionRefsCalls).toEqual([grantedId]);
});
+ it('preserves staged media and transcripts when the final DB transaction loses its ACK', async () => {
+ dbMock.txError = Object.assign(new Error('db worker transport closed'), {
+ code: DB_TRANSPORT_OUTCOME_UNKNOWN,
+ });
+ const filePath = await writeBundleFile(await buildBundle());
+ const inspect = await inspectShareFile(filePath);
+ if (inspect.encrypted) return;
+
+ await expect(
+ commitShareImport({
+ draftId: inspect.draftId,
+ workingDir: newWorkdir,
+ projectsRootOverride: projectsRoot,
+ sharedMediaRootOverride: sharedMediaRoot,
+ }),
+ ).rejects.toMatchObject({ code: DB_TRANSPORT_OUTCOME_UNKNOWN });
+
+ const importedRef = cindyMediaMock.ingestCalls[0]?.refs[0]?.refId;
+ expect(importedRef).toEqual(expect.any(String));
+ expect(cindyMediaMock.removeSessionRefsCalls).toEqual([]);
+ const key = newWorkdir.replace(/[^a-zA-Z0-9]/g, '-');
+ await expect(fsp.stat(path.join(projectsRoot, key, `${SID}.jsonl`))).resolves.toBeDefined();
+ await expect(
+ fsp.stat(path.join(sharedMediaRoot, importedRef as string, '2-doc.pdf')),
+ ).resolves.toBeDefined();
+ });
+
it('encrypted flow: inspect → wrong password → unlock → commit', async () => {
const filePath = await writeBundleFile(await buildBundle(), 'pw');
const inspect = await inspectShareFile(filePath);
@@ -1400,31 +1452,31 @@ describe('sessionShareImport', () => {
});
it('overwrite media cleanup removes every replaced session ref after commit', async () => {
- cindyMediaMock.removeSessionRefsCalls = [];
+ cindyMediaMock.removeSessionRefsIfDeletedCalls = [];
await cleanupReplacedSessionMediaRefs([
{ id: 'old-lead' },
{ id: 'old-worker' },
- ]);
+ ], {} as never);
- expect(cindyMediaMock.removeSessionRefsCalls).toEqual([
+ expect(cindyMediaMock.removeSessionRefsIfDeletedCalls).toEqual([
'old-lead',
'old-worker',
]);
});
it('overwrite media cleanup isolates failures and continues with the remaining graph', async () => {
- cindyMediaMock.removeSessionRefsCalls = [];
+ cindyMediaMock.removeSessionRefsIfDeletedCalls = [];
cindyMediaMock.removeSessionRefsErrorFor = 'old-lead';
await expect(
cleanupReplacedSessionMediaRefs([
{ id: 'old-lead' },
{ id: 'old-worker' },
- ]),
+ ], {} as never),
).resolves.toBeUndefined();
- expect(cindyMediaMock.removeSessionRefsCalls).toEqual([
+ expect(cindyMediaMock.removeSessionRefsIfDeletedCalls).toEqual([
'old-lead',
'old-worker',
]);
diff --git a/apps/desktop/src/main/session-share/sessionShareImport.ts b/apps/desktop/src/main/session-share/sessionShareImport.ts
index d9465c239f..9f18ffa8fe 100644
--- a/apps/desktop/src/main/session-share/sessionShareImport.ts
+++ b/apps/desktop/src/main/session-share/sessionShareImport.ts
@@ -23,7 +23,8 @@ import JSZip from 'jszip';
import { isClaudeProjectKeyExact, sanitizeClaudeProjectKey } from '@cindy/maker-core';
import { app } from 'electron';
-import { getDbClient } from '../localDb/client/current.js';
+import type { DbClient } from '../localDb/client/DbClient.js';
+import { isDbTransportOutcomeUnknown } from '../localDb/client/DbTransport.js';
import type {
SessionImportShareMessageRow,
SessionImportShareSessionRow,
@@ -49,9 +50,19 @@ import {
} from '../imageCacheStore.js';
import { resolveSafe as resolveVideoUrl } from '../videoCacheStore.js';
import { resolveSafe as resolveModelUrl } from '../modelCacheStore.js';
-import { parseBlobUrl, mimeForExt, resolveHashRef as resolveBlobHashRef } from '../cindy-media/blobStore.js';
+import {
+ parseBlobUrl,
+ mimeForExt,
+ resolveHashRef as resolveBlobHashRef,
+} from '../cindy-media/blobStore.js';
import { ingestMedia } from '../cindy-media/ingest.js';
-import { removeSessionRefs as removeSessionMediaRefs } from '../cindy-media/ledger.js';
+import type { MediaRefCompensationScope } from '../cindy-media/refCompensationJournal.js';
+import {
+ removeSessionRefs as removeSessionMediaRefs,
+ removeSessionRefsIfDeleted,
+ type LedgerDb,
+} from '../cindy-media/ledger.js';
+import { withSessionRouteLocks } from '../localDb/sessionRouteLock.js';
import { openPayload } from './xdtshareCrypto.js';
import {
@@ -126,7 +137,9 @@ function toPreview(manifest: XdtshareManifest): SharePreview {
};
}
-async function loadZipAndManifest(zipBytes: Buffer): Promise<{ zip: JSZip; manifest: XdtshareManifest }> {
+async function loadZipAndManifest(
+ zipBytes: Buffer,
+): Promise<{ zip: JSZip; manifest: XdtshareManifest }> {
const zip = await JSZip.loadAsync(zipBytes).catch(() => {
throw new XdtshareError('SHARE_FILE_INVALID', 'payload is not a readable zip');
});
@@ -243,6 +256,13 @@ export interface CommitShareImportOptions {
overwrite?: boolean;
}
+/** Stable owner-bound resources captured synchronously by the production IPC entry. */
+export interface CommitShareImportRuntimeScope {
+ dbClient: DbClient;
+ assertStillValid(): void;
+ refCompensationScope: MediaRefCompensationScope;
+}
+
export interface CommitShareImportResult {
sessionId: string;
fidelity: XdtshareFidelity;
@@ -292,10 +312,11 @@ interface WorkerImportPlan {
*/
export async function cleanupReplacedSessionMediaRefs(
sessions: ReadonlyArray<{ id: string }>,
+ db: LedgerDb,
): Promise<void> {
for (const session of sessions) {
try {
- const removed = await removeSessionMediaRefs(session.id);
+ const removed = await removeSessionRefsIfDeleted(session.id, db);
if (removed > 0) {
log.info('replaced session media refs removed', {
sessionId: session.id,
@@ -314,7 +335,18 @@ export async function cleanupReplacedSessionMediaRefs(
/** 第三段:落三层数据。前置校验全过才写;文件步登记 journal,失败逆序回滚。 */
export async function commitShareImport(
opts: CommitShareImportOptions,
+ runtimeScope: CommitShareImportRuntimeScope,
): Promise<CommitShareImportInternalResult> {
+ const dbClient = runtimeScope.dbClient;
+ const mediaDb = dbClient.drizzle;
+ const assertStillValid = runtimeScope.assertStillValid;
+ const guarded = async <T>(task: () => Promise<T>): Promise<T> => {
+ assertStillValid();
+ const result = await task();
+ assertStillValid();
+ return result;
+ };
+ assertStillValid();
sweepExpiredDrafts();
const draft = drafts.get(opts.draftId);
if (!draft) throw codedError('NOT_FOUND', 'draft expired or not found');
@@ -324,10 +356,10 @@ export async function commitShareImport(
const { zip, manifest } = draft;
// ── 解析包内数据(仍属只读阶段) ──
- const sessionSnapshot = await readJsonEntry(zip, 'session.json');
- const messages = await readMessagesJsonl(zip, 'messages.jsonl');
+ const sessionSnapshot = await guarded(() => readJsonEntry(zip, 'session.json'));
+ const messages = await guarded(() => readMessagesJsonl(zip, 'messages.jsonl'));
if (messages.length === 0) throw codedError('SHARE_FILE_INVALID', 'bundle has no messages');
- const mediaMap = await readMediaMap(zip);
+ const mediaMap = await guarded(() => readMediaMap(zip));
// 协同包:逐个读 Worker 的包内数据(Worker 允许 0 条消息——刚创建未派活)。
const workerPlans: WorkerImportPlan[] = [];
@@ -338,8 +370,8 @@ export async function commitShareImport(
manifest: workerManifest,
prefix,
newId: randomUUID(),
- snapshot: await readJsonEntry(zip, `${prefix}session.json`),
- messages: await readMessagesJsonl(zip, `${prefix}messages.jsonl`),
+ snapshot: await guarded(() => readJsonEntry(zip, `${prefix}session.json`)),
+ messages: await guarded(() => readMessagesJsonl(zip, `${prefix}messages.jsonl`)),
activeSdkSessionId: null,
});
}
@@ -352,13 +384,15 @@ export async function commitShareImport(
if (manifest.workspaceKind === 'project') {
const dir = typeof opts.workingDir === 'string' ? opts.workingDir.trim() : '';
if (!dir) throw codedError('INVALID_PARAMS', 'workingDir is required for project sessions');
- const stat = await fsp.stat(dir).catch(() => null);
+ const stat = await guarded(() => fsp.stat(dir).catch(() => null));
if (!stat?.isDirectory()) {
throw codedError('PRECONDITION_FAILED', 'workingDir does not exist or is not a directory');
}
workingDir = dir;
} else {
+ assertStillValid();
workingDir = ensureDialogueWorkspaceDir(newId, now);
+ assertStillValid();
}
// activeSdkSessionId 同样是不可信输入,且会流入落盘路径:codex 侧
@@ -367,7 +401,10 @@ export async function commitShareImport(
// 协同包的每个 Worker 与 lead 同口径校验。
const portableActiveSdkSessionId = manifest.activeSdkSessionId;
if (portableActiveSdkSessionId && !isSafePathSegment(portableActiveSdkSessionId)) {
- throw new XdtshareError('SHARE_FILE_INVALID', `unsafe activeSdkSessionId: ${portableActiveSdkSessionId}`);
+ throw new XdtshareError(
+ 'SHARE_FILE_INVALID',
+ `unsafe activeSdkSessionId: ${portableActiveSdkSessionId}`,
+ );
}
// .xdtshare 是他人给的不可信输入:sdkSessionId 会拼进落盘路径(`<id>.jsonl`),
// 恶意包塞 `../../evil` 可逃出转码目录写任意文件(review bot P1)。写盘/预检前
@@ -376,9 +413,7 @@ export async function commitShareImport(
transcripts: XdtshareManifest['transcripts'],
label: string,
): BundledTranscript[] => {
- const bundled = transcripts.filter(
- (t): t is BundledTranscript => t.path !== null,
- );
+ const bundled = transcripts.filter((t): t is BundledTranscript => t.path !== null);
for (const t of bundled) {
if (!isSafePathSegment(t.sdkSessionId)) {
throw new XdtshareError(
@@ -391,10 +426,7 @@ export async function commitShareImport(
};
const bundledTranscripts = filterBundled(manifest.transcripts, 'transcripts');
for (const plan of workerPlans) {
- if (
- plan.manifest.activeSdkSessionId &&
- !isSafePathSegment(plan.manifest.activeSdkSessionId)
- ) {
+ if (plan.manifest.activeSdkSessionId && !isSafePathSegment(plan.manifest.activeSdkSessionId)) {
throw new XdtshareError(
'SHARE_FILE_INVALID',
`unsafe worker activeSdkSessionId: ${plan.manifest.activeSdkSessionId}`,
@@ -432,7 +464,9 @@ export async function commitShareImport(
portableId: string | null,
): string | null =>
agentKind === 'pi'
- ? (portableId ? (piTranscriptTargets.get(portableId) ?? null) : null)
+ ? portableId
+ ? (piTranscriptTargets.get(portableId) ?? null)
+ : null
: portableId;
const activeSdkSessionId = resolveActiveSdkSessionId(
manifest.agentKind,
@@ -462,17 +496,22 @@ export async function commitShareImport(
),
];
for (const probe of conflictProbes) {
- const existing = await getDbClient().queryOne<{
- id: string;
- status: 'active' | 'archived';
- }>(
- `SELECT id, status FROM sessions
- WHERE agent_kind = ? AND sdk_session_id = ? AND status != 'deleted' LIMIT 1`,
- [probe.agentKind, probe.resumeId],
+ const existing = await guarded(() =>
+ dbClient.queryOne<{
+ id: string;
+ status: 'active' | 'archived';
+ }>(
+ `SELECT id, status FROM sessions
+ WHERE agent_kind = ? AND sdk_session_id = ? AND status != 'deleted' LIMIT 1`,
+ [probe.agentKind, probe.resumeId],
+ ),
);
if (existing) {
if (!opts.overwrite) {
- throw codedError('SHARE_CONFLICT', `session with same resume id already imported: ${existing.id}`);
+ throw codedError(
+ 'SHARE_CONFLICT',
+ `session with same resume id already imported: ${existing.id}`,
+ );
}
if (!conflictExisting.some((c) => c.id === existing.id)) conflictExisting.push(existing);
}
@@ -483,11 +522,12 @@ export async function commitShareImport(
// 命中其历次 team,从 Worker 反查所属 team,再把对应 lead 与全部 Worker
// session 纳入同一事务,防止旧隐藏 Worker/关系残留成孤儿或与新图并存。
for (const existing of [...conflictExisting]) {
- const graphRows = await getDbClient().query<{
- id: string;
- status: 'active' | 'archived';
- }>(
- `WITH related_leads AS (
+ const graphRows = await guarded(() =>
+ dbClient.query<{
+ id: string;
+ status: 'active' | 'archived';
+ }>(
+ `WITH related_leads AS (
SELECT lead_session_id AS id FROM orca_teams WHERE lead_session_id = ?
UNION
SELECT t.lead_session_id AS id
@@ -505,8 +545,9 @@ export async function commitShareImport(
SELECT s.id, s.status
FROM related_sessions r
JOIN sessions s ON s.id = r.id
- WHERE s.status != 'deleted'`,
- [existing.id, existing.id],
+ WHERE s.status != 'deleted'`,
+ [existing.id, existing.id],
+ ),
);
for (const row of graphRows) {
if (!conflictExisting.some((candidate) => candidate.id === row.id)) {
@@ -534,6 +575,11 @@ export async function commitShareImport(
});
}
};
+ // Keep this in a mutable cell: the assignments happen inside the route-lock
+ // callback, which TypeScript does not include in outer control-flow narrowing.
+ const finalTxState: {
+ outcome: 'not-started' | 'in-flight' | 'committed';
+ } = { outcome: 'not-started' };
try {
// 0. 覆盖导入命中的旧 session 不在编排层提前软删。patchSessionMetaInDb
@@ -547,7 +593,7 @@ export async function commitShareImport(
// 草稿开 worktree 创建同语义。失败即中止导入;成功登记 journal,后续
// 任一步失败逆序回滚时移除 worktree,不留孤儿。
if (opts.useWorktree && manifest.workspaceKind === 'project') {
- const detect = await detectCwd(workingDir).catch(() => null);
+ const detect = await guarded(() => detectCwd(workingDir).catch(() => null));
if (!detect?.isGitRepo || !detect.repoRoot) {
throw codedError(
'SHARE_WORKTREE_NOT_GIT',
@@ -555,8 +601,9 @@ export async function commitShareImport(
);
}
const baseRepo = detect.repoRoot;
- let wtName = (await suggestWorktreeName(baseRepo).catch(() => '')).trim();
+ let wtName = (await guarded(() => suggestWorktreeName(baseRepo).catch(() => ''))).trim();
if (!wtName) wtName = `auto-${Date.now().toString(36).slice(-6)}`;
+ assertStillValid();
const resp = await createWorktree({
sessionId: newId,
baseRepo,
@@ -571,6 +618,7 @@ export async function commitShareImport(
journal.push(async () => {
await removeWorktreeForSession(newId);
});
+ assertStillValid();
log.info('share import created worktree', { newId, baseRepo, worktreePath });
}
@@ -608,14 +656,18 @@ export async function commitShareImport(
if (!entry.zipPath) continue;
const file = zip.file(entry.zipPath);
if (!file) continue;
- const buffer = Buffer.from(await file.async('nodebuffer'));
+ const buffer = Buffer.from(await guarded(() => file.async('nodebuffer')));
const restored = await restoreMediaEntry({
entry,
buffer,
newSessionId: newId,
sharedMediaRoot,
journal,
+ db: mediaDb,
+ assertStillValid,
+ refCompensationScope: runtimeScope.refCompensationScope,
});
+ assertStillValid();
if (!restored) continue;
if (restored.kind === 'session-image') {
// 入仓形态只挂引用行(回滚走 removeSessionMediaRefs);老目录回落形态
@@ -639,7 +691,7 @@ export async function commitShareImport(
// 回滚只删引用行(账本);字节本身内容寻址无害,留给对账/回收器,
// 与 ingest 的"先字节后记账"崩溃语义一致。
journal.push(async () => {
- await removeSessionMediaRefs(newId).catch(() => undefined);
+ await removeSessionMediaRefs(newId, mediaDb).catch(() => undefined);
});
}
@@ -673,7 +725,7 @@ export async function commitShareImport(
// 保真度不降档)。
let transcriptsWritten = 0;
if (claudeTargetDir && transcriptsPlaceable) {
- await fsp.mkdir(claudeTargetDir, { recursive: true });
+ await guarded(() => fsp.mkdir(claudeTargetDir, { recursive: true }).then(() => undefined));
for (const restore of restorePlans) {
if (restore.agentKind !== 'cc') continue;
for (const t of restore.bundled) {
@@ -681,13 +733,17 @@ export async function commitShareImport(
if (!file) continue;
const target = path.join(claudeTargetDir, `${t.sdkSessionId}.jsonl`);
try {
- await fsp.writeFile(target, Buffer.from(await file.async('nodebuffer')), { flag: 'wx' });
+ const transcriptBytes = Buffer.from(await guarded(() => file.async('nodebuffer')));
+ assertStillValid();
+ await fsp.writeFile(target, transcriptBytes, { flag: 'wx' });
journal.push(async () => {
await fsp.rm(target, { force: true });
});
+ assertStillValid();
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;
log.info('transcript already on disk, reusing', { sdkSessionId: t.sdkSessionId });
+ assertStillValid();
}
transcriptsWritten += 1;
}
@@ -705,7 +761,12 @@ export async function commitShareImport(
const file = zip.file(transcript.path);
if (!target || !file || piTargetsWritten.has(target)) continue;
piTargetsWritten.add(target);
- await writeIfMissing(target, Buffer.from(await file.async('nodebuffer')), journal);
+ await writeIfMissing(
+ target,
+ Buffer.from(await guarded(() => file.async('nodebuffer'))),
+ journal,
+ assertStillValid,
+ );
transcriptsWritten += 1;
}
}
@@ -716,7 +777,7 @@ export async function commitShareImport(
const threadId = restore.activeSdkSessionId;
const stateEntry = zip.file(`${restore.prefix}codex-state/thread.json`);
const stateRows = stateEntry
- ? ((JSON.parse(await stateEntry.async('string'))) as {
+ ? (JSON.parse(await guarded(() => stateEntry.async('string'))) as {
threads: Array<Record<string, unknown>>;
threadDynamicTools: Array<Record<string, unknown>>;
threadSpawnEdges: Array<Record<string, unknown>>;
@@ -724,10 +785,14 @@ export async function commitShareImport(
: { threads: [], threadDynamicTools: [], threadSpawnEdges: [] };
const rolloutRef = restore.bundled[0] ?? null;
const rolloutFile = rolloutRef ? zip.file(rolloutRef.path) : null;
+ const rolloutBuffer = rolloutFile
+ ? Buffer.from(await guarded(() => rolloutFile.async('nodebuffer')))
+ : null;
+ assertStillValid();
const written = await importSharedCodexThread({
threadId,
stateRows,
- rolloutBuffer: rolloutFile ? Buffer.from(await rolloutFile.async('nodebuffer')) : null,
+ rolloutBuffer,
rolloutFilename: rolloutRef ? path.posix.basename(rolloutRef.path) : null,
newCwd: workingDir,
title: restore.title,
@@ -736,10 +801,15 @@ export async function commitShareImport(
journal.push(async () => {
await removeSharedCodexThread(threadId, written);
});
+ assertStillValid();
if (written.rolloutPath) transcriptsWritten += 1;
// 降档提示看 statePresent(state 行最终在不在),不能看 stateWritten——
// 删除后重导时行已存在、本次零插入,state 依然完好,不该提示。
- if (!written.statePresent && stateRows.threads.length > 0 && !notes.includes('codexStateSkipped')) {
+ if (
+ !written.statePresent &&
+ stateRows.threads.length > 0 &&
+ !notes.includes('codexStateSkipped')
+ ) {
notes.push('codexStateSkipped');
}
}
@@ -823,27 +893,33 @@ export async function commitShareImport(
}),
}
: undefined;
- await getDbClient().tx('session.importShare', {
- session: buildSessionRow({
- newId,
- agentKind: manifest.agentKind,
- title: manifest.title || 'Shared session',
- workspaceKind: manifest.workspaceKind,
- orcaRole: manifest.orca ? ('lead' as const) : null,
- snapshot: sessionSnapshot,
- draftPrefs,
- applyDraftPrefs: true,
- workingDir,
- worktreePath,
- activeSdkSessionId,
- now,
- }),
- messages: dbMessages,
- ...(conflictExisting.length > 0
- ? { replaceSessions: conflictExisting }
- : {}),
- ...(orcaTxArgs ? { orca: orcaTxArgs } : {}),
- });
+ await withSessionRouteLocks(
+ conflictExisting.map((session) => session.id),
+ async () => {
+ assertStillValid();
+ finalTxState.outcome = 'in-flight';
+ await dbClient.tx('session.importShare', {
+ session: buildSessionRow({
+ newId,
+ agentKind: manifest.agentKind,
+ title: manifest.title || 'Shared session',
+ workspaceKind: manifest.workspaceKind,
+ orcaRole: manifest.orca ? ('lead' as const) : null,
+ snapshot: sessionSnapshot,
+ draftPrefs,
+ applyDraftPrefs: true,
+ workingDir,
+ worktreePath,
+ activeSdkSessionId,
+ now,
+ }),
+ messages: dbMessages,
+ ...(conflictExisting.length > 0 ? { replaceSessions: conflictExisting } : {}),
+ ...(orcaTxArgs ? { orca: orcaTxArgs } : {}),
+ });
+ finalTxState.outcome = 'committed';
+ },
+ );
// ── 最终保真度(lead + 全部 Worker 聚合) ──
const bundledKeys = new Set(
@@ -878,13 +954,25 @@ export async function commitShareImport(
replacedSessions: conflictExisting,
};
} catch (err) {
- await rollback();
+ // A resolved final transaction is the import commit point. A dispatched
+ // worker RPC can also commit and then lose its ACK during an owner switch,
+ // timeout, or worker termination. In that explicitly classified ambiguous
+ // state, preserve staged files/refs: an orphan leak is recoverable, while
+ // deleting bytes that committed messages reference is permanent corruption.
+ // Deterministic worker/business failures still roll back normally.
+ const preserveStagedArtifacts =
+ finalTxState.outcome === 'in-flight' && isDbTransportOutcomeUnknown(err);
+ if (preserveStagedArtifacts) {
+ log.warn('share import final transaction outcome is unknown; preserving staged artifacts', {
+ sessionId: newId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ } else if (finalTxState.outcome !== 'committed') {
+ await rollback();
+ }
const code = (err as { code?: unknown }).code;
if (typeof code === 'string' && code !== 'ALREADY_EXISTS') throw err;
- throw codedError(
- 'SHARE_IMPORT_FAILED',
- err instanceof Error ? err.message : String(err),
- );
+ throw codedError('SHARE_IMPORT_FAILED', err instanceof Error ? err.message : String(err));
}
}
@@ -897,7 +985,8 @@ async function readJsonEntry(zip: JSZip, entryPath: string): Promise<Record<stri
if (!file) throw codedError('SHARE_FILE_INVALID', `${entryPath} missing`);
try {
const parsed = JSON.parse(await file.async('string')) as unknown;
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not object');
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
+ throw new Error('not object');
return parsed as Record<string, unknown>;
} catch {
throw codedError('SHARE_FILE_INVALID', `${entryPath} is not valid JSON`);
@@ -1014,23 +1103,34 @@ async function restoreMediaEntry(params: {
newSessionId: string;
sharedMediaRoot: string;
journal: Array<() => Promise<void>>;
+ db: LedgerDb;
+ assertStillValid: () => void;
+ refCompensationScope: MediaRefCompensationScope;
}): Promise<RestoredMedia | null> {
const { entry, buffer, newSessionId, sharedMediaRoot, journal } = params;
// 老包媒体入总仓的统一小工具:字节 → blob + import 引用,mime 按已验证来源
// 的扩展名反查;白名单外/账本不可用返回 null 由调用方走各自回落路径。
// 白名单即 blobStore 全集(含 .glb 模型)——比"图/音/视频"口径略宽是有意的:
// xdt-file 直读协议本就放行 .glb,入仓只是换了字节的住处。
- const ingestLegacyMedia = async (ext: string): Promise<{ url: string; absPath: string } | null> => {
+ const ingestLegacyMedia = async (
+ ext: string,
+ ): Promise<{ url: string; absPath: string } | null> => {
const mimeType = mimeForExt(ext.toLowerCase());
if (!mimeType) return null;
try {
- const written = await ingestMedia({
- buffer,
- mimeType,
- refs: [{ refKind: 'import', refId: newSessionId, originKind: 'user' }],
- });
+ const written = await ingestMedia(
+ {
+ buffer,
+ mimeType,
+ refs: [{ refKind: 'import', refId: newSessionId, originKind: 'user' }],
+ assertStillValid: params.assertStillValid,
+ refCompensationScope: params.refCompensationScope,
+ },
+ params.db,
+ );
return { url: written.url, absPath: resolveBlobHashRef(written.hash, written.ext).absPath };
} catch (err) {
+ params.assertStillValid();
log.warn('import media ingest failed, falling back to legacy dir', {
url: entry.url,
error: err instanceof Error ? err.message : String(err),
@@ -1056,18 +1156,18 @@ async function restoreMediaEntry(params: {
const targetDir = getSessionDir(newSessionId);
await fsp.mkdir(targetDir, { recursive: true });
const target = path.join(targetDir, parsed.filename);
- await writeIfMissing(target, buffer, journal);
+ await writeIfMissing(target, buffer, journal, params.assertStillValid);
return {
kind: 'session-image',
newUrl: `xdt-image://${newSessionId}/${encodeURIComponent(parsed.filename)}`,
};
}
- await writeIfMissing(absPath, buffer, journal);
+ await writeIfMissing(absPath, buffer, journal, params.assertStillValid);
return { kind: 'reserved' };
}
if (entry.kind === 'video') {
const { absPath } = resolveVideoUrl(entry.url);
- await writeIfMissing(absPath, buffer, journal);
+ await writeIfMissing(absPath, buffer, journal, params.assertStillValid);
return { kind: 'reserved' };
}
if (entry.kind === 'blob') {
@@ -1088,16 +1188,21 @@ async function restoreMediaEntry(params: {
return null;
}
// 挂 import 引用(归属导入会话,删会话时随 removeSessionRefs 走)。
- await ingestMedia({
- buffer,
- mimeType,
- refs: [{ refKind: 'import', refId: params.newSessionId, originKind: 'user' }],
- });
+ await ingestMedia(
+ {
+ buffer,
+ mimeType,
+ refs: [{ refKind: 'import', refId: params.newSessionId, originKind: 'user' }],
+ assertStillValid: params.assertStillValid,
+ refCompensationScope: params.refCompensationScope,
+ },
+ params.db,
+ );
return { kind: 'blob' };
}
if (entry.kind === 'model') {
const { absPath } = resolveModelUrl(entry.url);
- await writeIfMissing(absPath, buffer, journal);
+ await writeIfMissing(absPath, buffer, journal, params.assertStillValid);
return { kind: 'reserved' };
}
// loose:按 zipPath 里带序号的文件名落盘(天然去重),二次单段校验防穿越
@@ -1113,9 +1218,10 @@ async function restoreMediaEntry(params: {
const targetDir = path.join(sharedMediaRoot, newSessionId);
await fsp.mkdir(targetDir, { recursive: true });
const target = path.join(targetDir, filename);
- await writeIfMissing(target, buffer, journal);
+ await writeIfMissing(target, buffer, journal, params.assertStillValid);
return { kind: 'loose', newUrl: buildLooseUrl(scheme, target) };
} catch (err) {
+ params.assertStillValid();
log.warn('restore media entry failed', {
url: entry.url,
error: err instanceof Error ? err.message : String(err),
@@ -1129,20 +1235,32 @@ async function writeIfMissing(
target: string,
buffer: Buffer,
journal: Array<() => Promise<void>>,
+ assertStillValid: () => void,
): Promise<void> {
+ assertStillValid();
await fsp.mkdir(path.dirname(target), { recursive: true });
+ assertStillValid();
try {
await fsp.writeFile(target, buffer, { flag: 'wx' });
journal.push(async () => {
await fsp.rm(target, { force: true });
});
+ assertStillValid();
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;
+ assertStillValid();
}
}
const EFFORTS = new Set(['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']);
-const PERMISSION_MODES = new Set(['ask', 'default', 'acceptEdits', 'plan', 'auto', 'bypassPermissions']);
+const PERMISSION_MODES = new Set([
+ 'ask',
+ 'default',
+ 'acceptEdits',
+ 'plan',
+ 'auto',
+ 'bypassPermissions',
+]);
/** draftPrefs 缺省(旧调用方 / 测试)时按 agentKind 兜底的模型。 */
const FALLBACK_MODEL_BY_AGENT: Record<'cc' | 'codex' | 'pi', string> = {
@@ -1192,8 +1310,7 @@ function buildSessionRow(params: {
now,
} = params;
const draftPrefs = params.applyDraftPrefs ? params.draftPrefs : null;
- const str = (v: unknown, fallback: string): string =>
- typeof v === 'string' && v ? v : fallback;
+ const str = (v: unknown, fallback: string): string => (typeof v === 'string' && v ? v : fallback);
const num = (v: unknown, fallback: number): number =>
typeof v === 'number' && Number.isFinite(v) ? v : fallback;
const effort = str(draftPrefs?.effort, 'high');
diff --git a/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts b/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
index 4f6679a1ba..bf10cae7a4 100644
--- a/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
+++ b/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
@@ -19,6 +19,7 @@ import { eq, inArray } from 'drizzle-orm';
import { removeWorktreeForSession } from './WorktreeManager';
import * as store from './worktreeStore';
import { getDbClient } from '../localDb/client/current';
+import type { DbClient } from '../localDb/client/DbClient';
import { sessions } from '../localDb/schema';
import { createLogger } from '../logger';
@@ -35,7 +36,15 @@ const log = createLogger('sessionRemovalRecycle');
* 调用方约定:先确保该会话的 CLI 子进程已关闭(Windows 下子进程 cwd 在
* worktree 内会锁目录,git worktree remove 必败),再调本函数。
*/
-export async function recycleWorktreeForRemovedSession(sessionId: string): Promise<void> {
+export interface RecycleWorktreeForRemovedSessionOptions {
+ db?: DbClient['drizzle'];
+ isOwnerCurrent?: () => boolean;
+}
+
+export async function recycleWorktreeForRemovedSession(
+ sessionId: string,
+ options: RecycleWorktreeForRemovedSessionOptions = {},
+): Promise<void> {
const meta = store.get(sessionId);
if (!meta) return;
if (meta.ephemeral) {
@@ -44,7 +53,10 @@ export async function recycleWorktreeForRemovedSession(sessionId: string): Promi
);
return;
}
- const status = await readCurrentSessionStatus(sessionId);
+ const db = options.db ?? getDbClient().drizzle;
+ const isOwnerCurrent = options.isOwnerCurrent ?? (() => true);
+ if (!isOwnerCurrent()) return;
+ const status = await readCurrentSessionStatus(sessionId, db);
if (status !== 'deleted' && status !== 'archived') {
log.info(
`[sessionRemovalRecycle] skip worktree recycle for session ${sessionId}: current status=${status ?? 'missing'}`,
@@ -53,7 +65,8 @@ export async function recycleWorktreeForRemovedSession(sessionId: string): Promi
}
await removeWorktreeForSession(sessionId, {
canRemove: async () => {
- const currentStatus = await readCurrentSessionStatus(sessionId);
+ if (!isOwnerCurrent()) return false;
+ const currentStatus = await readCurrentSessionStatus(sessionId, db);
return currentStatus === 'deleted' || currentStatus === 'archived';
},
});
@@ -63,14 +76,19 @@ export async function recycleWorktreeForRemovedSession(sessionId: string): Promi
* 动态回收任务在关闭 CLI / 删除 worktree 前共用的实时状态守卫。
* 查询失败按不可回收处理,宁可保留也不误关已恢复为 active 的会话。
*/
-export async function isSessionStillRemovable(sessionId: string): Promise<boolean> {
- const status = await readCurrentSessionStatus(sessionId);
+export async function isSessionStillRemovable(
+ sessionId: string,
+ db: DbClient['drizzle'] = getDbClient().drizzle,
+): Promise<boolean> {
+ const status = await readCurrentSessionStatus(sessionId, db);
return status === 'deleted' || status === 'archived';
}
-async function readCurrentSessionStatus(sessionId: string): Promise<string | null> {
+async function readCurrentSessionStatus(
+ sessionId: string,
+ db: DbClient['drizzle'],
+): Promise<string | null> {
try {
- const db = getDbClient().drizzle;
const [row] = await db
.select({ status: sessions.status })
.from(sessions)
@@ -103,7 +121,12 @@ export async function reconcileWorktreesForDeletedSessions(): Promise<void> {
rows = await db
.select({ id: sessions.id, status: sessions.status })
.from(sessions)
- .where(inArray(sessions.id, candidates.map((m) => m.sessionId)));
+ .where(
+ inArray(
+ sessions.id,
+ candidates.map((m) => m.sessionId),
+ ),
+ );
} catch (err) {
// DB 不可用时不做任何删除(保守方向:漏收一轮无害,误删不可逆)。
log.warn(
diff --git a/packages/lizi-mcps/src/__tests__/archiveSessionsTool.test.ts b/packages/lizi-mcps/src/__tests__/archiveSessionsTool.test.ts
index 6ad7fcd369..c1e01d0db6 100644
--- a/packages/lizi-mcps/src/__tests__/archiveSessionsTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/archiveSessionsTool.test.ts
@@ -106,6 +106,30 @@ describe('archive_sessions tool', () => {
expect(parse(res)).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });
});
+ it('explains that deleted sessions cannot be restored through status tools', async () => {
+ const deps: ArchiveSessionsDeps = {
+ getSessionContext: () => ({
+ sessionId: 'current-session',
+ agentKind: 'claude-code',
+ workingDir: '/tmp/proj',
+ }),
+ setSessionsStatus: vi.fn(async () => ({
+ ok: false as const,
+ errorCode: 'PRECONDITION_FAILED' as const,
+ message: '已删除的任务不能恢复或归档: deleted-session',
+ })),
+ };
+ const registry = new XdtHelperToolRegistry();
+ registerUnarchiveSessionsTool(registry, deps);
+
+ const res = await registry.call('unarchive_sessions', {
+ session_ids: ['deleted-session'],
+ });
+
+ expect(res.isError).toBe(true);
+ expect(parse(res)).toMatchObject({ ok: false, errorCode: 'PRECONDITION_FAILED' });
+ });
+
it('rejects empty batch at schema boundary', async () => {
const { registry } = setup();
const res = await registry.call('archive_sessions', { session_ids: [] });
diff --git a/packages/lizi-mcps/src/xdt-helper/archive_sessions.ts b/packages/lizi-mcps/src/xdt-helper/archive_sessions.ts
index 2cafc40d55..da2bf8cc52 100644
--- a/packages/lizi-mcps/src/xdt-helper/archive_sessions.ts
+++ b/packages/lizi-mcps/src/xdt-helper/archive_sessions.ts
@@ -33,12 +33,13 @@ export interface SessionStatusChangeItem {
}
/**
- * host 回调结果。NOT_FOUND 表示批次里至少有一个 id 不存在 —— host 不做任何写入
- * (全有才写,避免半应用),message 里带上缺失的 id 方便 LLM 自纠。
+ * host 回调结果。NOT_FOUND 表示批次里至少有一个 id 不存在;
+ * PRECONDITION_FAILED 表示目标已经删除,通用状态工具不能将其复活。
+ * 两种情况 host 都不做任何写入(全有且可变更才写,避免半应用)。
*/
export type SetSessionsStatusResult = ControlResult<
{ changed: SessionStatusChangeItem[] },
- 'NOT_FOUND'
+ 'NOT_FOUND' | 'PRECONDITION_FAILED'
>;
export interface ArchiveSessionsDeps {
@@ -51,13 +52,15 @@ export interface ArchiveSessionsDeps {
const ARCHIVE_DESCRIPTION =
`批量归档 ${BRAND_NAME} 历史对话/session(把 status 置为 archived,从侧栏 active 列表移出)。` +
- '归档可逆、不删数据,要恢复用 unarchive_sessions。适合"清理已完成/过期会话"。' +
+ '归档可逆、不删数据,要恢复用 unarchive_sessions;已删除的 session 不能归档或恢复。' +
+ '适合"清理已完成/过期会话"。' +
'建议先用 history/list_sessions 找到目标 session_id。' +
- '失败码: NOT_FOUND(某些 id 不存在,整批不写) / NO_SESSION_CONTEXT / HOST_NOT_READY / INVALID_ARGS。';
+ '失败码: NOT_FOUND(某些 id 不存在,整批不写) / PRECONDITION_FAILED(目标已删除) / NO_SESSION_CONTEXT / HOST_NOT_READY / INVALID_ARGS。';
const UNARCHIVE_DESCRIPTION =
`批量取消归档 ${BRAND_NAME} 历史对话/session(把 status 置回 active,恢复到侧栏 active 列表)。` +
- '是 archive_sessions 的逆操作。失败码: NOT_FOUND / NO_SESSION_CONTEXT / HOST_NOT_READY / INVALID_ARGS。';
+ '是 archive_sessions 的逆操作;已删除的 session 不能通过此工具复活。' +
+ '失败码: NOT_FOUND / PRECONDITION_FAILED(目标已删除) / NO_SESSION_CONTEXT / HOST_NOT_READY / INVALID_ARGS。';
function dedupe(ids: string[]): { ids: string[]; duplicate: string | null } {
const seen = new Set<string>();