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: honor cancellation before archived task restoration writes

Dash02f9aa8fe212
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 16ff9f8075..be1a0bf7b4 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -777,6 +777,34 @@ describe('local-db:sessions:update handler wiring', () => {
}));
});
+ // PR #6403 P1: entry-time abort tests missed cancellation during DB awaits.
+ // Run the production restore/writer against SQLite, interrupting its read
+ // continuations or the issued write. DB tier; no timers or copied handler.
+ it.each(['initial-read', 'lifecycle-read', 'issued-write'] as const)(
+ 'honors the restore commit boundary when cancelled at %s', async stage => {
+ h.sqlite!.prepare("UPDATE sessions SET status = 'archived' WHERE id = ?").run('codex-local');
+ const controller = new AbortController();
+ const prepare = h.sqlite!.prepare.bind(h.sqlite!);
+ const interrupted = vi.spyOn(h.sqlite!, 'prepare').mockImplementation(sql => {
+ const selected = stage === 'initial-read' ? sql.startsWith('select "status", "source"')
+ : stage === 'lifecycle-read' ? sql.startsWith('select "source" from "sessions"')
+ : sql.startsWith('update "sessions"');
+ if (selected) queueMicrotask(() => controller.abort());
+ return prepare(sql);
+ });
+ try {
+ const restoring = restoreArchivedSessionForSend('codex-local', { routeLockHeld: true, signal: controller.signal });
+ if (stage === 'issued-write') await restoring;
+ else await expect(restoring).rejects.toThrow('Session send aborted');
+ expect(controller.signal.aborted).toBe(true);
+ expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id = ?').get('codex-local'))
+ .toEqual({ status: stage === 'issued-write' ? 'active' : 'archived' });
+ if (stage === 'issued-write') expect(h.tapWindowBroadcast).toHaveBeenCalled();
+ else expect(h.tapWindowBroadcast).not.toHaveBeenCalled();
+ } finally { interrupted.mockRestore(); }
+ },
+ );
+
it.each(['deleted', 'bot', 'worker', 'remote-worker'] as const)('does not restore %s tasks through ordinary send', async kind => {
h.sqlite!.prepare('UPDATE sessions SET status = ?, source = ?, orca_role = ?, orca_remote_lead = ? WHERE id = ?')
.run(kind === 'deleted' ? 'deleted' : 'archived', kind === 'bot' ? 'bot' : 'desktop',
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index dbbe298954..b233ab28d5 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -2173,7 +2173,7 @@ export async function updateSessionInDb(
* use the normal status writer so native projection and all clients see active. */
export async function restoreArchivedSessionForSend(
sessionId: string,
- options: { routeLockHeld?: boolean } = {},
+ options: { routeLockHeld?: boolean; signal?: AbortSignal } = {},
): Promise<void> {
const ownerScope = captureOwnerScope();
const db = getDbClient().drizzle;
@@ -2188,7 +2188,7 @@ export async function restoreArchivedSessionForSend(
if (row.source === 'bot' || row.orcaRole === 'worker' || row.orcaRemoteLead) {
throwIpcError('PRECONDITION_FAILED', 'Restore the managed task before continuing');
}
- await patchSessionMetaInDb(sessionId, { status: 'active' }, { routeLockHeld: true });
+ await patchSessionMetaInDb(sessionId, { status: 'active' }, { ...options, routeLockHeld: true });
};
if (options.routeLockHeld) await restore();
else await withSessionRouteLock(sessionId, restore);
@@ -2201,7 +2201,7 @@ export async function patchSessionMetaInDb(
title?: string;
pinnedAt?: string | null;
},
- options: { routeLockHeld?: boolean } = {},
+ options: { routeLockHeld?: boolean; signal?: AbortSignal } = {},
): Promise<ReturnType<typeof sessionToCamel>> {
const ownerScope = captureOwnerScope();
for (const k of Object.keys(patch)) {
@@ -2245,6 +2245,9 @@ export async function patchSessionMetaInDb(
await finalizeSharedTaskClosure(dbClient, prepared);
}
} else {
+ // All asynchronous preparation has finished. Once this write is issued,
+ // cancellation does not roll back a committed lifecycle transition.
+ if (options.signal?.aborted) throwIpcError('PRECONDITION_FAILED', 'Session send aborted');
await writeSessionPatch(db, sessionId, setObj, patch.status);
}
const row = await selectSessionWithCount(db, sessionId);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
index 15cae7b693..30d5ce5731 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
@@ -138,16 +138,12 @@ describe('Orca model-only picker intent admission', () => {
// PR #6403 P1: the composer already restores archived tasks, but Goal's
// direct-send lease did not. Execute the real lease, send boundary and model
// admission together; earlier picker tests stop before this boundary (unit).
- const directSendCases = ['archived', 'cross-engine', 'relocation', 'repicked-during-restore', 'config', 'agent', 'restore-failed', 'cancelled'] as const;
+ const directSendCases = ['archived', 'cross-engine', 'relocation', 'config', 'agent', 'restore-failed', 'cancelled'] as const;
it.each(directSendCases)('handles archived direct-send selection: %s', async mode => {
- const compile = (expression: string, bindings: Record<string, unknown>) => {
- const js = ts.transpileModule(`return ${expression};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
- return new Function(...Object.keys(bindings), js)(...Object.values(bindings));
- };
const row = { id: 's1', status: 'archived', agentKind: 'codex', model: 'old', providerId: 'provider', effort: 'low', fastMode: false,
sdkSessionId: null, remoteHostId: null, agentDeviceId: null };
const pending = createPendingAgentSwitchRegistry();
- const crossEngine = mode === 'cross-engine' || mode === 'repicked-during-restore';
+ const crossEngine = mode === 'cross-engine';
const intent: PendingAgentSwitchIntent = { targetAgentKind: crossEngine ? 'pi' : 'codex', model: 'new', providerId: 'provider',
...(mode === 'relocation' ? { targetAgentDeviceId: 'executor-device' } : !crossEngine ? { sameAgentSelection: true } : {}),
...(mode === 'config' ? { configStaged: true } : mode === 'agent' ? { runtimeSource: 'agent' } : {}),
@@ -165,10 +161,8 @@ describe('Orca model-only picker intent admission', () => {
});
const release = vi.fn();
const acquire = vi.fn(async () => release);
- let finishRestore: (() => void) | undefined;
const restore = vi.fn(async () => {
if (mode === 'restore-failed') throw new Error('restore failed');
- if (mode === 'repicked-during-restore') await new Promise<void>(resolve => { finishRestore = resolve; });
row.status = 'active';
});
const switchToDb = vi.fn(async (_id: string, patch: object) => {
@@ -206,25 +200,19 @@ describe('Orca model-only picker intent admission', () => {
lease.release();
} else if (mode !== 'restore-failed' && mode !== 'cancelled') {
const sending = directSend('s1', controller.signal);
- // A later picker choice while restore awaits must be the one applied.
- if (mode === 'repicked-during-restore') {
- await vi.waitFor(() => expect(restore).toHaveBeenCalledOnce());
- pending.set('s1', { ...intent, model: 'latest' });
- finishRestore!();
- }
const lease = await sending;
expect(row.status).toBe('active');
if (mode === 'archived') expect(applied).toHaveBeenCalledOnce();
else {
expect(switchToDb).toHaveBeenCalledOnce();
- expect(row.model).toBe(mode === 'repicked-during-restore' ? 'latest' : 'new');
+ expect(row.model).toBe('new');
expect(row.agentKind).toBe(mode === 'relocation' ? 'codex' : 'pi');
if (mode === 'relocation') expect(row.agentDeviceId).toBe('executor-device');
if (mode === 'cross-engine' || mode === 'relocation') expect(row).toMatchObject({ effort: 'high', fastMode: true });
}
expect(pending.get('s1')).toBeUndefined();
expect(acquire.mock.invocationCallOrder[0]).toBeLessThan(restore.mock.invocationCallOrder[0]);
- expect(restore).toHaveBeenCalledWith('s1', { routeLockHeld: true });
+ expect(restore).toHaveBeenCalledWith('s1', { routeLockHeld: true, signal: controller.signal });
expect(release).not.toHaveBeenCalled();
lease.release();
expect(release).toHaveBeenCalledOnce();
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index a672251d98..d604e09e27 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -10444,7 +10444,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const pendingSelection = agentSwitchPending.get(sessionId);
if (!signal?.aborted && isUserPendingAgentSwitchIntent(pendingSelection)) {
stage = 'direct-send:restoreArchivedSession';
- await restoreArchivedSessionForSend(sessionId, { routeLockHeld: true });
+ await restoreArchivedSessionForSend(sessionId, { routeLockHeld: true, signal });
}
stage = 'direct-send:reconcileBotModelRoute';
await reconcileBotModelRoute(sessionId, true);
diff --git a/docs/dev-rules/model-catalog-runtime.md b/docs/dev-rules/model-catalog-runtime.md
index 5c4e2f0cda..18631247a0 100644
--- a/docs/dev-rules/model-catalog-runtime.md
+++ b/docs/dev-rules/model-catalog-runtime.md
@@ -51,7 +51,8 @@ thread 配置,同时设置窗口和 90% 自动压缩预算,保留原生 5%
归档任务允许用户调整模型、推理强度与 Fast,不要求先恢复,也不因设置变化恢复任务。
模型选择沿用活动任务的暂存意图,下一次发送(含 Goal 直发)在现有发送锁内读取最新意图,经普通任务恢复入口恢复
-任务再应用;受管任务的恢复限制保持不变。暂存意图仍只在被控端
+任务再应用;取消在恢复状态写入发出前可见时保留归档,已发出的写入不补偿回滚。
+受管任务的恢复限制保持不变。暂存意图仍只在被控端
内存中保留,不新增跨进程恢复。已有用户模型意图时,无论同引擎、跨引擎或换执行电脑,
推理强度与 Fast 都更新完整待选意图,保留目标路由和窗口确认,不改写自动意图;否则
只保存任务字段,不重建归档时清掉的 runtime 状态。本地与远控档位均由 Main 协调提交,