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(sharing): persist closure before terminal task state

DavidShenf76daa04a8c3
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts
index 0b39ac9dbc..dccc5fa66d 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts
@@ -9,12 +9,18 @@ type HostRecord = {
const state = vi.hoisted(() => ({
accountId: 'owner', region: 'global', authenticated: true,
session: { mode: 'cloud', dataOwnerId: 'owner', generation: 1 }, boundary: false,
- db: { client: { query: vi.fn() }, clientEpoch: 1 },
+ db: { client: { query: vi.fn(), exec: vi.fn() }, clientEpoch: 1 },
hosts: [] as HostRecord[], dispatch: vi.fn(),
- captureClose: vi.fn(), close: vi.fn(), journalClose: vi.fn(),
+ captureClose: vi.fn(), close: vi.fn(), journalClose: vi.fn(), journalPrepare: vi.fn(), journalRollback: vi.fn(), journalFinalize: vi.fn(),
}));
vi.mock('../../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot: () => state.db }));
-vi.mock('../../localDb/sharedTasks.js', () => ({ createSharedTaskJournal: () => ({}), closeSharedTasksInJournalForSession: state.journalClose }));
+vi.mock('../../localDb/sharedTasks.js', () => ({
+ createSharedTaskJournal: () => ({}),
+ closeSharedTasksInJournalForSession: state.journalClose,
+ prepareSharedTasksForSession: state.journalPrepare,
+ rollbackPreparedSharedTasks: state.journalRollback,
+ finalizePreparedSharedTasks: state.journalFinalize,
+}));
vi.mock('../../appSessionState.js', () => ({
activeOwnerScopeKey: () => [state.session.mode, state.session.dataOwnerId, state.session.generation].join(':'),
getActiveAppSession: () => ({ ...state.session }), isAppSessionBoundaryPending: () => state.boundary,
@@ -36,7 +42,15 @@ vi.mock('../sharedTaskHost.js', () => ({
},
}));
-import { closeSharedTaskForTask, closeSharedTasksBeforeLogout, requireSharedTaskHost, startSharedTaskRuntime, stopSharedTaskRuntime } from '../sharedTaskRuntime';
+import {
+ closeSharedTaskForTask,
+ closeSharedTasksBeforeLogout,
+ prepareSharedTaskClosureForTask,
+ requireSharedTaskHost,
+ rollbackPreparedSharedTaskClosure,
+ startSharedTaskRuntime,
+ stopSharedTaskRuntime,
+} from '../sharedTaskRuntime';
function start() {
const client = { hasServerCapability: () => true, getStatus: () => 'online', start: vi.fn(), stop: vi.fn(), revoke: vi.fn() };
@@ -49,11 +63,14 @@ beforeEach(async () => {
vi.useFakeTimers();
state.accountId = 'owner'; state.region = 'global'; state.authenticated = true; state.boundary = false;
state.session = { mode: 'cloud', dataOwnerId: 'owner', generation: 1 };
- state.db = { client: { query: vi.fn() }, clientEpoch: 1 };
+ state.db = { client: { query: vi.fn(), exec: vi.fn() }, clientEpoch: 1 };
state.hosts.length = 0; state.dispatch.mockClear();
state.captureClose.mockReset().mockReturnValue(state.close);
state.close.mockReset().mockResolvedValue({ status: 'closed' });
state.journalClose.mockReset().mockResolvedValue(['sharedTask-a']);
+ state.journalPrepare.mockReset().mockResolvedValue({ sessionId: 'session', marker: 1, rowIds: [7] });
+ state.journalRollback.mockReset().mockResolvedValue(undefined);
+ state.journalFinalize.mockReset().mockResolvedValue(undefined);
});
afterEach(async () => {
await stopSharedTaskRuntime();
@@ -61,6 +78,23 @@ afterEach(async () => {
});
describe('shared runtime stable owner recommit', () => {
+ it('prepares and rolls back a terminal journal only in the captured profile database', async () => {
+ const db = state.db.client;
+ const prepared = await prepareSharedTaskClosureForTask('session', db);
+ expect(prepared).toEqual({ sessionId: 'session', marker: 1, rowIds: [7] });
+ expect(state.journalPrepare).toHaveBeenCalledWith(db, 'session');
+ await rollbackPreparedSharedTaskClosure(db, prepared);
+ expect(state.journalRollback).toHaveBeenCalledWith(db, prepared);
+ const { finalizePreparedSharedTaskClosure } = await import('../sharedTaskRuntime');
+ await finalizePreparedSharedTaskClosure(db, prepared);
+ expect(state.journalFinalize).toHaveBeenCalledWith(db, prepared);
+
+ expect(await prepareSharedTaskClosureForTask('session', {})).toBeNull();
+ await rollbackPreparedSharedTaskClosure({}, prepared);
+ expect(state.journalPrepare).toHaveBeenCalledOnce();
+ expect(state.journalRollback).toHaveBeenCalledOnce();
+ });
+
it('persists terminal changes without a relay binding and closes using captured credentials', async () => {
const db = state.db.client;
let finish!: (ids: string[]) => void;
@@ -70,7 +104,7 @@ describe('shared runtime stable owner recommit', () => {
expect(state.captureClose).toHaveBeenCalledWith('owner', 'global');
expect(state.close).not.toHaveBeenCalled();
state.accountId = 'new-owner'; state.region = 'cn';
- state.db = { client: { query: vi.fn() }, clientEpoch: 2 };
+ state.db = { client: { query: vi.fn(), exec: vi.fn() }, clientEpoch: 2 };
finish(['sharedTask-a']);
await pending;
expect(state.close).toHaveBeenCalledExactlyOnceWith('sharedTask-a');
@@ -100,7 +134,7 @@ describe('shared runtime stable owner recommit', () => {
state.session.generation++;
requireSharedTaskHost();
expect(state.hosts[1].options.creationState).toBe(original);
- state.db = { client: { query: vi.fn() }, clientEpoch: 2 };
+ state.db = { client: { query: vi.fn(), exec: vi.fn() }, clientEpoch: 2 };
start();
expect(state.hosts[2].options.creationState).not.toBe(original);
});
@@ -175,7 +209,7 @@ describe('shared runtime stable owner recommit', () => {
if (change === 'account') state.accountId = 'other';
if (change === 'stable-owner') state.session.dataOwnerId = 'other';
if (change === 'region') state.region = 'cn';
- if (change === 'database') state.db = { ...state.db, client: { query: vi.fn() } };
+ if (change === 'database') state.db = { ...state.db, client: { query: vi.fn(), exec: vi.fn() } };
if (change === 'database-epoch') state.db = { ...state.db, clientEpoch: state.db.clientEpoch + 1 };
if (change === 'signed-out') state.authenticated = false;
if (change === 'local') state.session.mode = 'local';
diff --git a/apps/desktop/src/main/device-link/sharedTaskRuntime.ts b/apps/desktop/src/main/device-link/sharedTaskRuntime.ts
index 2e47c8d018..d4eabdd6fb 100644
--- a/apps/desktop/src/main/device-link/sharedTaskRuntime.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskRuntime.ts
@@ -1,6 +1,13 @@
import { SHARED_TASK_CAPABILITY, type DeviceLinkClient } from '@cindy/device-link';
import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';
-import { closeSharedTasksInJournalForSession, createSharedTaskJournal } from '../localDb/sharedTasks.js';
+import {
+ closeSharedTasksInJournalForSession,
+ createSharedTaskJournal,
+ prepareSharedTasksForSession,
+ rollbackPreparedSharedTasks,
+ finalizePreparedSharedTasks,
+ type PreparedSharedTaskClosure,
+} from '../localDb/sharedTasks.js';
import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';
import { getAuthState, getCurrentUserId, getDeviceId, getActiveAuthRealm } from '../authManager.js';
import { createLogger } from '../logger.js';
@@ -143,3 +150,34 @@ export async function closeSharedTaskForTask(sessionId: string, database: unknow
// Network failure is retried from the terminal journal; never undo the task archive.
if (close) await Promise.allSettled([...ids].map((id) => close(id)));
}
+
+/** Persist a terminal close fence before the session status is changed. */
+export async function prepareSharedTaskClosureForTask(
+ sessionId: string,
+ database: unknown,
+): Promise<PreparedSharedTaskClosure | null> {
+ const db = getCurrentDbClientSnapshot();
+ if (!db || db.client !== database) return null;
+ return prepareSharedTasksForSession(db.client, sessionId);
+}
+
+/** Compensate a prepare when the corresponding terminal status write aborts. */
+export async function rollbackPreparedSharedTaskClosure(
+ database: unknown,
+ prepared: PreparedSharedTaskClosure | null,
+): Promise<void> {
+ if (!prepared) return;
+ // Rollback must use the captured profile DB even if the account boundary
+ // advanced while the terminal status write was being rejected.
+ if (!database || typeof (database as { exec?: unknown }).exec !== 'function') return;
+ await rollbackPreparedSharedTasks(database as Parameters<typeof rollbackPreparedSharedTasks>[0], prepared);
+}
+
+/** Promote a prepared close intent only after the session status is durable. */
+export async function finalizePreparedSharedTaskClosure(
+ database: unknown,
+ prepared: PreparedSharedTaskClosure | null,
+): Promise<void> {
+ if (!prepared || !database || typeof (database as { exec?: unknown }).exec !== 'function') return;
+ await finalizePreparedSharedTasks(database as Parameters<typeof finalizePreparedSharedTasks>[0], prepared);
+}
diff --git a/apps/desktop/src/main/localDb/__tests__/sharedTasks.test.ts b/apps/desktop/src/main/localDb/__tests__/sharedTasks.test.ts
index 5b3b0e230a..e018ecb376 100644
--- a/apps/desktop/src/main/localDb/__tests__/sharedTasks.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/sharedTasks.test.ts
@@ -2,7 +2,13 @@ import Database from 'better-sqlite3';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { closeSharedTasksInJournalForSession, createSharedTaskJournal } from '../sharedTasks.js';
+import {
+ closeSharedTasksInJournalForSession,
+ createSharedTaskJournal,
+ finalizePreparedSharedTasks,
+ prepareSharedTasksForSession,
+ rollbackPreparedSharedTasks,
+} from '../sharedTasks.js';
import type { SharedTaskSnapshot } from '@cindy/device-link';
const snapshot = (revision = 1): SharedTaskSnapshot => ({
@@ -24,6 +30,22 @@ beforeEach(() => {
afterEach(() => db.close());
describe('sharedTask authority journal', () => {
+ it('prepares a terminal fence and rolls back only that preparation', async () => {
+ await journal.recordAuthority(snapshot());
+ const writer = {
+ async exec(sql: string, params = []) { return db.prepare(sql).run(...params); },
+ async query<T>(sql: string, params: unknown[] = []) { return db.prepare(sql).all(...params) as T[]; },
+ };
+ const prepared = await prepareSharedTasksForSession(writer, 'session');
+ expect(prepared.rowIds).toHaveLength(1);
+ expect(await journal.latest()).toMatchObject([{ terminal: false }]);
+ await rollbackPreparedSharedTasks(writer, prepared);
+ expect(await journal.latest()).toMatchObject([{ terminal: false }]);
+ const committed = await prepareSharedTasksForSession(writer, 'session');
+ await finalizePreparedSharedTasks(writer, committed);
+ expect(await journal.latest()).toMatchObject([{ terminal: true }]);
+ });
+
it('hands off all generations of only the terminal task through the shared profile journal', async () => {
await journal.recordAuthority(snapshot());
await journal.recordAuthority({ ...snapshot(), sharedTaskId: 'new-share' });
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 5051c275df..8118cbeded 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -34,6 +34,9 @@ const h = vi.hoisted(() => ({
})),
closeSession: vi.fn(async (_sessionId: string) => undefined),
closeSharedTask: vi.fn(async (_sessionId: string, _database: unknown): Promise<void> => undefined),
+ prepareSharedTaskClosure: vi.fn(async (_sessionId: string, _database: unknown): Promise<{ sessionId: string; marker: number; rowIds: number[] } | null> => null),
+ rollbackSharedTaskClosure: vi.fn(async (_database: unknown, _prepared: unknown) => undefined),
+ finalizeSharedTaskClosure: vi.fn(async (_database: unknown, _prepared: unknown) => undefined),
commitBotProfileDeletion: vi.fn(async (): Promise<{ status: 'archived' | 'deleted'; sessionIds: string[] }> => ({ status: 'archived', sessionIds: [] })),
tapWindowBroadcast: vi.fn(),
windows: [] as Array<{
@@ -116,6 +119,9 @@ vi.mock('../../../git-context/prRefsStore', () => ({
vi.mock('../../../imageCacheStore', () => ({ removeSession: vi.fn(async () => undefined) }));
vi.mock('../../../device-link/sharedTaskRuntime.js', () => ({
closeSharedTaskForTask: h.closeSharedTask,
+ prepareSharedTaskClosureForTask: h.prepareSharedTaskClosure,
+ rollbackPreparedSharedTaskClosure: h.rollbackSharedTaskClosure,
+ finalizePreparedSharedTaskClosure: h.finalizeSharedTaskClosure,
}));
vi.mock('../recentWorkdirs', () => ({ upsertRecentWorkdir: h.upsertRecentWorkdir }));
vi.mock('../../../device-link/broadcast-tap.js', () => ({
@@ -869,6 +875,10 @@ describe('local-db:sessions:update handler wiring', () => {
it('cleans runtime state before releasing the local terminal status lock', async () => {
const order: string[] = [];
+ h.prepareSharedTaskClosure.mockImplementationOnce(async () => {
+ order.push('sharing-prepared');
+ return { sessionId: 'codex-local', marker: 1, rowIds: [7] };
+ });
h.runtimeCleanup.mockImplementationOnce(() => order.push('runtime-cleanup'));
h.closeSharedTask.mockImplementationOnce(async () => { order.push('sharing-closed'); });
h.routeLock.mockImplementationOnce(async (_sessionId, task) => {
@@ -880,13 +890,17 @@ describe('local-db:sessions:update handler wiring', () => {
await invokeUpdate('codex-local', { status: 'archived' });
- expect(order).toEqual(['runtime-cleanup', 'sharing-closed', 'lock-released']);
+ expect(order).toEqual(['sharing-prepared', 'runtime-cleanup', 'sharing-closed', 'lock-released']);
expect(h.runtimeCleanup).toHaveBeenCalledOnce();
expect(h.closeSharedTask).toHaveBeenCalledWith('codex-local', h.client);
});
it('cleans runtime state before releasing the remote terminal status lock', async () => {
const order: string[] = [];
+ h.prepareSharedTaskClosure.mockImplementationOnce(async () => {
+ order.push('sharing-prepared');
+ return { sessionId: 'codex-local', marker: 1, rowIds: [7] };
+ });
h.runtimeCleanup.mockImplementationOnce(() => order.push('runtime-cleanup'));
h.closeSharedTask.mockImplementationOnce(async () => { order.push('sharing-closed'); });
h.routeLock.mockImplementationOnce(async (_sessionId, task) => {
@@ -898,11 +912,35 @@ describe('local-db:sessions:update handler wiring', () => {
await patchSessionMetaInDb('codex-local', { status: 'archived' });
- expect(order).toEqual(['runtime-cleanup', 'sharing-closed', 'lock-released']);
+ expect(order).toEqual(['sharing-prepared', 'runtime-cleanup', 'sharing-closed', 'lock-released']);
expect(h.runtimeCleanup).toHaveBeenCalledOnce();
expect(h.closeSharedTask).toHaveBeenCalledWith('codex-local', h.client);
});
+ it('does not commit a terminal status when the shared-task journal cannot be prepared', async () => {
+ h.prepareSharedTaskClosure.mockRejectedValueOnce(new Error('disk failed'));
+
+ await expect(invokeUpdate('codex-local', { status: 'archived' })).rejects.toThrow(
+ 'Worktree is busy or its recovery record could not be saved',
+ );
+ expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id = ?').get('codex-local')).toEqual({ status: 'active' });
+ expect(h.closeSharedTask).not.toHaveBeenCalled();
+ expect(h.rollbackSharedTaskClosure).not.toHaveBeenCalled();
+ });
+
+ it('rolls back a prepared shared-task journal when the terminal status write fails', async () => {
+ h.prepareSharedTaskClosure.mockImplementationOnce(async () => {
+ h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('codex-local');
+ return { sessionId: 'codex-local', marker: 1, rowIds: [7] };
+ });
+
+ await expect(invokeUpdate('codex-local', { status: 'archived' })).rejects.toThrow('已删除的任务不能恢复或归档');
+ expect(h.rollbackSharedTaskClosure).toHaveBeenCalledWith(h.client, {
+ sessionId: 'codex-local', marker: 1, rowIds: [7],
+ });
+ expect(h.closeSharedTask).not.toHaveBeenCalled();
+ });
+
it.each([true, false])('closes shared tasks when Bot deletion transitions sessions to terminal status (keep=%s)', async (keepTaskHistory) => {
h.commitBotProfileDeletion.mockResolvedValue({
status: keepTaskHistory ? 'archived' : 'deleted',
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index daa2da432f..c551b58c23 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -227,6 +227,38 @@ async function withStatusWriteLock<T>(
return withSessionRouteLock(sessionId, write);
}
+type SharedTaskClosurePreparation = {
+ sessionId: string;
+ marker: number;
+ rowIds: number[];
+};
+
+async function prepareSharedTaskClosure(
+ sessionId: string,
+ dbClient: DbClient,
+): Promise<SharedTaskClosurePreparation | null> {
+ const { prepareSharedTaskClosureForTask } = await import('../../device-link/sharedTaskRuntime.js');
+ return prepareSharedTaskClosureForTask(sessionId, dbClient);
+}
+
+async function rollbackSharedTaskClosure(
+ dbClient: DbClient,
+ prepared: SharedTaskClosurePreparation | null,
+): Promise<void> {
+ if (!prepared) return;
+ const { rollbackPreparedSharedTaskClosure } = await import('../../device-link/sharedTaskRuntime.js');
+ await rollbackPreparedSharedTaskClosure(dbClient, prepared);
+}
+
+async function finalizeSharedTaskClosure(
+ dbClient: DbClient,
+ prepared: SharedTaskClosurePreparation | null,
+): Promise<void> {
+ if (!prepared) return;
+ const { finalizePreparedSharedTaskClosure } = await import('../../device-link/sharedTaskRuntime.js');
+ await finalizePreparedSharedTaskClosure(dbClient, prepared);
+}
+
async function requestWorktreeRecycle(
sessionId: string,
resources: readonly string[] = [],
@@ -1921,9 +1953,17 @@ export async function updateSessionInDb(
if (p.status !== undefined) await assertGenericSessionLifecycleAllowed(db, sid);
await moveGuard?.beforeWrite?.();
moveGuard?.assertCurrent();
- await writeSessionPatch(db, sid, setObj, p.status);
+ const terminal = p.status === 'archived' || p.status === 'deleted';
+ const prepared = terminal ? await prepareSharedTaskClosure(sid, dbClient) : null;
+ try {
+ await writeSessionPatch(db, sid, setObj, p.status);
+ } catch (error) {
+ await rollbackSharedTaskClosure(dbClient, prepared);
+ throw error;
+ }
+ await finalizeSharedTaskClosure(dbClient, prepared);
cleanupSessionRuntimeForTerminalStatus(sid, p.status);
- if (p.status === 'archived' || p.status === 'deleted') {
+ if (terminal) {
const { closeSharedTaskForTask } = await import('../../device-link/sharedTaskRuntime.js');
await closeSharedTaskForTask(sid, dbClient);
}
@@ -2086,7 +2126,15 @@ export async function patchSessionMetaInDb(
if (patch.title !== undefined) noteUserTitleWritten(sessionId);
const updated = await withStatusWriteLock(db, sessionId, patch.status, async () => {
if (patch.status !== undefined) await assertGenericSessionLifecycleAllowed(db, sessionId);
- await writeSessionPatch(db, sessionId, setObj, patch.status);
+ const terminal = patch.status === 'archived' || patch.status === 'deleted';
+ const prepared = terminal ? await prepareSharedTaskClosure(sessionId, dbClient) : null;
+ try {
+ await writeSessionPatch(db, sessionId, setObj, patch.status);
+ } catch (error) {
+ await rollbackSharedTaskClosure(dbClient, prepared);
+ throw error;
+ }
+ await finalizeSharedTaskClosure(dbClient, prepared);
const row = await selectSessionWithCount(db, sessionId);
if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');
if (patch.pinnedAt !== undefined && row.pinnedAt == null) {
@@ -2094,7 +2142,7 @@ export async function patchSessionMetaInDb(
row.summary = null;
}
cleanupSessionRuntimeForTerminalStatus(sessionId, patch.status);
- if (patch.status === 'archived' || patch.status === 'deleted') {
+ if (terminal) {
const { closeSharedTaskForTask } = await import('../../device-link/sharedTaskRuntime.js');
await closeSharedTaskForTask(sessionId, dbClient);
}
@@ -2283,26 +2331,43 @@ export async function setSessionsStatusInDb(
}
const physicalResources = await Promise.all([...new Set(resources)].map(physicalWorktreeKey));
return withWorktreeMutation(resources, async () => {
- if (status === 'archived') {
- for (const id of sessionIds) await requestWorktreeRecycle(id, perSession.get(id));
- }
- const rows = await 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' || code === 'PRECONDITION_FAILED') {
- throwIpcError(code, message);
+ const prepared: SharedTaskClosurePreparation[] = [];
+ let committed = false;
+ try {
+ if (status === 'archived') {
+ for (const id of sessionIds) {
+ const closure = await prepareSharedTaskClosure(id, dbClient);
+ if (closure) prepared.push(closure);
+ }
}
- throw err;
- });
- for (const item of rows) {
- cleanupSessionRuntimeForTerminalStatus(item.sessionId, item.status);
- if (item.status === 'archived') {
- const { closeSharedTaskForTask } = await import('../../device-link/sharedTaskRuntime.js');
- await closeSharedTaskForTask(item.sessionId, dbClient);
+ if (status === 'archived') {
+ for (const id of sessionIds) await requestWorktreeRecycle(id, perSession.get(id));
+ }
+ const rows = await 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' || code === 'PRECONDITION_FAILED') {
+ throwIpcError(code, message);
+ }
+ throw err;
+ });
+ committed = true;
+ for (const closure of prepared) await finalizeSharedTaskClosure(dbClient, closure);
+ for (const item of rows) {
+ cleanupSessionRuntimeForTerminalStatus(item.sessionId, item.status);
+ if (item.status === 'archived') {
+ const { closeSharedTaskForTask } = await import('../../device-link/sharedTaskRuntime.js');
+ await closeSharedTaskForTask(item.sessionId, dbClient);
+ }
+ }
+ for (const resource of physicalResources) notifyWorktreeRecycleOpportunity(resource);
+ return rows;
+ } catch (error) {
+ if (!committed) {
+ for (const closure of prepared) await rollbackSharedTaskClosure(dbClient, closure);
}
+ throw error;
}
- for (const resource of physicalResources) notifyWorktreeRecycleOpportunity(resource);
- return rows;
});
});
for (const item of applied) {
@@ -2378,11 +2443,28 @@ export async function deleteBotProfileAndDetachSessionsInDb(
sessionIds: ids,
keepTaskHistory,
});
- const committed =
- ids.length > 0 ? await withSessionRouteLocks(ids, commitDeletion) : await commitDeletion();
+ const prepared: SharedTaskClosurePreparation[] = [];
+ let committedStatus = false;
+ let committedResult: Awaited<ReturnType<typeof commitBotProfileDeletion>>;
+ try {
+ for (const id of ids) {
+ const closure = await prepareSharedTaskClosure(id, dbClient);
+ if (closure) prepared.push(closure);
+ }
+ committedResult = ids.length > 0 ? await withSessionRouteLocks(ids, commitDeletion) : await commitDeletion();
+ committedStatus = true;
+ } catch (error) {
+ if (!committedStatus) {
+ for (const closure of prepared) await rollbackSharedTaskClosure(dbClient, closure);
+ }
+ throw error;
+ }
+ const committed = committedResult;
const status = committed.status;
const committedSessionIds = [...new Set(committed.sessionIds)];
+ for (const closure of prepared) await finalizeSharedTaskClosure(dbClient, closure);
+
// Bot profile deletion commits terminal task status through a dedicated
// transaction, so it bypasses the ordinary session patch/status writers.
// Close the corresponding shared task only after that durable transition;
diff --git a/apps/desktop/src/main/localDb/sharedTaskClosureSql.ts b/apps/desktop/src/main/localDb/sharedTaskClosureSql.ts
index cec3f5f521..4b7c29f619 100644
--- a/apps/desktop/src/main/localDb/sharedTaskClosureSql.ts
+++ b/apps/desktop/src/main/localDb/sharedTaskClosureSql.ts
@@ -6,3 +6,17 @@ export const CLOSE_SHARED_TASKS_FOR_SESSION_SQL = `
FROM shared_task_events WHERE session_id = ?
ON CONFLICT (shared_task_id, kind, revision) DO NOTHING
`;
+
+/** Prepare a reversible closure intent before the session status changes. */
+export const PREPARE_SHARED_TASKS_FOR_SESSION_SQL = `
+ INSERT INTO shared_task_events (shared_task_id, session_id, revision, kind, terminal, snapshot, recorded_at)
+ SELECT DISTINCT shared_task_id, session_id, 0, 'local-close', 0, NULL, ?
+ FROM shared_task_events AS source
+ WHERE source.session_id = ?
+ AND NOT EXISTS (
+ SELECT 1 FROM shared_task_events AS existing
+ WHERE existing.shared_task_id = source.shared_task_id
+ AND existing.kind = 'local-close' AND existing.revision = 0
+ )
+ ON CONFLICT (shared_task_id, kind, revision) DO NOTHING
+`;
diff --git a/apps/desktop/src/main/localDb/sharedTasks.ts b/apps/desktop/src/main/localDb/sharedTasks.ts
index 434f5d003d..8b23402ce8 100644
--- a/apps/desktop/src/main/localDb/sharedTasks.ts
+++ b/apps/desktop/src/main/localDb/sharedTasks.ts
@@ -1,6 +1,62 @@
import { parseSharedTaskSnapshot, type SharedTaskIdentity, type SharedTaskSnapshot } from '@cindy/device-link';
import type { DbClient } from './client/DbClient.js';
-import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL } from './sharedTaskClosureSql.js';
+import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL, PREPARE_SHARED_TASKS_FOR_SESSION_SQL } from './sharedTaskClosureSql.js';
+
+let closureMarker = 0;
+
+function nextClosureMarker(): number {
+ // Keep markers distinct even when several terminal transitions happen in
+ // the same millisecond. The marker only identifies rows from one prepare.
+ const now = Date.now() * 1000;
+ closureMarker = Math.max(closureMarker + 1, now);
+ return closureMarker;
+}
+
+export interface PreparedSharedTaskClosure {
+ sessionId: string;
+ marker: number;
+ rowIds: number[];
+}
+
+/** Persist the local-close fence before a session enters a terminal state. */
+export async function prepareSharedTasksForSession(
+ db: Pick<DbClient, 'exec' | 'query'>,
+ sessionId: string,
+): Promise<PreparedSharedTaskClosure> {
+ const marker = nextClosureMarker();
+ await db.exec(PREPARE_SHARED_TASKS_FOR_SESSION_SQL, [marker, sessionId]);
+ const rows = await db.query<{ id: number }>(
+ "SELECT id FROM shared_task_events WHERE session_id = ? AND kind = 'local-close' AND revision = 0 AND terminal = 0",
+ [sessionId],
+ );
+ return { sessionId, marker, rowIds: rows.map((row) => row.id) };
+}
+
+/** Remove only a prepare whose terminal session write did not commit. */
+export async function rollbackPreparedSharedTasks(
+ db: Pick<DbClient, 'exec'>,
+ prepared: PreparedSharedTaskClosure,
+): Promise<void> {
+ if (prepared.rowIds.length === 0) return;
+ const placeholders = prepared.rowIds.map(() => '?').join(',');
+ await db.exec(
+ "DELETE FROM shared_task_events WHERE id IN (" + placeholders + ") AND session_id = ? AND kind = 'local-close' AND revision = 0 AND terminal = 0 AND recorded_at = ?",
+ [...prepared.rowIds, prepared.sessionId, prepared.marker],
+ );
+}
+
+/** Make a previously prepared closure durable after the terminal status commit. */
+export async function finalizePreparedSharedTasks(
+ db: Pick<DbClient, 'exec'>,
+ prepared: PreparedSharedTaskClosure,
+): Promise<void> {
+ if (prepared.rowIds.length === 0) return;
+ const placeholders = prepared.rowIds.map(() => '?').join(',');
+ await db.exec(
+ "UPDATE shared_task_events SET terminal = 1 WHERE id IN (" + placeholders + ") AND session_id = ? AND kind = 'local-close' AND revision = 0 AND terminal = 0",
+ [...prepared.rowIds, prepared.sessionId],
+ );
+}
/** Does not require a live Host; the captured profile DB owns these closures. */
export async function closeSharedTasksInJournalForSession(db: Pick<DbClient, 'exec' | 'query'>, sessionId: string): Promise<string[]> {