Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(agent): complete native fallback when target cleanup fails
Dash201b472c31eb
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.tsindex 07da82f16c..5f6f8f6f1b 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts@@ -91,6 +91,7 @@ describe('same-harness native relocation', () => {const { deps } = makeDeps({getSessionRow: vi.fn(async () => ({ ...row })),relocateNativeHistory: vi.fn(async () => failure === 'missing' ? null : 'transferred'),+ closeSession: vi.fn().mockResolvedValueOnce(undefined).mockRejectedValue(new Error('DEVICE_LINK_NOT_CONNECTED')),applyAgentSwitchToDb: vi.fn(async (_id, patch) => { row = { ...row, ...patch, providerId: patch.providerId ?? null }; }),getLiveSession: () => ({ isTurnRunning: () => false, sdkSessionId: failure === 'silent' ? 'fresh' : row.sdkSessionId ?? undefined }),bootstrapSwitchedSession: vi.fn(async () => { if (failure === 'rejected') throw new Error('cannot resume'); }),@@ -172,6 +173,41 @@ describe('same-harness native relocation', () => {expect(deps.bootstrapSwitchedSession).toHaveBeenCalledTimes(2);});+ it.each(['current', 'account-changed', 'history-cleared'] as const)('settles native resume fallback despite failed target cleanup (%s)', async state => {+ let owner = 1;+ let generation = 0;+ let row = makeRow({ workingDir: '/project', sdkSessionId: 'source-native' });+ let boundary: unknown;+ const { deps } = makeDeps({+ readOwnerGeneration: () => owner,+ readPendingHandoffGeneration: () => generation,+ getSessionRow: vi.fn(async () => ({ ...row })),+ getLiveSession: () => ({ isTurnRunning: () => false, sdkSessionId: row.sdkSessionId ?? undefined }),+ relocateNativeHistory: vi.fn(async () => 'transferred'),+ applyAgentSwitchToDb: vi.fn(async (_id, patch) => { row = { ...row, ...patch, providerId: patch.providerId ?? null }; }),+ insertBoundaryMessage: vi.fn(async (_id, content) => { boundary = content; return 'boundary-client-1'; }),+ applyResumeFallbackAtomically: vi.fn(async (_id, _clientId, content) => { row.sdkSessionId = null; boundary = content; }),+ closeSession: vi.fn().mockResolvedValueOnce(undefined).mockImplementation(async () => {+ if (state === 'account-changed') owner++;+ if (state === 'history-cleared') generation++;+ throw new Error('DEVICE_LINK_NOT_CONNECTED');+ }),+ bootstrapSwitchedSession: vi.fn().mockRejectedValueOnce(new Error('cannot resume')).mockResolvedValue(undefined),+ });+ const switching = performSessionAgentSwitch(deps, { ...validParams, targetAgentKind: 'claude-code', agentDeviceId: 'mini', applyNow: true });+ if (state !== 'current') {+ await expect(switching).rejects.toThrow(state === 'account-changed' ? 'REMOTE_AGENT_ACCOUNT_CHANGED' : 'history changed');+ expect(deps.applyResumeFallbackAtomically).not.toHaveBeenCalled();+ expect(deps.bootstrapSwitchedSession).toHaveBeenCalledOnce();+ return;+ }+ await expect(switching).resolves.toMatchObject({ switched: true, engineReady: true });+ expect(row.sdkSessionId).toBeNull();+ expect(boundary).toMatchObject({ resumed: false, nativeHistory: 'fallback', handoff: expect.stringContaining('你好') });+ expect(deps.setPendingHandoff).toHaveBeenLastCalledWith('s1', expect.stringContaining('你好'), 0);+ expect(deps.bootstrapSwitchedSession).toHaveBeenCalledTimes(2);+ });+it('does not commit native history after clear or cancellation during transfer', async () => {let generation = 0;const { deps } = makeDeps({diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.tsindex b39694edea..9093db9268 100644--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts@@ -1087,6 +1087,18 @@ export async function performSessionAgentSwitch(throw new Error('Session history changed during agent relocation');}};+ const closeFailedNativeSession = async () => {+ if (!deps.getLiveSession(sessionId)) return;+ try {+ await deps.closeSession(sessionId);+ } catch (error) {+ // The failed target is only cleanup. Its link cannot veto source rollback+ // or the atomic removal of an unusable native ID and restored boundary.+ deps.log.warn('agent-switch: failed native session cleanup failed; continuing fallback', {+ sessionId, error: error instanceof Error ? error.message : String(error),+ });+ }+ };if (relocating && !forcedRelocation && fromDbKind === toDbKind && deps.relocateNativeHistory) {// Close flushes the last native ID. Never snapshot the pre-close ID after a native fork/compact.const fresh = await deps.getSessionRow(sessionId);@@ -1149,7 +1161,7 @@ export async function performSessionAgentSwitch(|| (handoffGeneration !== undefined && deps.readPendingHandoffGeneration?.(sessionId) !== handoffGeneration)) {throw error;}- if (deps.getLiveSession(sessionId)) await deps.closeSession(sessionId);+ await closeFailedNativeSession();if (deps.readOwnerGeneration?.() !== ownerGeneration|| (handoffGeneration !== undefined && deps.readPendingHandoffGeneration?.(sessionId) !== handoffGeneration)) {throw error;@@ -1262,7 +1274,10 @@ export async function performSessionAgentSwitch(} catch (err) {if (relocating) assertTransferCurrent();if (relocatedNativeId || parked) {- if (relocatedNativeId && deps.getLiveSession(sessionId)) await deps.closeSession(sessionId);+ if (relocatedNativeId) {+ await closeFailedNativeSession();+ assertTransferCurrent();+ }// ---- resume 回落:清停泊 id → 换全量交接 → 全新原生会话重试 ----// 停泊原生会话可能已失效(transcript 被清理、CLI 升级不兼容等),这些// 只有 spawn 时才暴露。回落是确定性代码路径,不留半 resume 状态。diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 80d4a3306e..644ad20811 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -13,6 +13,7 @@ Pi 只改写副本首行的 session ID 与 cwd,使其指向接收端工作目`_cindyRequireNativeResume`:适配器等待 CLI 的初始化握手并拒绝静默新建,恢复失败交回宿主切换事务。该标记覆盖手动、配额均衡与启动失败换电脑;普通 Claude 无效会话自愈保持原语义。启动迁移无法保存原子回退所需的边界时,先还原源位置与 ID,再返回失败,不打开副本。这些命令不加入只读/断链自动重放名单。恢复失败回落已有的原子 resume fallback,不把切账号或清空历史当普通失败。+失败目标的关闭仅作尽力清理,断链错误不能阻止配额探测还原源路由或手动切换提交原子摘要回退;清理等待后仍须复核账号与历史代次,取消与改选继续阻止迟到提交。边界消息增加可选 `nativeHistory: restored | fallback`,桌面与手机在 fallback 时显示「已用摘要接续」;旧客户端忽略新增字段,仍能读取原有 handoff/resumed。无服务端、数据库 schema、环境变量或 Mobile 原生配置变化。回归:`relocateNativeHistory.test.ts`、`nativeHistoryTransfer.test.ts`、`nativeHistoryStorage.test.ts`、`sessionAgentSwitchHandler.test.ts`、device-link `remoteAgent.test.ts`。