Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): 续聊归档任务时先恢复任务与原生线程 (#6276)
Dash5e4222290eec
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 97434a5661..1be3f90754 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -177,6 +177,7 @@ import {broadcastSessionPatched,deleteBotProfileAndDetachSessionsInDb,patchSessionMetaInDb,+ restoreArchivedSessionForSend,persistSessionFields,registerSessionIpc,resumeDeletedPiSubagentCleanup,@@ -763,6 +764,51 @@ describe('local-db:sessions:update handler wiring', () => {expect(h.routeLock).toHaveBeenCalledWith('codex-local', expect.any(Function));});+ it('restores an archived task for send through the normal locked status writer and broadcast', async () => {+ h.sqlite!.prepare("UPDATE sessions SET status = 'archived' WHERE id = ?").run('codex-local');+ await restoreArchivedSessionForSend('codex-local');+ expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id = ?').get('codex-local')).toEqual({ status: 'active' });+ expect(h.routeLock).toHaveBeenCalledWith('codex-local', expect.any(Function));+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', expect.objectContaining({+ sessionId: 'codex-local', patch: { status: 'active' },+ }));+ });++ 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',+ kind === 'worker' ? 'worker' : null, kind === 'remote-worker' ? '{}' : null, 'codex-local');+ await expect(restoreArchivedSessionForSend('codex-local')).rejects.toThrow(+ kind === 'deleted' ? '[NOT_FOUND]' : '[PRECONDITION_FAILED]',+ );+ expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id = ?').get('codex-local'))+ .toEqual({ status: kind === 'deleted' ? 'deleted' : 'archived' });+ expect(h.tapWindowBroadcast).not.toHaveBeenCalled();+ });++ it('does not write or broadcast for an already active task', async () => {+ await restoreArchivedSessionForSend('codex-local');+ expect(h.tapWindowBroadcast).not.toHaveBeenCalled();+ });++ it('rechecks task status after acquiring the route lock', async () => {+ h.sqlite!.prepare("UPDATE sessions SET status = 'archived' WHERE id = ?").run('codex-local');+ h.routeLock.mockImplementationOnce(async (_id, task) => {+ h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('codex-local');+ return task();+ });+ await expect(restoreArchivedSessionForSend('codex-local')).rejects.toThrow('[NOT_FOUND]');+ expect(h.tapWindowBroadcast).not.toHaveBeenCalled();+ });++ it('does not restore after the task owner changes', async () => {+ h.captureOwnerScope = true;+ h.ownerCurrent = false;+ h.sqlite!.prepare("UPDATE sessions SET status = 'archived' WHERE id = ?").run('codex-local');+ await expect(restoreArchivedSessionForSend('codex-local')).rejects.toThrow('Task owner changed');+ expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id = ?').get('codex-local')).toEqual({ status: 'archived' });+ });+it('keeps the last legal sessions.effort when a fixed-effort model switch patches null', async () => {await persistSessionFields('pi-local', {model: 'x-ai-grok/grok-4.6',diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 7efc084d7b..4d9d30c761 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -2149,6 +2149,26 @@ export async function updateSessionInDb(});}+/** Sending continues an ordinary archived task. Serialize with archive/delete and+ * use the normal status writer so native projection and all clients see active. */+export async function restoreArchivedSessionForSend(sessionId: string): Promise<void> {+ const ownerScope = captureOwnerScope();+ const db = getDbClient().drizzle;+ await withSessionRouteLock(sessionId, async () => {+ const [row] = await db.select({+ status: sessions.status, source: sessions.source, orcaRole: sessions.orcaRole,+ orcaRemoteLead: sessions.orcaRemoteLead,+ }).from(sessions).where(eq(sessions.id, sessionId)).limit(1);+ if (!isOwnerScopeCurrent(ownerScope)) throwIpcError('PRECONDITION_FAILED', 'Task owner changed');+ if (row?.status === 'deleted') throwIpcError('NOT_FOUND', 'Session does not exist');+ if (row?.status !== 'archived') return;+ if (row.source === 'bot' || row.orcaRole === 'worker' || row.orcaRemoteLead) {+ throwIpcError('PRECONDITION_FAILED', 'Restore the managed task before continuing');+ }+ await patchSessionMetaInDb(sessionId, { status: 'active' });+ });+}+export async function patchSessionMetaInDb(sessionId: string,patch: {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex a3d0f5a622..40266a40a0 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -5067,13 +5067,13 @@ describe('AgentInputCoordinator send transaction', () => {}});- it('keeps a host preflight failure recoverable with host-send code and no dispatch', async () => {+ it.each(['WORKDIR_MISSING', 'LAZY_CREATE_FAILED'] as const)('keeps %s recoverable without leaving an active turn', async code => {const h = createHarness();const sid = 'host-preflight-failure';const first = makeItem('q-1', 'first');h.sendToAgent.mockResolvedValueOnce(- hostSendFailure('WORKDIR_MISSING', 'working directory is missing'),+ hostSendFailure(code, 'session preparation failed'),);h.coordinator.enqueue(sid, first);@@ -5082,14 +5082,15 @@ describe('AgentInputCoordinator send transaction', () => {const projection = latestProjection(h.projections);expect(projection.pendingQueue.map((q) => q.clientId)).toEqual(['q-1']);expect(projection.recovery).toEqual({ kind: 'queue-head', clientId: 'q-1' });- expect(projection.error).toContain('WORKDIR_MISSING');- expect(projection.error).toContain('working directory is missing');+ expect(projection.error).toContain(code);+ expect(projection.error).toContain('session preparation failed');+ expect(h.coordinator.hasActiveTurnForRewind(sid)).toBe(false);expect(mocks.createMessage).not.toHaveBeenCalled();expect(h.sendToAgent).toHaveBeenCalledTimes(1);expect(latestWarnPayload()).toEqual(expect.objectContaining({kind: 'host-send',- code: 'WORKDIR_MISSING',+ code,clientId: 'q-1',}),);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex a4a16ea0db..5e67e7d68b 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -2050,6 +2050,49 @@ describe('maker SEND transaction', () => {expect(lazySession.send).toHaveBeenCalled();});+ it('waits for task restoration before route switching and lazy resume', async () => {+ let release!: () => void;+ const restored = new Promise<void>(resolve => { release = resolve; });+ const { deps, session } = createDeps({+ getSession: vi.fn(() => undefined),+ restoreArchivedSessionForSend: vi.fn(() => restored),+ applyPendingAgentSwitch: vi.fn(async () => {}),+ });+ const sending = createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'continue', {+ id: 'session-1', agentKind: 'codex', workingDir: '/repo',+ });+ expect(deps.restoreArchivedSessionForSend).toHaveBeenCalledWith('session-1');+ expect(deps.applyPendingAgentSwitch).not.toHaveBeenCalled();+ expect(deps.bootstrapSession).not.toHaveBeenCalled();+ expect(session.send).not.toHaveBeenCalled();+ release();+ await expect(sending).resolves.toMatchObject({ accepted: true });+ expect(deps.bootstrapSession).toHaveBeenCalledOnce();+ });++ it('does not resume or dispatch if restoring task status fails', async () => {+ const { deps, session } = createDeps({+ restoreArchivedSessionForSend: vi.fn(async () => { throw new Error('restore failed'); }),+ });+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'continue'))+ .rejects.toThrow('restore failed');+ expect(deps.bootstrapSession).not.toHaveBeenCalled();+ expect(session.send).not.toHaveBeenCalled();+ });++ it.each(['before', 'during'] as const)('does not resume a send cancelled %s restoration', async timing => {+ const controller = new AbortController();+ if (timing === 'before') controller.abort();+ const { deps, session } = createDeps({+ restoreArchivedSessionForSend: vi.fn(async () => { controller.abort(); }),+ });+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'continue', undefined,+ { signal: controller.signal })).resolves.toMatchObject({ accepted: false });+ expect(deps.restoreArchivedSessionForSend).toHaveBeenCalledTimes(timing === 'before' ? 0 : 1);+ expect(deps.bootstrapSession).not.toHaveBeenCalled();+ expect(session.send).not.toHaveBeenCalled();+ });+it('restores a persisted writable parent without a filtered read-only child after restart', async () => {const lazySession = createSession({ id: 'restart-session', workDir: '/repo' });const { deps } = createDeps({diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex 5e125e98f9..826bc8e4be 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -503,6 +503,8 @@ export interface MakerSendTransactionDeps {* 随后本事务按空 session 走 lazy-create,避免 peek 之后对已关闭对象 send。*/prepareUnhealthySession?(sessionId: string): Promise<boolean | void>;+ /** Restore durable task status before route changes or native session resume. */+ restoreArchivedSessionForSend?(sessionId: string): Promise<void>;/*** session-agent-switch:pending 交接读取(agentHandoff 注册表)。命中时把交接* 文本前置进 wire payload(不影响 persistUserMessage 落库显示内容),并在@@ -1008,6 +1010,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makeif (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');const dispatchProductTurn = deps.prepareProductTurn?.(sessionId);const requestedSendOpts = (sendOpts ?? {}) as MakerSendOptions;+ if (!requestedSendOpts.signal?.aborted) {+ await deps.restoreArchivedSessionForSend?.(sessionId);+ }// session-agent-switch:pending 切换在发送时刻生效(用户语义:「消息真正发出// 去时才切」)。必须在 getSession 之前——apply 会 close 旧引擎的 live session,// 让下方走 lazy-create 按 DB 新值 spawn 新引擎。diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 11f9891a5c..57021cee4a 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -466,6 +466,7 @@ import {getSessionRowSnapshotStrict,persistSessionFields,recycleSessionWorktreeForStatusChange,+ restoreArchivedSessionForSend,scheduleWorktreeRecycleForStatusChange,setSessionRuntimeCleanup,} from '../localDb/ipc/sessions.js';@@ -16230,6 +16231,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}));const { sendToAgentAccepted: sendToAgentAcceptedUnlocked } = createMakerSendTransaction({+ restoreArchivedSessionForSend,prepareProductTurn: (sessionId) => {const dispatch = prepareUpstreamMergeTurn(sessionId);return dispatchdiff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex 1f5fcac726..3c59b609aa 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -162,6 +162,10 @@ SSH 或暂时失败留待重试;共享原生 ID 的活动任务优先,不关持有任务路由锁并验证当前 owner,使用原历史根与数据库根。Claude Code 与 Pi 当前没有原生归档接口,保持 Cindy 状态;历史扫描及重新导入不得覆盖 Cindy 的归档与归档任务的项目目录、额外目录及可写目录范围。手机远控复用宿主同一状态写入路径。+普通已归档任务再次发送时,宿主在恢复运行时前先恢复 Cindy 状态,沿用任务路由锁和状态广播。+若 Codex 的后台投影尚未取消归档,只对该线程明确的原生已归档错误调用 `thread/unarchive`,+记录移动后的历史位置并重试一次恢复;不新建线程、不重放用户消息,其他错误照常失败。+已删除任务、伙伴托管任务及协同 Worker 不经普通发送自动恢复。凭证、代理路由和模型目录仍按本轮选中账号准备,不能把历史根写回全局账号配置。跨历史根的原生进程从启动参数要求 `cli_auth_credentials_store="ephemeral"`,清除继承的原生身份环境变量;OAuth 通过独立的 external-auth adapter 在进程内安装目标账号 token,diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex c8480c31e5..75b8e50dd3 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -495,6 +495,62 @@ describe('Codex managed Skill startup', () => {});describe('Codex archive synchronization', () => {+ it.each(['success', 'without-path', 'unarchive-fails', 'resume-fails-again', 'other-thread'] as const)(+ 'recovers archived resume without replacing the thread (%s)', async outcome => {+ const id = '11111111-1111-4111-8111-111111111111';+ const archivedPath = '/history/archived_sessions/history.jsonl';+ const restoredPath = '/history/sessions/history.jsonl';+ const recordCodexThreadLocation = vi.fn(async () => {});+ const agent = new CodexAgent(createDeps({}, {+ ...(outcome !== 'without-path' ? { prepareCodexResumeSession: async () => archivedPath } : {}),+ recordCodexThreadLocation,+ }));+ let archived = true;+ let resumes = 0;+ const resumePaths: unknown[] = [];+ const host = installFakeHost(agent, (method, params) => {+ if (method === Method.ThreadResume) {+ resumes++;+ resumePaths.push((params as { path?: string }).path);+ if (archived || outcome === 'resume-fails-again') {+ const errorId = outcome === 'other-thread' ? 'other' : id;+ throw Object.assign(new Error(`codex app-server thread/resume error -32600: session ${errorId} is archived. Run \`codex unarchive ${errorId}\` to unarchive it first.`),+ { code: -32600, data: undefined });+ }+ return { thread: { id, path: restoredPath }, model: 'gpt-5.4' };+ }+ if (method === 'thread/read') return { thread: {+ id, path: archived ? archivedPath : restoredPath, status: { type: 'idle' },+ } };+ if (method === 'thread/unarchive') {+ if (outcome === 'unarchive-fails') throw new Error('unarchive unavailable');+ archived = false;+ return {};+ }+ return undefined;+ }, { codexHome: '/history' });+ try {+ const start = agent.startSession({ sessionId: 'restore', model: 'gpt-5.4',+ workingDir: '/repo', resumeSessionId: id });+ const successful = outcome === 'success' || outcome === 'without-path';+ if (successful) {+ const handle = await start;+ expect(handle.id).toBe(id);+ expect(resumePaths).toEqual([outcome === 'without-path' ? undefined : archivedPath, restoredPath]);+ expect(recordCodexThreadLocation).toHaveBeenCalledWith(id, '/history', restoredPath);+ await handle.close();+ } else {+ await expect(start).rejects.toThrow(outcome === 'unarchive-fails' ? 'unarchive unavailable' : 'is archived');+ }+ expect(resumes).toBe(successful || outcome === 'resume-fails-again' ? 2 : 1);+ const methods = host.request.mock.calls.map(([method]) => method);+ expect(methods.filter(method => method === 'thread/unarchive')).toHaveLength(outcome === 'other-thread' ? 0 : 1);+ expect(methods).not.toContain(Method.ThreadStart);+ expect(methods).not.toContain(Method.TurnStart);+ } finally { await agent.dispose(); }+ },+ );+it('uses the retained writer and records the native archive path without closing sibling tasks', async () => {const storage = { historyHome: '/history', sqliteHome: '/state' };const resolveCodexThreadStorage = vi.fn(async () => storage);diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex b2f2445c00..7574585643 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -1165,6 +1165,11 @@ function isExactUnloadedThreadReadError(error: unknown, threadId: string): boole`codex app-server thread/read error -32600: thread not loaded: ${threadId}`);}+function isExactArchivedThreadResumeError(error: unknown, threadId: string): boolean {+ return isExactThreadLookupError(error,+ `codex app-server thread/resume error -32600: session ${threadId} is archived. Run \`codex unarchive ${threadId}\` to unarchive it first.`);+}+function isExactThreadLookupError(error: unknown, message: string): boolean {if (typeof error !== 'object' || error === null) return false;const candidate = error as { code?: unknown; data?: unknown; message?: unknown };@@ -7172,7 +7177,7 @@ assertRouteCurrent();try {acquireHostBindingLeaseIfNeeded();assertCurrentHost('thread/resume');- const resp = await withMcpDiscoveryContext(() => {+ const resume = () => withMcpDiscoveryContext(() => {assertCurrentHost('thread/resume dispatch');return host.request<ThreadResumeResponse>(Method.ThreadResume, params, {...criticalThreadRpcOptions(),@@ -7182,6 +7187,28 @@ assertRouteCurrent();},});});+ let resp: ThreadResumeResponse;+ try {+ resp = await resume();+ } catch (error) {+ // A task can be restored before background archive projection catches up.+ // Recover only this exact native refusal, on the same host/history roots.+ // Missing indexed history must keep its existing fail-closed behavior.+ if (indexedRolloutMissing || !isExactArchivedThreadResumeError(error, opts.resumeSessionId)) throw error;+ // The native refusal proves resume did not load a writer. Restore the+ // pre-dispatch cancellation/route fence before another native request.+ startup.threadDispatched = false;+ assertCurrentHost('thread/unarchive');+ const restoredPath = await syncCodexArchiveState(+ (method, requestParams) => host.request(method, requestParams, criticalThreadRpcOptions()),+ opts.resumeSessionId, false, () => assertCurrentHost('thread/unarchive'),+ );+ await recordNativeThreadLocation({ id: opts.resumeSessionId, path: restoredPath });+ preparedResumePath = restoredPath;+ params.path = restoredPath;+ // One retry of session preparation; no user turn has been dispatched.+ resp = await resume();+ }assertCurrentHost('thread/resume');if (Object.hasOwn(resp, 'serviceTier')) {mutableServiceTier = normalizeServiceTier(resp.serviceTier) ?? null;