Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(agent): restore native probe source after route commit failure
Dash9a3368baeea5
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.tsindex 5f6f8f6f1b..95d8a0229f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts@@ -142,6 +142,47 @@ describe('same-harness native relocation', () => {expect(deps.confirmNativeHistoryFallback).not.toHaveBeenCalled();});+ it.each(['closed', 'close-rejected', 'account-changed', 'history-cleared'] as const)('rolls back a successful quota probe when the final route write fails (%s)', async state => {+ let row = makeRow({ workingDir: '/project', sdkSessionId: 'source-native', agentDeviceId: 'source' });+ const original = { ...row };+ let owner = 1;+ let generation = 0;+ let targetWrites = 0;+ let live = true;+ const { deps } = makeDeps({+ readOwnerGeneration: () => owner,+ readPendingHandoffGeneration: () => generation,+ getSessionRow: vi.fn(async () => ({ ...row })),+ getLiveSession: () => live ? { isTurnRunning: () => false, sdkSessionId: row.sdkSessionId ?? undefined } : undefined,+ relocateNativeHistory: vi.fn(async () => 'transferred'),+ applyAgentSwitchToDb: vi.fn(async (_id, patch) => {+ if (patch.sdkSessionId === 'transferred' && ++targetWrites === 2) throw new Error('route write failed');+ row = { ...row, ...patch, providerId: patch.providerId ?? null };+ }),+ bootstrapSwitchedSession: vi.fn(async () => { live = true; }),+ closeSession: vi.fn(async () => {+ live = false;+ if (targetWrites < 2) return;+ if (state === 'account-changed') owner++;+ if (state === 'history-cleared') generation++;+ if (state !== 'closed') throw new Error('DEVICE_LINK_NOT_CONNECTED');+ }),+ });+ await expect(performSessionAgentSwitch(deps, { ...validParams, targetAgentKind: 'claude-code', agentDeviceId: 'mini',+ applyNow: true, providerGroupSwitchReason: 'quota-rebalance', effort: 'high', fastMode: true })).rejects.toThrow('route write failed');+ expect(live).toBe(false);+ expect(deps.insertBoundaryMessage).not.toHaveBeenCalled();+ expect(deps.setPendingHandoff).not.toHaveBeenCalled();+ expect(deps.confirmNativeHistoryFallback).not.toHaveBeenCalled();+ if (state === 'account-changed' || state === 'history-cleared') {+ expect(deps.applyAgentSwitchToDb).toHaveBeenCalledTimes(2);+ expect(deps.setSessionProvider).toHaveBeenCalledTimes(1);+ return;+ }+ expect(row).toEqual(original);+ expect(deps.setSessionProvider).toHaveBeenLastCalledWith('s1', original.providerId);+ });+it.each([['claude-code', 'cc', null, 'mini'], ['codex', 'codex', 'mini', null], ['pi', 'pi', 'mini', 'studio'],] as const)('restores %s history from %s between computers before dispatch', async (kind, dbKind, from, to) => {diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.tsindex 9093db9268..6b0208bd68 100644--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts@@ -1099,6 +1099,26 @@ export async function performSessionAgentSwitch(});}};+ const restoreNativeProbeSource = async (error: unknown) => {+ // Cancel/selection changes still restore the source, but never restore old+ // history after clear or write the previous owner's route into a new account.+ const assertProbeOwner = () => {+ if (deps.readOwnerGeneration?.() !== ownerGeneration+ || (handoffGeneration !== undefined && deps.readPendingHandoffGeneration?.(sessionId) !== handoffGeneration)) {+ throw error;+ }+ };+ assertProbeOwner();+ await closeFailedNativeSession();+ assertProbeOwner();+ await deps.applyAgentSwitchToDb(sessionId, {+ agentKind: fromDbKind, model: row.model ?? model, providerId: row.providerId,+ sdkSessionId: sourceNativeId, agentDeviceId: currentAgentDeviceId,+ });+ assertProbeOwner();+ deps.setSessionProvider(sessionId, row.providerId);+ assertTransferCurrent();+ };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);@@ -1155,23 +1175,7 @@ export async function performSessionAgentSwitch(}nativeBootstrapReady = true;} catch (error) {- // Cancellation must not strand the task on a failed native copy. Do not- // restore stale history after clear or write into a different account.- if (deps.readOwnerGeneration?.() !== ownerGeneration- || (handoffGeneration !== undefined && deps.readPendingHandoffGeneration?.(sessionId) !== handoffGeneration)) {- throw error;- }- await closeFailedNativeSession();- if (deps.readOwnerGeneration?.() !== ownerGeneration- || (handoffGeneration !== undefined && deps.readPendingHandoffGeneration?.(sessionId) !== handoffGeneration)) {- throw error;- }- await deps.applyAgentSwitchToDb(sessionId, {- agentKind: fromDbKind, model: row.model ?? model, providerId: row.providerId,- sdkSessionId: sourceNativeId, agentDeviceId: currentAgentDeviceId,- });- deps.setSessionProvider(sessionId, row.providerId);- assertTransferCurrent();+ await restoreNativeProbeSource(error);relocatedNativeId = null;handoff = buildFullHandoff();deps.log.warn('agent-switch: native quota relocation failed; restored source before summary confirmation', {@@ -1189,18 +1193,25 @@ export async function performSessionAgentSwitch(if (relocating) assertTransferCurrent();// ---- commit point:此后切换生效 ----- await deps.applyAgentSwitchToDb(sessionId, {- agentKind: toDbKind,- model,- providerId: normalizedProviderId,- sdkSessionId: relocatedNativeId ?? parked?.sdkSessionId ?? null,- ...(typeof params.effort === 'string' && params.effort ? { effort: params.effort } : {}),- ...((typeof params.fastMode === 'boolean' || params.fastMode === 'ultrafast') ? { fastMode: params.fastMode } : {}),- // 组选回的当前位置在另一台电脑时也带上位置:提交按它判断窗口该查哪台的目录,不能拿本机目录。- ...(agentDeviceChanges || (orcaGroupReturnRebuild && targetAgentDeviceId)- ? { agentDeviceId: targetAgentDeviceId }- : {}),- });+ try {+ await deps.applyAgentSwitchToDb(sessionId, {+ agentKind: toDbKind,+ model,+ providerId: normalizedProviderId,+ sdkSessionId: relocatedNativeId ?? parked?.sdkSessionId ?? null,+ ...(typeof params.effort === 'string' && params.effort ? { effort: params.effort } : {}),+ ...((typeof params.fastMode === 'boolean' || params.fastMode === 'ultrafast') ? { fastMode: params.fastMode } : {}),+ // 组选回的当前位置在另一台电脑时也带上位置:提交按它判断窗口该查哪台的目录,不能拿本机目录。+ ...(agentDeviceChanges || (orcaGroupReturnRebuild && targetAgentDeviceId)+ ? { agentDeviceId: targetAgentDeviceId }+ : {}),+ });+ } catch (error) {+ // A successful probe already persisted and opened the target. If the final+ // settings write fails, the caller must see the original route, not a half switch.+ if (nativeBootstrapReady) await restoreNativeProbeSource(error);+ throw error;+ }if (normalizedProviderId !== undefined) {deps.setSessionProvider(sessionId, normalizedProviderId);}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 644ad20811..6352fcbf9f 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -14,6 +14,7 @@ Pi 只改写副本首行的 session ID 与 cwd,使其指向接收端工作目该标记覆盖手动、配额均衡与启动失败换电脑;普通 Claude 无效会话自愈保持原语义。启动迁移无法保存原子回退所需的边界时,先还原源位置与 ID,再返回失败,不打开副本。这些命令不加入只读/断链自动重放名单。恢复失败回落已有的原子 resume fallback,不把切账号或清空历史当普通失败。失败目标的关闭仅作尽力清理,断链错误不能阻止配额探测还原源路由或手动切换提交原子摘要回退;清理等待后仍须复核账号与历史代次,取消与改选继续阻止迟到提交。+配额探测成功后,正式路由写入若失败,同样关闭目标并还原源位置/原生 ID,再向调用方报错,不保留无边界记录的半切换状态。边界消息增加可选 `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`。