Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 供应商组第二期——分享的人运行中自动换电脑
Lizi7ebfe53e3806
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 0704daeacc..4c02c926d3 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -117,6 +117,7 @@ import {} from '../maker-ipc/register.js';import { MAKER_PUSH } from '../maker-ipc/channels.js';import { readProviderGroupBinding } from '../provider-group/bindings.js';+import { getProviderGroupGuestSwitch } from '../provider-group/guestSwitch.js';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';import { remoteBackgroundInvoke, remoteInvoke } from '../device-link/index.js';import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';@@ -2715,6 +2716,8 @@ export function getMaker(): Maker {}),// 供应商组分配到那台的任务:告诉那台直接运行,不再进入它自己的组(provider-groups.md §4 防转圈)。isGroupAssigned: (sessionId) => readProviderGroupBinding(sessionId) !== null,+ // 分享来的供应商被分享者建成了组:那台出问题时对方发来「需要换一台」,本机交接后带回凭证(§6.1)。+ groupSwitch: getProviderGroupGuestSwitch(),logger: desktopMakerLogger,}),makerMemory: makerMemoryManager,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.tsindex 83fb945da3..5db92c7f8e 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts@@ -1319,6 +1319,53 @@ describe('远程 Agent:选模型时换 Agent 所在电脑', () => {expect(h.calls).toEqual([]);});+ it('供应商组替分享的人换电脑:位置不变也强制全量交接、新建会话,分隔条不写电脑名', async () => {+ const h = relocationHarness({ agentDeviceId: 'share:alice-share', providerId: 'alice-anthropic' });+ const result = await performSessionAgentSwitch(h.deps, {+ sessionId: 's1',+ targetAgentKind: 'claude-code',+ model: 'anthropic/claude-opus-5-5[1m]',+ providerId: 'alice-anthropic',+ agentDeviceId: 'share:alice-share',+ applyNow: true,+ forceRelocation: true,+ });+ expect(result).toMatchObject({ switched: true });+ expect(h.selectSameAgentModel).not.toHaveBeenCalled();+ expect(h.findParkedEngineSession).not.toHaveBeenCalled();+ expect(h.assertAgentDeviceRouteUsable).toHaveBeenCalledWith('share:alice-share', 'claude-code', 'anthropic/claude-opus-5-5[1m]', 'alice-anthropic');+ expect(h.deps.applyAgentSwitchToDb).toHaveBeenCalledWith('s1', expect.objectContaining({ sdkSessionId: null }));+ const boundary = vi.mocked(h.deps.insertBoundaryMessage).mock.calls[0][1];+ expect(boundary).toMatchObject({+ fromAgentDeviceId: 'share:alice-share',+ toAgentDeviceId: 'share:alice-share',+ fromAgentDeviceName: null,+ toAgentDeviceName: null,+ resumed: false,+ });+ expect(boundary.handoff).toContain('Claude Code (on a different computer)');+ });++ it('强制换电脑只认内部立即执行:选择器登记与任务所在电脑上的任务都不受影响', async () => {+ const staged = relocationHarness({ agentDeviceId: 'share:alice-share' });+ await performSessionAgentSwitch(staged.deps, {+ ...backToTaskComputer,+ agentDeviceId: 'share:alice-share',+ forceRelocation: true,+ });+ expect(staged.selectSameAgentModel).toHaveBeenCalledTimes(1);+ expect(staged.calls).toEqual([]);++ const local = relocationHarness({ agentDeviceId: null });+ const result = await performSessionAgentSwitch(local.deps, {+ ...backToTaskComputer,+ applyNow: true,+ forceRelocation: true,+ });+ expect(result).toMatchObject({ switched: false });+ expect(local.deps.insertBoundaryMessage).not.toHaveBeenCalled();+ });+it('非法位置参数被拒绝', async () => {const h = relocationHarness();await expect(performSessionAgentSwitch(h.deps, { ...backToTaskComputer, agentDeviceId: 'bad id!' }))diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex d6fb342c44..fd9f46d392 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -32,6 +32,7 @@ import {readProviderGroupBinding,writeProviderGroupBinding,} from '../provider-group/bindings.js';+import { getProviderGroupGuestSwitch } from '../provider-group/guestSwitch.js';import { createProviderGroupLeaseReporter, type ProviderGroupLeaseReporter } from '../provider-group/leaseReporter.js';import {getProviderGroupDirectory,@@ -9508,6 +9509,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)providerId: route.providerId,agentDeviceId: route.agentDeviceId,applyNow: true,+ // 分享的人换电脑:位置仍是同一个分享,强制重新交接,由组所在电脑换一台。+ ...(switchOptions?.relocate ? { forceRelocation: true } : {}),// 发送前换电脑:随后的 lazy-create 按任务记录在新电脑上启动,不重复 bootstrap。...(switchOptions?.beforeSend ? { skipBootstrap: true } : {}),// 用户在等锁、读交接素材期间接手:在改动之前停下。@@ -9528,6 +9531,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await withSendToSessionLock(sessionId, run);},isTurnRunning: (sessionId) => maker.getSession(sessionId)?.isTurnRunning() ?? false,+ // 分享来的供应商被分享者建成了组:组所在电脑发来「需要换一台」时自动交接(provider-groups.md §6.1)。+ guestSwitch: getProviderGroupGuestSwitch(),continueSession: async (sessionId, token, info) =>agentInputCoordinatorHolder? agentInputCoordinatorHolder.continueAfterUsageLimitReset(sessionId, token, info)diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.tsindex 7c329d2cf1..3368f090cc 100644--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts@@ -439,6 +439,12 @@ export async function performSessionAgentSwitch(/** Recheck caller CAS after asynchronous validation, before staging any intent. */assertSelectionCurrent?: () => void;beforeMutation?: () => Promise<void>;+ /**+ * 仅限 main 内部(不接受 IPC 传入):Agent 位置不变也按换电脑重新交接、新建原生会话。供应商组替分享的人+ * 换电脑时任务的位置仍是同一个分享,实际运行的电脑由组所在电脑重新选(docs/product-rules/provider-groups.md §6.1)。+ * 只在 applyNow 且 Agent 在另一台电脑上时生效。+ */+ forceRelocation?: boolean;},): Promise<SessionAgentSwitchResult> {const { sessionId, targetAgentKind, model, providerId, signal } = params;@@ -514,9 +520,13 @@ export async function performSessionAgentSwitch(const targetAgentDeviceId =requestedAgentDeviceId === undefined ? currentAgentDeviceId : requestedAgentDeviceId;const agentDeviceChanges = targetAgentDeviceId !== currentAgentDeviceId;+ // 位置不变的强制换电脑(只认内部 applyNow 调用,且 Agent 在另一台电脑上):交接、提交、分隔条都按换电脑处理。+ const forcedRelocation =+ !agentDeviceChanges && params.forceRelocation === true && params.applyNow === true && targetAgentDeviceId !== null;+ const relocating = agentDeviceChanges || forcedRelocation;// 落到另一台电脑的完整切换(换引擎或换电脑):登记与落地前都按那台的目录裁决。同引擎同位置// 的模型选择走 selectSameAgentModel,在 SET_MODEL 链路里裁决。- if (targetAgentDeviceId && (agentDeviceChanges || fromDbKind !== toDbKind)) {+ if (targetAgentDeviceId && (relocating || fromDbKind !== toDbKind)) {await deps.assertAgentDeviceRouteUsable?.(targetAgentDeviceId,targetAgentKind,@@ -527,7 +537,7 @@ export async function performSessionAgentSwitch(throwIfAgentSwitchAborted(signal);params.assertSelectionCurrent?.();}- if (fromDbKind === toDbKind && !agentDeviceChanges) {+ if (fromDbKind === toDbKind && !relocating) {// Only picker calls stage a model choice here. Internal cross-engine apply/recovery// callers retain the existing same-engine no-op; send consumes staged choices below.if (deps.selectSameAgentModel && !params.applyNow) {@@ -624,14 +634,14 @@ export async function performSessionAgentSwitch(// Phase 2:目标引擎有停泊原生会话 → resume + 增量交接(只补离开期间的进展,// 工作状态区仍按全量历史提取);无绑定 → v1 全量交接 + 全新原生会话。// 换电脑时停泊的原生会话在原来那台电脑上,目标电脑接不上,一律全量交接。- const parked = deps.findParkedEngineSession && !agentDeviceChanges+ const parked = deps.findParkedEngineSession && !relocating? await deps.findParkedEngineSession(sessionId, toDbKind): null;const fullSourceMessages = await deps.listMessagesForHandoff(sessionId);throwIfAgentSwitchAborted(signal);const handoffOptsBase = {// 同引擎换电脑时两边引擎名相同,标出旧的那段跑在另一台电脑上。- fromLabel: agentDeviceChanges+ fromLabel: relocating? `${agentEngineLabel(fromDbKind)} (on a different computer)`: agentEngineLabel(fromDbKind),toLabel: agentEngineLabel(toDbKind),@@ -702,12 +712,13 @@ export async function performSessionAgentSwitch(handoff,resumed: !!parked,consumed: false,- ...(agentDeviceChanges+ ...(relocating? {fromAgentDeviceId: currentAgentDeviceId,toAgentDeviceId: targetAgentDeviceId,- fromAgentDeviceName: deps.describeAgentDevice?.(currentAgentDeviceId) ?? null,- toAgentDeviceName: deps.describeAgentDevice?.(targetAgentDeviceId) ?? null,+ // 强制换电脑时实际运行的电脑由对方选,本机不知道是哪台(也不该显示):分隔条写「另一台电脑」。+ fromAgentDeviceName: forcedRelocation ? null : deps.describeAgentDevice?.(currentAgentDeviceId) ?? null,+ toAgentDeviceName: forcedRelocation ? null : deps.describeAgentDevice?.(targetAgentDeviceId) ?? null,}: {}),};@@ -845,6 +856,7 @@ export async function performSessionAgentSwitch(resumed,handoffChars: handoff.length,...(agentDeviceChanges ? { agentDeviceChange: targetAgentDeviceId ? 'other-device' : 'task-device' } : {}),+ ...(forcedRelocation ? { agentDeviceChange: 'reassigned-by-provider-group' } : {}),});return {switched: true,diff --git a/apps/desktop/src/main/provider-group/__tests__/guestRelay.test.ts b/apps/desktop/src/main/provider-group/__tests__/guestRelay.test.tsindex 63c2644b28..d60b2fe2f6 100644--- a/apps/desktop/src/main/provider-group/__tests__/guestRelay.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/guestRelay.test.ts@@ -7,6 +7,7 @@ import { describe, expect, it, vi } from 'vitest';import type { ProviderGroupConfig, ProviderGroupMember } from '../../../shared/providerGroup';import { createProviderGroupExternalLoad } from '../externalLoad';import { createProviderGroupGuestRelay, PROVIDER_GROUP_GUEST_INCAPABLE_MS } from '../guestRelay';+import { PROVIDER_GROUP_MAX_REMOTE_COOLDOWN_MS } from '../remoteHandler';import { PROVIDER_GROUP_DEFAULT_COOLDOWN_MS, type ProviderGroupRouter } from '../router';function member(key: string, kind: ProviderGroupMember['kind'], agentDeviceId: string | null, providerId: string): ProviderGroupMember {@@ -82,6 +83,43 @@ describe('provider group guest relay planner', () => {expect(env.router.markCooling.mock.calls[0][2]).toBeLessThan(1_000 + PROVIDER_GROUP_DEFAULT_COOLDOWN_MS);});+ it('cools a computer whose relayed task failed mid-run for a reason of its own', () => {+ const env = setup([MINI]);+ const mini = { memberKey: MINI.key, agentDeviceId: 'mini', providerId: MINI.providerId, sameAccount: true };+ // 换到哪台都一样的失败:不冷却,也不换。+ expect(env.relay.noteRunFailure('anthropic', mini, { message: 'prompt is too long', sdkError: 'invalid_request' })).toBe(false);+ expect(env.router.markCooling).not.toHaveBeenCalled();+ expect(env.relay.noteRunFailure('anthropic', mini, { usageLimit: true, message: 'usage limit' })).toBe(true);+ expect(env.router.markCooling).toHaveBeenLastCalledWith('anthropic', MINI.key, 1_000 + PROVIDER_GROUP_DEFAULT_COOLDOWN_MS);+ expect(env.relay.noteRunFailure('anthropic', mini, { reason: 'remote_agent_closed' })).toBe(true);+ expect(env.router.markCooling.mock.calls.at(-1)?.[2]).toBeLessThan(1_000 + PROVIDER_GROUP_DEFAULT_COOLDOWN_MS);+ // 没有组的供应商,或那台已被移出组:不冷却、不换(成为普通的远程 Agent 任务)。+ const calls = env.router.markCooling.mock.calls.length;+ expect(env.relay.noteRunFailure('openai', mini, { usageLimit: true })).toBe(false);+ expect(env.relay.noteRunFailure('anthropic', { ...mini, memberKey: 'device:gone:anthropic' }, { usageLimit: true })).toBe(false);+ expect(env.router.markCooling.mock.calls.length).toBe(calls);+ });++ it('cools until the reported reset time, trusting it at most 8 days', () => {+ const router = { markCooling: vi.fn() } as unknown as ProviderGroupRouter & { markCooling: ReturnType<typeof vi.fn> };+ let resetAt = 1_000 + 3 * 60 * 60_000;+ const relay = createProviderGroupGuestRelay({+ router,+ readGroup: () => CONFIG,+ externalLoad: createProviderGroupExternalLoad({ now: () => 1_000 }),+ connect: () => ({ invoke: vi.fn(), poller: {} as never }),+ readResetAt: () => resetAt,+ now: () => 1_000,+ log: { warn: vi.fn() },+ });+ const mini = { memberKey: MINI.key, agentDeviceId: 'mini', providerId: MINI.providerId, sameAccount: true };+ relay.noteRunFailure('anthropic', mini, { usageLimit: true });+ expect(router.markCooling).toHaveBeenLastCalledWith('anthropic', MINI.key, resetAt);+ resetAt = 1_000 + 30 * 24 * 60 * 60_000;+ relay.noteRunFailure('anthropic', mini, { usageLimit: true });+ expect(router.markCooling).toHaveBeenLastCalledWith('anthropic', MINI.key, 1_000 + PROVIDER_GROUP_MAX_REMOTE_COOLDOWN_MS);+ });+it('counts relayed tasks while they run and asks computers to forget a shared user', async () => {const env = setup([MINI]);const load = env.relay.trackRun('anthropic', MINI.key);diff --git a/apps/desktop/src/main/provider-group/__tests__/guestSwitch.test.ts b/apps/desktop/src/main/provider-group/__tests__/guestSwitch.test.tsnew file mode 100644index 0000000000..33fdc008d0--- /dev/null+++ b/apps/desktop/src/main/provider-group/__tests__/guestSwitch.test.ts@@ -0,0 +1,46 @@+/**+ * 分享的人这边的「需要换一台」凭证(provider-groups.md §6.1):凭证紧挨在错误前面到达,只给那次错误用;+ * 交接后登记给下一次打开,带走即用掉;用户亲自接手时作废。+ */+import { describe, expect, it } from 'vitest';++import {+ createProviderGroupGuestSwitch,+ PROVIDER_GROUP_SWITCH_ARMED_TTL_MS,+ PROVIDER_GROUP_SWITCH_OFFER_TTL_MS,+} from '../guestSwitch';++describe('provider group guest switch tokens', () => {+ it('moves an offered token to the next open, once', () => {+ const tokens = createProviderGroupGuestSwitch(() => 0);+ expect(tokens.takeForOpen('s1')).toBeUndefined();+ tokens.offer('s1', 'token-a');+ expect(tokens.claim('s1')).toBe(true);+ expect(tokens.claim('s1')).toBe(false);+ expect(tokens.takeForOpen('s2')).toBeUndefined();+ expect(tokens.takeForOpen('s1')).toBe('token-a');+ expect(tokens.takeForOpen('s1')).toBeUndefined();+ });++ it('forgets tokens that are stale, released, or that the user took over from', () => {+ let now = 0;+ const tokens = createProviderGroupGuestSwitch(() => now);+ tokens.offer('s1', 'token-a');+ now += PROVIDER_GROUP_SWITCH_OFFER_TTL_MS + 1;+ expect(tokens.claim('s1')).toBe(false);++ tokens.offer('s1', 'token-b');+ tokens.drop('s1');+ expect(tokens.claim('s1')).toBe(false);++ tokens.offer('s1', 'token-c');+ expect(tokens.claim('s1')).toBe(true);+ tokens.release('s1');+ expect(tokens.takeForOpen('s1')).toBeUndefined();++ tokens.offer('s1', 'token-d');+ expect(tokens.claim('s1')).toBe(true);+ now += PROVIDER_GROUP_SWITCH_ARMED_TTL_MS + 1;+ expect(tokens.takeForOpen('s1')).toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/provider-group/__tests__/service.test.ts b/apps/desktop/src/main/provider-group/__tests__/service.test.tsindex 7f77824733..3dc65b192d 100644--- a/apps/desktop/src/main/provider-group/__tests__/service.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/service.test.ts@@ -10,6 +10,7 @@ import { describe, expect, it, vi } from 'vitest';import type { ProviderGroupConfig, ProviderGroupMember } from '../../../shared/providerGroup';import type { ProviderGroupBinding } from '../bindings';import type { ProviderGroupDirectory, ResolvedProviderGroupMember } from '../directory';+import { createProviderGroupGuestSwitch, PROVIDER_GROUP_SWITCH_OFFER_TTL_MS } from '../guestSwitch';import { createProviderGroupRouter, PROVIDER_GROUP_DEFAULT_COOLDOWN_MS } from '../router';import {createProviderGroupService,@@ -510,3 +511,82 @@ describe('beforeSend', () => {expect(h.bindings.get('s1')?.memberKey).toBe('local');});});++describe('onTurnError for a shared user (the sharer’s group picks the computer)', () => {+ const SHARE_ROUTE = 'share:share-from-alice';++ function guestHarness() {+ let clock = 5_000;+ const guestSwitch = createProviderGroupGuestSwitch(() => clock);+ const h = harness({ row: { agentDeviceId: SHARE_ROUTE, providerId: 'alice-anthropic' } });+ const service = createProviderGroupService({ ...h.deps, guestSwitch });+ return { ...h, service, guestSwitch, tick: (ms: number) => { clock += ms; } };+ }++ it('hands off and reopens with the token when the group computer asks to switch', async () => {+ const h = guestHarness();+ h.guestSwitch.offer('s1', 'token-aaaaaaaaaaaaaaaa');+ h.service.onTurnError('s1', { sdkError: 'rate_limit' }, 7);+ await flush();+ // 位置仍是同一个分享:强制重新交接。+ expect(h.deps.switchAgentLocation).toHaveBeenCalledWith('s1', {+ agentKind: 'claude-code',+ model: MODEL,+ providerId: 'alice-anthropic',+ agentDeviceId: SHARE_ROUTE,+ }, { isCurrent: expect.any(Function), relocate: true });+ // 交接时重新打开带上凭证(这里交接是假的,凭证仍在等打开)。+ expect(h.guestSwitch.takeForOpen('s1')).toBe('token-aaaaaaaaaaaaaaaa');+ expect(h.deps.continueSession).toHaveBeenCalledWith('s1', 99, expect.objectContaining({+ groupSwitch: { cause: 'usage-limit' },+ }));+ const info = (h.deps.continueSession.mock.calls[0] as unknown[])[2] as Record<string, unknown>;+ expect(info).not.toHaveProperty('agentSwitch');+ expect(h.deps.fallback).not.toHaveBeenCalled();+ // 分享来的电脑不在本机的任何组里:不冷却、不写绑定。+ expect(h.bindings.size).toBe(0);+ });++ it('leaves the error to the existing handling without a token from the group computer', async () => {+ const h = guestHarness();+ h.service.onTurnError('s1', { message: '[REMOTE_AGENT_SHARE_PAUSED] paused' }, 3);+ await flush();+ expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();+ expect(h.deps.fallback).toHaveBeenCalledWith('s1', { message: '[REMOTE_AGENT_SHARE_PAUSED] paused' }, 3);+ });++ it('ignores a stale token, a token the user already took over from, and failures any computer would hit', async () => {+ const stale = guestHarness();+ stale.guestSwitch.offer('s1', 'token-aaaaaaaaaaaaaaaa');+ stale.tick(PROVIDER_GROUP_SWITCH_OFFER_TTL_MS + 1);+ stale.service.onTurnError('s1', { sdkError: 'rate_limit' }, 1);+ await flush();+ expect(stale.deps.switchAgentLocation).not.toHaveBeenCalled();+ expect(stale.deps.fallback).toHaveBeenCalledTimes(1);++ const tookOver = guestHarness();+ tookOver.guestSwitch.offer('s1', 'token-aaaaaaaaaaaaaaaa');+ tookOver.service.noteUserAction('s1');+ tookOver.service.onTurnError('s1', { sdkError: 'rate_limit' }, 1);+ await flush();+ expect(tookOver.deps.switchAgentLocation).not.toHaveBeenCalled();++ const sameEverywhere = guestHarness();+ sameEverywhere.guestSwitch.offer('s1', 'token-aaaaaaaaaaaaaaaa');+ sameEverywhere.service.onTurnError('s1', { message: 'prompt is too long', sdkError: 'invalid_request' }, 1);+ await flush();+ expect(sameEverywhere.deps.switchAgentLocation).not.toHaveBeenCalled();+ expect(sameEverywhere.deps.fallback).toHaveBeenCalledTimes(1);+ });++ it('drops the token and hands back when the handoff does not go through', async () => {+ const h = guestHarness();+ h.guestSwitch.offer('s1', 'token-aaaaaaaaaaaaaaaa');+ h.deps.switchAgentLocation.mockRejectedValueOnce(new Error('[REMOTE_AGENT_SHARE_PAUSED] paused'));+ h.service.onTurnError('s1', { sdkError: 'rate_limit' }, 4);+ await flush();+ expect(h.guestSwitch.takeForOpen('s1')).toBeUndefined();+ expect(h.deps.continueSession).not.toHaveBeenCalled();+ expect(h.deps.fallback).toHaveBeenCalledWith('s1', { sdkError: 'rate_limit' }, 4);+ });+});diff --git a/apps/desktop/src/main/provider-group/guestRelay.ts b/apps/desktop/src/main/provider-group/guestRelay.tsindex a771313e0b..81a6f5c988 100644--- a/apps/desktop/src/main/provider-group/guestRelay.ts+++ b/apps/desktop/src/main/provider-group/guestRelay.ts@@ -10,9 +10,11 @@import type { AgentKind } from '@cindy/maker-core';import type { ProviderGroupConfig } from '../../shared/providerGroup.js';+import type { RelayRunFailure } from '../remote-agent/host/groupRelay.js';import type { GroupRelayMember, RemoteAgentGroupRelayDeps } from '../remote-agent/host/runHost.js';import type { RemoteAgentInvoke, RemoteAgentPoller } from '../remote-agent/controller/runClient.js';import type { ProviderGroupExternalLoad } from './externalLoad.js';+import { PROVIDER_GROUP_MAX_REMOTE_COOLDOWN_MS } from './remoteHandler.js';import {PROVIDER_GROUP_DEFAULT_COOLDOWN_MS,PROVIDER_GROUP_FAILURE_COOLDOWN_MS,@@ -28,6 +30,8 @@ export interface ProviderGroupGuestRelayDeps {readGroup(providerId: string): ProviderGroupConfig | null;externalLoad: ProviderGroupExternalLoad;connect(agentDeviceId: string): { invoke: RemoteAgentInvoke; poller: RemoteAgentPoller };+ /** 组内电脑报错里的用量重置时刻(unix ms);不提供时用量上限一律按默认时长冷却。 */+ readResetAt?(failure: RelayRunFailure): number | null;now(): number;log: { warn(message: string, meta?: Record<string, unknown>): void };}@@ -91,6 +95,23 @@ export function createProviderGroupGuestRelay(deps: ProviderGroupGuestRelayDeps));},+ noteRunFailure(providerId, member: GroupRelayMember, failure) {+ // 没有组,或那台已被移出组:已经在它上面的任务成为普通的远程 Agent 任务,不再自动换电脑(§9 #4)。+ if (!deps.readGroup(providerId)?.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;+ deps.router.markCooling(providerId, member.memberKey, until);+ return true;+ },+trackRun: (providerId, memberKey) => deps.externalLoad.trackRelay(providerId, memberKey),async forget(agentDeviceId, relay) {diff --git a/apps/desktop/src/main/provider-group/guestSwitch.ts b/apps/desktop/src/main/provider-group/guestSwitch.tsnew file mode 100644index 0000000000..c8bfd31bd7--- /dev/null+++ b/apps/desktop/src/main/provider-group/guestSwitch.ts@@ -0,0 +1,69 @@+/**+ * 分享的人这边的「需要换一台」(docs/product-rules/provider-groups.md §6.1「谁来执行换电脑 · 分享的人」)。+ *+ * 分享者把分享出来的供应商建成了组时,本机的任务由组所在电脑中转到组内某台电脑运行;本机看不到是哪台。那台+ * 因电脑本身的原因失败时,组所在电脑在事件流里先发来一张一次性凭证(排在那次错误前面)。本机据此自动交接+ * (新建会话并带上交接上下文)后重新打开,打开时带回凭证,组所在电脑再为它换一台。+ *+ * 只有持有组所在电脑发来的凭证才换:分享被暂停、删除、撤权等是分享本身的问题,不会触发换电脑。+ */++/** 凭证到达后多久内的那次错误才算数(凭证紧挨在错误前面送达,这里只防陈旧凭证误用)。 */+export const PROVIDER_GROUP_SWITCH_OFFER_TTL_MS = 2 * 60_000;+/** 交接后等重新打开带走凭证的时限(与组所在电脑那边的有效期一致)。 */+export const PROVIDER_GROUP_SWITCH_ARMED_TTL_MS = 10 * 60_000;++export interface ProviderGroupGuestSwitch {+ /** 组所在电脑发来凭证(任务的事件流里)。 */+ offer(sessionId: string, token: string): void;+ /** 这次错误要不要换一台:有新鲜的凭证则取走,登记给下一次打开,返回 true。 */+ claim(sessionId: string): boolean;+ /** 打开任务时带上的凭证(取走即用掉);没有返回 undefined。 */+ takeForOpen(sessionId: string): string | undefined;+ /** 交接没成:作废登记给下一次打开的凭证。 */+ release(sessionId: string): void;+ /** 用户亲自接手(发消息、重试、换模型):作废还没用上的凭证。 */+ drop(sessionId: string): void;+}++let shared: ProviderGroupGuestSwitch | null = null;++/** 运行期共用的一份(远程 Agent 打开任务与供应商组服务共用)。按任务 id 存放,任务 id 全局唯一,不随账号区分。 */+export function getProviderGroupGuestSwitch(): ProviderGroupGuestSwitch {+ shared ??= createProviderGroupGuestSwitch();+ return shared;+}++export function createProviderGroupGuestSwitch(now: () => number = Date.now): ProviderGroupGuestSwitch {+ const offered = new Map<string, { token: string; at: number }>();+ const armed = new Map<string, { token: string; at: number }>();++ return {+ offer(sessionId, token) {+ offered.set(sessionId, { token, at: now() });+ },++ claim(sessionId) {+ const entry = offered.get(sessionId);+ offered.delete(sessionId);+ if (!entry || now() - entry.at > PROVIDER_GROUP_SWITCH_OFFER_TTL_MS) return false;+ armed.set(sessionId, { token: entry.token, at: now() });+ return true;+ },++ takeForOpen(sessionId) {+ const entry = armed.get(sessionId);+ armed.delete(sessionId);+ if (!entry || now() - entry.at > PROVIDER_GROUP_SWITCH_ARMED_TTL_MS) return undefined;+ return entry.token;+ },++ release(sessionId) {+ armed.delete(sessionId);+ },++ drop(sessionId) {+ offered.delete(sessionId);+ },+ };+}diff --git a/apps/desktop/src/main/provider-group/service.ts b/apps/desktop/src/main/provider-group/service.tsindex f5df10b01b..e627e3376a 100644--- a/apps/desktop/src/main/provider-group/service.ts+++ b/apps/desktop/src/main/provider-group/service.ts@@ -32,6 +32,7 @@ import { isProviderShareAgentDeviceId } from '../../shared/providerShare.js';import type { InterruptedTurnErrorSignals } from '../maker-ipc/interruptedTurnAutoResume.js';import type { ProviderGroupBinding } from './bindings.js';import type { ProviderGroupDirectory } from './directory.js';+import type { ProviderGroupGuestSwitch } from './guestSwitch.js';import {PROVIDER_GROUP_DEFAULT_COOLDOWN_MS,PROVIDER_GROUP_FAILURE_COOLDOWN_MS,@@ -149,8 +150,13 @@ export interface ProviderGroupServiceDeps {switchAgentLocation(sessionId: string,route: { agentKind: AgentKind; model: string; providerId: string | null; agentDeviceId: string | null },- options?: { beforeSend?: boolean; isCurrent?: () => boolean },+ /** `relocate`:位置不变也重新交接、新建会话(分享的人换电脑,实际运行的电脑由组所在电脑重新选)。 */+ options?: { beforeSend?: boolean; isCurrent?: () => boolean; relocate?: boolean },): Promise<void>;+ /**+ * 分享的人这边的「需要换一台」凭证(guestSwitch.ts);不提供 = 分享来的供应商出错时一律交回原有处理。+ */+ guestSwitch?: Pick<ProviderGroupGuestSwitch, 'claim' | 'release' | 'drop'>;/** 这个任务现在是否正在运行一轮。 */isTurnRunning(sessionId: string): boolean;continueSession(@@ -442,37 +448,30 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Provreturn { binding, source, config };}- /** true = 已由本机制处理(含它自己交回原有处理);false = 不归它管,调用方照常交回。 */- async function failover(sessionId: string, signals: InterruptedTurnErrorSignals, token: number): Promise<boolean> {- const cause = classifyProviderGroupSwitchCause(signals);- if (!cause || !deps.readBinding(sessionId)) return false;- const bound = await loadBound(sessionId);- if (!bound?.config?.autoSwitch) return false;- const { binding, source, config } = bound;- if (!(await deps.isFailoverEligible(sessionId))) return false;- const row = await deps.readSessionRow(sessionId);- if (!row?.model || row.remoteHostId) return false;- const current = await verifyBinding(sessionId, source, binding, config, row);- if (!current) return false;- // 交接会关闭旧会话(关闭撤销限额等待):先取得这次错误的重试入口。用户已接手时什么都不做。- const lease = deps.leaseRecovery(sessionId, token);- if (!lease) return true;- // 用户在换电脑途中接手(重试、发消息、换模型)或那次错误已不是当前状态:之后的每一步都停手。+ /**+ * 登记一次进行中的换电脑:用户在途中接手(重试、发消息、换模型)或那次错误已不是当前状态时,之后的每一步都停手。+ * `handBack` 在不再换电脑时交回原有的报错与额度重置后自动继续;之前的交接若已关掉旧会话,换一个对当前状态+ * 有效的令牌。+ */+ async function withSwitchRun(+ sessionId: string,+ signals: InterruptedTurnErrorSignals,+ token: number,+ lease: object,+ body: (isCurrent: () => boolean, handBack: () => void) => Promise<void>,+ ): Promise<void> {const run = { superseded: false };const runs = runningSwitches.get(sessionId) ?? new Set();runs.add(run);runningSwitches.set(sessionId, runs);const isCurrent = () => !run.superseded && deps.isLeaseCurrent(sessionId, lease);- // 不再换电脑时交回原有的报错与额度重置后自动继续;之前的交接若已关掉旧会话,换一个对当前状态有效的令牌。const handBack = () => {if (!isCurrent()) return;const fallbackToken = deps.leaseRecovery(sessionId, token) ? token : deps.rearmContinue(sessionId, lease, null);if (fallbackToken !== null) deps.fallback(sessionId, signals, fallbackToken);};try {- await switchUntilSettled({- sessionId, signals, cause, binding, source, config, row: { ...row, model: row.model }, current, lease, isCurrent, handBack,- });+ await body(isCurrent, handBack);} catch (error) {deps.log.warn('provider group: automatic switch failed', { sessionId, error: errorText(error) });handBack();@@ -480,6 +479,84 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Provruns.delete(run);if (runs.size === 0 && runningSwitches.get(sessionId) === runs) runningSwitches.delete(sessionId);}+ }++ /** true = 已由本机制处理(含它自己交回原有处理);false = 不归它管,调用方照常交回。 */+ async function failover(sessionId: string, signals: InterruptedTurnErrorSignals, token: number): Promise<boolean> {+ const cause = classifyProviderGroupSwitchCause(signals);+ if (!cause) return false;+ if (!deps.readBinding(sessionId)) return guestFailover(sessionId, signals, token, cause);+ const bound = await loadBound(sessionId);+ if (!bound?.config?.autoSwitch) return false;+ const { binding, source, config } = bound;+ if (!(await deps.isFailoverEligible(sessionId))) return false;+ const row = await deps.readSessionRow(sessionId);+ if (!row?.model || row.remoteHostId) return false;+ const current = await verifyBinding(sessionId, source, binding, config, row);+ if (!current) return false;+ // 交接会关闭旧会话(关闭撤销限额等待):先取得这次错误的重试入口。用户已接手时什么都不做。+ const lease = deps.leaseRecovery(sessionId, token);+ if (!lease) return true;+ const boundRow = { ...row, model: row.model };+ await withSwitchRun(sessionId, signals, token, lease, (isCurrent, handBack) => switchUntilSettled({+ sessionId, signals, cause, binding, source, config, row: boundRow, current, lease, isCurrent, handBack,+ }));+ return true;+ }++ /**+ * 分享的人这边(§6.1):任务用的是分享来的供应商,分享者把它建成了组,实际运行的电脑由组所在电脑选,本机不知道+ * 是哪台。那台因电脑本身的原因失败时,组所在电脑先发来「需要换一台」凭证;本机交接(新建会话并带上交接上下文)+ * 后带着凭证重新打开,组所在电脑据此换一台,再继续这一轮。没有凭证不换:分享被暂停、删除、撤权是分享本身的+ * 问题,换到哪台都一样。+ */+ async function guestFailover(+ sessionId: string,+ signals: InterruptedTurnErrorSignals,+ token: number,+ cause: ProviderGroupSwitchCause,+ ): Promise<boolean> {+ const guestSwitch = deps.guestSwitch;+ if (!guestSwitch) return false;+ const row = await deps.readSessionRow(sessionId);+ const shareRoute = row?.agentDeviceId;+ if (!row?.model || row.remoteHostId || !shareRoute || !isProviderShareAgentDeviceId(shareRoute)) return false;+ if (!(await deps.isFailoverEligible(sessionId))) return false;+ if (!guestSwitch.claim(sessionId)) return false;+ const lease = deps.leaseRecovery(sessionId, token);+ if (!lease) {+ guestSwitch.release(sessionId);+ return true;+ }+ const model = row.model;+ await withSwitchRun(sessionId, signals, token, lease, async (isCurrent, handBack) => {+ try {+ // 位置仍是同一个分享:强制重新交接、新建会话,打开时带上凭证,由组所在电脑换一台。+ await deps.switchAgentLocation(sessionId, {+ agentKind: row.agentKind,+ model,+ providerId: row.providerId,+ agentDeviceId: shareRoute,+ }, { isCurrent, relocate: true });+ } catch (error) {+ guestSwitch.release(sessionId);+ deps.log.info('provider group: switching computer for a shared task stopped', { sessionId, error: errorText(error) });+ handBack();+ return;+ }+ deps.log.info('provider group: switched computer for a shared task', { sessionId, cause });+ if (!isCurrent()) return;+ const continueToken = deps.rearmContinue(sessionId, lease, deps.now());+ if (continueToken === null) return;+ const outcome = await deps.continueSession(sessionId, continueToken, {+ reason: USAGE_LIMIT_RESET_AUTO_RESUME_REASON,+ attempt: 1,+ maxAttempts: 1,+ sessionTotal: 0,+ groupSwitch: { cause },+ });+ if (outcome !== 'resumed') deps.cancelContinue(sessionId, continueToken);+ });return true;}@@ -774,6 +851,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): ProvnoteUserAction(sessionId) {for (const run of runningSwitches.get(sessionId) ?? []) run.superseded = true;router.resetTurn(sessionId);+ deps.guestSwitch?.drop(sessionId);},};}diff --git a/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts b/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.tsindex 92c3010026..f672b1c47a 100644--- a/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts@@ -15,7 +15,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { RemoteAgentPoller } from '../controller/poller';import { RemoteAgentRunClient } from '../controller/runClient';-import { relayKeyFor } from '../host/groupRelay';+import { relayKeyFor, type RelayRunFailure } from '../host/groupRelay';import {createRemoteAgentHost,hostSessionIdFor,@@ -35,6 +35,10 @@ let root: string;interface Started {input: HostedStartInput;sends: unknown[];+ /** 让这台上的 Agent 发出一个事件。 */+ emit(event: AgentEvent): void;+ /** 这台上是否正在运行一轮(写进状态)。 */+ running: boolean;}function fakeAgentHost(name: string, started: Started[], options: {@@ -46,7 +50,18 @@ function fakeAgentHost(name: string, started: Started[], options: {return createRemoteAgentHost({isAgentAvailable: () => true,startHosted: async (input) => {- const record: Started = { input, sends: [] };+ const queue: AgentEvent[] = [];+ let wake: (() => void) | null = null;+ const record: Started = {+ input,+ sends: [],+ running: false,+ emit(event) {+ queue.push(event);+ wake?.();+ wake = null;+ },+ };started.push(record);const handle: AgentSessionHandle = {id: `sdk-${name}-${input.hostSessionId}`,@@ -57,10 +72,14 @@ function fakeAgentHost(name: string, started: Started[], options: {},async steer() {},async abort() {},+ isTurnRunning: () => record.running,async close() {},events: () => ({[Symbol.asyncIterator]: (): AsyncIterator<AgentEvent> => ({- next: () => new Promise<IteratorResult<AgentEvent>>(() => undefined),+ next: async () => {+ while (queue.length === 0) await new Promise<void>((resolve) => { wake = resolve; });+ return { value: queue.shift()!, done: false };+ },}),}),getUsageSnapshot: () => ({ tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),@@ -112,7 +131,11 @@ async function waitFor(condition: () => boolean, ms = 3_000): Promise<void> {const MEMBER_MINI: GroupRelayMember = { memberKey: 'device:mini:anthropic-2', agentDeviceId: 'mini', providerId: 'anthropic-2', sameAccount: true };const MEMBER_STUDIO: GroupRelayMember = { memberKey: 'device:studio:anthropic', agentDeviceId: 'studio', providerId: 'anthropic', sameAccount: true };-function setup(options: { plans?: GroupRelayPlan[]; miniCapable?: boolean } = {}) {+function setup(options: {+ plans?: GroupRelayPlan[];+ miniCapable?: boolean;+ switchWorthy?: (failure: RelayRunFailure) => boolean;+} = {}) {const memberStarted: Record<string, Started[]> = { mini: [], studio: [] };const members = {mini: fakeAgentHost('mini', memberStarted.mini, {@@ -137,6 +160,8 @@ function setup(options: { plans?: GroupRelayPlan[]; miniCapable?: boolean } = {}return { invoke: poller.invoke, poller };}),noteStartFailure: vi.fn(),+ noteRunFailure: vi.fn((_providerId: string, _member: GroupRelayMember, failure: RelayRunFailure) =>+ options.switchWorthy?.(failure) ?? true),trackRun: vi.fn(() => ({ setRunning: vi.fn(), release: vi.fn() })),forget: vi.fn(async (agentDeviceId: string, relayKey: string) => {await memberInvoke(agentDeviceId)([{ op: 'forget', relay: relayKey }]);@@ -168,15 +193,36 @@ function runId(): string {async function openAsGuest(env: ReturnType<typeof setup>, guest: string, payload: Record<string, unknown>) {const poller = new RemoteAgentPoller(async (args) => jsonRoundTrip(await env.owner.handle(guest, jsonRoundTrip(args[0]))));let counter = 0;+ /** 受邀者按顺序收到的事件与状态。 */+ const stream: Array<{ t: 'event'; event: AgentEvent } | { t: 'state'; state: Record<string, unknown> }> = [];const client = new RemoteAgentRunClient(runId(), poller, {- onEvent: () => undefined,- onState: () => undefined,+ onEvent: (event) => {+ stream.push({ t: 'event', event: event as AgentEvent });+ },+ onState: (state) => {+ stream.push({ t: 'state', state });+ },onRequest: async () => ({ type: 'callback', value: undefined }),onWs: () => undefined,- onClosed: () => undefined,+ onClosed: (reason) => {+ closedReason = reason;+ },}, () => `22222222-2222-4222-8222-${String(++counter + runSeq * 100).padStart(12, '0')}`);+ let closedReason: string | null = null;const started = await client.open('claude-code', payload);- return { client, started };+ return { client, started, stream, isClosed: () => closedReason !== null };+}++const USAGE_LIMIT_ERROR: AgentEvent = {+ type: 'error',+ data: { message: 'You have hit your usage limit', isTerminal: true, usageLimit: true },+} as AgentEvent;++function switchTokenIn(stream: Awaited<ReturnType<typeof openAsGuest>>['stream']): string | undefined {+ for (const item of stream) {+ if (item.t === 'state' && typeof item.state.providerGroupSwitch === 'string') return item.state.providerGroupSwitch;+ }+ return undefined;}describe('provider group relay for shared users', () => {@@ -292,3 +338,156 @@ describe('provider group relay for shared users', () => {await client.close('close', 'navigation');});});++describe('provider group "switch to another computer" for shared users', () => {+ it('sends the switch token before the error, and the reopened task avoids the failed computer', async () => {+ const env = setup({+ plans: [+ { kind: 'member', ...MEMBER_MINI },+ { kind: 'member', ...MEMBER_STUDIO },+ { kind: 'member', ...MEMBER_STUDIO },+ ],+ });+ const first = await openAsGuest(env, GUEST_A, openPayload(SESSION, { acceptsGroupSwitch: true }));+ env.memberStarted.mini[0].emit(USAGE_LIMIT_ERROR);+ await waitFor(() => first.stream.some((item) => item.t === 'event' && item.event.type === 'error'));+ const token = switchTokenIn(first.stream);+ expect(token).toMatch(/^[A-Za-z0-9_-]{16,64}$/);+ const tokenAt = first.stream.findIndex((item) => item.t === 'state' && item.state.providerGroupSwitch === token);+ const errorAt = first.stream.findIndex((item) => item.t === 'event' && item.event.type === 'error');+ expect(tokenAt).toBeLessThan(errorAt);+ expect(env.relay.noteRunFailure).toHaveBeenCalledWith(+ 'shared-provider',+ MEMBER_MINI,+ expect.objectContaining({ usageLimit: true, message: 'You have hit your usage limit' }),+ );+ expect(env.relay.plan).toHaveBeenLastCalledWith(expect.objectContaining({ exclude: new Set([MEMBER_MINI.memberKey]) }));+ await first.client.close('close', 'navigation');++ // 受邀者交接后带着凭证重新打开(全新会话):组所在电脑避开出问题的那台。+ const reopened = await openAsGuest(env, GUEST_A, openPayload(SESSION, { acceptsGroupSwitch: true, groupSwitchToken: token }));+ expect(env.relay.plan).toHaveBeenLastCalledWith(expect.objectContaining({ exclude: new Set([MEMBER_MINI.memberKey]) }));+ expect(env.memberStarted.studio).toHaveLength(1);+ await reopened.client.close('close', 'navigation');+ });++ it('accepts a token only once, and only from the shared user and task it was sent to', async () => {+ const env = setup({+ plans: [+ { kind: 'member', ...MEMBER_MINI },+ { kind: 'member', ...MEMBER_STUDIO },+ { kind: 'member', ...MEMBER_STUDIO },+ { kind: 'member', ...MEMBER_STUDIO },+ { kind: 'member', ...MEMBER_STUDIO },+ ],+ });+ const first = await openAsGuest(env, GUEST_A, openPayload(SESSION, { acceptsGroupSwitch: true }));+ env.memberStarted.mini[0].emit(USAGE_LIMIT_ERROR);+ await waitFor(() => switchTokenIn(first.stream) !== undefined);+ const token = switchTokenIn(first.stream)!;+ await first.client.close('close', 'navigation');++ const otherGuest = await openAsGuest(env, GUEST_B, openPayload(SESSION, { groupSwitchToken: token }));+ expect(env.relay.plan).toHaveBeenLastCalledWith(expect.objectContaining({ exclude: new Set() }));+ await otherGuest.client.close('close', 'navigation');+ const otherTask = await openAsGuest(env, GUEST_A, openPayload('task-2', { groupSwitchToken: token }));+ expect(env.relay.plan).toHaveBeenLastCalledWith(expect.objectContaining({ exclude: new Set() }));+ await otherTask.client.close('close', 'navigation');++ const used = await openAsGuest(env, GUEST_A, openPayload(SESSION, { groupSwitchToken: token }));+ expect(env.relay.plan).toHaveBeenLastCalledWith(expect.objectContaining({ exclude: new Set([MEMBER_MINI.memberKey]) }));+ await used.client.close('close', 'navigation');+ const again = await openAsGuest(env, GUEST_A, openPayload(SESSION, { groupSwitchToken: token }));+ expect(env.relay.plan).toHaveBeenLastCalledWith(expect.objectContaining({ exclude: new Set() }));+ await again.client.close('close', 'navigation');+ });++ it('only forwards the original error to old shared users, or when the failure is not about the computer', async () => {+ const env = setup({+ plans: [{ kind: 'member', ...MEMBER_MINI }, { kind: 'member', ...MEMBER_MINI }],+ switchWorthy: (failure) => failure.usageLimit === true,+ });+ const legacy = await openAsGuest(env, GUEST_A, openPayload(SESSION));+ env.memberStarted.mini[0].emit(USAGE_LIMIT_ERROR);+ await waitFor(() => legacy.stream.some((item) => item.t === 'event' && item.event.type === 'error'));+ expect(switchTokenIn(legacy.stream)).toBeUndefined();+ // 没声明的受邀者:那台照样按组的口径冷却。+ expect(env.relay.noteRunFailure).toHaveBeenCalledTimes(1);+ await legacy.client.close('close', 'navigation');++ const declared = await openAsGuest(env, GUEST_B, openPayload(SESSION, { acceptsGroupSwitch: true }));+ env.memberStarted.mini[1].emit({ type: 'error', data: { message: 'prompt is too long', isTerminal: true } } as AgentEvent);+ await waitFor(() => declared.stream.some((item) => item.t === 'event' && item.event.type === 'error'));+ expect(switchTokenIn(declared.stream)).toBeUndefined();+ expect(env.relay.plan).toHaveBeenCalledTimes(2);+ await declared.client.close('close', 'navigation');+ });++ it('also offers another computer when the group ran the task on the group computer itself', async () => {+ const env = setup({ plans: [{ kind: 'local' }, { kind: 'member', ...MEMBER_MINI }, { kind: 'member', ...MEMBER_MINI }] });+ const first = await openAsGuest(env, GUEST_A, openPayload(SESSION, { acceptsGroupSwitch: true }));+ expect(env.ownerStarted).toHaveLength(1);+ env.ownerStarted[0].emit(USAGE_LIMIT_ERROR);+ await waitFor(() => first.stream.some((item) => item.t === 'event' && item.event.type === 'error'));+ const token = switchTokenIn(first.stream);+ expect(token).toBeDefined();+ const tokenAt = first.stream.findIndex((item) => item.t === 'state' && item.state.providerGroupSwitch === token);+ const errorAt = first.stream.findIndex((item) => item.t === 'event' && item.event.type === 'error');+ expect(tokenAt).toBeLessThan(errorAt);+ expect(env.relay.noteRunFailure).toHaveBeenCalledWith(+ 'shared-provider',+ expect.objectContaining({ memberKey: 'local' }),+ expect.objectContaining({ usageLimit: true }),+ );+ await first.client.close('close', 'navigation');++ const reopened = await openAsGuest(env, GUEST_A, openPayload(SESSION, { acceptsGroupSwitch: true, groupSwitchToken: token }));+ expect(env.relay.plan).toHaveBeenLastCalledWith(expect.objectContaining({ exclude: new Set(['local']) }));+ expect(env.memberStarted.mini).toHaveLength(1);+ await reopened.client.close('close', 'navigation');+ });++ it('offers another computer when the computer’s task ends unexpectedly in the middle of a turn', async () => {+ const env = setup({ plans: [{ kind: 'member', ...MEMBER_MINI }, { kind: 'member', ...MEMBER_STUDIO }] });+ const guest = await openAsGuest(env, GUEST_A, openPayload(SESSION, { acceptsGroupSwitch: true }));+ const record = env.memberStarted.mini[0];+ record.running = true;+ record.emit({ type: 'text', data: { text: 'working' } } as AgentEvent);+ await waitFor(() => guest.stream.some((item) => item.t === 'state' && item.state.turnRunning === true));+ // 那台把组所在电脑的任务结束了(撤权、崩溃等),不是正常收尾。+ await env.members.mini.purgeControllers((controller) => controller === OWNER_DEVICE);+ await waitFor(() => guest.isClosed());+ expect(switchTokenIn(guest.stream)).toMatch(/^[A-Za-z0-9_-]{16,64}$/);+ expect(env.relay.noteRunFailure).toHaveBeenCalledWith(+ 'shared-provider',+ MEMBER_MINI,+ expect.objectContaining({ reason: 'remote_agent_closed' }),+ );+ });++ it('stops offering once every computer has been tried this round', async () => {+ const env = setup({+ plans: [+ { kind: 'member', ...MEMBER_MINI },+ { kind: 'member', ...MEMBER_STUDIO },+ { kind: 'member', ...MEMBER_STUDIO },+ { kind: 'unavailable' },+ ],+ });+ const first = await openAsGuest(env, GUEST_A, openPayload(SESSION, { acceptsGroupSwitch: true }));+ env.memberStarted.mini[0].emit(USAGE_LIMIT_ERROR);+ await waitFor(() => switchTokenIn(first.stream) !== undefined);+ await first.client.close('close', 'navigation');+ const second = await openAsGuest(env, GUEST_A, openPayload(SESSION, {+ acceptsGroupSwitch: true,+ groupSwitchToken: switchTokenIn(first.stream),+ }));+ env.memberStarted.studio[0].emit(USAGE_LIMIT_ERROR);+ await waitFor(() => second.stream.some((item) => item.t === 'event' && item.event.type === 'error'));+ expect(env.relay.plan).toHaveBeenLastCalledWith(expect.objectContaining({+ exclude: new Set([MEMBER_MINI.memberKey, MEMBER_STUDIO.memberKey]),+ }));+ expect(switchTokenIn(second.stream)).toBeUndefined();+ await second.client.close('close', 'navigation');+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.tsindex ea3233ced6..e18df08227 100644--- a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts@@ -10,6 +10,7 @@ import { mapClaudeHostedEvent } from '../controller/eventMap';import { execServerActions, execServerCommand } from '../controller/execServerRelay';import { collectProjectInstructionFiles } from '../controller/projectFiles';import { approvalActionsFor, innerShellScript } from '../controller/proxyHandle';+import { takeGroupSwitchState } from '../controller/startRemote';import { EventLog, LineSplitter } from '../eventLog';import { ExecutorWorkspace } from '../executor/workspace';import { createRunTunnel } from '../host/tunnel';@@ -166,9 +167,27 @@ describe('wire payloads', () => {// 组所在电脑替受邀者中转的任务带不透明的 relay 键;格式不对丢弃。expect(decodeOpenPayload({ ...base, relay: 'a1b2c3d4e5f60718293a4b5c6d7e8f90' }).relay).toBe('a1b2c3d4e5f60718293a4b5c6d7e8f90');expect(decodeOpenPayload({ ...base, relay: '../x' })).not.toHaveProperty('relay');+ // 「需要换一台」:声明只认 true,凭证格式不对丢弃。+ expect(decodeOpenPayload({ ...base, acceptsGroupSwitch: true }).acceptsGroupSwitch).toBe(true);+ expect(decodeOpenPayload({ ...base, acceptsGroupSwitch: 1 })).not.toHaveProperty('acceptsGroupSwitch');+ expect(decodeOpenPayload({ ...base, groupSwitchToken: 'Zm9vYmFyYmF6cXV4MTIzNDU2' }).groupSwitchToken).toBe('Zm9vYmFyYmF6cXV4MTIzNDU2');+ expect(decodeOpenPayload({ ...base, groupSwitchToken: 'short' })).not.toHaveProperty('groupSwitchToken');expect(() => decodeOpenPayload({ sessionId: 's', options: { model: 'm' }, workspace: { workingDir: '/p', platform: 'beos' } })).toThrow();});+ it('takes the provider group switch token out of the state instead of merging it', () => {+ const offered: string[] = [];+ const offer = (token: string) => offered.push(token);+ const state = { turnRunning: true };+ expect(takeGroupSwitchState(state, offer)).toBe(state);+ expect(takeGroupSwitchState({ providerGroupSwitch: 'Zm9vYmFyYmF6cXV4MTIzNDU2' }, offer)).toBeNull();+ expect(takeGroupSwitchState({ providerGroupSwitch: 'Zm9vYmFyYmF6cXV4MTIzNDU2', model: 'm' }, offer)).toEqual({ model: 'm' });+ // 格式不对的凭证丢弃,也不进状态。+ expect(takeGroupSwitchState({ providerGroupSwitch: { evil: true }, model: 'm' }, offer)).toEqual({ model: 'm' });+ expect(takeGroupSwitchState({ providerGroupSwitch: 'Zm9vYmFyYmF6cXV4MTIzNDU2' }, undefined)).toBeNull();+ expect(offered).toEqual(['Zm9vYmFyYmF6cXV4MTIzNDU2', 'Zm9vYmFyYmF6cXV4MTIzNDU2']);+ });+it('restores known per-turn policies and confirms everything for unknown ones', async () => {const encoded = await encodeSendOptions({turnPermissionPolicy: {diff --git a/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.tsindex 3900d922dd..2acf3ce1e9 100644--- a/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts@@ -314,6 +314,33 @@ describe('remote agent round trip', () => {host.dispose();});+ it('declares provider group switch support and brings back the token after a handoff', async () => {+ const host = createHost();+ const base = makeDeps(host);+ const opened: Array<Record<string, unknown>> = [];+ const invoke: StartRemoteAgentDeps['invoke'] = async (args) => {+ const request = args[0] as { op?: string; payload?: { json?: Record<string, unknown> } };+ if (request.op === 'open' && request.payload?.json) opened.push(request.payload.json);+ return base.invoke(args);+ };+ const offered: string[] = [];+ const handle = await startRemoteAgentSession('pi', { sessionId: 's4', workingDir: project, model: 'm' }, {+ ...base,+ invoke,+ groupSwitch: { token: 'Zm9vYmFyYmF6cXV4MTIzNDU2', offer: (token) => offered.push(token) },+ });+ expect(opened[0]).toMatchObject({ acceptsGroupSwitch: true, groupSwitchToken: 'Zm9vYmFyYmF6cXV4MTIzNDU2' });+ await handle.close({ reason: 'navigation' });++ // 没接供应商组的调用方:打开时不声明。+ const plain = await startRemoteAgentSession('pi', { sessionId: 's5', workingDir: project, model: 'm' }, { ...base, invoke });+ expect(opened[1]).not.toHaveProperty('acceptsGroupSwitch');+ expect(opened[1]).not.toHaveProperty('groupSwitchToken');+ await plain.close({ reason: 'navigation' });+ expect(offered).toEqual([]);+ host.dispose();+ });+it('refuses controllers that are no longer allowed', async () => {authorized = false;const host = createHost();diff --git a/apps/desktop/src/main/remote-agent/controller/service.ts b/apps/desktop/src/main/remote-agent/controller/service.tsindex 3460904ffb..36268d0c89 100644--- a/apps/desktop/src/main/remote-agent/controller/service.ts+++ b/apps/desktop/src/main/remote-agent/controller/service.ts@@ -57,6 +57,14 @@ export interface DeviceAgentServiceDeps {extractPdfText?: PdfTextExtractor;/** 这个任务由供应商组分配(本机的组或另一台电脑上的组):打开时告诉那台不要再进入它自己的组。 */isGroupAssigned?(sessionId: string): boolean;+ /**+ * 供应商组「需要换一台」(分享的人,docs/product-rules/provider-groups.md §6.1):打开任务时声明支持并带回交接后+ * 要用的凭证,对方发来的新凭证交回这里。+ */+ groupSwitch?: {+ takeForOpen(sessionId: string): string | undefined;+ offer(sessionId: string, token: string): void;+ };logger: Logger;}@@ -140,12 +148,23 @@ export function createDeviceAgentStarter(deps: DeviceAgentServiceDeps) {}}}+ const sessionId = opts.sessionId;+ const groupSwitch = sessionId && deps.groupSwitch ? deps.groupSwitch : null;+ const switchToken = groupSwitch && sessionId ? groupSwitch.takeForOpen(sessionId) : undefined;return startRemoteAgentSession(input.agentKind, opts, {invoke: poller.invoke,poller,rgPath: deps.rgPath(),codexPath: () => deps.codexPath?.(),- ...(opts.sessionId && deps.isGroupAssigned?.(opts.sessionId) ? { groupAssigned: true } : {}),+ ...(sessionId && deps.isGroupAssigned?.(sessionId) ? { groupAssigned: true } : {}),+ ...(groupSwitch && sessionId+ ? {+ groupSwitch: {+ ...(switchToken ? { token: switchToken } : {}),+ offer: (token: string) => groupSwitch.offer(sessionId, token),+ },+ }+ : {}),prepareMcp: async ({ kind, opts: startOpts, vendorOptions }): Promise<PreparedRemoteMcp> => {const extra = await deps.prepareMcpBridge(deps.mcpProviders(), deps.logger, {agentKind: kind,diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.tsindex 296cbb1e85..acf3cc90a2 100644--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts@@ -8,7 +8,14 @@import os from 'node:os';import path from 'node:path';-import type { RemoteAgentKind, RemoteAgentReply, RemoteAgentReverseRequest, RemoteAgentStreamItem } from '@cindy/device-link';+import {+ REMOTE_AGENT_GROUP_SWITCH_STATE_KEY,+ REMOTE_AGENT_RELAY_KEY_PATTERN,+ type RemoteAgentKind,+ type RemoteAgentReply,+ type RemoteAgentReverseRequest,+ type RemoteAgentStreamItem,+} from '@cindy/device-link';import type { AgentEvent, AgentSessionHandle, StartSessionOptions } from '@cindy/maker-core';import { RemoteExecutor, type ExecutorCaptureHooks } from '../executor/executor';@@ -69,6 +76,11 @@ export interface StartRemoteAgentDeps {codexPath?: () => string | undefined;/** 这个任务由供应商组分配到那台:告诉那台直接运行,不再进入它自己的组(防转圈)。 */groupAssigned?: boolean;+ /**+ * 供应商组「需要换一台」(分享的人,docs/product-rules/provider-groups.md §6.1):提供即在打开时声明支持。+ * `token` 是交接后重新打开时带回的凭证;对方发来新凭证时交给 `offer`。+ */+ groupSwitch?: { token?: string; offer(token: string): void };newId(): string;log?: {info(message: string, meta?: Record<string, unknown>): void;@@ -85,6 +97,20 @@ function parentOf(value: string): string | null {return /^[A-Za-z]:$/.test(parent) ? null : parent;}+/**+ * 取走对方状态里的「需要换一台」凭证(供应商组,组所在电脑发来):格式正确才交给 `offer`;凭证不并入任务状态。+ * 返回剩下的状态,取走后什么都不剩时返回 null。+ */+export function takeGroupSwitchState(+ state: Record<string, unknown>,+ offer: ((token: string) => void) | undefined,+): Record<string, unknown> | null {+ if (!(REMOTE_AGENT_GROUP_SWITCH_STATE_KEY in state)) return state;+ const { [REMOTE_AGENT_GROUP_SWITCH_STATE_KEY]: token, ...rest } = state;+ if (typeof token === 'string' && REMOTE_AGENT_RELAY_KEY_PATTERN.test(token)) offer?.(token);+ return Object.keys(rest).length ? rest : null;+}+/*** 影子目录(对方电脑上的路径) → 本机真实路径的映射。虚拟工作区使用固定 opaque 层级,旧协议* 仍按真实路径逐级镜像;同步过去的个人 Skill 等映射回你这台的个人配置目录。越具体的放越前面。@@ -201,7 +227,11 @@ export async function startRemoteAgentSession(if (controller) controller.onEvent(event);else early.push({ type: 'event', value: event });},- onState: (state) => {+ onState: (incoming) => {+ // 组所在电脑发来的「需要换一台」凭证(排在那次错误前面):交给供应商组服务,不进任务状态。+ const remaining = takeGroupSwitchState(incoming, deps.groupSwitch?.offer);+ if (!remaining) return;+ let state = remaining;const projection = state.workspaceProjection as Parameters<typeof shadowAliases>[0] | undefined;if (projection?.virtualWorkspace === true && typeof projection.shadowDir === 'string') {workspace.setAliases(shadowAliases(projection, workspace.workingDir, personalRoots, { extraDirs, writableDirs }));@@ -266,6 +296,8 @@ export async function startRemoteAgentSession(personal: collectedPersonal?.personal ?? { files: [] },mcpServers: [...mcp.servers.keys()],...(deps.groupAssigned ? { groupAssigned: true } : {}),+ ...(deps.groupSwitch ? { acceptsGroupSwitch: true } : {}),+ ...(deps.groupSwitch?.token ? { groupSwitchToken: deps.groupSwitch.token } : {}),};let startedRaw: Record<string, unknown>;diff --git a/apps/desktop/src/main/remote-agent/host/groupRelay.ts b/apps/desktop/src/main/remote-agent/host/groupRelay.tsindex ad6c853dc1..092b716e30 100644--- a/apps/desktop/src/main/remote-agent/host/groupRelay.ts+++ b/apps/desktop/src/main/remote-agent/host/groupRelay.ts@@ -5,11 +5,13 @@* - 受邀者在组内电脑上的身份是本机为它取的不透明键(relay),不带分享与成员信息;* - 受邀者的任务 id 换成按(受邀者, 任务 id)派生的 id,两个受邀者用同一个 id 也不会在组内电脑上撞车;* - 组内电脑报出的、会透露它是谁或它与本机关系的错误,换成中性的「暂时不可用」;- * - 启动阶段换电脑时,每次尝试的 WebSocket 连接编号加前缀,不同尝试的连接不会混在一起。+ * - 启动阶段换电脑时,每次尝试的 WebSocket 连接编号加前缀,不同尝试的连接不会混在一起;+ * - 运行中那台因电脑本身的原因失败时,给声明了支持的受邀者发一张「需要换一台」的一次性凭证(§6.1)。*/-import { createHash } from 'node:crypto';+import { createHash, randomBytes } from 'node:crypto';-import type { RemoteAgentErrorInfo } from '@cindy/device-link';+import { REMOTE_AGENT_GROUP_SWITCH_STATE_KEY, type RemoteAgentErrorInfo } from '@cindy/device-link';+import { isTerminalAgentErrorEvent, type AgentEvent } from '@cindy/maker-core';/** 受邀者在组内电脑上的不透明键(32 位十六进制)。 */export function relayKeyFor(guestController: string): string {@@ -53,6 +55,42 @@ export function relayConnId(attempt: number, connId: string): string {return `r${attempt}-${connId}`.slice(0, 64);}+/** 「需要换一台」凭证在受邀者事件流里的状态键。 */+export const GROUP_SWITCH_STATE_KEY = REMOTE_AGENT_GROUP_SWITCH_STATE_KEY;++/** 一张「需要换一台」凭证(一次性,32 个 base64url 字符)。 */+export function newGroupSwitchToken(): string {+ return randomBytes(24).toString('base64url');+}++/** 组内电脑上任务失败时用来判断换不换电脑的结构化信号(与本机任务的终态错误判定同一组字段)。 */+export interface RelayRunFailure {+ message?: string;+ sdkError?: string;+ reason?: string;+ errorStatus?: number;+ usageLimit?: boolean;+ usageResetAt?: number;+ codexErrorInfo?: string;+}++/** 组内电脑转来的事件是不是一次终态错误;是则取出判断原因用的字段。 */+export function relayRunFailureOf(event: unknown): RelayRunFailure | null {+ if (!event || typeof event !== 'object' || typeof (event as { type?: unknown }).type !== 'string') return null;+ const typed = event as AgentEvent;+ if (!isTerminalAgentErrorEvent(typed)) return null;+ const data = typed.data && typeof typed.data === 'object' ? typed.data as Record<string, unknown> : {};+ return {+ ...(typeof data.message === 'string' ? { message: data.message } : {}),+ ...(typeof data.sdkError === 'string' ? { sdkError: data.sdkError } : {}),+ ...(typeof data.reason === 'string' ? { reason: data.reason } : {}),+ ...(typeof data.errorStatus === 'number' ? { errorStatus: data.errorStatus } : {}),+ ...(data.usageLimit === true ? { usageLimit: true } : {}),+ ...(typeof data.usageResetAt === 'number' && Number.isFinite(data.usageResetAt) ? { usageResetAt: data.usageResetAt } : {}),+ ...(typeof data.codexErrorInfo === 'string' ? { codexErrorInfo: data.codexErrorInfo } : {}),+ };+}+/** 受邀者推来的帧属于哪次尝试的哪条连接;不是当前尝试的返回 null(丢弃)。 */export function relayMemberConnId(attempt: number, guestConnId: string): string | null {const prefix = `r${attempt}-`;diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.tsindex 02ce95e820..c3a754b284 100644--- a/apps/desktop/src/main/remote-agent/host/runHost.ts+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts@@ -48,13 +48,18 @@ import { RemoteAgentRunClient, type RemoteAgentInvoke, type RemoteAgentPoller }import { EventLog, waitForAny } from '../eventLog';import { createGuestUsageMeter, type GuestUsageSample } from './guestUsage';import {+ GROUP_SWITCH_STATE_KEY,+ newGroupSwitchToken,relayConnId,relayErrorForGuest,relayErrorInfoFrom,relayKeyFor,relayMemberConnId,+ relayRunFailureOf,relaySessionIdFor,+ type RelayRunFailure,} from './groupRelay';+import { PROVIDER_GROUP_LOCAL_MEMBER_KEY } from '../../../shared/providerGroup';import { projectPathText } from '../executor/workspace';import {MAX_ANCESTOR_LEVELS,@@ -91,6 +96,12 @@ export const REMOTE_AGENT_HOST_RETAIN_MS = 60_000;export const REMOTE_AGENT_MAX_RELAYED_RUNS_PER_CONTROLLER = REMOTE_AGENT_MAX_RUNS_PER_CONTROLLER * 4;/** 受邀者的任务交给组内电脑时,启动阶段最多换几台。 */const MAX_RELAY_START_ATTEMPTS = 8;+/** 「需要换一台」凭证多久内有效(受邀者那边交接通常几秒内完成,重开时带回)。 */+export const GROUP_SWITCH_TOKEN_TTL_MS = 10 * 60_000;+/** 距上一次换电脑超过这么久算新的一轮(与供应商组本机任务的一轮同一口径)。 */+const GROUP_SWITCH_ROUND_MS = 30 * 60_000;+/** 那台上的任务以这些原因结束是正常收尾,不算失败。 */+const NORMAL_RELAY_CLOSE_REASONS = new Set(['closed', 'detached', 'ended', 'superseded']);const UPLOAD_IDLE_MS = 2 * 60_000;const MAX_STAGED_BYTES_PER_CONTROLLER = REMOTE_AGENT_MAX_PAYLOAD_BYTES * 2;const MAX_DECOMPRESSED_BYTES = 128 * 1024 * 1024;@@ -205,6 +216,11 @@ export interface GroupRelayMember {sameAccount: boolean;}+/** 组里的本机这一台(受邀者的任务直接在本机运行时用来冷却与避开它)。 */+function localGroupMember(providerId: string): GroupRelayMember {+ return { memberKey: PROVIDER_GROUP_LOCAL_MEMBER_KEY, agentDeviceId: '', providerId, sameAccount: false };+}+export type GroupRelayPlan =/** 组里选中了本机。 */| { kind: 'local' }@@ -219,6 +235,11 @@ export interface RemoteAgentGroupRelayDeps {connect(agentDeviceId: string): { invoke: RemoteAgentInvoke; poller: RemoteAgentPoller };/** 那台在启动阶段没能接下任务(连不上、登录失效等):按组的口径冷却。 */noteStartFailure(providerId: string, member: GroupRelayMember, error: unknown): void;+ /**+ * 那台上的任务运行中失败(终态错误,或一轮进行中任务意外结束):问题出在那台电脑本身时按组的口径冷却它并+ * 返回 true(可以换一台);用户停止、上下文超限等换到哪台都一样的失败返回 false。+ */+ noteRunFailure(providerId: string, member: GroupRelayMember, failure: RelayRunFailure): boolean;/** 计入那台组内电脑的负载(按它是否正在运行一轮)。 */trackRun(providerId: string, memberKey: string): { setRunning(running: boolean): void; release(): void };/** 删掉受邀者后,请接过它任务的组内电脑清掉留下的会话记录与目录。 */@@ -233,6 +254,8 @@ interface RelayBackend {attempt: number;/** 那台已经开始运行(启动阶段失败才能换下一台)。 */started: boolean;+ /** 那台上正在运行一轮(按它报来的状态)。 */+ turnRunning: boolean;/** 推帧按任务串行,保证 Codex exec-server 帧的顺序。 */pushChain: Promise<void>;model?: string;@@ -288,6 +311,11 @@ interface Run {relayKey?: string;/** 本机是组所在电脑、把这个受邀者任务转给了组内电脑。 */relay?: RelayBackend;+ /**+ * 本机是组所在电脑、这是受邀者自己的任务(不是被中转来的),受邀者声明了支持「需要换一台」:在本机或组内电脑上+ * 运行中失败时可以发凭证。+ */+ acceptsGroupSwitch?: boolean;}/** 控制端真实路径 → 影子目录里逐级镜像的目录名(去掉本机文件系统不允许的字符)。 */@@ -410,6 +438,13 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {const now = deps.now ?? Date.now;const runs = new Map<string, Run>();const uploads = new Map<string, Upload>();+ /** 发给受邀者的「需要换一台」凭证 → 发给了谁的哪个任务、重新打开时要避开哪些台。一次性,过期作废。 */+ const groupSwitchTokens = new Map<string, { controller: string; hostSessionId: string; exclude: string[]; expiresAt: number }>();+ /**+ * 受邀者任务这一轮已经因为电脑本身的原因换下来的组内电脑(控制端 + 本机侧任务 id → 那几台):同一轮每台最多+ * 试一次,都试过就不再发凭证,受邀者照常看到原来的错误。那台上一轮正常结束或 30 分钟没再换算新的一轮。+ */+ const groupSwitchRounds = new Map<string, { tried: Set<string>; at: number }>();/** 影子目录重建按 hostSessionId 串行:同一任务的两次打开不并发争用同一个目录。 */const shadowLocks = new Map<string, Promise<unknown>>();let sweepTimer: ReturnType<typeof setInterval> | null = null;@@ -905,10 +940,26 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {}async function pumpEvents(run: Run, handle: AgentSessionHandle): Promise<void> {+ /** 供应商组:本机这一台上这一轮出过终态错误。 */+ let groupTurnFailed = false;try {for await (const event of handle.events()) {if (run.closing) break;if (run.trust === 'guest') meterGuestUsage(run, handle.model, event);+ if (run.acceptsGroupSwitch) {+ // 受邀者的任务按组分到了本机这一台:本机运行中失败时同样可以换一台(凭证排在错误前面)。+ const failure = relayRunFailureOf(event);+ if (failure) {+ groupTurnFailed = true;+ const token = await groupSwitchOfferFor(run, localGroupMember(run.providerId!), failure, handle.model)+ .catch(() => null);+ if (run.closing) break;+ if (token) append(run, { t: 'state', state: { [GROUP_SWITCH_STATE_KEY]: token } });+ } else if (event.type === 'done') {+ noteGroupSwitchTurnEnded(run, groupTurnFailed);+ groupTurnFailed = false;+ }+ }append(run, { t: 'event', event });emitState(run);}@@ -934,8 +985,10 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {/** 转给组内电脑的打开载荷:已按受邀者复核过;来源换成那台上的供应商,带防转圈标记与受邀者的 relay 键。 */function relayedOpenPayload(run: Run, payload: RemoteAgentOpenPayload, member: GroupRelayMember): RemoteAgentOpenPayload {+ // 「需要换一台」只在受邀者与本机之间:组内电脑不认识也不需要。+ const { acceptsGroupSwitch: _accepts, groupSwitchToken: _token, ...rest } = payload;return {- ...payload,+ ...rest,sessionId: relaySessionIdFor(run.controller, payload.sessionId),groupAssigned: true,relay: relayKeyFor(run.controller),@@ -943,6 +996,77 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {};}+ /** 这个受邀者任务这一轮换下来的组内电脑,记上刚出问题的这台,返回要避开的全部。 */+ function noteGroupSwitchTried(run: Run, failed: GroupRelayMember): Set<string> {+ const at = now();+ for (const [roundKey, round] of groupSwitchRounds) {+ if (at - round.at > GROUP_SWITCH_ROUND_MS) groupSwitchRounds.delete(roundKey);+ }+ const roundKey = key(run.controller, run.hostSessionId!);+ const round = groupSwitchRounds.get(roundKey) ?? { tried: new Set<string>(), at };+ round.tried.add(failed.memberKey);+ round.at = at;+ groupSwitchRounds.set(roundKey, round);+ return new Set(round.tried);+ }++ /**+ * 受邀者任务在组内电脑(含本机这一台)上运行中失败:问题出在那台时按组的口径冷却它;受邀者声明了支持、组里还有+ * 能接的电脑(这一轮换下来的不算)时返回一张「需要换一台」凭证,调用方把它排在那次错误前面送出。+ */+ async function groupSwitchOfferFor(+ run: Run,+ member: GroupRelayMember,+ failure: RelayRunFailure,+ model: string,+ ): Promise<string | null> {+ const relayDeps = deps.groupRelay;+ if (!relayDeps || !run.providerId || !run.hostSessionId) return null;+ if (!relayDeps.noteRunFailure(run.providerId, member, failure)) return null;+ // 旧版受邀者不认识这个状态:照旧只转出原来的错误。+ if (!run.acceptsGroupSwitch) return null;+ const exclude = noteGroupSwitchTried(run, member);+ const next = await relayDeps.plan({ kind: run.kind, model, providerId: run.providerId, exclude }).catch(() => null);+ const canMove = next?.kind === 'member' || (next?.kind === 'local' && deps.isAgentAvailable(run.kind));+ if (!canMove || run.closing) return null;+ deps.log?.info('remote agent: offered the shared user another computer in the provider group', {+ runId: run.id,+ from: member.memberKey,+ tried: exclude.size,+ });+ return issueGroupSwitchToken(run, exclude);+ }++ /** 那台上一轮的结果:正常结束则这个任务的换电脑记录重新从头算。 */+ function noteGroupSwitchTurnEnded(run: Run, failed: boolean): void {+ if (!failed && run.hostSessionId) groupSwitchRounds.delete(key(run.controller, run.hostSessionId));+ }++ /** 发一张「需要换一台」凭证:只认发给的这个受邀者的这个任务,过期作废。 */+ function issueGroupSwitchToken(run: Run, exclude: ReadonlySet<string>): string {+ const at = now();+ for (const [token, entry] of groupSwitchTokens) {+ if (entry.expiresAt <= at) groupSwitchTokens.delete(token);+ }+ const token = newGroupSwitchToken();+ groupSwitchTokens.set(token, {+ controller: run.controller,+ hostSessionId: run.hostSessionId!,+ exclude: [...exclude],+ expiresAt: at + GROUP_SWITCH_TOKEN_TTL_MS,+ });+ return token;+ }++ /** 受邀者交接后重新打开时带回的凭证:有效则用掉,返回要避开的那几台;无效(别人的、过期、用过)返回空。 */+ function takeGroupSwitchToken(controller: string, hostSessionId: string, token: string | undefined): string[] {+ if (!token) return [];+ const entry = groupSwitchTokens.get(token);+ if (!entry || entry.controller !== controller || entry.hostSessionId !== hostSessionId) return [];+ groupSwitchTokens.delete(token);+ return entry.expiresAt > now() ? entry.exclude : [];+ }+/*** 启动中转任务。全新任务在那台没接下(还没开始运行)时换组里下一台,受邀者无感;续接只能回到原来那台。* 组里选回本机时改在本机运行。@@ -951,11 +1075,12 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {run: Run,payload: RemoteAgentOpenPayload,first: GroupRelayMember,- options: { fresh: boolean },+ /** `avoid`:「需要换一台」后重新打开时,这一轮已经换下来的组内电脑,启动阶段换台也不回到它们。 */+ options: { fresh: boolean; avoid?: readonly string[] },): Promise<void> {const relayDeps = deps.groupRelay!;const groupProviderId = run.providerId!;- const tried = new Set<string>();+ const tried = new Set<string>(options.avoid ?? []);let member: GroupRelayMember | null = first;let lastError: unknown = null;for (let attempt = 1; member && attempt <= MAX_RELAY_START_ATTEMPTS && !run.closing; attempt += 1) {@@ -968,42 +1093,102 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {member: current,attempt,started: false,+ turnRunning: false,pushChain: Promise.resolve(),load,};const wsOpened = new Set<string>();+ // 「需要换一台」(§6.1 分享的人):那台运行中失败时先问组里还有没有能接的电脑,期间那台转来的后续内容+ // 按原顺序暂存,凭证排在错误前面送达;受邀者那边据此自动交接后重新打开。+ let held: Array<() => void> | null = null;+ const emit = (deliver: () => void) => {+ if (held) held.push(deliver);+ else deliver();+ };+ /** 这一轮在那台出过终态错误(这一轮结束时不算「正常结束」)。 */+ let turnFailed = false;+ /** 失败时先(异步)判定要不要发凭证,期间那台转来的内容暂存,凭证排在错误前面。 */+ const holdForGroupSwitch = (failure: RelayRunFailure, deliver: () => void): void => {+ const queue: Array<() => void> = [deliver];+ held = queue;+ void groupSwitchOfferFor(run, current, failure, backend.model ?? payload.options.model)+ .catch(() => null)+ .then((token) => {+ if (token && !run.closing && run.relay === backend) {+ append(run, { t: 'state', state: { [GROUP_SWITCH_STATE_KEY]: token } });+ }+ })+ .finally(() => {+ held = null;+ for (const fn of queue) fn();+ });+ };backend.client = new RemoteAgentRunClient(randomUUID(), connection.poller, {onEvent: (event) => {if (run.closing || run.relay !== backend) return;meterGuestUsage(run, backend.model, event as AgentEvent);- append(run, { t: 'event', event });+ const deliver = () => {+ if (!run.closing) append(run, { t: 'event', event });+ };+ const failure = relayRunFailureOf(event);+ if (failure) {+ turnFailed = true;+ if (!held) {+ holdForGroupSwitch(failure, deliver);+ return;+ }+ }+ if ((event as { type?: unknown }).type === 'done') {+ noteGroupSwitchTurnEnded(run, turnFailed);+ turnFailed = false;+ }+ emit(deliver);},onState: (state) => {if (run.closing || run.relay !== backend) return;const projection = state.workspaceProjection as { mirrorRoot?: unknown } | undefined;if (typeof projection?.mirrorRoot === 'string') run.virtualRoot = projection.mirrorRoot;if (typeof state.model === 'string') backend.model = state.model;- if (typeof state.turnRunning === 'boolean') backend.load.setRunning(state.turnRunning);+ if (typeof state.turnRunning === 'boolean') {+ backend.turnRunning = state.turnRunning;+ backend.load.setRunning(state.turnRunning);+ }if (run.hostSessionId) {void recordGuestSession(run.controller, undefined, run.hostSessionId, [typeof state.id === 'string' ? state.id : undefined,typeof state.requestSessionId === 'string' ? state.requestSessionId : undefined,], current);}- append(run, { t: 'state', state });+ // 组内电脑不能替本机发凭证。+ const { [GROUP_SWITCH_STATE_KEY]: _forged, ...forwarded } = state;+ emit(() => {+ if (!run.closing) append(run, { t: 'state', state: forwarded });+ });},onRequest: (request, signal) => reverse(run, request, signal),onWs: (item) => {if (run.closing || run.relay !== backend) return;const connId = relayConnId(attempt, item.connId);if (item.kind === 'open') wsOpened.add(connId);- append(run, { ...item, connId });+ emit(() => {+ if (!run.closing) append(run, { ...item, connId });+ });},onClosed: (reason, error) => {// 启动阶段的收尾由下面的 catch 处理(可能换下一台);开始运行之后那台结束了,这个任务也结束。if (run.relay !== backend || run.closing || !backend.started) return;- run.log.append({ t: 'closed', reason, ...(error ? { error: relayErrorForGuest(error) } : {}) });- void finishRun(run, reason, 'navigation', false, true);+ const finish = () => {+ if (run.closing) return;+ run.log.append({ t: 'closed', reason, ...(error ? { error: relayErrorForGuest(error) } : {}) });+ void finishRun(run, reason, 'navigation', false, true);+ };+ // 一轮进行中那台的任务意外结束(离线、崩溃等):与终态错误一样可以换一台。+ const unexpected = backend.turnRunning && !NORMAL_RELAY_CLOSE_REASONS.has(reason);+ if (unexpected && !held) {+ holdForGroupSwitch({ reason: 'remote_agent_closed', ...(error?.message ? { message: error.message } : {}) }, finish);+ return;+ }+ emit(finish);},}, randomUUID, deps.log);run.relay = backend;@@ -1468,16 +1653,24 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {// 供应商组(本机是组所在电脑):受邀者的任务按组分给组内电脑,本机中转。被中转过来的任务(带 relay)// 与已由供应商组分配的任务(防转圈)直接在本机运行。续接只能回到当初运行它的那台。let relayTo: GroupRelayMember | null = null;- if (controllerTrust === 'guest' && !relayKey && !payload.groupAssigned && deps.groupRelay && providerId) {+ /** 受邀者因「需要换一台」交接后重新打开:这一轮已经换下来的组内电脑(凭证只认这个受邀者的这个任务)。 */+ let avoid: string[] = [];+ const groupRouted = controllerTrust === 'guest' && !relayKey && !payload.groupAssigned && !!deps.groupRelay && !!providerId;+ if (groupRouted && deps.groupRelay && providerId) {const resumeId = payload.options.resumeSessionId;if (resumeId) {relayTo = await relayMemberOf(controller, resumeId);} else {+ avoid = takeGroupSwitchToken(+ controller,+ hostSessionIdFor(controller, payload.sessionId),+ payload.groupSwitchToken,+ );const plan = await deps.groupRelay.plan({kind: request.agentKind,model: payload.options.model,providerId,- exclude: new Set(),+ exclude: new Set(avoid),});if (plan?.kind === 'unavailable') fail('REMOTE_AGENT_UNAVAILABLE', 'no computer can run this task right now');if (plan?.kind === 'member') {@@ -1508,6 +1701,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {pushSeq: new Set(),pushParts: new Map(),...(providerId ? { providerId } : {}),+ ...(groupRouted && payload.acceptsGroupSwitch === true ? { acceptsGroupSwitch: true } : {}),};runs.set(key(controller, request.runId), run);ensureSweep();@@ -1517,7 +1711,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {// 先登记再中转:中转中途失败时,分享删除也能找到并清理(含通知那台组内电脑)。run.hostSessionId = hostSessionIdFor(controller, payload.sessionId);void recordGuestSession(controller, undefined, run.hostSessionId, [])- .then(() => startRelay(run, payload, member, { fresh: !payload.options.resumeSessionId }))+ .then(() => startRelay(run, payload, member, { fresh: !payload.options.resumeSessionId, avoid })).catch(async (error) => {append(run, { t: 'start-failed', error: relayErrorInfoFrom(error) });await finishRun(run, 'start-failed', 'navigation', false);diff --git a/apps/desktop/src/main/remote-agent/host/service.ts b/apps/desktop/src/main/remote-agent/host/service.tsindex 1dd02e78f8..6a55e206d7 100644--- a/apps/desktop/src/main/remote-agent/host/service.ts+++ b/apps/desktop/src/main/remote-agent/host/service.ts@@ -23,6 +23,7 @@ import { readProviderGroup } from '../../provider-group/store.js';import { remoteAgentPollerFor } from '../controller/service';import { getProviderShareUsageStore, installProviderShareUsageStore } from '../../device-link/providerShareUsageStore.js';import { readDeviceLinkSettings } from '../../device-link/settings-store.js';+import { readTurnUsageResetAt } from '../../goal-host/usageLimit.js';import { getDesktopProviderService } from '../../maker-host/createDesktopProviderService.js';import { registerGuestProviderRoute } from '../../maker-host/guest-provider-route-store.js';import { isRemoteProviderInvocationAllowed } from '../../maker-host/remote-provider-access-store.js';@@ -159,6 +160,8 @@ export function installRemoteAgentHost(options: { getMaker: () => Maker; userDatconst poller = remoteAgentPollerFor(agentDeviceId, remoteBackgroundInvoke, log);return { invoke: poller.invoke, poller };},+ // 组内电脑的报错用那台机器的本地时间:不带时区的钟点不按本机时区理解。+ readResetAt: (failure) => readTurnUsageResetAt(failure, Date.now(), { localTimeZoneTrusted: false }),now: () => Date.now(),log,}),diff --git a/apps/desktop/src/main/remote-agent/wire.ts b/apps/desktop/src/main/remote-agent/wire.tsindex f9b9b206b4..0f24e82839 100644--- a/apps/desktop/src/main/remote-agent/wire.ts+++ b/apps/desktop/src/main/remote-agent/wire.ts@@ -154,6 +154,14 @@ export interface RemoteAgentOpenPayload {* 隔离运行,会话记录与目录按(控制端, relay)分开。只发给 caps 声明了 guestRelay 的电脑。*/relay?: string;+ /**+ * 任务所在电脑支持「需要换一台」(docs/product-rules/provider-groups.md §6.1 分享的人):组所在电脑中转的+ * 任务在组内电脑上因电脑本身的原因失败时,先在事件流里发一个 `providerGroupSwitch` 状态(一次性凭证)+ * 再转出错误,任务所在电脑据此自动交接后重新打开。只有声明了的电脑才会收到这个状态。+ */+ acceptsGroupSwitch?: boolean;+ /** 自动交接后重新打开时带回的那张一次性凭证:组所在电脑据此避开出问题的那台。 */+ groupSwitchToken?: string;options: RemoteAgentWireStartOptions;workspace: RemoteAgentWireWorkspace;projectFiles: RemoteAgentWireFile[];@@ -296,6 +304,10 @@ export function decodeOpenPayload(value: unknown): RemoteAgentOpenPayload {...(value.virtualWorkspace === true ? { virtualWorkspace: true } : {}),...(value.groupAssigned === true ? { groupAssigned: true } : {}),...(typeof value.relay === 'string' && REMOTE_AGENT_RELAY_KEY_PATTERN.test(value.relay) ? { relay: value.relay } : {}),+ ...(value.acceptsGroupSwitch === true ? { acceptsGroupSwitch: true } : {}),+ ...(typeof value.groupSwitchToken === 'string' && REMOTE_AGENT_RELAY_KEY_PATTERN.test(value.groupSwitchToken)+ ? { groupSwitchToken: value.groupSwitchToken }+ : {}),options: decodeStartOptions(value.options),workspace: decodeWorkspace(value.workspace),projectFiles,diff --git a/apps/desktop/src/renderer/__tests__/autoResumePresentation.test.ts b/apps/desktop/src/renderer/__tests__/autoResumePresentation.test.tsindex f6baa39b9c..458f209867 100644--- a/apps/desktop/src/renderer/__tests__/autoResumePresentation.test.ts+++ b/apps/desktop/src/renderer/__tests__/autoResumePresentation.test.ts@@ -134,4 +134,11 @@ describe('provider group switch presentation', () => {expect(readAutoResumeInfo({ reason: 'usage-limit-reset', agentSwitch: { from: 'A', to: 'B', cause: 'other' } })).toEqual({ usageLimitReset: true });});++ it('reads a shared user’s switch without any computer names', () => {+ expect(readAutoResumeInfo({ reason: 'usage-limit-reset', groupSwitch: { cause: 'overload' } }))+ .toEqual({ usageLimitReset: true, groupSwitch: { cause: 'overload' } });+ expect(readAutoResumeInfo({ reason: 'usage-limit-reset', groupSwitch: { cause: 'other' } }))+ .toEqual({ usageLimitReset: true });+ });});diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsxindex b133ad5f38..214617d287 100644--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx@@ -968,6 +968,8 @@ function AutoResumeActionRow({from: info.agentSwitch.from,to: info.agentSwitch.to,})+ : info.groupSwitch+ ? t('chat.systemCard.autoResume.groupSwitch'): usageLimitReset? t('chat.systemCard.autoResume.labelUsageReset'): livediff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 7fc8188bf4..8e133cdbb5 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -301,11 +301,11 @@"loading": "Reading share link…","askTitle": "{{name}} Wants to Share {{provider}} with You","providerOnDevice": "{{provider}} · {{device}}",- "factRuns": "The Agent runs on {{name}}’s computer with {{provider}}",+ "factRuns": "The Agent runs with {{provider}} on {{name}}’s computer or another computer {{name}} arranges","factRunsDetail": "Usage counts toward {{name}}’s {{provider}}, and {{name}} can see your usage","factFiles": "Your project files and commands still run on your own computer","factFilesDetail": "Your session permissions still apply",- "factPrivacy": "Chat content and files the Agent reads pass through and are saved on {{name}}’s computer",+ "factPrivacy": "Chat content and files the Agent reads pass through {{name}}’s computer and are saved on the computer that runs the session","factPrivacyDetail": "{{name}} only sees your nickname and avatar","factApproval": "After you send the request, it takes effect only once {{name}} approves","factApprovalDetail": "{{name}} can pause or remove this share at any time",@@ -374,7 +374,7 @@"open": "Open Link","cancel": "Cancel"},- "detailNote": "The agent runs on {{name}}'s computer, using their sign-in and quota. To use it, choose it in the model list when you start a task.",+ "detailNote": "The agent runs on {{name}}'s computer or another computer {{name}} arranges, using their sign-in and quota. Chat content and files the agent reads pass through {{name}}'s computer and are saved on the computer that runs the session. To use it, choose it in the model list when you start a task.","modelsTitle": "Available Models","modelsLoading": "Loading the models they shared…","modelsRefused": "The owner’s computer isn’t allowing this share right now. It may not allow remote control, “Allow remote use” may be off for this provider, or their Cindy may still be starting. Try again shortly, or ask them to check both settings.",@@ -419,7 +419,7 @@"empty": "Add {{provider}} from your other computers and tasks will pick one automatically","loading": "Loading provider group…","loadFailed": "Couldn’t load the provider group",- "note": "For tasks on this computer, the Agent runs on the computer the group picks"+ "note": "For sessions on this computer and sessions of people you share with, the group picks the computer that runs the Agent"},"strategy": {"label": "Group Strategy",@@ -10557,7 +10557,8 @@"auth": "{{from}} is signed out; continued on {{to}}","unavailable": "Couldn’t reach {{from}}; continued on {{to}}","overload": "{{from}} was overloaded; continued on {{to}}"- }+ },+ "groupSwitch": "Continued on another computer automatically"},"autoResumeSeparator": {"label": "Connection interrupted — resumed automatically"diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex c6f2a6836f..9ee64b4fc2 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -299,11 +299,11 @@"loading": "共有リンクを読み込み中…","askTitle": "{{name}} が {{provider}} をあなたに共有しようとしています","providerOnDevice": "{{provider}} · {{device}}",- "factRuns": "Agent は {{name}} のパソコン上で {{provider}} を使って実行されます",+ "factRuns": "Agent は {{name}} のパソコン、または {{name}} が手配した別のパソコンで {{provider}} を使って実行されます","factRunsDetail": "使用量は {{name}} の {{provider}} に計上され、{{name}} はあなたの使用量を確認できます","factFiles": "プロジェクトのファイルとコマンドは引き続きあなたのパソコンで実行されます","factFilesDetail": "あなたのセッションの権限が適用されます",- "factPrivacy": "チャットの内容と Agent が読み取ったファイルの内容は {{name}} のパソコンを経由し、保存されます",+ "factPrivacy": "チャットの内容と Agent が読み取ったファイルの内容は {{name}} のパソコンを経由し、実際にセッションを実行するパソコンに保存されます","factPrivacyDetail": "{{name}} に表示されるのはあなたのニックネームとアバターだけです","factApproval": "申請を送った後、{{name}} が承認すると有効になります","factApprovalDetail": "{{name}} はこの共有をいつでも停止または削除できます",@@ -372,7 +372,7 @@"open": "リンクを開く","cancel": "キャンセル"},- "detailNote": "Agent は {{name}} のパソコンで動き、相手のログインとクォータを使います。タスクを新規作成するときにモデル一覧で選ぶと使えます。",+ "detailNote": "Agent は {{name}} のパソコン、または {{name}} が手配した別のパソコンで動き、相手のログインとクォータを使います。チャットの内容と Agent が読み取ったファイルの内容は {{name}} のパソコンを経由し、実際にセッションを実行するパソコンに保存されます。タスクを新規作成するときにモデル一覧で選ぶと使えます。","modelsTitle": "利用できるモデル","modelsLoading": "相手が公開しているモデルを読み込んでいます…","modelsRefused": "相手のパソコンが今この共有の読み込みを許可していません。リモート操作を許可していないか、このプロバイダーの「リモート利用を許可」がオフになっているか、相手の Cindy が起動したばかりでまだ準備できていない可能性があります。しばらくしてから再試行するか、相手にこの 2 つの設定を確認してもらってください。",@@ -416,7 +416,7 @@"empty": "ほかのパソコンの {{provider}} を追加すると、セッションが自動でいずれかを選んで実行します","loading": "プロバイダーグループを読み込み中…","loadFailed": "プロバイダーグループを読み込めませんでした",- "note": "このパソコンのセッションは、Agent がグループに選ばれたパソコンで実行されます"+ "note": "このパソコンのセッションと共有相手のセッションは、グループが選んだパソコンで Agent が実行されます"},"strategy": {"label": "グループの割り当て方式",@@ -10533,7 +10533,8 @@"auth": "{{from}} のログインが切れたため、{{to}} で続行しました","unavailable": "{{from}} に接続できないため、{{to}} で続行しました","overload": "{{from}} のサービスが混雑しているため、{{to}} で続行しました"- }+ },+ "groupSwitch": "別のパソコンに自動で切り替えて続行しました"},"autoResumeSeparator": {"label": "接続が中断されたため、自動的に再開しました"diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 89ae70c130..8e20602e04 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -299,11 +299,11 @@"loading": "공유 링크를 읽는 중…","askTitle": "{{name}}님이 {{provider}}을(를) 공유하려고 합니다","providerOnDevice": "{{provider}} · {{device}}",- "factRuns": "Agent는 {{name}}님의 컴퓨터에서 {{provider}}로 실행됩니다",+ "factRuns": "Agent는 {{name}}님의 컴퓨터 또는 {{name}}님이 마련한 다른 컴퓨터에서 {{provider}}로 실행됩니다","factRunsDetail": "사용량은 {{name}}님의 {{provider}}에 계산되며 {{name}}님이 내 사용량을 볼 수 있습니다","factFiles": "프로젝트 파일과 명령은 계속 내 컴퓨터에서 실행됩니다","factFilesDetail": "내 세션 권한이 그대로 적용됩니다",- "factPrivacy": "채팅 내용과 Agent가 읽은 파일 내용은 {{name}}님의 컴퓨터를 거쳐 저장됩니다",+ "factPrivacy": "채팅 내용과 Agent가 읽은 파일 내용은 {{name}}님의 컴퓨터를 거쳐, 실제로 세션을 실행하는 컴퓨터에 저장됩니다","factPrivacyDetail": "{{name}}님에게는 내 닉네임과 프로필 사진만 표시됩니다","factApproval": "요청을 보낸 뒤 {{name}}님이 승인해야 적용됩니다","factApprovalDetail": "{{name}}님은 언제든지 이 공유를 일시 중지하거나 삭제할 수 있습니다",@@ -372,7 +372,7 @@"open": "링크 열기","cancel": "취소"},- "detailNote": "Agent는 {{name}}님의 컴퓨터에서 실행되며 상대방의 로그인과 할당량을 씁니다. 새 작업을 만들 때 모델 목록에서 선택하면 사용할 수 있습니다.",+ "detailNote": "Agent는 {{name}}님의 컴퓨터 또는 {{name}}님이 마련한 다른 컴퓨터에서 실행되며 상대방의 로그인과 할당량을 씁니다. 채팅 내용과 Agent가 읽은 파일 내용은 {{name}}님의 컴퓨터를 거쳐, 실제로 세션을 실행하는 컴퓨터에 저장됩니다. 새 작업을 만들 때 모델 목록에서 선택하면 사용할 수 있습니다.","modelsTitle": "사용 가능한 모델","modelsLoading": "상대방이 공개한 모델을 불러오는 중…","modelsRefused": "상대방 컴퓨터가 지금 이 공유를 읽도록 허용하지 않습니다. 원격 제어를 허용하지 않았거나 이 제공자의 원격 사용 허용이 꺼져 있거나, 상대방 Cindy가 방금 시작되어 아직 준비되지 않았을 수 있습니다. 잠시 후 다시 시도하거나 상대방에게 두 설정을 확인해 달라고 하세요.",@@ -416,7 +416,7 @@"empty": "다른 컴퓨터의 {{provider}}을(를) 추가하면 세션이 자동으로 한 대를 골라 실행합니다","loading": "제공자 그룹을 불러오는 중…","loadFailed": "제공자 그룹을 불러오지 못했습니다",- "note": "이 컴퓨터의 세션은 Agent가 그룹이 선택한 컴퓨터에서 실행됩니다"+ "note": "이 컴퓨터의 세션과 공유받은 사람의 세션은 그룹이 선택한 컴퓨터에서 Agent가 실행됩니다"},"strategy": {"label": "그룹 배정 방식",@@ -10533,7 +10533,8 @@"auth": "{{from}}의 로그인이 만료되어 {{to}}에서 이어서 진행했습니다","unavailable": "{{from}}에 연결할 수 없어 {{to}}에서 이어서 진행했습니다","overload": "{{from}}의 서비스가 혼잡해 {{to}}에서 이어서 진행했습니다"- }+ },+ "groupSwitch": "다른 컴퓨터로 자동 전환해 이어서 진행했습니다"},"autoResumeSeparator": {"label": "연결이 중단되어 자동으로 재개되었습니다"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex cd817c6d70..36b0e287ff 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -299,11 +299,11 @@"loading": "正在读取分享链接…","askTitle": "{{name}} 想把 {{provider}} 分享给你","providerOnDevice": "{{provider}} · {{device}}",- "factRuns": "Agent 在 {{name}} 的电脑上用 {{provider}} 运行",+ "factRuns": "Agent 在 {{name}} 的电脑或 {{name}} 安排的其他电脑上用 {{provider}} 运行","factRunsDetail": "用量计入 {{name}} 的 {{provider}},{{name}} 能看到你的用量","factFiles": "你的项目文件和命令仍在你自己的电脑上执行","factFilesDetail": "由你的任务权限把关",- "factPrivacy": "对话内容和 Agent 读取的文件内容会经过并保存在 {{name}} 的电脑上",+ "factPrivacy": "对话内容和 Agent 读取的文件内容会经过 {{name}} 的电脑,并保存在实际运行任务的那台电脑上","factPrivacyDetail": "{{name}} 只会看到你的昵称和头像","factApproval": "发送申请后,需要 {{name}} 同意才会生效","factApprovalDetail": "{{name}} 可以随时关闭或删除这个分享",@@ -372,7 +372,7 @@"open": "打开链接","cancel": "取消"},- "detailNote": "Agent 在 {{name}} 的电脑上运行,用的是对方的登录和配额。新建任务时在模型列表里选择它就能用。",+ "detailNote": "Agent 在 {{name}} 的电脑或 {{name}} 安排的其他电脑上运行,用的是对方的登录和配额。对话内容和 Agent 读取的文件内容会经过 {{name}} 的电脑,并保存在实际运行任务的那台电脑上。新建任务时在模型列表里选择它就能用。","modelsTitle": "可用的模型","modelsLoading": "正在读取对方开放的模型…","modelsRefused": "对方电脑暂时不让读取这个分享:可能没有允许远程控制、关了这个供应商的「允许被远程调用」,也可能对方的 Cindy 刚启动、还没准备好。请稍后重试,或让对方检查这两项设置。",@@ -416,7 +416,7 @@"empty": "加入其他电脑上的 {{provider}},任务会自动选一台运行","loading": "正在读取供应商组…","loadFailed": "未能读取供应商组",- "note": "这台电脑上的任务,Agent 在被选中的电脑上运行"+ "note": "这台电脑上的任务和分享的人的任务,都由组选一台电脑运行 Agent"},"strategy": {"label": "组策略",@@ -10533,7 +10533,8 @@"auth": "{{from}} 登录已失效,已换到 {{to}} 继续","unavailable": "{{from}} 连不上,已换到 {{to}} 继续","overload": "{{from}} 的服务繁忙,已换到 {{to}} 继续"- }+ },+ "groupSwitch": "已自动换一台电脑继续"},"autoResumeSeparator": {"label": "连接中断,已自动继续"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 7d586d1921..090ff3f8d0 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -299,11 +299,11 @@"loading": "正在讀取分享連結…","askTitle": "{{name}} 想把 {{provider}} 分享給你","providerOnDevice": "{{provider}} · {{device}}",- "factRuns": "Agent 在 {{name}} 的電腦上用 {{provider}} 執行",+ "factRuns": "Agent 在 {{name}} 的電腦或 {{name}} 安排的其他電腦上用 {{provider}} 執行","factRunsDetail": "用量計入 {{name}} 的 {{provider}},{{name}} 能看到你的用量","factFiles": "你的專案檔案和指令仍在你自己的電腦上執行","factFilesDetail": "由你的任務權限把關",- "factPrivacy": "對話內容和 Agent 讀取的檔案內容會經過並儲存在 {{name}} 的電腦上",+ "factPrivacy": "對話內容和 Agent 讀取的檔案內容會經過 {{name}} 的電腦,並儲存在實際執行任務的那台電腦上","factPrivacyDetail": "{{name}} 只會看到你的暱稱和頭像","factApproval": "傳送申請後,需要 {{name}} 同意才會生效","factApprovalDetail": "{{name}} 可以隨時關閉或刪除這個分享",@@ -372,7 +372,7 @@"open": "開啟連結","cancel": "取消"},- "detailNote": "Agent 在 {{name}} 的電腦上執行,使用的是對方的登入和配額。新建任務時在模型列表裡選擇它就能用。",+ "detailNote": "Agent 在 {{name}} 的電腦或 {{name}} 安排的其他電腦上執行,使用的是對方的登入和配額。對話內容和 Agent 讀取的檔案內容會經過 {{name}} 的電腦,並儲存在實際執行任務的那台電腦上。新建任務時在模型列表裡選擇它就能用。","modelsTitle": "可用的模型","modelsLoading": "正在讀取對方開放的模型…","modelsRefused": "對方電腦暫時不讓讀取這個分享:可能沒有允許遠端控制、關了這個供應商的「允許遠端呼叫」,也可能對方的 Cindy 剛啟動、還沒準備好。請稍後重試,或請對方檢查這兩項設定。",@@ -416,7 +416,7 @@"empty": "加入其他電腦上的 {{provider}},任務會自動選一臺執行","loading": "正在讀取供應商組…","loadFailed": "未能讀取供應商組",- "note": "這臺電腦上的任務,Agent 在被選中的電腦上執行"+ "note": "這臺電腦上的任務和你分享的人的任務,都由組選一台電腦執行 Agent"},"strategy": {"label": "組策略",@@ -10532,7 +10532,8 @@"auth": "{{from}} 登入已失效,已換到 {{to}} 繼續","unavailable": "{{from}} 連不上,已換到 {{to}} 繼續","overload": "{{from}} 的服務繁忙,已換到 {{to}} 繼續"- }+ },+ "groupSwitch": "已自動換一台電腦繼續"},"autoResumeSeparator": {"label": "連線中斷,已自動繼續"diff --git a/apps/desktop/src/renderer/lib/autoResumePresentation.ts b/apps/desktop/src/renderer/lib/autoResumePresentation.tsindex ce70a1b04d..9daf259d43 100644--- a/apps/desktop/src/renderer/lib/autoResumePresentation.ts+++ b/apps/desktop/src/renderer/lib/autoResumePresentation.ts@@ -2,6 +2,7 @@ import {USAGE_LIMIT_RESET_AUTO_RESUME_REASON,type AutoResumeAgentSwitch,type AutoResumeAgentSwitchCause,+ type AutoResumeGroupSwitch,} from '../../shared/agentInputQueue';import type { ChatMessage, ContinuationInFlightProjectionCapability } from './makerChatStore';@@ -10,6 +11,8 @@ export interface AutoResumeCardInfo {usageLimitReset?: boolean;/** 供应商组自动换电脑后继续(与 usageLimitReset 同时出现)。 */agentSwitch?: AutoResumeAgentSwitch;+ /** 分享者的供应商组替分享的人换了一台电脑后继续(不知道是哪台,不显示电脑名称)。 */+ groupSwitch?: AutoResumeGroupSwitch;error?: string;attempt?: number;maxAttempts?: number;@@ -35,6 +38,7 @@ export function readAutoResumeInfo(data?: Record<string, unknown>): AutoResumeCareturn {...(data?.reason === USAGE_LIMIT_RESET_AUTO_RESUME_REASON ? { usageLimitReset: true } : {}),...(readAgentSwitch(data?.agentSwitch) ? { agentSwitch: readAgentSwitch(data?.agentSwitch)! } : {}),+ ...(readGroupSwitch(data?.groupSwitch) ? { groupSwitch: readGroupSwitch(data?.groupSwitch)! } : {}),...(typeof data?.error === 'string' && data.error.length > 0 ? { error: data.error } : {}),...(num(data?.attempt) !== undefined ? { attempt: num(data?.attempt) } : {}),...(num(data?.maxAttempts) !== undefined ? { maxAttempts: num(data?.maxAttempts) } : {}),@@ -55,6 +59,13 @@ function readAgentSwitch(value: unknown): AutoResumeAgentSwitch | null {return { from: from.slice(0, 128), to: to.slice(0, 128), cause: cause as AutoResumeAgentSwitchCause };}+function readGroupSwitch(value: unknown): AutoResumeGroupSwitch | null {+ if (!value || typeof value !== 'object') return null;+ const { cause } = value as Record<string, unknown>;+ if (!AGENT_SWITCH_CAUSES.includes(cause as AutoResumeAgentSwitchCause)) return null;+ return { cause: cause as AutoResumeAgentSwitchCause };+}+/** Synthetic continuation inputs own turns; steering messages do not replace that owner. */export function findLastUserInputClientId(messages: readonly ChatMessage[]): string | null {for (let i = messages.length - 1; i >= 0; i--) {diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.tsindex 090fa515d8..5e2cdf7472 100644--- a/apps/desktop/src/shared/agentInputQueue.ts+++ b/apps/desktop/src/shared/agentInputQueue.ts@@ -209,6 +209,15 @@ export interface AutoResumeInfo {* 后的续跑同一条路径):活动行据此显示「{from} {原因},已换到 {to} 继续」。旧端忽略该字段。*/agentSwitch?: AutoResumeAgentSwitch;+ /**+ * 分享的人这边的自动换电脑(分享者的供应商组替它换了一台,本机不知道是哪台):活动行显示「已自动换一台+ * 电脑继续」,不出现电脑名称(docs/product-rules/provider-groups.md §8)。旧端忽略该字段。+ */+ groupSwitch?: AutoResumeGroupSwitch;+}++export interface AutoResumeGroupSwitch {+ cause: AutoResumeAgentSwitchCause;}export type AutoResumeAgentSwitchCause = 'usage-limit' | 'auth' | 'unavailable' | 'overload';diff --git a/apps/mobile/src/__tests__/autoResumePresentation.test.ts b/apps/mobile/src/__tests__/autoResumePresentation.test.tsindex 6fc425b6bc..3ef07fe6dd 100644--- a/apps/mobile/src/__tests__/autoResumePresentation.test.ts+++ b/apps/mobile/src/__tests__/autoResumePresentation.test.ts@@ -87,4 +87,11 @@ describe('provider group computer switch', () => {expect(readMobileAutoResumeInfo({ reason: 'usage-limit-reset', agentSwitch: { from: 'A', cause: 'auth' } })).toEqual({ usageLimitReset: true });});++ it('reads a shared user’s switch without any computer names', () => {+ expect(readMobileAutoResumeInfo({ reason: 'usage-limit-reset', groupSwitch: { cause: 'usage-limit' } }))+ .toEqual({ usageLimitReset: true, groupSwitch: { cause: 'usage-limit' } });+ expect(readMobileAutoResumeInfo({ reason: 'usage-limit-reset', groupSwitch: {} }))+ .toEqual({ usageLimitReset: true });+ });});diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.jsonindex 3da42ac96b..30352ae10d 100644--- a/apps/mobile/src/i18n/locales/en/message.json+++ b/apps/mobile/src/i18n/locales/en/message.json@@ -271,7 +271,8 @@"auth": "{{from}} is signed out; continued on {{to}}","unavailable": "Couldn’t reach {{from}}; continued on {{to}}","overload": "{{from}} was overloaded; continued on {{to}}"- }+ },+ "groupSwitch": "Continued on another computer automatically"},"modelLabel": "Model","sessionLabel": "Session",diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.jsonindex f37b3158b8..fe2fc57354 100644--- a/apps/mobile/src/i18n/locales/ja/message.json+++ b/apps/mobile/src/i18n/locales/ja/message.json@@ -271,7 +271,8 @@"auth": "{{from}} のログインが切れたため、{{to}} で続行しました","unavailable": "{{from}} に接続できないため、{{to}} で続行しました","overload": "{{from}} のサービスが混雑しているため、{{to}} で続行しました"- }+ },+ "groupSwitch": "別のパソコンに自動で切り替えて続行しました"},"modelLabel": "モデル","sessionLabel": "セッション",diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.jsonindex d70b260422..4f03797bf2 100644--- a/apps/mobile/src/i18n/locales/ko/message.json+++ b/apps/mobile/src/i18n/locales/ko/message.json@@ -271,7 +271,8 @@"auth": "{{from}}의 로그인이 만료되어 {{to}}에서 이어서 진행했습니다","unavailable": "{{from}}에 연결할 수 없어 {{to}}에서 이어서 진행했습니다","overload": "{{from}}의 서비스가 혼잡해 {{to}}에서 이어서 진행했습니다"- }+ },+ "groupSwitch": "다른 컴퓨터로 자동 전환해 이어서 진행했습니다"},"modelLabel": "모델","sessionLabel": "세션",diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.jsonindex d6bb515cc3..bd6dd19bb8 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 @@"auth": "{{from}} 登录已失效,已换到 {{to}} 继续","unavailable": "{{from}} 连不上,已换到 {{to}} 继续","overload": "{{from}} 的服务繁忙,已换到 {{to}} 继续"- }+ },+ "groupSwitch": "已自动换一台电脑继续"},"modelLabel": "模型","sessionLabel": "任务",diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.jsonindex 3f657a9259..6fbb9abd27 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 @@"auth": "{{from}} 登入已失效,已換到 {{to}} 繼續","unavailable": "{{from}} 連不上,已換到 {{to}} 繼續","overload": "{{from}} 的服務繁忙,已換到 {{to}} 繼續"- }+ },+ "groupSwitch": "已自動換一台電腦繼續"},"modelLabel": "模型","sessionLabel": "任務",diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 809e16c9d9..d06d54f97c 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -5328,6 +5328,8 @@ function MobileAutoResumeActionRow({from: info.agentSwitch.from,to: info.agentSwitch.to,})+ : info.groupSwitch+ ? t('message.systemCard.autoResume.groupSwitch'): info.usageLimitReset? t('message.systemCard.autoResume.usageReset'): state === 'live'diff --git a/apps/mobile/src/session/autoResumePresentation.ts b/apps/mobile/src/session/autoResumePresentation.tsindex bd2b0e0d7a..72c8852881 100644--- a/apps/mobile/src/session/autoResumePresentation.ts+++ b/apps/mobile/src/session/autoResumePresentation.ts@@ -22,11 +22,25 @@ function readAgentSwitch(value: unknown): MobileAutoResumeAgentSwitch | undefinereturn { from: from.slice(0, 128), to: to.slice(0, 128), cause: cause as MobileAutoResumeAgentSwitchCause };}+/** 对齐桌面 AutoResumeGroupSwitch:分享者的供应商组替分享的人换了一台电脑(不显示电脑名称)。 */+export interface MobileAutoResumeGroupSwitch {+ cause: MobileAutoResumeAgentSwitchCause;+}++function readGroupSwitch(value: unknown): MobileAutoResumeGroupSwitch | undefined {+ if (!value || typeof value !== 'object') return undefined;+ const { cause } = value as Record<string, unknown>;+ if (!AGENT_SWITCH_CAUSES.includes(cause as MobileAutoResumeAgentSwitchCause)) return undefined;+ return { cause: cause as MobileAutoResumeAgentSwitchCause };+}+export interface MobileAutoResumeInfo {/** 账号用量上限重置后自动继续(不是重连:不展示重试次数)。 */usageLimitReset?: boolean;/** 供应商组自动换电脑后继续(与 usageLimitReset 同时出现)。 */agentSwitch?: MobileAutoResumeAgentSwitch;+ /** 分享的人这边的自动换电脑:活动行写「已自动换一台电脑继续」。 */+ groupSwitch?: MobileAutoResumeGroupSwitch;error?: string;attempt?: number;maxAttempts?: number;@@ -52,9 +66,11 @@ export function readMobileAutoResumeInfo(data?: Record<string, unknown>): Mobileconst maxAttempts = usageLimitReset ? undefined : number(data?.maxAttempts);const sessionTotal = usageLimitReset ? undefined : number(data?.sessionTotal);const agentSwitch = readAgentSwitch(data?.agentSwitch);+ const groupSwitch = readGroupSwitch(data?.groupSwitch);return {...(usageLimitReset ? { usageLimitReset: true } : {}),...(agentSwitch ? { agentSwitch } : {}),+ ...(groupSwitch ? { groupSwitch } : {}),...(typeof data?.error === 'string' && data.error.trim() ? { error: data.error } : {}),...(attempt !== undefined ? { attempt } : {}),...(maxAttempts !== undefined ? { maxAttempts } : {}),diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex d5ff59e6bf..9dbaddc7fb 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -91,7 +91,8 @@ Claude Code 终态 error 事件可带 `usageResetAt`(unix ms)。服务端无`autoResumeInfo` 新增可选字段 `agentSwitch: { from, to, cause }`(cause 为 `usage-limit` / `auth` /`unavailable` / `overload`),Desktop 与 Mobile 据此显示「{from} {原因},已换到 {to} 继续」;字段缺失或不合法时照常显示 `usage-limit-reset` 的文案,旧客户端忽略该字段。P1 不改远程 Agent 协议:被分配到别的电脑的-任务就是普通的远程 Agent 任务。+任务就是普通的远程 Agent 任务。分享的人这边的自动换电脑(P2c,2026-10-10)另加可选字段 `groupSwitch: { cause }`+(不带电脑名称),Desktop 与 Mobile 显示「已自动换一台电脑继续」;旧客户端忽略,显示「用量已恢复,已自动继续」。## Agent 跨设备历史发现与搜索@@ -758,6 +759,29 @@ B 上的 Worker 是一条普通任务,`sessions.orca_remote_lead`(migration 01`provider-group/guestRelay.ts`(选电脑);回归见 `remote-agent/__tests__/groupRelay.test.ts`(三端同进程)、`provider-group/__tests__/guestRelay.test.ts`、`remote-agent/__tests__/poll.test.ts`。+## 供应商组:受邀者运行中换电脑(P2c)++产品规则见 [`provider-groups.md`](../product-rules/provider-groups.md) §6.1「谁来执行换电脑 · 分享的人」。上一节的中转任务在组内+电脑 M 上因那台本身的原因失败时,交接要用到对话记录,只能由受邀者 G 执行;组所在电脑 O 只负责告诉 G「需要换一台」并在+G 重新打开时换一台。G 与 O 之间新增三项可选内容,O 与 M 之间不变:++- **open 载荷新增可选 `acceptsGroupSwitch: true`**(`remote-agent/wire.ts`,只认 `true`):G 声明认识下面的凭证状态。新 G 打开+ 远程 Agent 任务时一律声明;O 只在中转任务上使用。旧 O 丢弃这个字段。+- **事件流里的凭证状态 `{ t: 'state', state: { providerGroupSwitch: <token> } }`**(`REMOTE_AGENT_GROUP_SWITCH_STATE_KEY`,+ 凭证格式同 `REMOTE_AGENT_RELAY_KEY_PATTERN`):O 看到 M 转来的终态错误(或一轮进行中 M 的任务意外结束;组选中 O 本机、任务在+ O 本机运行时同样适用)、按组口径判定是那台的问题、并确认组里还有能接的电脑后,**先**追加这条状态,**再**转出原来的错误;判定与选电脑期间 M 转来的后续内容按原顺序+ 暂存,不乱序。只发给声明了 `acceptsGroupSwitch` 的 G;旧 G 只看到原来的错误(行为同 P2b)。G 取走凭证、不并入任务状态+ (`controller/startRemote.ts` `takeGroupSwitchState`)。O 丢弃 M 转来的同名状态,M 不能替 O 发凭证。+- **open 载荷新增可选 `groupSwitchToken`**:G 自动交接(全量交接 + 全新原生会话)后重新打开时带回凭证。O 只认发给这个受邀者、+ 这个任务(按 O 侧的 `hostSessionId`)且未过期(10 分钟)的凭证,用一次即作废;有效时选电脑避开这一轮已经换下来的组内电脑,+ 无效时按普通新任务选。凭证只影响选哪台,不扩大任何权限;它与 `relay` / `groupAssigned` 一样不转给 M。+- 同一轮每台组内电脑最多换一次(O 按(受邀者, 任务)记录);那台上一轮正常结束或距上次换电脑超过 30 分钟算新的一轮。+- G 只在持有凭证时才换电脑:分享暂停、删除、撤权等来自 O 本身的错误没有凭证,照旧交回原有处理。+- 不改 relay、服务器与数据库。实现:`remote-agent/host/runHost.ts`(暂存与发凭证、校验凭证)、`host/groupRelay.ts`、+ `provider-group/guestRelay.ts`(运行中失败的冷却)、`provider-group/guestSwitch.ts` 与 `provider-group/service.ts`(G 侧凭证与+ 自动交接)、`maker-ipc/sessionAgentSwitchHandler.ts`(仅内部可用的 `forceRelocation`);回归见+ `remote-agent/__tests__/groupRelay.test.ts`、`provider-group/__tests__/service.test.ts`、`guestSwitch.test.ts`。+## 事实来源| 内容 | 权威来源 |diff --git a/docs/product-rules/provider-groups.md b/docs/product-rules/provider-groups.mdindex 375eaba5cd..d2e7378e4b 100644--- a/docs/product-rules/provider-groups.md+++ b/docs/product-rules/provider-groups.md@@ -3,8 +3,8 @@> 产品方案:2026-10-09 用户确认(含自动换电脑、受邀者不提醒、自定义供应商按名称匹配、不设数量上限)。> 2026-10-10 用户确认:同账号其他电脑经组使用时**直接连到选中的组内电脑**(不经组所在电脑中转),> 分享的人仍经组所在电脑中转;被组收进去的远程供应商与分享,在同账号其他电脑上只显示组那一项。-> 实现进度见 §12:P1 已实现;P2 同账号直连与模型列表只显示组(P2a)、分享的人经组中转与启动阶段换电脑(P2b)已实现,-> 分享的人运行中换电脑与申请弹窗新说法(P2c)未实现;P3 未实现。+> 实现进度见 §12:P1 已实现;P2 全部已实现:同账号直连与模型列表只显示组(P2a)、分享的人经组中转与启动阶段换电脑(P2b)、+> 分享的人运行中换电脑与申请弹窗新说法(P2c);P3 未实现。> 交互设计稿见 [`docs/design-previews/provider-groups/index.html`](../design-previews/provider-groups/index.html)。> 读取时机:新增或修改供应商组、组策略、组内电脑的添加与状态、经供应商组的任务分配或转发、> 供应商组用量与「远程与分享」页之前。@@ -179,9 +179,22 @@- 同账号其他电脑(直连):任务所在的电脑直接看到组内电脑的报错,自己换:把需要冷却的电脑报告给组所在电脑,再问它下一台(带上这一轮试过的),交接与续跑与组所在电脑自己的任务同一套。组所在电脑读不到时(离线、断线)不换电脑、绑定不动,交回原有的报错;确认组已删除或这台已不在组里时才解除绑定,任务成为普通的远程 Agent 任务。- - 分享的人:组所在电脑告诉任务所在的电脑「需要换一台」,那边自动交接后重新打开,+ - 分享的人(P2c,2026-10-10):组所在电脑告诉任务所在的电脑「需要换一台」,那边自动交接后重新打开,组所在电脑再为它选新电脑。任务所在的电脑需要更新到支持这个功能的版本;旧版本只会看到原有的报错,- 可以手动换模型。(P2b)+ 可以手动换模型。具体做法:+ - 任务所在的电脑打开任务时声明支持(可选字段 `acceptsGroupSwitch`)。组内电脑(包括组所在电脑本机)上的任务因 §6.1 列出的原因+ 失败(终态错误,或一轮进行中那台的任务意外结束)时,组所在电脑先按组的口径冷却那台,再看组里还有没有能接的+ 电脑(这一轮已经换下来的不算);有就在事件流里先发一张一次性凭证,再转出原来的错误。旧版本、没有能接的+ 电脑、或换到哪台都一样的失败,只转出原来的错误。+ - 任务所在的电脑只在持有这张凭证时才换:分享被暂停、删除、撤权是分享本身的问题,没有凭证,不会触发换电脑。+ 凭证只用于紧随其后的那次错误(2 分钟内);用户亲自接手(发消息、重试、换模型)即作废。+ - 换法与组所在电脑自己的任务相同:任务的位置仍是同一个分享,强制交接(全量交接 + 全新原生会话,分隔条写+ 「Agent 已改到另一台电脑上运行」,不写电脑名称),重新打开时带回凭证,组所在电脑据此避开这一轮换下来的+ 电脑;然后按额度重置后自动继续的路径续跑这一轮,活动记录写「已自动换一台电脑继续」。交接没成时交回原有的+ 报错与额度重置后自动继续。+ - 凭证只认发给的那个受邀者的那个任务,用过、过期(10 分钟)即作废;组内电脑转来的同名状态一律丢弃,组内电脑+ 不能替组所在电脑发凭证。同一轮每台组内电脑最多试一次;那台上一轮正常结束,或距上次换电脑超过 30 分钟,+ 算新的一轮。- **不续接的打开**(第一次运行、交接后的新会话)优先回到原电脑;原电脑不可用或满载时换一台,绑定改到新电脑,旧电脑上的会话不能再续接。- **模型**:组对外提供组内电脑模型的并集;新任务只分给提供所选模型的电脑。任务中途换模型时在当前组内电脑上核对,@@ -275,8 +288,9 @@- [供应商分享](provider-sharing.md):§4.1 第 3 步的告知不论有没有组都改用 §8 的说法;§1「Agent 在分享者电脑上运行」、§7.2 管理页、§7.4 用量、§9 安全不变量在有组时按本文调整;实现时同步修订该文。- 远程 Agent 协议:新增 §4 的「已由供应商组分配」可选标记(`groupAssigned`);同账号直连新增同账号通道- `provider-group:remote` 与目录里的组摘要;分享的人的「需要换一台」(P2b):任务所在电脑打开任务时声明支持(可选字段),- 组所在电脑只对声明了的电脑发出。其余沿用现有协议,不改服务端。兼容做法见 §14,登记见+ `provider-group:remote` 与目录里的组摘要;分享的人经组所在电脑中转(P2b)新增 `relay`、`guestRelay` 与 `forget`;+ 分享的人的「需要换一台」(P2c):任务所在电脑打开任务时声明支持(可选字段 `acceptsGroupSwitch`),组所在电脑只对+ 声明了的电脑在事件流里发出凭证状态(`providerGroupSwitch`),重新打开时带回(`groupSwitchToken`)。其余沿用现有协议,不改服务端。兼容做法见 §14,登记见`docs/dev-rules/protocol-compatibility.md`「供应商组」。- [跨电脑复制任务](task-device-migration.md) 与已建任务换 Agent 所在电脑:§6.1 的自动换电脑与手动「换一台继续」都复用现有交接,不新增交接机制。@@ -291,7 +305,7 @@| P1(已实现) | 供应商组设置与「远程与分享」页的组一块;组所在电脑自己的任务按组选电脑(选定后就是普通的本机或远程 Agent 任务)与自动换电脑;组内电脑状态与本次运行内的冷却;换电脑的活动记录(桌面与手机) || P2a(已实现) | 同账号其他电脑经组直连:问组所在电脑选电脑、直接连过去、本机自动换电脑并报告冷却;运行中任务报告给组所在电脑计入负载;防转圈标记;同账号其他电脑的模型列表与设置页只显示组、组项标出供应商组与组内电脑状态 || P2b(已实现) | 分享的人经组所在电脑中转;使用方隔离;同账号组内电脑接受被中转的受邀者(隔离);续接回到原来那台;启动阶段换电脑;删除受邀者时通知组内电脑清理 |-| P2c | 分享的人运行中换电脑:「需要换一台」信号与受邀者那边的自动交接、活动记录「已自动换一台电脑继续」;申请弹窗的新说法 |+| P2c(已实现) | 分享的人运行中换电脑:「需要换一台」信号与受邀者那边的自动交接、活动记录「已自动换一台电脑继续」(桌面与手机);申请弹窗与「分享给我的供应商」详情的新说法;「远程与分享」页写明分享的人的任务也按组分配 || P3 | 两个维度的用量;全部失败时逐台列出原因、按全组最早恢复的一台等待;手机端显示实际运行电脑 |## 13. 验收@@ -323,7 +337,7 @@| 组所在电脑 | 组只在新版本里存在。降级到旧版本后组不生效,这个供应商回到只在本机运行;经组分到其他电脑的任务在旧版本里不能续接,需要换模型或新开任务。同账号其他电脑问它时得到 `CHANNEL_NOT_ALLOWED`、目录里也没有组摘要,当作没有组照常直接连它;已经经它的组分到别处的任务留在原处,成为普通的远程 Agent 任务 || 组内电脑 | 照常作为普通的同账号远程供应商或分享来的供应商接任务。「已由供应商组分配」标记对它是不认识的字段,解码时丢弃;它本来没有组,也不会转圈。旧版同账号组内电脑不声明 `guestRelay`,组所在电脑不给它分受邀者的任务(它不会按受邀者隔离);旧版分享来的组内电脑本来就把组所在电脑当受邀者,照常接,只是不按受邀者再细分作用域(组所在电脑自己按受邀者隔离) || 同账号其他电脑 | 直连由任务所在的电脑执行,旧版本不认识组:选组所在电脑的这个供应商时直接在组所在电脑上运行(没有组),模型列表里组内电脑照常单独显示、没有供应商组的标注 |-| 分享的人 | 照常使用,中转对它透明(协议不变)。打开任务阶段的换电脑由组所在电脑完成,旧版本同样享受;运行中失败时它没有声明支持「需要换一台」,组所在电脑照旧返回原来的错误(如用量上限),用户像现在一样换模型或稍后重试。(运行中换电脑见 P2c) |+| 分享的人 | 照常使用,中转对它透明(协议不变)。打开任务阶段的换电脑由组所在电脑完成,旧版本同样享受;运行中失败时它没有声明支持「需要换一台」,组所在电脑照旧返回原来的错误(如用量上限),用户像现在一样换模型或稍后重试。新版本声明支持,运行中失败时自动换一台(§6.1)。旧版本申请弹窗仍是「Agent 在 {分享者} 的电脑上运行」(§8 已知差异) || 受邀者申请 | 申请弹窗由受邀者自己的 Cindy 显示,旧版本仍是原来的说法(§8 已知差异) |- 本地数据:供应商组设置只新增存储,不改已有的供应商、远程调用与分享数据;涉及数据库时按diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.mdindex 594e9f6bd9..c836c9bdf6 100644--- a/docs/product-rules/provider-sharing.md+++ b/docs/product-rules/provider-sharing.md@@ -6,8 +6,9 @@> 客户端与服务端的工作拆分见 [`docs/provider-sharing-implementation-plan.md`](../provider-sharing-implementation-plan.md)。> 读取时机:新增或修改供应商分享、分享链接、分享申请与审批、分享管理页,或受邀者使用> 分享供应商的任何路径之前。-> 分享出去的供应商建了[供应商组](provider-groups.md)时,§1 的运行位置、§4.1 第 3 步的告知、§7.2 管理页、§7.4 用量-> 与 §9 安全不变量按该文调整(方案阶段,尚未实现)。+> 分享出去的供应商建了[供应商组](provider-groups.md)时,§1 的运行位置、§7.2 管理页、§7.4 用量+> 与 §9 安全不变量按该文调整:受邀者的任务按组分配与中转、运行中自动换电脑已实现(2026-10-10,P2b / P2c),+> 按组的用量(§7.4)在 P3。§4.1 第 3 步的告知不论有没有组都已改用该文 §8 的说法(2026-10-10)。## 1. 定位@@ -73,8 +74,9 @@3. **受邀者确认并申请**:Cindy 弹窗展示:- 分享者是谁(见 §6 身份展示);- 分享的是什么:供应商名称与所在电脑;- - 运行方式:Agent 在分享者的电脑上运行,受邀者的文件和命令仍在自己电脑上执行;- - 隐私:对话内容和 Agent 读到的文件内容会经过并保存在分享者的电脑上;+ - 运行方式:Agent 在分享者的电脑或分享者安排的其他电脑上运行(分享者可能建了[供应商组](provider-groups.md);+ 不论有没有组都这样写,之后建组不需要再提醒),受邀者的文件和命令仍在自己电脑上执行;+ - 隐私:对话内容和 Agent 读到的文件内容会经过分享者的电脑,并保存在实际运行任务的那台电脑上;- 身份:受邀者的昵称和头像会展示给分享者,不展示邮箱、手机号等其他信息。受邀者点「发送申请」后才真正提交;取消不提交,链接在 5 分钟有效期内保持未使用。@@ -236,8 +238,9 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):的内网,对受邀者关闭;联网搜索由模型服务方执行,保持可用。同账号远程供应商不受影响。实现:Claude Code 用 SDK `tools` 白名单,Codex 按功能清单关闭白名单之外的功能,Pi 只放行 Cindy扩展注册的工具(`packages/maker-core/src/agents/{shared/device-hosted,codex/device-hosted-guest,pi/cindy-bridge-source}.ts`)。-6. **受邀者隐私**:申请前明确告知对话与文件内容会经过并保存在分享者电脑上;分享被删除或受邀者- 退出后,分享者电脑清理该受邀者的 Agent 会话记录与镜像文件。+6. **受邀者隐私**:申请前明确告知对话与文件内容会经过分享者的电脑,并保存在实际运行任务的那台电脑上+ (有供应商组时可能是分享者安排的其他电脑);分享被删除或受邀者退出后,分享者电脑清理该受邀者的 Agent+ 会话记录与镜像文件,并请接过它任务的组内电脑清理([供应商组](provider-groups.md) §4)。7. **受邀者自己的权限**:受邀者电脑上的文件与命令操作仍由受邀者自己的任务权限档把关,分享不放宽受邀者本机的任何限制。diff --git a/packages/device-link/src/remoteAgent.ts b/packages/device-link/src/remoteAgent.tsindex 2129671829..8068c0d522 100644--- a/packages/device-link/src/remoteAgent.ts+++ b/packages/device-link/src/remoteAgent.ts@@ -162,9 +162,15 @@ export type RemoteAgentRequest =*/| { op: 'forget'; relay: string };-/** 供应商组为受邀者取的不透明键(组所在电脑按受邀者派生,不含身份信息)。 */+/** 供应商组为受邀者取的不透明键(组所在电脑按受邀者派生,不含身份信息);「需要换一台」凭证同一格式。 */export const REMOTE_AGENT_RELAY_KEY_PATTERN = /^[A-Za-z0-9_-]{16,64}$/;+/**+ * 供应商组「需要换一台」:组所在电脑在中转任务的事件流里发出的状态键,值是一次性凭证。只发给打开任务时+ * 声明了 acceptsGroupSwitch 的控制端,排在那次错误前面;控制端取走凭证、不并入任务状态。+ */+export const REMOTE_AGENT_GROUP_SWITCH_STATE_KEY = 'providerGroupSwitch';+/** 与 maker-core AgentSessionTeardownReason 同值。 */export const REMOTE_AGENT_TEARDOWN_REASONS = ['navigation', 'account-boundary', 'app-quit'] as const;export type RemoteAgentTeardownReason = (typeof REMOTE_AGENT_TEARDOWN_REASONS)[number];