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): recheck active turn before session move

nothingyuancando1f63974186bb
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index cfda31e2b6..13d41738ee 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -7203,6 +7203,16 @@ app.on('ready', async () => {
registerLocalDbIpc({
cancelSessionOperations: cancelIOSSimulatorSessionOperations,
cleanupRemovedSession: cleanupIOSSimulatorRemovedSession,
+ closeIdleSessionForMove: async (sessionId) => {
+ const maker = getMakerIfReady();
+ if (maker?.getSession(sessionId)?.isTurnRunning()) return false;
+ if (maker) {
+ await rehydrateCloseSuppression.withSuppressed(sessionId, () =>
+ maker.closeSession(sessionId),
+ );
+ }
+ return true;
+ },
reconcilePersistedSessionRuntimes: reconcilePersistedIOSSimulatorOwnership,
withSessionLock: withSendToSessionLock,
// Mirrors exactly what the resume handler requires (`maker-ipc/register.ts`):
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 2b6b693cf0..82151cef27 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -30,7 +30,7 @@ const h = vi.hoisted(() => ({
relocate: vi.fn(async (): Promise<{ persistedSdkSessionId: string | null }> => ({
persistedSdkSessionId: null,
})),
- closeSession: vi.fn(async () => undefined),
+ closeSession: vi.fn(async (_sessionId: string) => undefined),
tapWindowBroadcast: vi.fn(),
summarizeSession: vi.fn(async () => undefined),
stopAndRemovePiSubagentRuns: vi.fn(async (_root: string) => true),
@@ -40,6 +40,7 @@ const h = vi.hoisted(() => ({
isSessionAlive: (id: string) => boolean;
closeSession: (id: string) => Promise<void>;
} | null => null),
+ closeIdleSessionForMove: vi.fn(async (_sessionId: string) => true),
withRehydrateCloseSuppressed: vi.fn(
async (_sessionId: string, task: () => Promise<void>) => task(),
),
@@ -222,13 +223,18 @@ beforeEach(() => {
h.clearPiSubagentDeletedTombstone.mockClear();
h.clearPiSubagentDeletedTombstone.mockImplementation(async () => undefined);
h.getMakerIfReady.mockReset();
+ h.closeIdleSessionForMove.mockReset();
+ h.closeIdleSessionForMove.mockImplementation(async (sessionId) => {
+ await h.withRehydrateCloseSuppressed(sessionId, () => h.closeSession(sessionId));
+ return true;
+ });
h.withRehydrateCloseSuppressed.mockClear();
h.withRehydrateCloseSuppressed.mockImplementation(async (_sessionId, task) => task());
h.getMakerIfReady.mockReturnValue({ isSessionAlive: () => false, closeSession: h.closeSession });
h.userDataDir = mkdtempSync(path.join(os.tmpdir(), 'cindy-sessions-update-'));
createDb();
setSessionRouteLockImplementation(h.routeLock);
- registerSessionIpc();
+ registerSessionIpc(undefined, { closeIdleSessionForMove: h.closeIdleSessionForMove });
});
afterEach(async () => {
@@ -707,6 +713,19 @@ describe('local-db:sessions:update handler wiring', () => {
);
});
+ it('rejects moving a local Pi/Codex session whose turn became active', async () => {
+ h.closeIdleSessionForMove.mockResolvedValueOnce(false);
+
+ await expect(
+ invokeUpdate('codex-local', { workingDir: '/new/dir' }),
+ ).rejects.toThrow('[PRECONDITION_FAILED]');
+
+ expect(
+ h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('codex-local'),
+ ).toEqual({ working_dir: '/old/dir' });
+ expect(h.closeSession).not.toHaveBeenCalled();
+ });
+
it('does not reacquire the route lock for a combined workingDir and status patch', async () => {
await invokeUpdate('codex-local', { workingDir: '/new/dir', status: 'active' });
diff --git a/apps/desktop/src/main/localDb/ipc/registerAll.ts b/apps/desktop/src/main/localDb/ipc/registerAll.ts
index ebafb21f78..f0ce8d932d 100644
--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts
+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts
@@ -81,6 +81,8 @@ export interface RegisterLocalDbIpcOpts {
cancelSessionOperations?: (sessionId: string) => Promise<void>;
/** Release Host-owned runtime and ownership after task removal is revalidated. */
cleanupRemovedSession?: (sessionId: string) => Promise<void>;
+ /** Close a moved local Pi/Codex runtime after revalidating that its turn is idle. */
+ closeIdleSessionForMove?: (sessionId: string) => Promise<boolean>;
/** Reconcile persisted Host-owned task runtimes once the owner DB is readable. */
reconcilePersistedSessionRuntimes?: () => Promise<void>;
/** Serialize startup tombstone cleanup with task restore/start/send operations. */
@@ -234,7 +236,9 @@ export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {
return result;
});
- registerSessionIpc(getCurrentDbClientUserId);
+ registerSessionIpc(getCurrentDbClientUserId, {
+ closeIdleSessionForMove: opts.closeIdleSessionForMove,
+ });
registerMessageIpc();
registerRemoteHistoryIpc();
registerSessionImportIpc();
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 3985c09696..bdb294e0f3 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -76,6 +76,11 @@ export interface SessionRecycleScope {
mediaDb: DbClient['drizzle'];
}
+export interface RegisterSessionIpcOpts {
+ /** Close a local Pi/Codex runtime only if its current turn is idle. */
+ closeIdleSessionForMove?: (sessionId: string) => Promise<boolean>;
+}
+
let sessionRemovalCancelOperations: SessionRemovalCancelOperations | null = null;
let sessionRemovalCleanup: SessionRemovalCleanup | null = null;
@@ -952,6 +957,7 @@ export async function clearSessionContextInDb(sessionId: string, atMs?: number):
export function registerSessionIpc(
readSessionListLogScope: () => string | null = () => null,
+ opts: RegisterSessionIpcOpts = {},
): void {
// interrupted-turn-resume 假阳性修复:每次 last_turn_ended_at 真正落库(正常收尾 /
// barrier 版收尾 / ack)都广播 lastTurnEndedAt patch —— renderer 的 session 快照可能
@@ -1417,10 +1423,13 @@ export function registerSessionIpc(
// before persisting the new directory so the next send lazily recreates the
// runtime with the moved session's cwd instead of continuing in the old one.
if (movingLocalNonClaudeSession) {
- const makerHost = await import('../../maker-host/index.js');
- await makerHost.withRehydrateCloseSuppressed(sid, async () => {
- await makerHost.getMakerIfReady()?.closeSession(sid);
- });
+ if (!opts.closeIdleSessionForMove) {
+ throwIpcError('INTERNAL', '会话移动 runtime 操作未配置');
+ }
+ const idle = await opts.closeIdleSessionForMove(sid);
+ if (idle === false) {
+ throwIpcError('PRECONDITION_FAILED', '运行中的任务不能移动');
+ }
}
// 只有纯设置字段(model/effort 等)才跳过 bump;凡带 activity 字段
// (clearedAt / sdkSessionId / status / token 用量等)仍需更新 updatedAt,