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。

refactor(provider-group): 换不换电脑统一成一个判定,默认出问题就换

Lizi04e85b40a98d
diff --git a/apps/desktop/src/main/device-link/invoke-context.ts b/apps/desktop/src/main/device-link/invoke-context.ts
index 68157db322..f9c52f7ca5 100644
--- a/apps/desktop/src/main/device-link/invoke-context.ts
+++ b/apps/desktop/src/main/device-link/invoke-context.ts
@@ -56,6 +56,14 @@ export function runDeviceLinkInvokeContext<T>(
return storage.run(context, fn);
}
+/**
+ * 在本机自己发起的内部操作里运行 `fn`,不继承调用方的 device-link 来源:比如供应商组在发送前替任务换电脑,
+ * 触发它的可能是手机发来的一条消息,但换电脑本身是本机的决定,不能按「来自控制端」把错误码降级。
+ */
+export function runOutsideDeviceLinkInvokeContext<T>(fn: () => T): T {
+ return storage.exit(fn);
+}
+
export function getDeviceLinkInvokeContext(): DeviceLinkInvokeContext | null {
return storage.getStore() ?? null;
}
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.ts
index 03fdb3c8a2..c38802d830 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
@@ -1002,6 +1002,7 @@ function unsupportedChatBridgeImageError(feature = "input content part 'input_im
function createHarness(opts?: {
getRecoveryContextSnapshot?: (sessionId: string, userClientId: string) => Promise<RecoveryContextSnapshot>;
providerGroupSwitchCandidate?: AgentInputCoordinatorDeps['providerGroupSwitchCandidate'];
+ providerGroupUndeliveredSendSignals?: AgentInputCoordinatorDeps['providerGroupUndeliveredSendSignals'];
}) {
let running = false;
let liveRunningOverride: boolean | null | 'unknown' = null;
@@ -1203,6 +1204,9 @@ function createHarness(opts?: {
...(opts?.providerGroupSwitchCandidate
? { providerGroupSwitchCandidate: opts.providerGroupSwitchCandidate }
: {}),
+ ...(opts?.providerGroupUndeliveredSendSignals
+ ? { providerGroupUndeliveredSendSignals: opts.providerGroupUndeliveredSendSignals }
+ : {}),
noteSessionClearBoundary,
resolveSessionReferences,
refreshAgentReferencesBeforeDispatch,
@@ -14097,6 +14101,45 @@ describe('provider group computer switch hold', () => {
expect(h.coordinator.getProviderGroupSwitchHoldId(sid)).toBeNull();
});
+ it('hands a stored message whose agent did not start to the same switch, without showing the error', async () => {
+ const sid = 'group-hold-undelivered';
+ const signals = { message: '[REMOTE_AGENT_DEVICE_UNREACHABLE] gone', reason: 'provider_group_agent_start_failed' };
+ const candidate = vi.fn<NonNullable<AgentInputCoordinatorDeps['providerGroupSwitchCandidate']>>(() => 'unavailable');
+ const undelivered = vi.fn<NonNullable<AgentInputCoordinatorDeps['providerGroupUndeliveredSendSignals']>>(() => signals);
+ const h = createHarness({ providerGroupSwitchCandidate: candidate, providerGroupUndeliveredSendSignals: undelivered });
+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {
+ await persistQueuedUserMessage(sessionId, sendOpts);
+ return hostSendFailure('LAZY_CREATE_FAILED', '[REMOTE_AGENT_DEVICE_UNREACHABLE] gone');
+ });
+ h.coordinator.enqueue(sid, makeItem('q-first', 'original long task'));
+ await flush();
+
+ expect(undelivered).toHaveBeenCalledWith(sid, expect.objectContaining({ kind: 'host-send', code: 'LAZY_CREATE_FAILED' }));
+ // 与终态错误同一条路:先登记先不呈现,再交给 onUsageLimitedTurnError(供应商组据此换电脑后重发原消息)。
+ expect(h.projections.every((projection) => projection.error === null)).toBe(true);
+ expect(latestProjection(h.projections).autoResumePending).toMatchObject({ groupSwitchPending: { cause: 'unavailable' } });
+ expect(latestProjection(h.projections).recovery?.kind).toBe('active-turn');
+ expect(h.onUsageLimitedTurnError).toHaveBeenCalledWith(
+ sid,
+ expect.objectContaining({ reason: 'provider_group_agent_start_failed' }),
+ expect.objectContaining({ clientId: 'q-first' }),
+ expect.any(Number),
+ );
+ });
+
+ it('keeps the plain error for a stored message the group does not take', async () => {
+ const sid = 'group-hold-undelivered-none';
+ const h = createHarness({ providerGroupUndeliveredSendSignals: () => null });
+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {
+ await persistQueuedUserMessage(sessionId, sendOpts);
+ return hostSendFailure('LAZY_CREATE_FAILED', 'boom');
+ });
+ h.coordinator.enqueue(sid, makeItem('q-first', 'original long task'));
+ await flush();
+ expect(latestProjection(h.projections).error).toContain('LAZY_CREATE_FAILED');
+ expect(h.onUsageLimitedTurnError).not.toHaveBeenCalled();
+ });
+
it('ends the hold when the user takes over', async () => {
const sid = 'group-hold-user';
const { h } = await failWhileSwitching(sid);
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index fee5d1a1d4..ddf873bdb2 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -440,6 +440,15 @@ export interface AgentInputCoordinatorDeps {
signals: InterruptedTurnErrorSignals,
item: AgentInputQueuedMessage,
) => AutoResumeAgentSwitchCause | null;
+ /**
+ * **纯判定**:已落库的消息没能派发出去(打开任务时 Agent 没能启动、链路已断请求没发出去)时,这次失败要不要交给
+ * 供应商组换电脑(与终态错误同一条路:`providerGroupSwitchCandidate` 登记先不呈现,再 `onUsageLimitedTurnError`)。
+ * 返回判定用的字段;送达不明(请求超时等)或不归供应商组管时返回 null,照原有方式报错。
+ */
+ providerGroupUndeliveredSendSignals?: (
+ sessionId: string,
+ failure: unknown,
+ ) => InterruptedTurnErrorSignals | null;
/**
* **纯判定**:这条 terminal error 有没有可能被自愈接管(`isInterruptedTurnError`)。
* 不消耗额度、不排期、无副作用。
@@ -5180,11 +5189,17 @@ export class AgentInputCoordinator {
latest.activeTurn = null;
this.notifyRejectedUserTurn(sessionId, head);
this.notifyUndispatchedUserTurn(sessionId, head, 'failed');
+ // 确定没送达的失败交给供应商组换电脑(与终态错误同一条路,先登记先不呈现,再 emit)。
+ const groupSignals = !rewound && !schedulerOrigin
+ ? this.providerGroupUndeliveredSignals(sessionId, err)
+ : null;
+ if (groupSignals) this.holdForProviderGroupSwitch(sessionId, latest, head, latest.error!, groupSignals);
if (!rewound) {
this.persistTerminalSendError(sessionId, latest.error!);
this.notifyPersistedSendRejected(sessionId, latest.error!);
}
this.emit(sessionId);
+ if (groupSignals) this.notifyUsageLimitedTurnError(sessionId, head, latest.error!, groupSignals);
// 派发边界刚刚放开,队里可能还压着别的消息 —— 用户那条路靠 clearError 顺带唤醒,
// scheduler 这条没有人点,必须自己唤一次。
if (schedulerOrigin) this.scheduleDrain(sessionId, 'scheduler-prompt-cancelled');
@@ -5333,11 +5348,17 @@ export class AgentInputCoordinator {
...logFields,
},
);
+ // 确定没送达的失败(打开任务时 Agent 没能启动等)交给供应商组换电脑:先登记先不呈现,再 emit。
+ const groupSignals = !cancelledByUserBoundary && !rewoundScheduler && !schedulerOrigin
+ ? this.providerGroupUndeliveredSignals(sessionId, result)
+ : null;
+ if (groupSignals) this.holdForProviderGroupSwitch(sessionId, latest, item, message, groupSignals);
if (!cancelledByUserBoundary && !rewoundScheduler) {
this.persistTerminalSendError(sessionId, message);
this.notifyPersistedSendRejected(sessionId, message);
}
this.emit(sessionId);
+ if (groupSignals) this.notifyUsageLimitedTurnError(sessionId, item, message, groupSignals);
// activeTurn 上面已置空,但队里可能还压着别的消息 —— 用户那条路靠 clearError 顺带
// 唤醒,scheduler 这条没有 recovery、没有人点,必须自己唤一次(review #944 第十轮 P1)。
if (schedulerOrigin) this.scheduleDrain(sessionId, 'scheduler-prompt-cancelled');
@@ -6552,6 +6573,21 @@ export class AgentInputCoordinator {
}
}
+ /** 已落库却没派发出去的这次失败要不要交给供应商组换电脑(`providerGroupUndeliveredSendSignals`)。 */
+ private providerGroupUndeliveredSignals(
+ sessionId: string,
+ failure: unknown,
+ ): InterruptedTurnErrorSignals | null {
+ const classify = this.deps.providerGroupUndeliveredSendSignals;
+ if (!classify) return null;
+ try {
+ return classify(sessionId, failure);
+ } catch (err) {
+ log.warn('providerGroupUndeliveredSendSignals failed', { sessionId, error: errorMessage(err) });
+ return null;
+ }
+ }
+
/** 这次终态错误会不会真的交给 `onUsageLimitedTurnError`(与 notifyUsageLimitedTurnError 同一判据)。 */
private willNotifyUsageLimitedTurnError(
state: SessionInputState,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index ed7a9df240..bc417d1bd5 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -63,7 +63,7 @@ import {
} from '../provider-group/service.js';
import { createProviderGroupHeldTurnErrors } from '../provider-group/heldTurnErrors.js';
import { createProviderGroupHeldWorkerTerminals } from '../provider-group/heldWorkerTerminals.js';
-import { classifyProviderGroupSwitchCause } from '../provider-group/switchCause.js';
+import { providerGroupSwitchCause, providerGroupUndeliveredSendSignals } from '../provider-group/failurePolicy.js';
import { listProviderGroups, readProviderGroup } from '../provider-group/store.js';
import {
isRemoteProviderInvocationAllowed,
@@ -1221,6 +1221,7 @@ import {
isDeviceLinkInvoke,
isMobileControllerInvoke,
readDeviceLinkInvokeSourceDevice,
+ runOutsideDeviceLinkInvokeContext,
} from '../device-link/invoke-context.js';
import { stampSharedTaskInput } from './sharedTaskInput.js';
import { createSharedTaskContextUsageGuard } from './sharedTaskContextUsage.js';
@@ -3633,7 +3634,12 @@ export function applyDirectoryGrants(
return accepted;
},
persist: (patch) => persistSessionFields(sessionId, patch),
- terminate: () => maker.closeSession(sessionId),
+ // 远程 Agent 正在跑一轮时不当场关:那台只是暂时连不上,本机执行器已回到原来的目录(文件读写由本机执行器
+ // 把关),库里也还是原来那份;这一轮结束后再重建。当场关会把进行中的一轮杀掉,且不是那台电脑的问题,
+ // 供应商组也不会换电脑(docs/product-rules/provider-groups.md §6.1「本机的操作不打断进行中的远程一轮」)。
+ terminate: () => (sess?.agentDeviceId && sess.isTurnRunning()
+ ? maker.closeSessionIfCurrent(sess, 'runtime-refresh', { afterCurrentTurn: true })
+ : maker.closeSession(sessionId)),
});
if (result.changed || result.rejectedCount > 0) log.info(label, {
sessionId,
@@ -3704,6 +3710,14 @@ async function syncLibraryReadonlyExtraDir(
const remote = await sessionIsRemote(sessionId);
if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
const nextRoot = !remote && grantRoot && sessionId === focused ? grantRoot : null;
+ // 没有 Library 槽可撤、这次也不给:什么都不变,不碰运行中的会话。否则每次切换焦点都要把每个开着的任务的附加
+ // 目录重新下发一遍,远程 Agent 那台恰好连不上时回滚失败、会话被关,正在跑的一轮就此中断(2026-10-11 实测)。
+ // 运行时的 Library 槽只会来自已落库的那份(启动从库里读,改动先改运行时再落库,落库失败回滚),库里没有即运行时没有。
+ if (!nextRoot) {
+ const persisted = await readSessionExtraDirsFromDb(sessionId).catch(() => null);
+ if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
+ if (persisted && !persisted.some(isLibraryExtraDirSlot)) continue;
+ }
try {
const applied = await applyLibraryReadonlyExtraDir(sessionId, nextRoot);
if (nextRoot && applied?.some(isLibraryExtraDirSlot)) granted = true;
@@ -9721,7 +9735,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const assertCurrent = () => {
if (isCurrent && !isCurrent()) throw new Error(PROVIDER_GROUP_SUPERSEDED_ERROR);
};
- const run = async () => {
+ // 换电脑是本机的决定:即使这次发送来自手机或另一台电脑,也不继承它的 device-link 来源,否则换不过去的
+ // 原因(那台连不上等)会被降级成 PRECONDITION_FAILED,判定认不出是那台的问题,就不再试下一台。
+ const run = () => runOutsideDeviceLinkInvokeContext(async () => {
assertCurrent();
const result = await performSessionAgentSwitch(agentSwitchDeps, {
sessionId,
@@ -9741,7 +9757,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
// 同引擎同位置等情况会按 no-op 返回:没有真正换过去,按交接失败处理。
if (!result.switched) throw new Error('provider group: the agent switch did not apply');
- };
+ // 运行中换电脑:换过去的那台没能把 Agent 启动起来时按换不过去处理,由调用方按同一个判定换下一台,不把续跑
+ // 交给一台起不来的电脑(续跑会再失败,协同 Worker 还会一直停在运行中)。发送前换电脑随后照常 lazy-create。
+ if (!switchOptions?.beforeSend && !result.engineReady) {
+ throw new Error(result.bootstrapError || '[REMOTE_AGENT_UNAVAILABLE] the agent did not start on that computer');
+ }
+ });
// 发送前换电脑已在发送事务里;运行中失败后的换电脑是异步触发的,与其他内部调用一样在发送锁内交接,
// 不与用户同时发来的消息交错。
if (switchOptions?.beforeSend) {
@@ -16768,8 +16789,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 纯判定:供应商组会先试着换电脑时,这次错误先不呈现(provider-groups.md §6.1)。
providerGroupSwitchCandidate: (sessionId, signals) =>
providerGroupService?.mayHandleTurnError(sessionId, signals)
- ? classifyProviderGroupSwitchCause(signals)
+ ? providerGroupSwitchCause(signals, 'run')
: null,
+ // 已落库的消息在打开任务时就没送出去(Agent 没能启动等):与运行中失败同一条换电脑流程(§6.1)。
+ providerGroupUndeliveredSendSignals: (sessionId, failure) => {
+ const signals = providerGroupUndeliveredSendSignals(failure);
+ return signals && providerGroupService?.mayHandleTurnError(sessionId, signals) ? signals : null;
+ },
onUsageLimitedTurnError: (sessionId, signals, _item, candidateToken) => {
// 供应商组分配的任务先试自动换电脑,不换时由它交回额度重置后自动继续。
if (!providerGroupService) {
@@ -17232,14 +17258,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
autoResumeBookkeeping.surfaceSuppressedErrorForRetry(sessionId, item.clientId);
},
persistTerminalSendError: (sessionId, message) => {
- onTurnErrorEvent(
- sessionId,
- {
- message,
- ...(isPiPromptRpcTimeoutError({ message }) ? { reason: 'pi-prompt-timeout' } : {}),
- },
- null,
- );
+ const data = {
+ message,
+ ...(isPiPromptRpcTimeoutError({ message }) ? { reason: 'pi-prompt-timeout' } : {}),
+ };
+ // 供应商组正为这次没送出去的失败换电脑(与终态错误同一套):error 行先暂存,没换成时再落。
+ const holdId = agentInputCoordinatorHolder?.getProviderGroupSwitchHoldId(sessionId) ?? null;
+ if (holdId !== null && providerGroupHeldErrors.stash(sessionId, holdId, data, null)) return;
+ onTurnErrorEvent(sessionId, data, null);
},
onUnconfirmedAutoResumeTurn: (sessionId, item) => {
const attemptToken = autoResumeAttemptToken(item);
@@ -21049,7 +21075,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
effort as 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',
);
},
- terminateSession: () => maker.closeSession(sessionId),
+ // 远程 Agent 正在跑一轮、那台只是回得慢:不当场关(会把这一轮杀掉,且不是那台电脑的问题,供应商组也
+ // 不会换电脑),这一轮结束后再按已落库的档位重建(provider-groups.md §6.1「本机的操作不打断进行中的远程一轮」)。
+ terminateSession: async () => {
+ if (sess.agentDeviceId && sess.isTurnRunning()) {
+ await maker.closeSessionIfCurrent(sess, 'runtime-refresh', { afterCurrentTurn: true });
+ return;
+ }
+ await maker.closeSession(sessionId);
+ },
});
if (result === 'session-terminated') {
log.warn('set-effort: timed-out runtime session terminated for lazy rebuild', {
diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
index a426590290..7287edf95c 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
@@ -292,6 +292,11 @@ export interface SessionAgentSwitchResult {
model: string;
/** 新引擎 live session 是否已就绪;false 时下一条消息走 lazy-create 重试。 */
engineReady: boolean;
+ /**
+ * engineReady=false 时新会话没能启动的原因(错误原文)。供应商组换电脑据此判断是不是那台电脑的问题、要不要
+ * 换下一台(provider-group/failurePolicy)。
+ */
+ bootstrapError?: string;
/**
* turn 运行中登记为 pending:切换不打断当前 turn,推迟到下一条消息发送时刻
* 由 send 事务执行(applyPendingAgentSwitchIfIdle)。true 时 switched=false,
@@ -829,6 +834,7 @@ export async function performSessionAgentSwitch(
deps.setPendingHandoff(sessionId, handoff, handoffGeneration);
let engineReady = true;
+ let bootstrapError: string | undefined;
let resumed = !!parked;
let retryPending = false;
// resume 模式无视 skipBootstrap:只有 eager spawn 才能确定性观测 resume 失败
@@ -923,6 +929,7 @@ export async function performSessionAgentSwitch(
await deps.bootstrapSwitchedSession(sessionId);
} catch (err2) {
engineReady = false;
+ bootstrapError = err2 instanceof Error ? err2.message : String(err2);
deps.log.warn('agent-switch: fresh bootstrap after resume fallback failed', {
sessionId,
targetAgentKind,
@@ -932,6 +939,7 @@ export async function performSessionAgentSwitch(
}
} else {
engineReady = false;
+ bootstrapError = err instanceof Error ? err.message : String(err);
deps.log.warn('agent-switch: bootstrap new engine failed; next send will lazy-create', {
sessionId,
targetAgentKind,
@@ -957,6 +965,7 @@ export async function performSessionAgentSwitch(
agentKind: targetAgentKind,
model,
engineReady,
+ ...(bootstrapError !== undefined ? { bootstrapError } : {}),
...(retryPending ? { retryPending: true } : {}),
};
});
diff --git a/apps/desktop/src/main/provider-group/__tests__/failurePolicy.test.ts b/apps/desktop/src/main/provider-group/__tests__/failurePolicy.test.ts
new file mode 100644
index 0000000000..6af9262a75
--- /dev/null
+++ b/apps/desktop/src/main/provider-group/__tests__/failurePolicy.test.ts
@@ -0,0 +1,207 @@
+/**
+ * 供应商组「这次失败怎么办」的唯一判定(provider-groups.md §6.1「怎么判断换不换」):默认换,只有换到哪台都一样、
+ * 或不是那台电脑的问题时不换。下面按「故障 × 阶段」列出验收表,所有路径(新任务启动、运行中、换过去、分享的人
+ * 中转)都问这一个判定。
+ */
+import { SESSION_CLOSED_MID_TURN_MESSAGE } from '@cindy/maker-core';
+import { describe, expect, it } from 'vitest';
+
+import {
+ decideProviderGroupFailure,
+ describeProviderGroupFailure,
+ PROVIDER_GROUP_AGENT_START_FAILED_REASON,
+ PROVIDER_GROUP_SUPERSEDED_ERROR,
+ PROVIDER_GROUP_UNAVAILABLE_ERROR,
+ providerGroupFailureSignals,
+ providerGroupUndeliveredSendSignals,
+ type ProviderGroupFailurePhase,
+} from '../failurePolicy';
+import type { InterruptedTurnErrorSignals } from '../../maker-ipc/interruptedTurnAutoResume';
+
+const switchTo = (cause: string, connection: 'lost' | 'check' | null = null) => ({
+ action: 'switch',
+ cause,
+ connection,
+ cool: cause === 'usage-limit' || cause === 'auth' || cause === 'overload',
+});
+const stay = (why: string) => ({ action: 'stay', why });
+
+const PHASES: ProviderGroupFailurePhase[] = ['start', 'run', 'target'];
+
+describe('decideProviderGroupFailure — the account on that computer', () => {
+ it.each<[string, InterruptedTurnErrorSignals, ReturnType<typeof switchTo>]>([
+ ['usage limit (Claude tag)', { sdkError: 'rate_limit' }, switchTo('usage-limit')],
+ ['usage limit (Codex tag)', { codexErrorInfo: 'usageLimitExceeded' }, switchTo('usage-limit')],
+ ['billing depleted', { sdkError: 'billing_error' }, switchTo('usage-limit')],
+ ['HTTP 429', { errorStatus: 429, message: 'rate limited' }, switchTo('usage-limit')],
+ ['signed out (tag)', { sdkError: 'authentication_failed' }, switchTo('auth')],
+ ['signed out (401)', { errorStatus: 401 }, switchTo('auth')],
+ ['signed out (Codex)', { codexErrorInfo: 'unauthorized' }, switchTo('auth')],
+ ['invalid API key text', { message: 'Invalid API key provided' }, switchTo('auth')],
+ ['agent not authenticated at start', { message: 'Claude Code is not authenticated' }, switchTo('auth')],
+ ['overloaded (529)', { errorStatus: 529 }, switchTo('overload')],
+ ['overloaded (Codex)', { codexErrorInfo: 'serverOverloaded' }, switchTo('overload')],
+ ])('%s → switch and record it in the group (cool)', (_name, signals, expected) => {
+ for (const phase of PHASES) expect(decideProviderGroupFailure(signals, phase)).toEqual(expected);
+ });
+});
+
+describe('decideProviderGroupFailure — that computer cannot be reached or cannot take the task', () => {
+ it.each<[string, InterruptedTurnErrorSignals, ReturnType<typeof switchTo>]>([
+ // 只是连接断了:先等它恢复,现读第一次就连得上算恢复。
+ ['device unreachable', { message: '[REMOTE_AGENT_DEVICE_UNREACHABLE] unreachable' }, switchTo('unavailable', 'lost')],
+ ['Cindy restarted there (expired)', { message: '[REMOTE_AGENT_EXPIRED] session expired' }, switchTo('unavailable', 'lost')],
+ ['Cindy restarted there (not found)', { message: '[REMOTE_AGENT_NOT_FOUND] no such session' }, switchTo('unavailable', 'lost')],
+ // 可能连不上:现读一次,确实连不上才等。
+ ['reader gave up (2 minutes)', {
+ message: '[REMOTE_AGENT_UNAVAILABLE] The computer running this agent is unreachable.',
+ reason: 'remote_agent_closed',
+ }, switchTo('unavailable', 'check')],
+ ['agent there stopped unexpectedly', { reason: 'remote_agent_closed', message: 'stream broke' }, switchTo('unavailable', 'check')],
+ ['shared computer unreachable', { message: '[REMOTE_AGENT_SHARE_UNAVAILABLE] not available' }, switchTo('unavailable', 'check')],
+ ['too busy', { message: '[REMOTE_AGENT_BUSY] too many tasks' }, switchTo('unavailable', 'check')],
+ // 那台本身现在不能接:不等,直接换。
+ ['remote invocation turned off', { message: '[REMOTE_AGENT_PROVIDER_NOT_ALLOWED] not allowed' }, switchTo('unavailable')],
+ ['model not offered there', { message: '[REMOTE_AGENT_MODEL_UNAVAILABLE] no such model' }, switchTo('unavailable')],
+ ['share paused', { message: '[REMOTE_AGENT_SHARE_PAUSED] paused' }, switchTo('unavailable')],
+ ['share removed', { message: '[REMOTE_AGENT_SHARE_REMOVED] removed' }, switchTo('unavailable')],
+ ['account changed there', { message: '[REMOTE_AGENT_ACCOUNT_CHANGED] changed' }, switchTo('unavailable')],
+ ['Cindy too old there', { message: '[REMOTE_AGENT_PEER_TOO_OLD] too old' }, switchTo('unavailable')],
+ ['agent not installed there', { message: '[REMOTE_AGENT_UNSUPPORTED] codex is not available on this computer' }, switchTo('unavailable')],
+ ['wrapped code in the middle', { message: 'open failed: [REMOTE_AGENT_DEVICE_UNREACHABLE] gone' }, switchTo('unavailable', 'lost')],
+ ])('%s → switch (no cooling)', (_name, signals, expected) => {
+ for (const phase of PHASES) expect(decideProviderGroupFailure(signals, phase)).toEqual(expected);
+ });
+});
+
+describe('decideProviderGroupFailure — everything else is that computer’s problem (default: switch)', () => {
+ it.each<[string, InterruptedTurnErrorSignals]>([
+ ['agent ended mid-turn', {
+ message: 'Session event loop stopped unexpectedly without a terminal event',
+ reason: 'session_event_loop_crashed',
+ }],
+ ['agent event loop crashed', { message: 'Session event loop stopped unexpectedly: boom', reason: 'session_event_loop_crashed' }],
+ ['no error details', { message: '任务执行失败(模型未返回错误详情)。', reason: 'turn-failed' }],
+ ['502 after retries', { message: 'API Error: 502 Bad Gateway', errorStatus: 502 }],
+ ['503 after retries', { message: 'Service Unavailable', errorStatus: 503 }],
+ ['stream cut after retries', { message: 'API Error: Connection closed mid-response.', sdkError: 'server_error' }],
+ ['network timeout after retries', { message: 'Request timed out' }],
+ ['stalled turn after retries', { message: 'no events', reason: 'turn_no_event_timeout' }],
+ ['Codex reconnect stalled', { message: 'stalled', reason: 'codex_reconnect_stalled' }],
+ ['SDK stream crashed', { message: 'crash', reason: 'sdk_stream_crashed' }],
+ ['unknown agent start error', { message: 'spawn ENOENT' }],
+ ])('%s → switch with cause failed, not recorded in the group', (_name, signals) => {
+ for (const phase of PHASES) expect(decideProviderGroupFailure(signals, phase)).toEqual(switchTo('failed'));
+ });
+});
+
+describe('decideProviderGroupFailure — any computer would fail the same way (stay)', () => {
+ it.each<[string, InterruptedTurnErrorSignals, string]>([
+ ['prompt too long', { sdkError: 'invalid_request', message: 'prompt is too long' }, 'context'],
+ ['context overflow reason', { reason: 'context-overflow', message: 'too long' }, 'context'],
+ ['Codex context window', { codexErrorInfo: 'contextWindowExceeded', message: 'x' }, 'context'],
+ ['Codex history oversized', { reason: 'codex_history_oversized', message: 'x' }, 'context'],
+ ['output limit', { reason: 'output-limit', message: 'x' }, 'context'],
+ ['invalid request', { sdkError: 'invalid_request', message: 'messages: field required' }, 'invalid-request'],
+ ['HTTP 400', { errorStatus: 400, message: 'bad request' }, 'invalid-request'],
+ ['HTTP 413', { errorStatus: 413, message: 'too large' }, 'invalid-request'],
+ ['Codex bad request', { codexErrorInfo: 'badRequest', message: 'x' }, 'invalid-request'],
+ ['content policy', { codexErrorInfo: 'cyberPolicy', message: 'x' }, 'policy'],
+ ['tool loop', { reason: 'tool_use_loop_detected', message: 'loop' }, 'tool-loop'],
+ ['permission denied by user', { message: 'Permission denied by user' }, 'user'],
+ ['tool execution failed', { reason: 'turn-failed', message: 'Tool execution failed' }, 'local'],
+ ['cancelled before dispatch', { reason: 'cancelled-before-dispatch', message: 'x' }, 'user'],
+ ])('%s → stay (%s)', (_name, signals, why) => {
+ for (const phase of PHASES) expect(decideProviderGroupFailure(signals, phase)).toEqual(stay(why));
+ });
+
+ it('does not count usage limits wrapped as invalid_request as a request problem', () => {
+ expect(decideProviderGroupFailure({ sdkError: 'invalid_request', errorStatus: 429, message: 'rate limited' }, 'run'))
+ .toEqual(switchTo('usage-limit'));
+ });
+});
+
+describe('decideProviderGroupFailure — not that computer’s problem (stay)', () => {
+ it('this computer closed the running session itself (Library sync, setting change, …)', () => {
+ expect(decideProviderGroupFailure({ message: SESSION_CLOSED_MID_TURN_MESSAGE, reason: 'session_event_loop_crashed' }, 'run'))
+ .toEqual(stay('local'));
+ });
+
+ it('the user took over during the switch', () => {
+ for (const phase of PHASES) {
+ expect(decideProviderGroupFailure({ message: PROVIDER_GROUP_SUPERSEDED_ERROR }, phase)).toEqual(stay('user'));
+ }
+ });
+
+ it('the whole group is unavailable', () => {
+ expect(decideProviderGroupFailure({ message: PROVIDER_GROUP_UNAVAILABLE_ERROR }, 'run')).toEqual(stay('group-unavailable'));
+ });
+
+ it('the task itself cannot be switched right now (start / target only)', () => {
+ for (const code of ['SESSION_RUNNING', 'NOT_FOUND', 'PRECONDITION_FAILED', 'UNSUPPORTED_CAPABILITY']) {
+ const signals = { message: `[${code}] nope` };
+ expect(decideProviderGroupFailure(signals, 'start')).toEqual(stay('task-state'));
+ expect(decideProviderGroupFailure(signals, 'target')).toEqual(stay('task-state'));
+ }
+ });
+
+ it('nothing to decide on', () => {
+ expect(decideProviderGroupFailure(undefined, 'run')).toEqual(stay('no-signal'));
+ expect(decideProviderGroupFailure({}, 'run')).toEqual(stay('no-signal'));
+ });
+});
+
+describe('providerGroupFailureSignals', () => {
+ it('reads thrown errors and plain records the same way', () => {
+ expect(providerGroupFailureSignals(new Error('[REMOTE_AGENT_BUSY] x'))).toEqual({ message: '[REMOTE_AGENT_BUSY] x' });
+ expect(providerGroupFailureSignals('boom')).toEqual({ message: 'boom' });
+ expect(providerGroupFailureSignals({ sdkError: 'rate_limit' })).toEqual({ sdkError: 'rate_limit' });
+ expect(providerGroupFailureSignals(null)).toEqual({});
+ });
+});
+
+describe('providerGroupUndeliveredSendSignals', () => {
+ it('treats an agent that did not start for a stored message as a start failure', () => {
+ const signals = providerGroupUndeliveredSendSignals({
+ kind: 'host-send', accepted: false, code: 'LAZY_CREATE_FAILED', message: '[REMOTE_AGENT_DEVICE_UNREACHABLE] gone',
+ });
+ expect(signals).toEqual({ message: '[REMOTE_AGENT_DEVICE_UNREACHABLE] gone', reason: PROVIDER_GROUP_AGENT_START_FAILED_REASON });
+ expect(decideProviderGroupFailure(signals, 'run')).toEqual(switchTo('unavailable', 'lost'));
+ });
+
+ it('keeps start-phase rules for the start failure (local admission errors stay)', () => {
+ const signals = providerGroupUndeliveredSendSignals({
+ kind: 'host-send', accepted: false, code: 'LAZY_CREATE_FAILED', message: '[PRECONDITION_FAILED] model disabled',
+ });
+ expect(decideProviderGroupFailure(signals, 'run')).toEqual(stay('task-state'));
+ // 展示文案带宿主错误码前缀时同样看里面那层。
+ expect(decideProviderGroupFailure({ message: 'LAZY_CREATE_FAILED: [PRECONDITION_FAILED] x', reason: PROVIDER_GROUP_AGENT_START_FAILED_REASON }, 'run'))
+ .toEqual(stay('task-state'));
+ });
+
+ it('accepts link failures where the request was never sent', () => {
+ const error = Object.assign(new Error('[REMOTE_AGENT_UNAVAILABLE] target device offline'), { code: 'DEVICE_OFFLINE' });
+ expect(providerGroupUndeliveredSendSignals(error)?.reason).toBe(PROVIDER_GROUP_AGENT_START_FAILED_REASON);
+ });
+
+ it('never re-sends when delivery is unknown (timeouts) or the failure is not about starting', () => {
+ expect(providerGroupUndeliveredSendSignals(Object.assign(new Error('[REMOTE_AGENT_UNAVAILABLE] timed out'), { code: 'TIMEOUT' })))
+ .toBeNull();
+ expect(providerGroupUndeliveredSendSignals({ kind: 'host-send', accepted: false, code: 'WORKDIR_MISSING', message: 'x' }))
+ .toBeNull();
+ expect(providerGroupUndeliveredSendSignals({ kind: 'session-dispatch', accepted: false, reason: 'cancelled-before-dispatch' }))
+ .toBeNull();
+ });
+});
+
+describe('describeProviderGroupFailure', () => {
+ it('logs codes and structured fields only, never the error text', () => {
+ const signals = { message: '[REMOTE_AGENT_BUSY] secret prompt text', reason: 'remote_agent_closed', errorStatus: 503 };
+ const described = describeProviderGroupFailure(signals, decideProviderGroupFailure(signals, 'run'));
+ expect(described).toEqual({
+ action: 'switch', cause: 'unavailable', connection: 'check', cool: false,
+ code: 'REMOTE_AGENT_BUSY', reason: 'remote_agent_closed', errorStatus: 503,
+ });
+ expect(JSON.stringify(described)).not.toContain('secret');
+ });
+});
diff --git a/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.ts b/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.ts
index 300b0a0f20..af90d76aab 100644
--- a/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.ts
@@ -496,7 +496,9 @@ describe('old tasks already running on the group computer', () => {
});
it('retries group adoption after a startup failure when the initial group read timed out', async () => {
- const h = harness({ row: { sdkSessionId: 'native-1' }, live: false });
+ // 运行过、但没有原生会话要续接(回退或清空后):这次打开反正是全新会话,启动失败可以直接换下一台。
+ const h = harness({ live: false });
+ h.deps.hasAssistantHistory.mockResolvedValue(true);
h.remote.readGroup.mockResolvedValueOnce(undefined);
const context = await h.service.assignBeforeStart(START);
@@ -515,6 +517,23 @@ describe('old tasks already running on the group computer', () => {
expect(h.bindings.get('s1')).toMatchObject({ memberKey: STUDIO.key, groupDeviceId: OWNER });
});
+ it('does not release a bound task when the group computer is merely slow to answer (timeout is not "group deleted")', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = harness({ live: true });
+ h.bindings.set('s1', { providerId: 'anthropic', memberKey: OWNER_LOCAL.key, groupDeviceId: OWNER, at: 1 });
+ // 组所在电脑一直不回(慢,或者正忙):超时只说明读不到,不能当作组已删除。
+ h.remote.readGroup.mockImplementation(() => new Promise(() => {}));
+ const assigned = h.service.assignBeforeStart(START);
+ await vi.advanceTimersByTimeAsync(3_100);
+ expect(await assigned).toBeNull();
+ expect(h.bindings.get('s1')).toMatchObject({ memberKey: OWNER_LOCAL.key, groupDeviceId: OWNER });
+ expect(h.deps.markReleased).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('keeps an existing bound task pending when its group read times out before reopening', async () => {
const h = harness({ live: false });
h.bindings.set('s1', { providerId: 'anthropic', memberKey: OWNER_LOCAL.key, groupDeviceId: OWNER, at: 1 });
@@ -535,8 +554,19 @@ describe('old tasks already running on the group computer', () => {
expect(h.bindings.get('s1')).toMatchObject({ memberKey: STUDIO.key, groupDeviceId: OWNER });
});
- it('returns a start context for an old task whose live session is gone, so startup failure can move it', async () => {
+ it('does not move an old task at start when its native session must be resumed (that needs a handoff)', async () => {
const h = harness({ row: { sdkSessionId: 'native-1' }, live: false, picks: [STUDIO] });
+ expect(await h.service.assignBeforeStart(START)).toBeNull();
+ // 仍纳入组:之后打开失败、运行中失败走带交接的自动换电脑。
+ expect(h.bindings.get('s1')).toMatchObject({ memberKey: OWNER_LOCAL.key, groupDeviceId: OWNER });
+ const unreadable = harness({ row: { sdkSessionId: 'native-1' }, live: false });
+ unreadable.remote.readGroup.mockResolvedValueOnce(undefined);
+ expect(await unreadable.service.assignBeforeStart(START)).toBeNull();
+ });
+
+ it('returns a start context for an old task whose live session is gone, so startup failure can move it', async () => {
+ const h = harness({ live: false, picks: [STUDIO] });
+ h.deps.hasAssistantHistory.mockResolvedValue(true);
const context = await h.service.assignBeforeStart(START);
expect(context).toMatchObject({
diff --git a/apps/desktop/src/main/provider-group/__tests__/router.test.ts b/apps/desktop/src/main/provider-group/__tests__/router.test.ts
index 68a3e89d40..70acbfead2 100644
--- a/apps/desktop/src/main/provider-group/__tests__/router.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/router.test.ts
@@ -93,3 +93,20 @@ describe('provider group running count', () => {
expect(pick).toMatchObject({ kind: 'member', member: { key: SHARE_B.key } });
});
});
+
+describe('provider group picks for this computer’s own tasks', () => {
+ it('reserves the chosen computer until the task starts, so tasks opened together spread out', async () => {
+ const bindings: Record<string, ProviderGroupBinding> = {};
+ const running: string[] = [];
+ const router = harness({}, bindings, running);
+ const first = await router.pick({ providerId: 'anthropic', agentKind: 'claude-code', model: MODEL, reserveFor: 's1' });
+ const second = await router.pick({ providerId: 'anthropic', agentKind: 'claude-code', model: MODEL, reserveFor: 's2' });
+ expect(first.kind === 'member' && second.kind === 'member' && first.member.key !== second.member.key).toBe(true);
+
+ // 开始运行一轮之后按绑定计,不再重复计那份临时占用。
+ if (first.kind !== 'member') throw new Error('expected a member');
+ bindings.s1 = { providerId: 'anthropic', memberKey: first.member.key, at: 1 };
+ running.push('s1');
+ expect(router.running('anthropic', first.member.key)).toBe(1);
+ });
+});
diff --git a/apps/desktop/src/main/provider-group/__tests__/service.test.ts b/apps/desktop/src/main/provider-group/__tests__/service.test.ts
index e36543dd98..846a812275 100644
--- a/apps/desktop/src/main/provider-group/__tests__/service.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/service.test.ts
@@ -190,10 +190,20 @@ describe('assignBeforeStart', () => {
expect(h.bindings.get('s1')?.memberKey).toBe('local');
});
- it('keeps an old task on its current computer but returns a start context after its live session is gone', async () => {
+ it('does not move an old task at start while its native session must be resumed (that needs a handoff)', async () => {
const h = harness({ row: { sdkSessionId: 'native-1' } });
h.deps.hasAssistantHistory.mockResolvedValue(true);
h.deps.hasLiveSession.mockReturnValue(false);
+ expect(await h.service.assignBeforeStart({ sessionId: 's1', agentKind: 'claude-code', model: MODEL })).toBeNull();
+ // 仍纳入组:打开失败、运行中失败走带交接的自动换电脑。
+ expect(h.bindings.get('s1')?.memberKey).toBe(LOCAL.key);
+ });
+
+ it('keeps an old task on its current computer but returns a start context after its live session is gone', async () => {
+ // 运行过、但没有原生会话要续接(回退或清空后):这次打开反正是全新会话。
+ const h = harness();
+ h.deps.hasAssistantHistory.mockResolvedValue(true);
+ h.deps.hasLiveSession.mockReturnValue(false);
const context = await h.service.assignBeforeStart({
sessionId: 's1',
@@ -696,7 +706,10 @@ describe('waiting for a computer that cannot be reached before switching (§6.1)
});
it('counts a dropped connection that is already back as one retry and continues on the same computer', async () => {
- for (const signals of [UNREACHABLE, { reason: 'remote_agent_closed', message: 'remote agent closed' }]) {
+ for (const signals of [UNREACHABLE, {
+ reason: 'remote_agent_lost',
+ message: '[REMOTE_AGENT_UNAVAILABLE] The computer running this agent is unreachable.',
+ }]) {
const h = onMini();
h.probe.mockResolvedValue('ok');
await h.service.onTurnError('s1', signals, 7, h.hooks);
@@ -1084,12 +1097,59 @@ describe('beforeSend', () => {
expect(loose.deps.readSessionRow).not.toHaveBeenCalled();
});
- it('keeps the binding when the move fails, so the send reports the original problem', async () => {
+ it('keeps the binding when the move fails for a reason that is not about the target, so the send reports it', async () => {
const h = harness({ offline: ['local'] });
h.bindings.set('s1', { providerId: 'anthropic', memberKey: 'local', at: 1 });
- h.deps.switchAgentLocation.mockRejectedValueOnce(new Error('unreachable'));
+ h.deps.switchAgentLocation.mockRejectedValueOnce(new Error('[SESSION_RUNNING] busy'));
await h.service.beforeSend('s1');
expect(h.bindings.get('s1')?.memberKey).toBe('local');
+ expect(h.deps.switchAgentLocation).toHaveBeenCalledTimes(1);
+ });
+
+ it('tries the next computer when the move fails because of the target (default: switch)', async () => {
+ const h = harness({ offline: ['local'] });
+ h.bindings.set('s1', { providerId: 'anthropic', memberKey: 'local', at: 1 });
+ h.deps.switchAgentLocation.mockRejectedValueOnce(new Error('spawn ENOENT'));
+ await h.service.beforeSend('s1');
+ expect(h.deps.switchAgentLocation).toHaveBeenCalledTimes(2);
+ expect(h.bindings.get('s1')?.memberKey).not.toBe('local');
+ });
+});
+
+describe('onTurnError — one decision for every failure (failurePolicy)', () => {
+ it('switches when the agent there ends mid-turn without a terminal event (default: switch), without cooling it', async () => {
+ const h = harness();
+ h.bindings.set('s1', { providerId: 'anthropic', memberKey: 'local', at: 1 });
+ await h.service.onTurnError('s1', {
+ message: 'Session event loop stopped unexpectedly without a terminal event',
+ reason: 'session_event_loop_crashed',
+ }, 7);
+ expect(h.deps.switchAgentLocation).toHaveBeenCalledTimes(1);
+ expect(h.deps.continueSession).toHaveBeenCalledWith('s1', 99, expect.objectContaining({
+ agentSwitch: expect.objectContaining({ cause: 'failed' }),
+ }));
+ // 不是那台账号的问题:不记进组的状态,新任务照常可以分给它。
+ expect(h.router.coolingUntil('anthropic', 'local')).toBeNull();
+ });
+
+ it('does not switch when this computer closed the running session itself', async () => {
+ const h = harness();
+ h.bindings.set('s1', { providerId: 'anthropic', memberKey: 'local', at: 1 });
+ await h.service.onTurnError('s1', {
+ message: 'Session closed before the current turn delivered a terminal event',
+ reason: 'session_event_loop_crashed',
+ }, 7);
+ expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();
+ expect(h.deps.fallback).toHaveBeenCalledTimes(1);
+ });
+
+ it('writes one decision line per failure with codes only', async () => {
+ const h = harness();
+ h.bindings.set('s1', { providerId: 'anthropic', memberKey: 'local', at: 1 });
+ await h.service.onTurnError('s1', { message: '[REMOTE_AGENT_BUSY] private details', errorStatus: 503 }, 7);
+ const decision = (h.deps.log.info.mock.calls as unknown[][]).find((call) => call[0] === 'provider group: failure decision');
+ expect(decision?.[1]).toMatchObject({ sessionId: 's1', phase: 'run', action: 'switch', cause: 'unavailable', code: 'REMOTE_AGENT_BUSY' });
+ expect(JSON.stringify(decision)).not.toContain('private details');
});
});
diff --git a/apps/desktop/src/main/provider-group/__tests__/switchCause.test.ts b/apps/desktop/src/main/provider-group/__tests__/switchCause.test.ts
deleted file mode 100644
index efdd448588..0000000000
--- a/apps/desktop/src/main/provider-group/__tests__/switchCause.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * 哪些失败会自动换电脑(provider-groups.md §6.1):白名单判定,认不出的一律不换。
- */
-import { describe, expect, it } from 'vitest';
-
-import { classifyProviderGroupSwitchCause, isProviderGroupConnectionLoss } from '../switchCause';
-
-describe('classifyProviderGroupSwitchCause', () => {
- it('switches on usage limits, quota and billing depletion', () => {
- expect(classifyProviderGroupSwitchCause({ sdkError: 'rate_limit' })).toBe('usage-limit');
- expect(classifyProviderGroupSwitchCause({ codexErrorInfo: 'usageLimitExceeded' })).toBe('usage-limit');
- expect(classifyProviderGroupSwitchCause({ sdkError: 'billing_error' })).toBe('usage-limit');
- });
-
- it('switches when the computer is unreachable or its agent stopped', () => {
- expect(classifyProviderGroupSwitchCause({ message: '[REMOTE_AGENT_UNAVAILABLE] remote agent request failed' })).toBe('unavailable');
- expect(classifyProviderGroupSwitchCause({ message: '[REMOTE_AGENT_SHARE_PAUSED] paused' })).toBe('unavailable');
- expect(classifyProviderGroupSwitchCause({ reason: 'remote_agent_closed' })).toBe('unavailable');
- });
-
- it('switches when that computer is signed out', () => {
- expect(classifyProviderGroupSwitchCause({ sdkError: 'authentication_failed' })).toBe('auth');
- expect(classifyProviderGroupSwitchCause({ errorStatus: 401 })).toBe('auth');
- expect(classifyProviderGroupSwitchCause({ message: 'Invalid API key provided' })).toBe('auth');
- });
-
- it('switches on overload only after the existing retries gave up', () => {
- expect(classifyProviderGroupSwitchCause({ errorStatus: 529 })).toBe('overload');
- });
-
- it('does not switch for failures any computer would hit', () => {
- expect(classifyProviderGroupSwitchCause({ sdkError: 'invalid_request', message: 'prompt is too long' })).toBeNull();
- expect(classifyProviderGroupSwitchCause({ message: 'Permission denied by user' })).toBeNull();
- expect(classifyProviderGroupSwitchCause({ reason: 'turn-failed', message: 'Tool execution failed' })).toBeNull();
- expect(classifyProviderGroupSwitchCause(undefined)).toBeNull();
- });
-});
-
-describe('isProviderGroupConnectionLoss', () => {
- it('recognises failures that only say the connection to that computer dropped', () => {
- expect(isProviderGroupConnectionLoss({ reason: 'remote_agent_closed' })).toBe(true);
- expect(isProviderGroupConnectionLoss({ message: '[REMOTE_AGENT_DEVICE_UNREACHABLE] unreachable' })).toBe(true);
- expect(isProviderGroupConnectionLoss({ message: '[REMOTE_AGENT_EXPIRED] session expired' })).toBe(true);
- expect(isProviderGroupConnectionLoss({ message: '[REMOTE_AGENT_NOT_FOUND] no such session' })).toBe(true);
- });
-
- it('does not treat a reachable computer that refuses or cannot run the task as a dropped connection', () => {
- expect(isProviderGroupConnectionLoss({ message: '[REMOTE_AGENT_UNAVAILABLE] the agent could not start' })).toBe(false);
- expect(isProviderGroupConnectionLoss({ message: '[REMOTE_AGENT_PROVIDER_NOT_ALLOWED] not allowed' })).toBe(false);
- expect(isProviderGroupConnectionLoss({ message: '[REMOTE_AGENT_SHARE_PAUSED] paused' })).toBe(false);
- expect(isProviderGroupConnectionLoss({ sdkError: 'rate_limit' })).toBe(false);
- expect(isProviderGroupConnectionLoss(undefined)).toBe(false);
- });
-});
diff --git a/apps/desktop/src/main/provider-group/failurePolicy.ts b/apps/desktop/src/main/provider-group/failurePolicy.ts
new file mode 100644
index 0000000000..c8841fdf43
--- /dev/null
+++ b/apps/desktop/src/main/provider-group/failurePolicy.ts
@@ -0,0 +1,316 @@
+/**
+ * 供应商组「这次失败怎么办」的唯一判定(docs/product-rules/provider-groups.md §6.1「怎么判断换不换」)。
+ *
+ * 所有路径都问这里:新任务启动失败、运行中的终态错误、发送前与换电脑途中换不过去、组所在电脑替分享的人中转时
+ * 组内电脑的失败、协同 Worker。路径只负责「拿到这次失败」与「执行决定」,不再各自判断换不换、等不等、记不记进组。
+ *
+ * 默认换(2026-10-11 用户确认:出问题就换,除非换到哪台都一样)。不换的只有:
+ * - 换到哪台都一样:上下文超出上限、请求本身无效、内容被拒、工具循环被拦、权限确认被拒、本机准入(模型停用等);
+ * - 不是那台电脑的问题:本机主动关掉了会话、用户已经接手、任务此刻的状态不允许(在运行、已删除等)。
+ *
+ * 换的时候再分两件事:
+ * - `connection`:要不要先等那台恢复(连不上时);
+ * - `cool`:要不要记进组的状态——只有那台账号的问题(用量上限、登录失效、服务繁忙)记进去,使用方自己连不过去、
+ * 那台 Agent 起不来等不记(2026-10-11 用户确认:组内状态以组所在电脑为准,使用方自己的问题不记进组)。
+ *
+ * 走到运行中这一步的已是终态错误:偶发的网络 / 过载抖动先由中断自愈在同一台重试,重试用尽才会到这里,
+ * 对应「同一台连续失败才算」。
+ */
+import { SESSION_CLOSED_MID_TURN_MESSAGE } from '@cindy/maker-core';
+
+import type { AutoResumeAgentSwitchCause } from '../../shared/agentInputQueue.js';
+import { isBillingDepletionError } from '../../shared/usageLimitRecovery.js';
+import { classifyTurnOverload, classifyTurnUsageLimit } from '../goal-host/usageLimit.js';
+import { isContextOverflowErrorData, isOversizedHistoryErrorData } from '../maker-ipc/contextOverflowRollover.js';
+import type { InterruptedTurnErrorSignals } from '../maker-ipc/interruptedTurnAutoResume.js';
+
+/**
+ * - usage-limit:用量上限、额度或余额用完、请求频率限制;
+ * - auth:那台电脑的供应商登录失效、被拒绝或被停用;
+ * - overload:供应商服务过载,现有重试用尽;
+ * - unavailable:那台电脑离线、不可达、关闭了远程调用、分享被暂停或删除、不提供这个模型;
+ * - failed:那台出了别的问题(Agent 起不来、意外退出、服务报错且重试用尽等)。
+ */
+export type ProviderGroupFailureCause = AutoResumeAgentSwitchCause;
+
+/**
+ * 失败发生在哪一步:
+ * - start:Agent 还没开始运行(打开任务、启动 Agent);
+ * - run:运行中的终态错误;
+ * - target:换电脑时换不过去(要换过去的那台的问题,或任务此刻的状态不允许)。
+ */
+export type ProviderGroupFailurePhase = 'start' | 'run' | 'target';
+
+/**
+ * 和那台的连接:
+ * - lost:只是连接断了(断线、对方 Cindy 重启后会话没了):先等它恢复;现读第一次就连得上也算恢复,留在原电脑继续;
+ * - check:可能连不上(离线、读取放弃、分享连不上):现读一次,确实连不上才等;连得上说明问题不在连接,直接换。
+ */
+export type ProviderGroupFailureConnection = 'lost' | 'check';
+
+export type ProviderGroupFailureDecision =
+ | { action: 'stay'; why: ProviderGroupStayReason }
+ | {
+ action: 'switch';
+ cause: ProviderGroupFailureCause;
+ /** null = 问题不在连接,不等,直接换。 */
+ connection: ProviderGroupFailureConnection | null;
+ /** 记进组的状态(冷却那台)。 */
+ cool: boolean;
+ };
+
+export type ProviderGroupStayReason =
+ | 'no-signal'
+ | 'context'
+ | 'invalid-request'
+ | 'policy'
+ | 'tool-loop'
+ | 'user'
+ | 'local'
+ | 'task-state'
+ | 'group-unavailable';
+
+/** 换电脑途中用户已接手:交接在改动之前停下(不是目标电脑的问题)。 */
+export const PROVIDER_GROUP_SUPERSEDED_ERROR = 'provider group: superseded by user action';
+
+/** 组里没有能接这个任务的电脑(本机任务的错误码,渲染端按 chat.remoteError 给文案)。 */
+export const PROVIDER_GROUP_UNAVAILABLE_ERROR =
+ '[REMOTE_AGENT_GROUP_UNAVAILABLE] no computer in the provider group can run this task right now';
+
+/** 远程 Agent 任务结束时本机给的 reason(remote-agent/controller/proxyHandle):lost = 连续拉不到那台,closed = 那台那边结束了。 */
+const REMOTE_AGENT_LOST_REASON = 'remote_agent_lost';
+const REMOTE_AGENT_CLOSED_REASON = 'remote_agent_closed';
+
+/** 只说明连接断了:那台本身没问题(断线、对方 Cindy 重启后会话没了)。 */
+const CONNECTION_LOST_CODES = new Set(['REMOTE_AGENT_DEVICE_UNREACHABLE', 'REMOTE_AGENT_EXPIRED', 'REMOTE_AGENT_NOT_FOUND']);
+/** 可能连不上:现读一次再说。 */
+const CONNECTION_CHECK_CODES = new Set([
+ 'REMOTE_AGENT_UNAVAILABLE',
+ 'REMOTE_AGENT_SHARE_UNAVAILABLE',
+ 'REMOTE_AGENT_BUSY',
+ 'DEVICE_LINK_DEVICE_OFFLINE',
+ 'DEVICE_OFFLINE',
+ 'NOT_CONNECTED',
+ 'PEER_RESET',
+ 'LINK_CLOSED',
+ 'LINK_NOT_OPEN',
+ 'TIMEOUT',
+ 'INVOKE_TIMEOUT',
+]);
+/** 那台本身现在不能接这个任务(不是连接的问题):直接换。 */
+const MEMBER_UNAVAILABLE_CODES = new Set([
+ 'REMOTE_AGENT_PROVIDER_NOT_ALLOWED',
+ 'REMOTE_AGENT_MODEL_UNAVAILABLE',
+ 'REMOTE_AGENT_SHARE_PAUSED',
+ 'REMOTE_AGENT_SHARE_REMOVED',
+ 'REMOTE_AGENT_ACCOUNT_CHANGED',
+ 'REMOTE_AGENT_PEER_TOO_OLD',
+ 'REMOTE_AGENT_UNSUPPORTED',
+ 'ACCESS_REVOKED',
+ 'REMOTE_DISABLED',
+ 'CHANNEL_NOT_ALLOWED',
+]);
+
+/** 本机记下的、换到哪台都一样或与那台无关的 reason(translator / Cindy 自己给出的稳定 key)。 */
+const STAY_REASONS: ReadonlyMap<string, ProviderGroupStayReason> = new Map([
+ ['context-overflow', 'context'],
+ ['codex_history_oversized', 'context'],
+ ['output-limit', 'context'],
+ ['tool_use_loop_detected', 'tool-loop'],
+ ['user-denied', 'user'],
+ ['user_rejected', 'user'],
+ ['user-revoked', 'user'],
+ ['cancelled-before-dispatch', 'user'],
+ ['turn_continuation_cancelled', 'user'],
+ ['permission-tighten-interrupt-failed', 'local'],
+ ['approved-skill-snapshot-failed', 'local'],
+ ['approved-repo-root-changed', 'local'],
+ ['approval-working-dir-mismatch', 'local'],
+ ['approval-resolver-unavailable', 'local'],
+ ['runtime-skills-missing', 'local'],
+]);
+
+/** Codex 结构化错误里换到哪台都一样的(上下文、请求无效、内容策略、本机沙箱)。 */
+const STAY_CODEX_ERRORS: ReadonlyMap<string, ProviderGroupStayReason> = new Map([
+ ['contextWindowExceeded', 'context'],
+ ['badRequest', 'invalid-request'],
+ ['cyberPolicy', 'policy'],
+ ['sandboxError', 'local'],
+]);
+
+/** 用户在权限确认里拒绝了、取消了:换到哪台都一样。 */
+const USER_DECISION_TEXT = /\b(?:permission denied by (?:the )?user|user (?:denied|rejected|declined) (?:the )?(?:permission|request|tool))\b/i;
+/** 工具本身执行出错、任务所在电脑上的工作目录不在了(文件和命令都在任务所在电脑,换 Agent 所在电脑也一样)。 */
+const TOOL_FAILURE_TEXT = /\btool (?:execution|call) failed\b|\bworking directory is missing\b/i;
+const AUTH_TEXT = /\b(?:authentication[_ ](?:failed|error)|invalid[_ -]?(?:x-)?api[_ -]?key|unauthorized|not (?:logged in|authenticated)|login (?:has )?expired|oauth token (?:has )?expired|token (?:has been )?revoked)\b/i;
+/** 开头的错误码,如 `[REMOTE_AGENT_UNAVAILABLE] …`、`[SESSION_RUNNING] …`。 */
+const LEADING_CODE = /^\s*\[([A-Z][A-Z0-9_]+)\]/;
+/** 消息里任意位置的远程错误码(包装过的错误可能把它放在中间)。 */
+const REMOTE_CODE = /\[(REMOTE_AGENT_[A-Z_]+)\]/;
+/** 任务此刻的状态不允许(在运行、已删除、参数不对等):Cindy 自己的错误码,与那台电脑无关。 */
+const TASK_STATE_CODES = new Set([
+ 'SESSION_RUNNING',
+ 'NOT_FOUND',
+ 'INVALID_PARAMS',
+ 'UNSUPPORTED_CAPABILITY',
+ 'PRECONDITION_FAILED',
+ 'SEND_CANCELLED_BEFORE_DISPATCH',
+ 'OWNER_CHANGED',
+ 'ACCOUNT_BOUNDARY',
+ 'WORKDIR_MISSING',
+]);
+
+/** 发送失败的展示文案带一层宿主错误码前缀(`LAZY_CREATE_FAILED: …`),判定看里面那层。 */
+const HOST_SEND_PREFIX = /^\s*[A-Z][A-Z0-9_]+:\s+/;
+
+function errorCodeOf(message: string): string | null {
+ const inner = message.replace(HOST_SEND_PREFIX, '');
+ return REMOTE_CODE.exec(inner)?.[1] ?? LEADING_CODE.exec(inner)?.[1] ?? null;
+}
+
+/** 把任意失败(终态错误的字段、启动或换电脑时抛出的错误)整理成判定用的字段。 */
+export function providerGroupFailureSignals(error: unknown): InterruptedTurnErrorSignals {
+ if (error instanceof Error) {
+ const code = (error as { code?: unknown }).code;
+ const message = error.message || (typeof code === 'string' ? `[${code}]` : '');
+ return { message };
+ }
+ if (typeof error === 'string') return { message: error };
+ if (error && typeof error === 'object') return error as InterruptedTurnErrorSignals;
+ return {};
+}
+
+const switchTo = (
+ cause: ProviderGroupFailureCause,
+ connection: ProviderGroupFailureConnection | null,
+): ProviderGroupFailureDecision => ({
+ action: 'switch',
+ cause,
+ connection,
+ cool: cause === 'usage-limit' || cause === 'auth' || cause === 'overload',
+});
+
+/**
+ * 这次失败怎么办。`phase` 只影响一件事:启动与换过去这两步里,Cindy 自己的错误码(任务在运行、已删除、模型停用等)
+ * 说明问题在本机这边,不换;运行中的终态错误不带这类错误码。
+ */
+export function decideProviderGroupFailure(
+ signals: InterruptedTurnErrorSignals | null | undefined,
+ phase: ProviderGroupFailurePhase,
+): ProviderGroupFailureDecision {
+ if (!signals) return { action: 'stay', why: 'no-signal' };
+ const message = typeof signals.message === 'string' ? signals.message : '';
+ const reason = typeof signals.reason === 'string' ? signals.reason : '';
+ if (!message && !reason && !signals.sdkError && signals.errorStatus === undefined
+ && !signals.usageLimit && !signals.codexErrorInfo) {
+ return { action: 'stay', why: 'no-signal' };
+ }
+
+ // 已落库的消息在打开任务时就没送出去:按启动阶段判定。
+ const effectivePhase = reason === PROVIDER_GROUP_AGENT_START_FAILED_REASON ? 'start' : phase;
+
+ // ── 不是那台电脑的问题 ──
+ if (message === PROVIDER_GROUP_SUPERSEDED_ERROR) return { action: 'stay', why: 'user' };
+ // 本机主动关掉了还在运行的会话(本机的操作,不是那台的问题)。
+ if (message.startsWith(SESSION_CLOSED_MID_TURN_MESSAGE)) return { action: 'stay', why: 'local' };
+ const code = errorCodeOf(message);
+ if (code === 'REMOTE_AGENT_GROUP_UNAVAILABLE') return { action: 'stay', why: 'group-unavailable' };
+ if (effectivePhase !== 'run' && code && TASK_STATE_CODES.has(code)) return { action: 'stay', why: 'task-state' };
+
+ // ── 换到哪台都一样 ──
+ const stayReason = STAY_REASONS.get(reason);
+ if (stayReason) return { action: 'stay', why: stayReason };
+ if (signals.toolLoop) return { action: 'stay', why: 'tool-loop' };
+ if (USER_DECISION_TEXT.test(message)) return { action: 'stay', why: 'user' };
+ if (TOOL_FAILURE_TEXT.test(message)) return { action: 'stay', why: 'local' };
+ if (isContextOverflowErrorData(signals) || isOversizedHistoryErrorData(signals)) return { action: 'stay', why: 'context' };
+ const codexStay = signals.codexErrorInfo ? STAY_CODEX_ERRORS.get(signals.codexErrorInfo) : undefined;
+ if (codexStay) return { action: 'stay', why: codexStay };
+
+ // ── 那台账号的问题:换,并记进组的状态 ──
+ // 过载先于用量上限判(529 / serverOverloaded 也会被用量判定认作限流):过载只短冷却,用量上限按重置时刻冷却。
+ if (classifyTurnOverload(signals)) return switchTo('overload', null);
+ if (isBillingDepletionError(signals) || classifyTurnUsageLimit(signals)) return switchTo('usage-limit', null);
+ if (
+ signals.sdkError === 'authentication_failed'
+ || signals.codexErrorInfo === 'unauthorized'
+ || signals.errorStatus === 401
+ || AUTH_TEXT.test(message)
+ ) {
+ return switchTo('auth', null);
+ }
+
+ // 请求本身无效:换到哪台都一样(放在账号问题之后:429 / 401 有时也带 invalid_request 的外壳)。
+ if (
+ signals.sdkError === 'invalid_request'
+ || signals.errorStatus === 400
+ || signals.errorStatus === 413
+ || signals.errorStatus === 422
+ ) {
+ return { action: 'stay', why: 'invalid-request' };
+ }
+
+ // ── 那台连不上或不能用 ──
+ if (code && CONNECTION_LOST_CODES.has(code)) return switchTo('unavailable', 'lost');
+ if (code && MEMBER_UNAVAILABLE_CODES.has(code)) return switchTo('unavailable', null);
+ // 连续拉不到那台(remote-agent/controller/proxyHandle):只说明连接断了。
+ if (reason === REMOTE_AGENT_LOST_REASON) return switchTo('unavailable', 'lost');
+ if ((code && CONNECTION_CHECK_CODES.has(code)) || reason === REMOTE_AGENT_CLOSED_REASON) return switchTo('unavailable', 'check');
+
+ // ── 其余:那台出了别的问题,换 ──
+ return switchTo('failed', null);
+}
+
+/**
+ * 已落库的用户消息确定没有送到 Agent 的失败(打开任务时 Agent 没能启动、发送时链路已断而请求根本没发出去):
+ * 当作这一轮还没有产出就失败,交给与运行中失败同一条换电脑流程(换过去后重发原消息)。送达不明的(请求超时等)
+ * 返回 null:可能已经在跑,重发会让同一条消息执行两次(§6.1)。
+ */
+export const PROVIDER_GROUP_AGENT_START_FAILED_REASON = 'provider_group_agent_start_failed';
+
+const UNDELIVERED_HOST_SEND_CODES = new Set(['LAZY_CREATE_FAILED', 'REHYDRATE_FAILED']);
+/** 设备互联在请求发出之前就拒绝的(没有连接、对方离线):确定没送达。超时、断在半路的不算。 */
+const UNDELIVERED_LINK_CODES = new Set(['DEVICE_OFFLINE', 'NOT_CONNECTED', 'LINK_NOT_OPEN', 'DEVICE_LINK_DEVICE_OFFLINE']);
+
+export function providerGroupUndeliveredSendSignals(failure: unknown): InterruptedTurnErrorSignals | null {
+ if (!failure || typeof failure !== 'object') return null;
+ const record = failure as { kind?: unknown; code?: unknown; message?: unknown };
+ const message = typeof record.message === 'string' ? record.message : '';
+ if (record.kind === 'host-send' && typeof record.code === 'string' && UNDELIVERED_HOST_SEND_CODES.has(record.code)) {
+ return { message, reason: PROVIDER_GROUP_AGENT_START_FAILED_REASON };
+ }
+ if (failure instanceof Error && typeof record.code === 'string' && UNDELIVERED_LINK_CODES.has(record.code)) {
+ return { message, reason: PROVIDER_GROUP_AGENT_START_FAILED_REASON };
+ }
+ return null;
+}
+
+/** 运行中、启动阶段换下一台用的简写:不换返回 null。 */
+export function providerGroupSwitchCause(
+ signals: InterruptedTurnErrorSignals | null | undefined,
+ phase: ProviderGroupFailurePhase,
+): ProviderGroupFailureCause | null {
+ const decision = decideProviderGroupFailure(signals, phase);
+ return decision.action === 'switch' ? decision.cause : null;
+}
+
+/**
+ * 决定日志用的摘要:只带错误码与结构化字段,不带错误原文(原文可能含对话内容)。
+ */
+export function describeProviderGroupFailure(
+ signals: InterruptedTurnErrorSignals | null | undefined,
+ decision: ProviderGroupFailureDecision,
+): Record<string, unknown> {
+ const message = typeof signals?.message === 'string' ? signals.message : '';
+ return {
+ action: decision.action,
+ ...(decision.action === 'switch'
+ ? { cause: decision.cause, ...(decision.connection ? { connection: decision.connection } : {}), cool: decision.cool }
+ : { why: decision.why }),
+ ...(errorCodeOf(message) ? { code: errorCodeOf(message) } : {}),
+ ...(signals?.reason ? { reason: signals.reason } : {}),
+ ...(signals?.sdkError ? { sdkError: signals.sdkError } : {}),
+ ...(signals?.errorStatus !== undefined ? { errorStatus: signals.errorStatus } : {}),
+ ...(signals?.codexErrorInfo ? { codexErrorInfo: signals.codexErrorInfo } : {}),
+ };
+}
diff --git a/apps/desktop/src/main/provider-group/guestRelay.ts b/apps/desktop/src/main/provider-group/guestRelay.ts
index 24adc940e4..abb216335a 100644
--- a/apps/desktop/src/main/provider-group/guestRelay.ts
+++ b/apps/desktop/src/main/provider-group/guestRelay.ts
@@ -15,8 +15,8 @@ import type { GroupRelayLoad, GroupRelayMember, RemoteAgentGroupRelayDeps } from
import type { RemoteAgentInvoke, RemoteAgentPoller } from '../remote-agent/controller/runClient.js';
import { PROVIDER_GROUP_MAX_REMOTE_COOLDOWN_MS } from './remoteHandler.js';
import { PROVIDER_GROUP_DEFAULT_COOLDOWN_MS, PROVIDER_GROUP_FAILURE_COOLDOWN_MS } from './router.js';
+import { decideProviderGroupFailure, describeProviderGroupFailure, providerGroupFailureSignals } from './failurePolicy.js';
import type { ProviderGroupOwnerScope } from './runtime.js';
-import { classifyProviderGroupSwitchCause } from './switchCause.js';
/** 同账号电脑不支持接受受邀者任务时,多久内不再试它。 */
export const PROVIDER_GROUP_GUEST_INCAPABLE_MS = 10 * 60_000;
@@ -29,7 +29,7 @@ export interface ProviderGroupGuestRelayDeps {
/** 组内电脑报错里的用量重置时刻(unix ms);不提供时用量上限一律按默认时长冷却。 */
readResetAt?(failure: RelayRunFailure): number | null;
now(): number;
- log: { warn(message: string, meta?: Record<string, unknown>): void };
+ log: { info?(message: string, meta?: Record<string, unknown>): void; warn(message: string, meta?: Record<string, unknown>): void };
}
function errorText(error: unknown): string {
@@ -93,38 +93,58 @@ export function createProviderGroupGuestRelay(deps: ProviderGroupGuestRelayDeps)
noteStartFailure(providerId, member: GroupRelayMember, error) {
const message = errorText(error);
- // 那台太旧、还不能按受邀者隔离:不冷却它(本机自己的任务照常分过去),只是一阵子不再给它受邀者的任务。
- if (/REMOTE_AGENT_PEER_TOO_OLD|REMOTE_AGENT_UNSUPPORTED/.test(message)) {
+ // 同账号那台太旧、还不能按受邀者隔离:不冷却它(本机自己的任务照常分过去),只是一阵子不再给它受邀者的任务。
+ // 分享来的电脑本来就把本机当受邀者隔离,不会因为这个原因接不下(真接不下时按下面的判定换下一台)。
+ if (member.sameAccount && /REMOTE_AGENT_PEER_TOO_OLD|REMOTE_AGENT_UNSUPPORTED/.test(message)) {
incapable.set(member.agentDeviceId, deps.now() + PROVIDER_GROUP_GUEST_INCAPABLE_MS);
- return;
+ return true;
}
- const cause = classifyProviderGroupSwitchCause({ message });
- // 连不上、起不来不记进组的状态:下次选电脑时现读那台(状态以本机读到的为准,2026-10-11)。
- if (!cause || cause === 'unavailable') return;
- const now = deps.now();
- deps.scope().router.markCooling(
- providerId,
- member.memberKey,
- now + (cause === 'usage-limit' ? PROVIDER_GROUP_DEFAULT_COOLDOWN_MS : PROVIDER_GROUP_FAILURE_COOLDOWN_MS),
- );
+ // 与本机自己的任务同一个判定(failurePolicy):换到哪台都一样的不换,那台账号的问题记进组的状态;
+ // 连不上、起不来不记进组的状态,下次选电脑时现读那台(状态以本机读到的为准,2026-10-11)。
+ const signals = providerGroupFailureSignals(error);
+ const decision = decideProviderGroupFailure(signals, 'start');
+ deps.log.info?.('provider group: failure decision', {
+ phase: 'start',
+ relay: true,
+ member: member.memberKey,
+ ...describeProviderGroupFailure(signals, decision),
+ });
+ if (decision.action !== 'switch') return false;
+ if (decision.cool) {
+ const now = deps.now();
+ deps.scope().router.markCooling(
+ providerId,
+ member.memberKey,
+ now + (decision.cause === 'usage-limit' ? PROVIDER_GROUP_DEFAULT_COOLDOWN_MS : PROVIDER_GROUP_FAILURE_COOLDOWN_MS),
+ );
+ }
+ return true;
},
noteRunFailure(providerId, member: GroupRelayMember, failure) {
// 没有组,或那台已被移出组:已经在它上面的任务成为普通的远程 Agent 任务,不再自动换电脑(§9 #4)。
const config = deps.readGroup(providerId);
if (!config?.members.some((m) => m.key === member.memberKey)) return false;
- const cause = classifyProviderGroupSwitchCause(failure);
- if (!cause) return false;
- const now = deps.now();
- // 组内电脑报来的重置时刻按那台的口径取(readResetAt 不采用不带时区的钟点),最多信 8 天。
- const resetAt = cause === 'usage-limit' ? deps.readResetAt?.(failure) ?? null : null;
- const until = cause === 'usage-limit'
- ? (resetAt !== null && resetAt > now
- ? Math.min(resetAt, now + PROVIDER_GROUP_MAX_REMOTE_COOLDOWN_MS)
- : now + PROVIDER_GROUP_DEFAULT_COOLDOWN_MS)
- : now + PROVIDER_GROUP_FAILURE_COOLDOWN_MS;
- // 只记那台账号的问题(用量上限、登录失效、服务繁忙);连不上不记,照常换一台。
- if (cause !== 'unavailable') deps.scope().router.markCooling(providerId, member.memberKey, until);
+ const decision = decideProviderGroupFailure(failure, 'run');
+ deps.log.info?.('provider group: failure decision', {
+ phase: 'run',
+ relay: true,
+ member: member.memberKey,
+ ...describeProviderGroupFailure(failure, decision),
+ });
+ if (decision.action !== 'switch') return false;
+ // 只记那台账号的问题(用量上限、登录失效、服务繁忙);连不上、起不来不记,照常换一台。
+ if (decision.cool) {
+ const now = deps.now();
+ // 组内电脑报来的重置时刻按那台的口径取(readResetAt 不采用不带时区的钟点),最多信 8 天。
+ const resetAt = decision.cause === 'usage-limit' ? deps.readResetAt?.(failure) ?? null : null;
+ const until = decision.cause === 'usage-limit'
+ ? (resetAt !== null && resetAt > now
+ ? Math.min(resetAt, now + PROVIDER_GROUP_MAX_REMOTE_COOLDOWN_MS)
+ : now + PROVIDER_GROUP_DEFAULT_COOLDOWN_MS)
+ : now + PROVIDER_GROUP_FAILURE_COOLDOWN_MS;
+ deps.scope().router.markCooling(providerId, member.memberKey, until);
+ }
// 冷却照常(之后的新任务避开它);组设置里关掉了自动换电脑时不发凭证,受邀者照现有方式看到错误(§6.1)。
return config.autoSwitch;
},
diff --git a/apps/desktop/src/main/provider-group/router.ts b/apps/desktop/src/main/provider-group/router.ts
index f53c8ad16a..cc5580202e 100644
--- a/apps/desktop/src/main/provider-group/router.ts
+++ b/apps/desktop/src/main/provider-group/router.ts
@@ -69,8 +69,16 @@ export interface ProviderGroupPickInput {
* 占用,不会全落到同一台。
*/
onPicked?(memberKey: string): void;
+ /**
+ * 本机任务:选中的同一步给这个任务记上临时占用(PROVIDER_GROUP_LOCAL_PROVISIONAL_MS),直到它开始运行一轮
+ * (之后按运行中的绑定计)。本机同时开的几个任务不会读到同一份负载、全落到同一台。
+ */
+ reserveFor?: string;
}
+/** 本机任务选中后、开始运行一轮之前的临时占用时长(与同账号电脑选中后的临时占用相同)。 */
+export const PROVIDER_GROUP_LOCAL_PROVISIONAL_MS = 30_000;
+
export type ProviderGroupPickResult =
| { kind: 'none' }
| { kind: 'member'; member: ProviderGroupMember; label: string; resolved: ResolvedProviderGroupMember[] }
@@ -124,6 +132,8 @@ export function createProviderGroupRouter(deps: ProviderGroupRouterDeps): Provid
const lastPicked = new Map<string, string>();
const tried = new Map<string, { at: number; keys: Set<string> }>();
+ /** 本机任务刚选中、还没开始运行一轮的临时占用:任务 id → 那台。 */
+ const provisional = new Map<string, { providerId: string; memberKey: string; until: number }>();
function currentTried(sessionId: string): Set<string> | null {
const entry = tried.get(sessionId);
@@ -153,6 +163,15 @@ export function createProviderGroupRouter(deps: ProviderGroupRouterDeps): Provid
count++;
}
}
+ const now = deps.now();
+ for (const [sessionId, entry] of provisional) {
+ // 已经开始运行一轮的按上面的绑定计,不重复计;过期的放掉(没能启动等)。
+ if (entry.until <= now || deps.isTurnRunning(sessionId)) {
+ provisional.delete(sessionId);
+ continue;
+ }
+ if (entry.providerId === providerId && entry.memberKey === memberKey) count++;
+ }
return count + (deps.externalRunning?.(providerId, memberKey) ?? 0);
}
@@ -203,6 +222,13 @@ export function createProviderGroupRouter(deps: ProviderGroupRouterDeps): Provid
});
if (!key) return { kind: 'unavailable', resolved };
lastPicked.set(input.providerId, key);
+ if (input.reserveFor) {
+ provisional.set(input.reserveFor, {
+ providerId: input.providerId,
+ memberKey: key,
+ until: deps.now() + PROVIDER_GROUP_LOCAL_PROVISIONAL_MS,
+ });
+ }
input.onPicked?.(key);
const chosen = resolved.find((r) => r.member.key === key)!;
return { kind: 'member', member: chosen.member, label: chosen.label, resolved };
diff --git a/apps/desktop/src/main/provider-group/service.ts b/apps/desktop/src/main/provider-group/service.ts
index 489bae7a16..e10c35f7ec 100644
--- a/apps/desktop/src/main/provider-group/service.ts
+++ b/apps/desktop/src/main/provider-group/service.ts
@@ -49,17 +49,16 @@ import {
type ProviderGroupRouter,
} from './router.js';
import {
- classifyProviderGroupSwitchCause,
- isProviderGroupConnectionLoss,
- type ProviderGroupSwitchCause,
-} from './switchCause.js';
+ decideProviderGroupFailure,
+ describeProviderGroupFailure,
+ PROVIDER_GROUP_UNAVAILABLE_ERROR,
+ providerGroupFailureSignals,
+ type ProviderGroupFailureCause,
+ type ProviderGroupFailureDecision,
+ type ProviderGroupFailurePhase,
+} from './failurePolicy.js';
-/** 换电脑途中用户已接手:交接在改动之前停下(不是目标电脑的问题)。 */
-export const PROVIDER_GROUP_SUPERSEDED_ERROR = 'provider group: superseded by user action';
-
-/** 组里没有能接这个任务的电脑(本机任务的错误码,渲染端按 chat.remoteError 给文案)。 */
-export const PROVIDER_GROUP_UNAVAILABLE_ERROR =
- '[REMOTE_AGENT_GROUP_UNAVAILABLE] no computer in the provider group can run this task right now';
+export { PROVIDER_GROUP_SUPERSEDED_ERROR, PROVIDER_GROUP_UNAVAILABLE_ERROR } from './failurePolicy.js';
export interface ProviderGroupSessionRow {
agentKind: AgentKind;
@@ -322,12 +321,16 @@ function errorText(error: unknown): string {
return error instanceof Error ? error.message : typeof error === 'string' ? error : '';
}
-function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | null> {
+/**
+ * 等 `promise` 最多 `ms`:超时或失败返回 undefined(= 读不到)。不能用 null:组设置读到了「没有这个组」就是 null,
+ * 组所在电脑慢一点不能被当成组已删除、把任务移出组。
+ */
+function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {
let timer: ReturnType<typeof setTimeout> | undefined;
return Promise.race([
- promise.catch(() => null),
- new Promise<null>((resolve) => {
- timer = setTimeout(() => resolve(null), ms);
+ promise.catch(() => undefined),
+ new Promise<undefined>((resolve) => {
+ timer = setTimeout(() => resolve(undefined), ms);
}),
]).finally(() => clearTimeout(timer));
}
@@ -351,7 +354,8 @@ interface GroupSource {
model: string;
exclude: ReadonlySet<string>;
}): Promise<SourcePick>;
- cool(providerId: string, memberKey: string, cause: ProviderGroupSwitchCause, resetAt: number | null): void;
+ /** 记进组的状态(只在判定说要记时调用:那台账号的问题)。 */
+ cool(providerId: string, memberKey: string, cause: ProviderGroupFailureCause, resetAt: number | null): void;
/** 组的状态里这台现在冷却中(组所在电脑记着它账号的问题)。 */
isKnownDown(providerId: string, memberKey: string): Promise<boolean>;
/** 发送前:这台现在该不该换掉;null = 读不到,照常发送。 */
@@ -548,8 +552,8 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
}
/** 换过去失败只是因为这台电脑连不上那台(那台本身可能没问题):值得等它恢复。 */
- function isUnreachableTarget(error: unknown): boolean {
- return isProviderGroupConnectionLoss({ message: errorText(error) });
+ function isUnreachableTarget(decision: ProviderGroupFailureDecision): boolean {
+ return decision.action === 'switch' && decision.connection !== null;
}
/**
@@ -568,7 +572,16 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
}
if (!route.agentDeviceId || !deps.directory.offlineForMs) return false;
const offlineFor = await withTimeout(deps.directory.offlineForMs(route.agentDeviceId), PROVIDER_GROUP_BEFORE_SEND_TIMEOUT_MS);
- return offlineFor !== null && offlineFor >= PROVIDER_GROUP_RECENT_DROP_MS;
+ return typeof offlineFor === 'number' && offlineFor >= PROVIDER_GROUP_RECENT_DROP_MS;
+ }
+
+ /**
+ * 运行过的任务这次打开能不能在启动阶段直接换到组里下一台:要重新打开(没有开着的会话),而且没有原生会话要续接。
+ * 有原生会话时它在原来那台上,换过去必须带交接,不能拿着原来那台的会话 id 去别处打开(那边认不出,会悄悄开一个
+ * 没有上下文的新会话)。
+ */
+ function mayReopenElsewhere(sessionId: string, row: ProviderGroupSessionRow): boolean {
+ return deps.hasLiveSession?.(sessionId) === false && !row.sdkSessionId;
}
/** 这一轮结束(放弃换电脑、用户接手):下一轮重新从头试、重新等。 */
@@ -592,21 +605,51 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
};
}
- function coolUntil(cause: ProviderGroupSwitchCause, resetAt: number | null): number {
+ function coolUntil(cause: ProviderGroupFailureCause, resetAt: number | null): number {
const now = deps.now();
return cause === 'usage-limit'
? (resetAt !== null && resetAt > now ? resetAt : now + PROVIDER_GROUP_DEFAULT_COOLDOWN_MS)
: now + PROVIDER_GROUP_FAILURE_COOLDOWN_MS;
}
+ /** 只有那台账号的问题记进组的状态(failurePolicy 的 `cool`);调用方已按判定过滤,这里再挡一次。 */
+ function isAccountCause(cause: ProviderGroupFailureCause): cause is ProviderGroupRemoteCoolCause {
+ return cause === 'usage-limit' || cause === 'auth' || cause === 'overload';
+ }
+
+ /** 判定 + 决定日志(只带错误码与结构化字段,不带错误原文)。 */
+ function decide(
+ sessionId: string,
+ signals: InterruptedTurnErrorSignals,
+ phase: ProviderGroupFailurePhase,
+ member?: string,
+ ): ProviderGroupFailureDecision {
+ const decision = decideProviderGroupFailure(signals, phase);
+ deps.log.info('provider group: failure decision', {
+ sessionId,
+ phase,
+ ...(member ? { member } : {}),
+ ...describeProviderGroupFailure(signals, decision),
+ });
+ return decision;
+ }
+
const localSource: GroupSource = {
ownerDeviceId: null,
async readGroup(providerId) {
return deps.readGroup(providerId);
},
- async pick({ providerId, agentKind, model, exclude }) {
- // 带着这一轮试过的来选:试过不行说明状态可能旧了,现读最新状态再选。
- const pick = await router.pick({ providerId, agentKind, model, exclude, ...(exclude.size > 0 ? { fresh: true } : {}) });
+ async pick({ sessionId, providerId, agentKind, model, exclude }) {
+ // 带着这一轮试过的来选:试过不行说明状态可能旧了,现读最新状态再选。选中的同一步记上临时占用:本机同时
+ // 开的几个任务不会读到同一份负载、全落到同一台(与同账号电脑、分享的人问组所在电脑同一做法)。
+ const pick = await router.pick({
+ providerId,
+ agentKind,
+ model,
+ exclude,
+ reserveFor: sessionId,
+ ...(exclude.size > 0 ? { fresh: true } : {}),
+ });
if (pick.kind !== 'member') return { kind: pick.kind };
return {
kind: 'member',
@@ -619,9 +662,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
};
},
cool(providerId, memberKey, cause, resetAt) {
- // 连不上只在这一轮避开,不把本机的连接故障扩散成后续全局冷却;
- // 其它原因(额度、登录、过载)仍按组的冷却策略处理。
- if (cause === 'unavailable') return;
+ if (!isAccountCause(cause)) return;
router.markCooling(providerId, memberKey, coolUntil(cause, resetAt));
},
async isKnownDown(providerId, memberKey) {
@@ -682,8 +723,8 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
return { kind: 'member', member, label: pick.label, labelOf };
},
cool(providerId, memberKey, cause, resetAt) {
- // 连不上只由发现它的这台电脑自己避开(这一轮已试过),不替全组判断:可能只是这台连不过去。
- if (cause === 'unavailable') return;
+ // 连不上、起不来只由发现它的这台电脑自己避开(这一轮已试过),不替全组判断:可能只是这台连不过去。
+ if (!isAccountCause(cause)) return;
void remote.cool(ownerDeviceId, { providerId, memberKey, cause, resetAt }).catch((error) => {
deps.log.warn('provider group: reporting a computer to cool down failed', { error: errorText(error) });
});
@@ -945,13 +986,14 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
token: number,
hooks: ProviderGroupTurnErrorHooks | undefined,
): Promise<boolean> {
- const cause = classifyProviderGroupSwitchCause(signals);
- if (!cause) return false;
+ const decision = decide(sessionId, signals, 'run');
+ if (decision.action !== 'switch') return false;
+ const { cause } = decision;
if (!deps.readBinding(sessionId) && !(await adoptOnFailure(sessionId))) {
return guestFailover(sessionId, signals, token, cause, hooks);
}
const bound = await loadBound(sessionId);
- if (!bound) return cause === 'unavailable' ? reconnectWithoutGroup(sessionId, signals, token, hooks) : false;
+ if (!bound) return decision.connection ? reconnectWithoutGroup(sessionId, signals, token, decision, hooks) : false;
const { binding, source, config } = bound;
if (!config) {
await releaseDeletedGroup(sessionId, groupOf(source, binding.providerId));
@@ -969,14 +1011,14 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
const boundRow = { ...row, model: row.model };
await withSwitchRun(sessionId, signals, token, lease, hooks, async (isCurrent, handBack) => {
// 连不上先等那台恢复:恢复了留在原电脑继续这一轮(不交接),等不到再换。
- if (cause === 'unavailable') {
+ if (decision.connection) {
let waited = false;
const route = source.routeOf(current, row.providerId);
const outcome = await awaitReturn(sessionId, route, current.key, isCurrent, (attempt) => {
waited = true;
hooks?.reconnecting?.(attempt, PROVIDER_GROUP_RECONNECT_MAX_ATTEMPTS);
}, {
- connectionLost: isProviderGroupConnectionLoss(signals),
+ connectionLost: decision.connection === 'lost',
knownDown: () => knownDown(source, binding.providerId, current.key, route),
});
if (outcome === 'stopped') return;
@@ -987,7 +1029,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
if (waited) hooks?.switching?.();
}
await switchUntilSettled({
- sessionId, signals, cause, binding, source, config, row: boundRow, current, lease, isCurrent, handBack, hooks,
+ sessionId, signals, decision, binding, source, config, row: boundRow, current, lease, isCurrent, handBack, hooks,
});
});
return true;
@@ -1026,6 +1068,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
sessionId: string,
signals: InterruptedTurnErrorSignals,
token: number,
+ decision: ProviderGroupFailureDecision & { action: 'switch' },
hooks: ProviderGroupTurnErrorHooks | undefined,
): Promise<boolean> {
const binding = deps.readBinding(sessionId);
@@ -1040,7 +1083,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
const outcome = await awaitReturn(sessionId, route, binding.memberKey, isCurrent, (attempt) => {
hooks?.reconnecting?.(attempt, PROVIDER_GROUP_RECONNECT_MAX_ATTEMPTS);
}, {
- connectionLost: isProviderGroupConnectionLoss(signals),
+ connectionLost: decision.connection === 'lost',
knownDown: () => knownDown(null, binding.providerId, binding.memberKey, route),
});
if (outcome === 'stopped') return;
@@ -1110,7 +1153,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
sessionId: string,
signals: InterruptedTurnErrorSignals,
token: number,
- cause: ProviderGroupSwitchCause,
+ cause: ProviderGroupFailureCause,
hooks: ProviderGroupTurnErrorHooks | undefined,
): Promise<boolean> {
const guestSwitch = deps.guestSwitch;
@@ -1161,7 +1204,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
async function switchUntilSettled(input: {
sessionId: string;
signals: InterruptedTurnErrorSignals;
- cause: ProviderGroupSwitchCause;
+ decision: ProviderGroupFailureDecision & { action: 'switch' };
binding: ProviderGroupBinding;
source: GroupSource;
config: ProviderGroupConfig;
@@ -1172,8 +1215,9 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
handBack: () => void;
hooks: ProviderGroupTurnErrorHooks | undefined;
}): Promise<void> {
- const { sessionId, signals, cause, binding, source, config, row, current, lease, isCurrent, handBack, hooks } = input;
- source.cool(binding.providerId, current.key, cause, deps.readResetAt(signals));
+ const { sessionId, signals, decision, binding, source, config, row, current, lease, isCurrent, handBack, hooks } = input;
+ const { cause } = decision;
+ if (decision.cool) source.cool(binding.providerId, current.key, cause, deps.readResetAt(signals));
source.invalidate(current);
const tried = router.markTried(sessionId, current.key);
// 这条消息发出前刚换不过去的电脑不再重复去试、重复去等。
@@ -1226,10 +1270,10 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
}, { isCurrent });
} catch (error) {
await restoreBindingAfterFailedSwitch(sessionId, source, binding.providerId, config);
- // 只有目标电脑本身的问题(连不上、分享暂停、Agent 起不来等)才记到它头上并换下一台;任务在运行、
+ // 与失败本身同一个判定:目标电脑的问题(连不上、分享暂停、Agent 起不来等)换下一台;任务在运行、
// 已删除、用户已接手等与目标无关的失败直接结束,不冷却任何电脑。
- const targetCause = classifyProviderGroupSwitchCause({ message: errorText(error) });
- if (!targetCause || !isCurrent()) {
+ const target = decide(sessionId, providerGroupFailureSignals(error), 'target', pick.member.key);
+ if (target.action !== 'switch' || !isCurrent()) {
deps.log.info('provider group: switching computer stopped', { sessionId, error: errorText(error) });
handBack();
return;
@@ -1240,8 +1284,8 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
error: errorText(error),
});
router.markTried(sessionId, pick.member.key);
- source.cool(binding.providerId, pick.member.key, targetCause, null);
- skipped.failed(pick.member, isUnreachableTarget(error));
+ if (target.cool) source.cool(binding.providerId, pick.member.key, target.cause, null);
+ skipped.failed(pick.member, isUnreachableTarget(target));
continue;
}
deps.log.info('provider group: switched computer', { sessionId, cause, to: pick.member.key });
@@ -1274,8 +1318,9 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
const source = remoteSource(ownerDeviceId);
const groupProviderId = row.providerId;
// 只给从没运行过的任务按策略选电脑;已经运行过的任务先纳入组并留在原电脑。
- // 但如果原生会话已经不存在(例如远程电脑刚断线、旧句柄已被清理),这次打开仍然是
- // 启动阶段:保留原绑定并返回启动上下文,让 bootstrap 失败时能自动试组内下一台。
+ // 已经运行过、但这次要重新打开、而且没有要续接的原生会话(回退或清空后):仍是启动阶段,返回启动上下文,
+ // 启动失败时直接试组内下一台(反正都是全新会话)。有原生会话要续接的不在启动阶段换:会话在原来那台上,
+ // 换过去要带交接,交给发送前检查与失败后的自动换电脑(都走交接)。
// 问不到组所在电脑时照常启动,出错时再补。
const hasRun = Boolean(row.sdkSessionId || (await deps.hasAssistantHistory(sessionId)));
// 已经明确解除过这个组的老任务不再询问组所在电脑,也不自动纳回。
@@ -1284,7 +1329,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
? await withTimeout(source.readGroup(groupProviderId), PROVIDER_GROUP_ADOPT_TIMEOUT_MS)
: await source.readGroup(groupProviderId).catch(() => undefined);
if (config === undefined) {
- if (!hasRun || deps.hasLiveSession?.(sessionId) !== false) return null;
+ if (!hasRun || !mayReopenElsewhere(sessionId, row)) return null;
// §6:启动时问不到组所在电脑照常启动;若这次启动失败,带着原路由在失败路径再读组,
// 让老任务仍能纳入组并尝试下一台。此时不能写绑定,成功启动就继续作为普通远程任务。
const placeholder = pendingMember(providerGroupMemberKey(null, row.providerId), row.providerId, null);
@@ -1307,9 +1352,9 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
const current = currentKey ? config.members.find((member) => member.key === currentKey) : undefined;
if (!current) return null;
if (!(await adopt(sessionId, source, groupProviderId, current.key))) return null;
- // Live session 仍在时,运行中错误交给 failover;只有需要重新打开时才让启动
- // 失败路径直接换下一台,避免把正常运行中的老任务提前迁走。
- if (deps.hasLiveSession?.(sessionId) !== false) return null;
+ // Live session 仍在时,运行中错误交给 failover;只有需要重新打开、又没有原生会话要续接时才让启动
+ // 失败路径直接换下一台,避免把正常运行中的老任务提前迁走、把要续接的会话不带交接地开到别处。
+ if (!mayReopenElsewhere(sessionId, row)) return null;
const route = source.routeOf(current, null);
return {
sessionId,
@@ -1363,7 +1408,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
.catch(() => undefined);
const hasRun = Boolean(row.sdkSessionId || (await deps.hasAssistantHistory(sessionId)));
if (config === undefined) {
- if (deps.hasLiveSession?.(sessionId) !== false) return null;
+ if (!mayReopenElsewhere(sessionId, row)) return null;
const member = pendingMember(
existingBinding.memberKey,
row.providerId ?? existingBinding.providerId,
@@ -1388,10 +1433,10 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
return null;
});
// 从没运行过的任务(上次全部没能启动、重启应用后再打开等):带上启动上下文,这次启动失败时仍能
- // 换组里下一台。已经运行过的任务在原来那台上有原生会话,换电脑要走交接;原生会话已经
- // 不在时则仍属于启动阶段,失败后直接换下一台。
+ // 换组里下一台。已经运行过的任务在原来那台上有原生会话,换电脑要走交接(发送前检查、失败后的自动换电脑);
+ // 没有原生会话要续接(回退或清空后)时仍属于启动阶段,失败后直接换下一台。
if (!current) return null;
- if (hasRun && deps.hasLiveSession?.(sessionId) !== false) return null;
+ if (hasRun && !mayReopenElsewhere(sessionId, row)) return null;
const localProviderId = current.kind === 'local' && !source.ownerDeviceId ? row.providerId : binding.providerId;
return {
sessionId,
@@ -1411,13 +1456,13 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
const config = groupProviderId ? deps.readGroup(groupProviderId) : null;
if (!groupProviderId || !config) return null;
// 已经运行过的任务(建组前就在用、回退或清空等清掉了原生会话)不按策略挪走:留在本机并纳入组。
- // live session 仍在时之后的运行中错误走 failover;会话已经被清掉时,这次启动失败要能直接换下一台。
+ // live session 仍在时之后的运行中错误走 failover;没有原生会话要续接时,这次启动失败要能直接换下一台。
const hasRun = Boolean(row.sdkSessionId || (await deps.hasAssistantHistory(sessionId)));
if (hasRun) {
const local = config.members.find((member) => member.kind === 'local');
if (!local) return null;
if (!(await adopt(sessionId, localSource, groupProviderId, local.key))) return null;
- if (deps.hasLiveSession?.(sessionId) !== false) return null;
+ if (!mayReopenElsewhere(sessionId, row)) return null;
return {
sessionId,
groupProviderId,
@@ -1454,10 +1499,10 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
},
async nextAfterStartFailure(context, error) {
- const cause = classifyProviderGroupSwitchCause({ message: errorText(error) })
- ?? (/not authenticated|login/i.test(errorText(error)) ? 'auth' : null);
+ const decision = decide(context.sessionId, providerGroupFailureSignals(error), 'start', context.member.key);
const source = sourceFor(context.groupDeviceId);
- if (!cause || !source) return null;
+ if (decision.action !== 'switch' || !source) return null;
+ const { cause } = decision;
const config = await source.readGroup(context.groupProviderId).catch(() => undefined);
// 启动阶段同样:组所在电脑确认组已删除时立即解除绑定,读不到不动。
if (config === null) {
@@ -1467,7 +1512,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
return null;
}
if (!config?.autoSwitch) return null;
- source.cool(context.groupProviderId, context.member.key, cause, null);
+ if (decision.cool) source.cool(context.groupProviderId, context.member.key, cause, null);
source.invalidate(context.member);
const tried = router.markTried(context.sessionId, context.member.key);
const pick = await source.pick({
@@ -1536,7 +1581,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
},
mayHandleTurnError(sessionId, signals) {
- if (!classifyProviderGroupSwitchCause(signals)) return false;
+ if (decideProviderGroupFailure(signals, 'run').action !== 'switch') return false;
const binding = deps.readBinding(sessionId);
if (!binding) return deps.guestSwitch?.hasOffer(sessionId) === true;
if (binding.groupDeviceId) return deps.remote !== undefined;
@@ -1659,9 +1704,9 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
return;
} catch (error) {
await restoreBindingAfterFailedSwitch(sessionId, source, binding.providerId, config);
- // 只有目标电脑本身的问题才换下一台;与目标无关的失败(任务在运行、已删除等)照常发到原电脑。
- const targetCause = classifyProviderGroupSwitchCause({ message: errorText(error) });
- if (!targetCause || !isCurrent()) {
+ // 与失败本身同一个判定:目标电脑的问题换下一台;与目标无关的失败(任务在运行、已删除等)照常发到原电脑。
+ const target = decide(sessionId, providerGroupFailureSignals(error), 'target', pick.member.key);
+ if (target.action !== 'switch' || !isCurrent()) {
deps.log.warn('provider group: moving a task before sending failed', { sessionId, error: errorText(error) });
if (failedTargets.length > 0 && isCurrent()) preSendFailed.set(sessionId, { keys: failedTargets, at: deps.now() });
return;
@@ -1673,8 +1718,8 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
});
if (!failedTargets.includes(pick.member.key)) failedTargets.push(pick.member.key);
router.markTried(sessionId, pick.member.key);
- source.cool(binding.providerId, pick.member.key, targetCause, null);
- skipped.failed(pick.member, isUnreachableTarget(error));
+ if (target.cool) source.cool(binding.providerId, pick.member.key, target.cause, null);
+ skipped.failed(pick.member, isUnreachableTarget(target));
}
}
} finally {
diff --git a/apps/desktop/src/main/provider-group/switchCause.ts b/apps/desktop/src/main/provider-group/switchCause.ts
deleted file mode 100644
index 5290322d66..0000000000
--- a/apps/desktop/src/main/provider-group/switchCause.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * 哪些失败会触发自动换电脑(docs/product-rules/provider-groups.md §6.1):问题出在那台电脑或它的
- * 账号上才换;用户停止、权限被拒、上下文超限、请求无效、内容被拒、工具出错等换到哪台都一样,
- * 不换。这里只做白名单判定,认不出的一律不换。
- *
- * 走到这里的已是终态错误:偶发的网络 / 过载抖动先由中断自愈按现有规则重试,重试用尽才会到这里,
- * 对应「同一台连续失败才算」。
- */
-import { classifyTurnOverload, classifyTurnUsageLimit } from '../goal-host/usageLimit.js';
-import type { InterruptedTurnErrorSignals } from '../maker-ipc/interruptedTurnAutoResume.js';
-import type { AutoResumeAgentSwitchCause } from '../../shared/agentInputQueue.js';
-import { isBillingDepletionError } from '../../shared/usageLimitRecovery.js';
-
-/**
- * - usage-limit:用量上限、额度或余额用完、请求频率限制;
- * - auth:那台电脑的供应商登录失效、被拒绝或被停用;
- * - unavailable:那台电脑离线、不可达、关闭了远程调用、分享被暂停或删除,或 Agent 没能启动;
- * - overload:供应商服务过载,现有重试用尽。
- */
-export type ProviderGroupSwitchCause = AutoResumeAgentSwitchCause;
-
-const REMOTE_UNAVAILABLE = /\[REMOTE_AGENT_(?:UNAVAILABLE|PROVIDER_NOT_ALLOWED|DEVICE_UNREACHABLE|MODEL_UNAVAILABLE|SHARE_PAUSED|SHARE_REMOVED|SHARE_UNAVAILABLE|ACCOUNT_CHANGED|EXPIRED|PEER_TOO_OLD|BUSY|NOT_FOUND)\]/;
-const AUTH_TEXT = /\b(?:authentication[_ ](?:failed|error)|invalid[_ -]?(?:x-)?api[_ -]?key|unauthorized|not logged in|login (?:has )?expired|oauth token (?:has )?expired|token (?:has been )?revoked)\b/i;
-
-export function classifyProviderGroupSwitchCause(
- signals: InterruptedTurnErrorSignals | null | undefined,
-): ProviderGroupSwitchCause | null {
- if (!signals) return null;
- const message = typeof signals.message === 'string' ? signals.message : '';
- if (signals.reason === 'remote_agent_closed' || REMOTE_UNAVAILABLE.test(message)) return 'unavailable';
- if (classifyTurnOverload(signals)) return 'overload';
- if (isBillingDepletionError(signals) || classifyTurnUsageLimit(signals)) return 'usage-limit';
- if (
- signals.sdkError === 'authentication_failed'
- || signals.codexErrorInfo === 'unauthorized'
- || signals.errorStatus === 401
- || AUTH_TEXT.test(message)
- ) {
- return 'auth';
- }
- return null;
-}
-
-/** 只说明连接断了的远程错误(那台本身没问题,断线、远程 Cindy 重启后会话没了)。 */
-const REMOTE_CONNECTION_LOST = /\[REMOTE_AGENT_(?:DEVICE_UNREACHABLE|EXPIRED|NOT_FOUND)\]/;
-
-/**
- * 这次失败只是和那台的连接断了:等它恢复时,现读第一次就已连得上,也算一次重试、留在原电脑继续(断线刚好已恢复),
- * 不急着换电脑。其余「连不上」(远程调用被关、分享暂停、Agent 没能启动等)现读连得上说明问题不在连接,直接换。
- */
-export function isProviderGroupConnectionLoss(signals: InterruptedTurnErrorSignals | null | undefined): boolean {
- if (!signals) return false;
- const message = typeof signals.message === 'string' ? signals.message : '';
- return signals.reason === 'remote_agent_closed' || REMOTE_CONNECTION_LOST.test(message);
-}
diff --git a/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts b/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts
index 38f7e65db3..5c73643cec 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts
@@ -184,7 +184,8 @@ function setup(options: {
}
return { invoke: poller.invoke, poller };
}),
- noteStartFailure: vi.fn(),
+ // 与本机任务同一个判定:默认换下一台(guestRelay 的判定见 provider-group/__tests__/guestRelay.test.ts)。
+ noteStartFailure: vi.fn(() => true),
noteRunFailure: vi.fn((_providerId: string, _member: GroupRelayMember, failure: RelayRunFailure) =>
options.switchWorthy?.(failure) ?? true),
trackRun: vi.fn(() => ({ setRunning: vi.fn(), release: vi.fn() })),
diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
index a4434b957d..5536766382 100644
--- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
+++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
@@ -453,7 +453,9 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand
data: {
message: message ?? `[REMOTE_AGENT_UNAVAILABLE] The agent on the other computer stopped (${reason}).`,
isTerminal: true,
- reason: 'remote_agent_closed',
+ // 拉不到那台(连续 2 分钟)只说明连接断了,那台本身可能没事:供应商组先等它恢复、恢复了留在原电脑继续;
+ // 其余(对方出错收尾、撤权、流不可信等)是那台那边的问题(provider-group/failurePolicy)。
+ reason: reason === 'unreachable' ? 'remote_agent_lost' : 'remote_agent_closed',
},
source: started.agentKind,
});
diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.ts
index c3871e6d63..353a43f2f7 100644
--- a/apps/desktop/src/main/remote-agent/host/runHost.ts
+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts
@@ -265,8 +265,11 @@ export interface RemoteAgentGroupRelayDeps {
}): Promise<GroupRelayPlan | null>;
/** 经设备互联连某台组内电脑的远程 Agent 通道(与本机作为控制端共用拉取器)。 */
connect(agentDeviceId: string): { invoke: RemoteAgentInvoke; poller: RemoteAgentPoller };
- /** 那台在启动阶段没能接下任务(连不上、登录失效等):按组的口径冷却。 */
- noteStartFailure(providerId: string, member: GroupRelayMember, error: unknown): void;
+ /**
+ * 那台在启动阶段没能接下任务:按组的口径判定(provider-group/failurePolicy),那台账号的问题冷却它。返回 true =
+ * 可以换下一台;false = 换到哪台都一样(模型停用、请求无效等),照原来的错误报给受邀者。
+ */
+ noteStartFailure(providerId: string, member: GroupRelayMember, error: unknown): boolean;
/**
* 那台上的任务运行中失败(终态错误,或一轮进行中任务意外结束):问题出在那台电脑本身时按组的口径冷却它,组设置
* 允许自动换电脑时返回 true(可以换一台);用户停止、上下文超限等换到哪台都一样的失败返回 false。
@@ -1399,7 +1402,8 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
for (const connId of wsOpened) append(run, { t: 'ws', connId, kind: 'close' });
if (run.closing || !options.fresh) break;
tried.add(current.memberKey);
- relayDeps.noteStartFailure(groupProviderId, current, error);
+ // 与本机自己的任务同一个判定:换到哪台都一样的失败不再换,照原来的错误报给受邀者。
+ if (!relayDeps.noteStartFailure(groupProviderId, current, error)) break;
deps.log?.warn('remote agent: provider group computer did not take the shared task; trying the next one', {
runId: run.id,
member: current.memberKey,
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 3fce8732b7..c1ca46b2d3 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -10634,7 +10634,8 @@
"usage-limit": "{{from}} hit its usage limit; continued on {{to}}",
"auth": "{{from}} is signed out; continued on {{to}}",
"unavailable": "Couldn’t reach {{from}}; continued on {{to}}",
- "overload": "{{from}} was overloaded; continued on {{to}}"
+ "overload": "{{from}} was overloaded; continued on {{to}}",
+ "failed": "{{from}} ran into a problem; continued on {{to}}"
},
"agentReconnect": {
"named": "Reconnected to {{computer}}; continued there",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 7494b9456c..8e4f342471 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -10610,7 +10610,8 @@
"usage-limit": "{{from}} が使用量の上限に達したため、{{to}} で続行しました",
"auth": "{{from}} のログインが切れたため、{{to}} で続行しました",
"unavailable": "{{from}} に接続できないため、{{to}} で続行しました",
- "overload": "{{from}} のサービスが混雑しているため、{{to}} で続行しました"
+ "overload": "{{from}} のサービスが混雑しているため、{{to}} で続行しました",
+ "failed": "{{from}} で問題が起きたため、{{to}} で続行しました"
},
"agentReconnect": {
"named": "{{computer}} に再接続し、続行しました",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 3fabb7b459..98ff9bc032 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -10610,7 +10610,8 @@
"usage-limit": "{{from}}이(가) 사용량 한도에 도달해 {{to}}에서 이어서 진행했습니다",
"auth": "{{from}}의 로그인이 만료되어 {{to}}에서 이어서 진행했습니다",
"unavailable": "{{from}}에 연결할 수 없어 {{to}}에서 이어서 진행했습니다",
- "overload": "{{from}}의 서비스가 혼잡해 {{to}}에서 이어서 진행했습니다"
+ "overload": "{{from}}의 서비스가 혼잡해 {{to}}에서 이어서 진행했습니다",
+ "failed": "{{from}}에서 문제가 생겨 {{to}}에서 이어서 진행했습니다"
},
"agentReconnect": {
"named": "{{computer}}에 다시 연결되어 이어서 진행했습니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 945c3a84f8..34b5b6107b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -10610,7 +10610,8 @@
"usage-limit": "{{from}} 撞到用量上限,已换到 {{to}} 继续",
"auth": "{{from}} 登录已失效,已换到 {{to}} 继续",
"unavailable": "{{from}} 连不上,已换到 {{to}} 继续",
- "overload": "{{from}} 的服务繁忙,已换到 {{to}} 继续"
+ "overload": "{{from}} 的服务繁忙,已换到 {{to}} 继续",
+ "failed": "{{from}} 出了问题,已换到 {{to}} 继续"
},
"agentReconnect": {
"named": "已重新连上 {{computer}},继续运行",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 42e64733cf..9cd35f37ec 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -10609,7 +10609,8 @@
"usage-limit": "{{from}} 達到用量上限,已換到 {{to}} 繼續",
"auth": "{{from}} 登入已失效,已換到 {{to}} 繼續",
"unavailable": "{{from}} 連不上,已換到 {{to}} 繼續",
- "overload": "{{from}} 的服務繁忙,已換到 {{to}} 繼續"
+ "overload": "{{from}} 的服務繁忙,已換到 {{to}} 繼續",
+ "failed": "{{from}} 出了問題,已換到 {{to}} 繼續"
},
"agentReconnect": {
"named": "已重新連上 {{computer}},繼續執行",
diff --git a/apps/desktop/src/renderer/lib/autoResumePresentation.ts b/apps/desktop/src/renderer/lib/autoResumePresentation.ts
index 07521947d3..a858efa4c6 100644
--- a/apps/desktop/src/renderer/lib/autoResumePresentation.ts
+++ b/apps/desktop/src/renderer/lib/autoResumePresentation.ts
@@ -60,7 +60,7 @@ export function readAutoResumeInfo(data?: Record<string, unknown>): AutoResumeCa
};
}
-const AGENT_SWITCH_CAUSES: readonly AutoResumeAgentSwitchCause[] = ['usage-limit', 'auth', 'unavailable', 'overload'];
+const AGENT_SWITCH_CAUSES: readonly AutoResumeAgentSwitchCause[] = ['usage-limit', 'auth', 'unavailable', 'overload', 'failed'];
function readAgentSwitch(value: unknown): AutoResumeAgentSwitch | null {
if (!value || typeof value !== 'object') return null;
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index 868e5cbac1..54b1152a81 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -232,7 +232,11 @@ export interface AutoResumeGroupSwitch {
cause: AutoResumeAgentSwitchCause;
}
-export type AutoResumeAgentSwitchCause = 'usage-limit' | 'auth' | 'unavailable' | 'overload';
+/**
+ * 换电脑的原因(docs/product-rules/provider-groups.md §6.1)。`failed` = 那台出了别的问题(Agent 意外退出、服务报错
+ * 用尽重试等)。旧端不认识的原因整条忽略,活动行退回「用量已恢复,已自动继续」。
+ */
+export type AutoResumeAgentSwitchCause = 'usage-limit' | 'auth' | 'unavailable' | 'overload' | 'failed';
export interface AutoResumeAgentSwitch {
/** 原电脑的显示名。 */
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index 0b66fbb3b0..dac685aa0d 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -271,7 +271,8 @@
"usage-limit": "{{from}} hit its usage limit; continued on {{to}}",
"auth": "{{from}} is signed out; continued on {{to}}",
"unavailable": "Couldn’t reach {{from}}; continued on {{to}}",
- "overload": "{{from}} was overloaded; continued on {{to}}"
+ "overload": "{{from}} was overloaded; continued on {{to}}",
+ "failed": "{{from}} ran into a problem; continued on {{to}}"
},
"agentReconnect": {
"named": "Reconnected to {{computer}}; continued there",
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index 82cd310872..88f7f67623 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -271,7 +271,8 @@
"usage-limit": "{{from}} が使用量の上限に達したため、{{to}} で続行しました",
"auth": "{{from}} のログインが切れたため、{{to}} で続行しました",
"unavailable": "{{from}} に接続できないため、{{to}} で続行しました",
- "overload": "{{from}} のサービスが混雑しているため、{{to}} で続行しました"
+ "overload": "{{from}} のサービスが混雑しているため、{{to}} で続行しました",
+ "failed": "{{from}} で問題が起きたため、{{to}} で続行しました"
},
"agentReconnect": {
"named": "{{computer}} に再接続し、続行しました",
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index 2e4e1ab189..12fd36bbb2 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -271,7 +271,8 @@
"usage-limit": "{{from}}이(가) 사용량 한도에 도달해 {{to}}에서 이어서 진행했습니다",
"auth": "{{from}}의 로그인이 만료되어 {{to}}에서 이어서 진행했습니다",
"unavailable": "{{from}}에 연결할 수 없어 {{to}}에서 이어서 진행했습니다",
- "overload": "{{from}}의 서비스가 혼잡해 {{to}}에서 이어서 진행했습니다"
+ "overload": "{{from}}의 서비스가 혼잡해 {{to}}에서 이어서 진행했습니다",
+ "failed": "{{from}}에서 문제가 생겨 {{to}}에서 이어서 진행했습니다"
},
"agentReconnect": {
"named": "{{computer}}에 다시 연결되어 이어서 진행했습니다",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index 7d7df206f8..6fffe31ab2 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -271,7 +271,8 @@
"usage-limit": "{{from}} 撞到用量上限,已换到 {{to}} 继续",
"auth": "{{from}} 登录已失效,已换到 {{to}} 继续",
"unavailable": "{{from}} 连不上,已换到 {{to}} 继续",
- "overload": "{{from}} 的服务繁忙,已换到 {{to}} 继续"
+ "overload": "{{from}} 的服务繁忙,已换到 {{to}} 继续",
+ "failed": "{{from}} 出了问题,已换到 {{to}} 继续"
},
"agentReconnect": {
"named": "已重新连上 {{computer}},继续运行",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.json
index 1ed97cb059..9ea524765c 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@ -271,7 +271,8 @@
"usage-limit": "{{from}} 達到用量上限,已換到 {{to}} 繼續",
"auth": "{{from}} 登入已失效,已換到 {{to}} 繼續",
"unavailable": "{{from}} 連不上,已換到 {{to}} 繼續",
- "overload": "{{from}} 的服務繁忙,已換到 {{to}} 繼續"
+ "overload": "{{from}} 的服務繁忙,已換到 {{to}} 繼續",
+ "failed": "{{from}} 出了問題,已換到 {{to}} 繼續"
},
"agentReconnect": {
"named": "已重新連上 {{computer}},繼續執行",
diff --git a/apps/mobile/src/session/autoResumePresentation.ts b/apps/mobile/src/session/autoResumePresentation.ts
index bcf35aeba3..00ef0e45ba 100644
--- a/apps/mobile/src/session/autoResumePresentation.ts
+++ b/apps/mobile/src/session/autoResumePresentation.ts
@@ -3,7 +3,7 @@ import type { ContinuationInFlightProjectionCapability } from '@/session/types';
/** 对齐桌面 USAGE_LIMIT_RESET_AUTO_RESUME_REASON(apps/desktop/src/shared/agentInputQueue.ts)。 */
const USAGE_LIMIT_RESET_REASON = 'usage-limit-reset';
-export type MobileAutoResumeAgentSwitchCause = 'usage-limit' | 'auth' | 'unavailable' | 'overload';
+export type MobileAutoResumeAgentSwitchCause = 'usage-limit' | 'auth' | 'unavailable' | 'overload' | 'failed';
/** 对齐桌面 AutoResumeAgentSwitch:供应商组自动换电脑后继续。 */
export interface MobileAutoResumeAgentSwitch {
@@ -12,7 +12,7 @@ export interface MobileAutoResumeAgentSwitch {
cause: MobileAutoResumeAgentSwitchCause;
}
-const AGENT_SWITCH_CAUSES: readonly MobileAutoResumeAgentSwitchCause[] = ['usage-limit', 'auth', 'unavailable', 'overload'];
+const AGENT_SWITCH_CAUSES: readonly MobileAutoResumeAgentSwitchCause[] = ['usage-limit', 'auth', 'unavailable', 'overload', 'failed'];
function readAgentSwitch(value: unknown): MobileAutoResumeAgentSwitch | undefined {
if (!value || typeof value !== 'object') return undefined;
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 1e170e6c8d..2bd3f25819 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -137,6 +137,12 @@ export const MANUAL_ABORT_RECOVERY_GRACE_MS = 15_000;
/** Shared confirmation budget for provider interrupt ACK and send acceptance. */
const GRACEFUL_STOP_CONFIRMATION_TIMEOUT_MS = 5_000;
+/**
+ * Terminal error message when this host closes a session while its turn is still running.
+ * Hosts match it to tell a local close apart from the agent dying on its own.
+ */
+export const SESSION_CLOSED_MID_TURN_MESSAGE = 'Session closed before the current turn delivered a terminal event';
+
/**
* turn 零事件看门狗的计时分片长度。额度按片累加,片尾核对真实经过时间,
* 借此把系统挂起(合盖睡眠)的那段排除掉 —— 见 armTurnStallSlice。
@@ -1490,7 +1496,7 @@ export class Session {
// close() fences late provider events before entering here. Settle the
// owned product turn ourselves before listeners and its claim are lost.
// Never retry: tools may already have performed external side effects.
- this.settleUnfinishedTurn('Session closed before the current turn delivered a terminal event');
+ this.settleUnfinishedTurn(SESSION_CLOSED_MID_TURN_MESSAGE);
this.clearTurnStallWatchdog();
this.clearTerminalErrorDrain();
this.cancelSendReservation(this.sendReservation);