Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(provider-group): 修复远程限额失败漏切换与重复续跑 (#7459)
Lizif3d9068c9b6d
diff --git a/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts b/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.tsindex 941173b501..eb18cf3acd 100644--- a/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts@@ -47,7 +47,7 @@ interface Started {/** 这台上是否正在运行一轮(写进状态)。 */running: boolean;/** 这台上的 Agent 事件流意外结束(进程退出等)。 */- end(): void;+ end(error?: Error): void;}function fakeAgentHost(name: string, started: Started[], options: {@@ -62,6 +62,7 @@ function fakeAgentHost(name: string, started: Started[], options: {failStart?: boolean;/** 这台的 Agent 一启动就结束。 */endImmediately?: boolean;+ onSend?: (record: Started) => void | Promise<void>;/** 转分享的同意(本机是分享者)。 */reshare?: Parameters<typeof createRemoteAgentHost>[0]['reshare'];resolveProvider?: NonNullable<Parameters<typeof createRemoteAgentHost>[0]['providerAccess']>['resolve'];@@ -78,6 +79,7 @@ function fakeAgentHost(name: string, started: Started[], options: {const queue: AgentEvent[] = [];let wake: (() => void) | null = null;let ended = false;+ let endError: Error | undefined;const record: Started = {input,sends: [],@@ -87,8 +89,9 @@ function fakeAgentHost(name: string, started: Started[], options: {wake?.();wake = null;},- end() {+ end(error) {ended = true;+ endError = error;wake?.();wake = null;},@@ -100,6 +103,7 @@ function fakeAgentHost(name: string, started: Started[], options: {model: input.options.model,async send(message) {record.sends.push(message);+ await options.onSend?.(record);},async steer() {},async abort() {},@@ -110,6 +114,7 @@ function fakeAgentHost(name: string, started: Started[], options: {next: async () => {if (options.endImmediately) return { value: undefined as unknown as AgentEvent, done: true };while (queue.length === 0 && !ended) await new Promise<void>((resolve) => { wake = resolve; });+ if (queue.length === 0 && endError) throw endError;if (queue.length === 0) return { value: undefined as unknown as AgentEvent, done: true };return { value: queue.shift()!, done: false };},@@ -205,11 +210,12 @@ function setup(options: {miniCapable?: boolean;switchWorthy?: (failure: RelayRunFailure) => boolean;/** mini 这台的 Agent 表现。 */- mini?: { failStart?: boolean; endImmediately?: boolean;+ mini?: { failStart?: boolean; endImmediately?: boolean; onSend?: (record: Started) => void | Promise<void>;isAgentAvailable?: Parameters<typeof createRemoteAgentHost>[0]['isAgentAvailable'] };memberBinder?: Parameters<typeof createRemoteAgentHost>[0]['bindGuestProviderRoute'];/** 组所在电脑本机的 Agent 表现(组选中本机这一台时)。 */- owner?: { failStart?: boolean; prepareImageEvent?: Parameters<typeof createRemoteAgentHost>[0]['prepareImageEvent'];+ owner?: { failStart?: boolean; onSend?: (record: Started) => void | Promise<void>;+ prepareImageEvent?: Parameters<typeof createRemoteAgentHost>[0]['prepareImageEvent'];modelAccess?: Partial<NonNullable<Parameters<typeof createRemoteAgentHost>[0]['providerAccess']>>;isAgentAvailable?: Parameters<typeof createRemoteAgentHost>[0]['isAgentAvailable'] };/** 截住组所在电脑发给组内电脑的请求(模拟回包丢失、应答慢)。 */@@ -880,6 +886,220 @@ describe('provider group relay: starting, load and cleanup', () => {});describe('provider group "switch to another computer" for shared users', () => {+ // provider-groups.md §6.1, unit: exercise the real host, relay and run client.+ // Existing cases emitted a terminal event independently of send(), missing the+ // quota RPC rejection that could overtake the switch offer and lose recovery.+ // Cover local/relayed execution and both native-event orders; one failure must+ // produce one offer/error before rejecting send, then one send on the new host.+ it.each(['local', 'member'] as const)('settles quota replies through one switch offer on %s', async placement => {+ for (const eventFirst of [true, false]) {+ const onSend = (record: Started) => {+ if (eventFirst) record.emit(USAGE_LIMIT_ERROR);+ throw new Error('You have hit your usage limit');+ };+ const env = setup({+ plans: [+ placement === 'local' ? { kind: 'local' } : { kind: 'member', ...MEMBER_MINI },+ { kind: 'member', ...MEMBER_STUDIO },+ { kind: 'member', ...MEMBER_STUDIO },+ ],+ ...(placement === 'local' ? { owner: { onSend } } : { mini: { onSend } }),+ });+ const first = await openAsGuest(env, GUEST_A, openPayload(`${SESSION}-${eventFirst}`, { acceptsGroupSwitch: true }));+ const record = placement === 'local' ? env.ownerStarted[0] : env.memberStarted.mini[0];+ try {+ await expect(first.client.call('send', [{ type: 'user', content: 'finish the task' }, { throwOnStartFailure: true }]))+ .rejects.toThrow('usage limit');+ const token = switchTokenIn(first.stream);+ expect(token).toBeDefined();+ const errors = () => first.stream.filter(item => item.t === 'event' && item.event.type === 'error');+ expect(errors()).toHaveLength(1);+ expect(first.stream.findIndex(item => item.t === 'state' && item.state.providerGroupSwitch === token))+ .toBeLessThan(first.stream.findIndex(item => item.t === 'event' && item.event.type === 'error'));++ // A late or repeated SDK terminal must not offer another switch or resume.+ record.emit(USAGE_LIMIT_ERROR);+ record.emit({ type: 'status', source: 'claude-code', data: { status: 'quota-tail-flushed' } });+ await waitFor(() => first.stream.some(item => item.t === 'event'+ && (item.event.data as { status?: string })?.status === 'quota-tail-flushed'));+ expect(errors()).toHaveLength(1);+ expect(first.stream.filter(item => item.t === 'state' && item.state.providerGroupSwitch)).toHaveLength(1);+ expect(env.relay.noteRunFailure).toHaveBeenCalledTimes(1);+ await first.client.close('close', 'navigation');++ const next = await openAsGuest(env, GUEST_A, openPayload(`${SESSION}-${eventFirst}`, {+ acceptsGroupSwitch: true, groupSwitchToken: token,+ }));+ try {+ await next.client.call('send', [{ type: 'user', content: 'finish the task' }, {}]);+ expect(env.memberStarted.studio[0].sends).toHaveLength(1);+ expect(record.sends).toHaveLength(1);+ } finally {+ await next.client.close('close', 'navigation');+ }+ } finally {+ await first.client.close('close', 'navigation');+ for (const host of [env.owner, ...Object.values(env.members)]) { await host.abortAll(); host.dispose(); }+ }+ }+ });++ it('does not turn an uncertain send timeout into a quota event or switch offer', async () => {+ const env = setup({ mini: { onSend: () => { throw new Error('request timed out'); } } });+ const first = await openAsGuest(env, GUEST_A, openPayload(SESSION, { acceptsGroupSwitch: true }));+ try {+ await expect(first.client.call('send', [{ type: 'user', content: 'finish the task' }, {}]))+ .rejects.toThrow('request timed out');+ expect(switchTokenIn(first.stream)).toBeUndefined();+ expect(first.stream.some(item => item.t === 'event' && item.event.type === 'error')).toBe(false);+ expect(env.relay.noteRunFailure).not.toHaveBeenCalled();+ expect(env.memberStarted.mini[0].sends).toHaveLength(1);+ } finally {+ await first.client.close('close', 'navigation');+ for (const host of [env.owner, ...Object.values(env.members)]) { await host.abortAll(); host.dispose(); }+ }+ });++ it('ignores an obsolete quota rejection after the user stops and sends again', async () => {+ let entered!: () => void;+ const sending = new Promise<void>(resolve => { entered = resolve; });+ let release!: () => void;+ const response = new Promise<void>(resolve => { release = resolve; });+ const env = setup({ mini: { onSend: async record => {+ if (record.sends.length > 1) return;+ entered();+ await response;+ throw new Error('You have hit your usage limit');+ } } });+ const first = await openAsGuest(env, GUEST_A, openPayload(SESSION, { acceptsGroupSwitch: true }));+ const obsolete = first.client.call('send', [{ type: 'user', content: 'old attempt' }, {}]).catch(error => error);+ try {+ await sending;+ await first.client.call('abort', []);+ await first.client.call('send', [{ type: 'user', content: 'new attempt' }, { groupNewRound: true }]);+ release();+ expect(await obsolete).toMatchObject({ message: expect.stringContaining('usage limit') });+ expect(env.memberStarted.mini[0].sends).toHaveLength(2);+ expect(switchTokenIn(first.stream)).toBeUndefined();+ expect(first.stream.some(item => item.t === 'event' && item.event.type === 'error')).toBe(false);+ expect(env.relay.noteRunFailure).not.toHaveBeenCalled();+ } finally {+ release();+ await first.client.close('close', 'navigation');+ for (const host of [env.owner, ...Object.values(env.members)]) { await host.abortAll(); host.dispose(); }+ }+ });++ // A delayed group decision used to let the RPC rejection overtake its terminal+ // event. Keep it pending while another controller completes a send on the same+ // member: the failure's scope is one run, without resetting any shared link.+ it('holds a quota rejection behind its switch decision without blocking another controller', async () => {+ const env = setup({+ plans: [{ kind: 'member', ...MEMBER_MINI }, { kind: 'member', ...MEMBER_MINI }],+ mini: { onSend: record => {+ if (record !== failing) return;+ record.emit(USAGE_LIMIT_ERROR);+ throw new Error('You have hit your usage limit');+ } },+ });+ const first = await openAsGuest(env, GUEST_A, openPayload(SESSION, { acceptsGroupSwitch: true }));+ const failing = env.memberStarted.mini[0];+ const other = await openAsGuest(env, GUEST_B, openPayload(SESSION, { acceptsGroupSwitch: true }));+ let release!: () => void;+ const decision = new Promise<void>(resolve => { release = resolve; });+ env.relay.plan.mockImplementationOnce(async () => {+ await decision;+ return { kind: 'member', ...MEMBER_STUDIO };+ });+ let rejected = false;+ const send = first.client.call('send', [{ type: 'user', content: 'finish the task' }, {}]).catch(error => {+ rejected = true;+ return error;+ });+ try {+ await waitFor(() => env.relay.plan.mock.calls.length === 3);+ await other.client.call('send', [{ type: 'user', content: 'unrelated task' }, {}]);+ expect(env.memberStarted.mini[1].sends).toHaveLength(1);+ expect(other.isClosed()).toBe(false);+ expect(switchTokenIn(other.stream)).toBeUndefined();+ expect(rejected).toBe(false);+ release();+ expect(await send).toMatchObject({ message: expect.stringContaining('usage limit') });+ expect(switchTokenIn(first.stream)).toBeDefined();+ expect(first.stream.filter(item => item.t === 'event' && item.event.type === 'error')).toHaveLength(1);+ } finally {+ release();+ await Promise.all([first.client.close('close', 'navigation'), other.client.close('close', 'navigation')]);+ for (const host of [env.owner, ...Object.values(env.members)]) { await host.abortAll(); host.dispose(); }+ }+ });++ // Review r4386499053: an SDK stream/legacy member can end after rejecting send,+ // before the next-member decision completes. Only passive shutdown must wait;+ // otherwise closing invalidates the pending offer before it reaches the guest.+ it.each([+ ['local', 'end'], ['local', 'error'], ['local', 'explicit'],+ ['member', 'end'], ['member', 'error'], ['member', 'explicit'],+ ] as const)('settles pending quota recovery on %s shutdown (%s)', async (placement, endKind) => {+ let rejectQuota = placement === 'member';+ const env = setup({+ plans: [+ placement === 'local' ? { kind: 'local' } : { kind: 'member', ...MEMBER_MINI },+ { kind: 'member', ...MEMBER_MINI },+ ],+ owner: { onSend: () => { throw new Error('You have hit your usage limit'); } },+ // Model an older member returning a quota rejection without a native error.+ intercept: async (_device, request, forward) => {+ if (rejectQuota && request.op === 'call' && request.method === 'send') {+ rejectQuota = false;+ throw new Error('You have hit your usage limit');+ }+ return forward();+ },+ });+ const first = await openAsGuest(env, GUEST_A, openPayload(SESSION, { acceptsGroupSwitch: true }));+ const record = placement === 'local' ? env.ownerStarted[0] : env.memberStarted.mini[0];+ const other = await openAsGuest(env, GUEST_B, openPayload(SESSION));+ const memberEnded = placement === 'member'+ ? vi.spyOn(env.relay.connect(MEMBER_MINI.agentDeviceId).poller, 'unregister')+ : null;+ let release!: () => void;+ const decision = new Promise<void>(resolve => { release = resolve; });+ env.relay.plan.mockImplementationOnce(async () => {+ await decision;+ return { kind: 'member', ...MEMBER_STUDIO };+ });+ const send = first.client.call('send', [{ content: 'finish the task' }, {}]).catch(error => error);+ try {+ await waitFor(() => env.relay.plan.mock.calls.length === 3);+ if (endKind === 'explicit') {+ await first.client.close('close', 'navigation');+ expect(first.isClosed()).toBe(true);+ release();+ await send;+ expect(switchTokenIn(first.stream)).toBeUndefined();+ expect(first.stream.some(item => item.t === 'event' && item.event.type === 'error')).toBe(false);+ return;+ }+ record.end(endKind === 'error' ? new Error('agent stream ended unexpectedly') : undefined);+ if (memberEnded) await waitFor(() => memberEnded.mock.calls.length > 0);+ // Another full round trip lets the passive end propagate while plan waits.+ await other.client.call('send', [{ content: 'unrelated task' }, {}]);+ expect(first.isClosed()).toBe(false);+ expect(other.isClosed()).toBe(false);+ release();+ expect(await send).toMatchObject({ message: expect.stringContaining('usage limit') });+ await waitFor(() => first.isClosed());+ expect(switchTokenIn(first.stream)).toBeDefined();+ expect(first.stream.filter(item => item.t === 'event' && item.event.type === 'error')).toHaveLength(1);+ expect(env.relay.noteRunFailure).toHaveBeenCalledTimes(1);+ } finally {+ release();+ await Promise.all([first.client.close('close', 'navigation'), other.client.close('close', 'navigation')]);+ for (const host of [env.owner, ...Object.values(env.members)]) { await host.abortAll(); host.dispose(); }+ }+ });+it('sends the switch token before the error, and the reopened task avoids the failed computer', async () => {const env = setup({plans: [diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.tsindex 0c322ff18b..e16d8b8f5d 100644--- a/apps/desktop/src/main/remote-agent/host/runHost.ts+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts@@ -76,6 +76,7 @@ import {type RelayRunFailure,} from './groupRelay';import { PROVIDER_GROUP_LOCAL_MEMBER_KEY } from '../../../shared/providerGroup';+import { isAccountUsageLimitError } from '../../maker-ipc/usageLimitAutoResume';import { projectPathText } from '../executor/workspace';import {MAX_ANCESTOR_LEVELS,@@ -460,6 +461,9 @@ interface Run {localWs?: Set<string>;/** 本机 Agent 上一次报来的「正在运行一轮」。 */turnRunning?: boolean;+ /** 同一次发送的限额 RPC 失败与终态事件共用一次交付,下一次发送时作废。 */+ quotaFailure?: { delivery: Promise<void>; deliver?: () => void };+ lastSendCallId?: string;}/** 控制端真实路径 → 影子目录里逐级镜像的目录名(去掉本机文件系统不允许的字符)。 */@@ -1494,10 +1498,17 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {if (run.closing) break;lastEventType = event.type;meterRunUsage(run, handle.model, event);+ const failure = relayRunFailureOf(event);+ if (failure && isAccountUsageLimitError(failure)) {+ groupTurnFailed = true;+ await deliverQuotaFailure(run, localGroupMember(run.providerId ?? ''), failure, handle.model, () => {+ append(run, { t: 'event', event });+ });+ continue;+ }// 受邀者的任务按组分到了本机这一台:本机运行中失败时同样按组的口径冷却(旧版受邀者也一样),声明了支持的// 还可以换一台(凭证排在错误前面)。if (run.acceptsGroupSwitch || run.groupLoad) {- const failure = relayRunFailureOf(event);if (failure) {groupTurnFailed = true;const token = await groupSwitchOfferFor(run, localGroupMember(run.providerId!), failure, handle.model)@@ -1505,7 +1516,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {if (run.closing) break;if (token) append(run, { t: 'state', state: { [GROUP_SWITCH_STATE_KEY]: token } });} else if (event.type === 'done') {- noteGroupSwitchTurnEnded(run, groupTurnFailed);+ noteGroupSwitchTurnEnded(run, groupTurnFailed || !!run.quotaFailure);groupTurnFailed = false;}}@@ -1516,10 +1527,15 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {streamFailed = true;streamError = error;}+ // RPC 的限额拒绝可能先到、没有原生终态;流结束或抛错都不能抢先作废切换入口。+ await waitForQuotaFailureDelivery(run).catch(error => {+ if (!streamFailed) streamError = error;+ streamFailed = true;+ });// 受邀者的任务按组分到了本机这一台、一轮进行中本机的 Agent 意外结束(进程退出、事件流中断):与组内电脑上的// 任务意外结束一样可以换一台——凭证排在收尾前面,收尾按出错处理,受邀者那边才会把这一轮当作失败。const midTurn = run.turnRunning === true && lastEventType !== 'done';- if (run.acceptsGroupSwitch && !run.closing && midTurn && !groupTurnFailed) {+ if (run.acceptsGroupSwitch && !run.closing && midTurn && !groupTurnFailed && !run.quotaFailure) {const info = streamFailed ? remoteAgentErrorInfo(streamError) : RELAY_UNAVAILABLE_ERROR;const token = await groupSwitchOfferFor(run, localGroupMember(run.providerId!), {reason: 'remote_agent_closed',@@ -1626,11 +1642,59 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {return issueGroupSwitchToken(run, exclude);}+ /**+ * SDK 的限额终态与 send() 拒绝可能按任意顺序到达。先交付凭证与唯一一次终态,再返回 RPC 失败,+ * 控制端才能在 active turn 仍在时接管;迟到的同次终态不再触发第二次交接或续跑。+ */+ function deliverQuotaFailure(+ run: Run,+ member: GroupRelayMember,+ failure: RelayRunFailure,+ model: string,+ deliver?: () => void,+ ): Promise<void> {+ if (run.quotaFailure) {+ // 选下一台期间原生终态到了,优先保留它的结构化字段与事件来源。+ if (deliver) run.quotaFailure.deliver = deliver;+ return run.quotaFailure.delivery;+ }+ const pending = { delivery: Promise.resolve(), deliver };+ run.quotaFailure = pending;+ pending.delivery = Promise.resolve().then(async () => {+ const token = run.relay || run.acceptsGroupSwitch || run.groupLoad+ ? await groupSwitchOfferFor(run, member, failure, model).catch(() => null)+ : null;+ if (run.closing || run.quotaFailure !== pending) return;+ if (token) append(run, { t: 'state', state: { [GROUP_SWITCH_STATE_KEY]: token } });+ if (pending.deliver) pending.deliver();+ else append(run, {+ t: 'event',+ event: { type: 'error', source: run.kind, data: { ...failure, isTerminal: true, usageLimit: true } },+ });+ emitState(run);+ });+ return pending.delivery;+ }++ /** 只供被动结束等待;显式关闭仍直接走 finishRun,不等待组选下一台。 */+ async function waitForQuotaFailureDelivery(run: Run): Promise<void> {+ let pending = run.quotaFailure;+ while (!run.closing && pending) {+ await pending.delivery;+ if (run.quotaFailure === pending) return;+ pending = run.quotaFailure;+ }+ }+/*** 受邀者亲自接手(发消息、重试、换模型)后的这次发送:这个任务这一轮已经换下来的电脑清零(§6.1「一轮的边界」),* 之前因故换下、现在已恢复的电脑又能接手。标记只在本机读,去掉后再交给 Agent 或转给组内电脑。*/- function takeGroupNewRound(run: Run, method: RemoteAgentMethod, args: unknown[]): unknown[] {+ function takeGroupNewRound(run: Run, callId: string, method: RemoteAgentMethod, args: unknown[]): unknown[] {+ if (method === 'send') {+ run.quotaFailure = undefined;+ run.lastSendCallId = callId;+ }const opts = args[1];if (method !== 'send' || !opts || typeof opts !== 'object' || Array.isArray(opts) || !('groupNewRound' in opts)) return args;const { groupNewRound, ...rest } = opts as Record<string, unknown>;@@ -1718,9 +1782,17 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {let turnFailed = false;/** 失败时先(异步)判定要不要发凭证,期间那台转来的内容暂存,凭证排在错误前面。 */const holdForGroupSwitch = (failure: RelayRunFailure, deliver: () => void): void => {- const queue: Array<() => void> = [deliver];+ const quota = isAccountUsageLimitError(failure);+ if (quota && held) {+ void deliverQuotaFailure(run, current, failure, backend.model ?? payload.options.model, deliver);+ return;+ }+ const queue: Array<() => void> = quota ? [] : [deliver];held = queue;- void groupSwitchOfferFor(run, current, failure, backend.model ?? payload.options.model)+ const delivery = quota+ ? deliverQuotaFailure(run, current, failure, backend.model ?? payload.options.model, deliver)+ : groupSwitchOfferFor(run, current, failure, backend.model ?? payload.options.model);+ void delivery.catch(() => null).then((token) => {if (token && !run.closing && run.relay === backend) {@@ -1748,6 +1820,10 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {});void finishRun(run, reason, 'navigation', false, true);};+ if (run.quotaFailure) {+ void waitForQuotaFailureDelivery(run).then(() => emit(finish), finish);+ return;+ }// 一轮进行中那台的任务意外结束(离线、崩溃等):与终态错误一样可以换一台。const unexpected = backend.turnRunning && !NORMAL_RELAY_CLOSE_REASONS.has(reason);if (unexpected && !held) {@@ -1777,13 +1853,13 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {const failure = relayRunFailureOf(event);if (failure) {turnFailed = true;- if (!held) {+ if (!held || isAccountUsageLimitError(failure)) {holdForGroupSwitch(failure, deliver);return;}}if ((event as { type?: unknown }).type === 'done') {- noteGroupSwitchTurnEnded(run, turnFailed);+ noteGroupSwitchTurnEnded(run, turnFailed || !!run.quotaFailure);turnFailed = false;}emit(deliver);@@ -1944,7 +2020,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {async function relayCall(run: Run, relay: RelayBackend, callId: string, method: RemoteAgentMethod, payload: RemoteAgentPayload): Promise<void> {try {const raw = await resolvePayload(run.controller, payload);- const args = takeGroupNewRound(run, method, Array.isArray(raw) ? raw : []);+ const args = takeGroupNewRound(run, callId, method, Array.isArray(raw) ? raw : []);let callArgs: unknown[] = args;if (method === 'setVendorOptions') callArgs = [sanitizeGuestVendorOptions(args[0])];if (method === 'setExtraDirs') {@@ -1971,7 +2047,14 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {if (method === 'commitRewindFiles' && run.kind === 'claude-code') run.rewindPending = true;append(run, { t: 'result', callId, ok: true, ...(value !== undefined ? { value: JSON.parse(JSON.stringify(value)) } : {}) });} catch (error) {- append(run, { t: 'result', callId, ok: false, error: relayErrorInfoFrom(error) });+ const info = relayErrorInfoFrom(error);+ if (method === 'send' && run.lastSendCallId === callId && run.relay === relay) {+ if (run.quotaFailure) await run.quotaFailure.delivery;+ else if (isAccountUsageLimitError(info)) {+ await deliverQuotaFailure(run, relay.member, info, relay.model ?? run.authorizedModel ?? '');+ }+ }+ append(run, { t: 'result', callId, ok: false, error: info });} finally {run.calls.set(callId, 'done');if (run.calls.size > MAX_REMEMBERED_CALLS) {@@ -2081,7 +2164,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {if (run.closing) fail('REMOTE_AGENT_EXPIRED', 'task has ended');if (!handle) fail('REMOTE_AGENT_UNAVAILABLE', 'agent has not started');const raw = await resolvePayload(run.controller, payload);- const args = takeGroupNewRound(run, method, Array.isArray(raw) ? raw : []);+ const args = takeGroupNewRound(run, callId, method, Array.isArray(raw) ? raw : []);const target = (handle as unknown as Record<string, unknown>)[method];if (typeof target !== 'function') fail('REMOTE_AGENT_UNSUPPORTED', `${method} is not supported by this agent`);let callArgs: unknown[] = args;@@ -2159,7 +2242,14 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {if (method === 'commitRewindFiles' && run.kind === 'claude-code') run.rewindPending = true;append(run, { t: 'result', callId, ok: true, ...(value !== undefined ? { value: JSON.parse(JSON.stringify(value)) } : {}) });} catch (error) {- append(run, { t: 'result', callId, ok: false, error: remoteAgentErrorInfo(error) });+ const info = remoteAgentErrorInfo(error);+ if (method === 'send' && run.lastSendCallId === callId) {+ if (run.quotaFailure) await run.quotaFailure.delivery;+ else if (isAccountUsageLimitError(info)) {+ await deliverQuotaFailure(run, localGroupMember(run.providerId ?? ''), info, handle?.model ?? run.authorizedModel ?? '');+ }+ }+ append(run, { t: 'result', callId, ok: false, error: info });} finally {run.calls.set(callId, 'done');if (run.calls.size > MAX_REMEMBERED_CALLS) {diff --git a/docs/product-rules/provider-groups.md b/docs/product-rules/provider-groups.mdindex 9ace7cc8a0..bd67c235c9 100644--- a/docs/product-rules/provider-groups.md+++ b/docs/product-rules/provider-groups.md@@ -412,6 +412,9 @@续跑复用额度重置后自动继续的同一条路径(`continueAfterUsageLimitReset`),活动记录在这条续跑记录上带`agentSwitch`(原电脑、新电脑、原因);旧版本手机与桌面不认识该字段,显示成「用量已恢复,已自动继续」。Agent 还没开始运行就失败(打开任务阶段)时,在启动入口直接换下一台。代码在 `apps/desktop/src/main/provider-group/`。+ 远程发送的限额拒绝与 SDK 限额终态按同一次发送合并:无论哪条先到,都先完成切换判定并交付唯一一次终态,再返回发送失败;+ 需要切换时凭证排在终态之前。+ 防止发送回包提前清掉续跑入口;迟到或重复的同次终态不再次交接、续跑。新发送作废旧交付,不能确认是否送达的超时不据此重发。- **谁来执行换电脑**:交接要用到任务的对话记录,所以由任务所在的电脑执行。- 组所在电脑自己的任务:组所在电脑直接换。- 同账号其他电脑(直连):任务所在的电脑直接看到组内电脑的报错,自己换:把需要冷却的电脑报告给组所在电脑,