Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(provider-group): 正用着组那一项的老任务也纳入组,撞上限时自动换电脑
Lizi48fa1958e4ab
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 13e3b53f4a..803dd9ff11 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -27,7 +27,9 @@ import { readDeviceProviderViews } from '../remote-agent/controller/deviceCataloimport { checkDeviceRoute } from '../remote-agent/controller/deviceRouteCheck.js';import { isProviderShareAgentDeviceId } from '../../shared/providerShare.js';import {+ isProviderGroupReleased,listRemoteProviderGroupBindings,+ markProviderGroupReleased,readProviderGroupBinding,writeProviderGroupBinding,} from '../provider-group/bindings.js';@@ -9483,6 +9485,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)localDeviceId: getSelfDeviceId,readBinding: readProviderGroupBinding,writeBinding: (sessionId, binding) => writeProviderGroupBinding(sessionId, binding),+ isReleased: isProviderGroupReleased,+ markReleased: (sessionId, group) => markProviderGroupReleased(sessionId, group),readSessionRow: readProviderGroupSessionRow,resolveImplicitProvider: resolveProviderGroupImplicitProvider,persistRoute: persistProviderGroupRoute,diff --git a/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.ts b/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.tsindex 87297a7cd3..ed40ca48cc 100644--- a/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.ts@@ -7,11 +7,12 @@import { describe, expect, it, vi } from 'vitest';import type { ProviderGroupConfig, ProviderGroupMember, ProviderGroupView } from '../../../shared/providerGroup';-import type { ProviderGroupBinding } from '../bindings';+import type { ProviderGroupBinding, ProviderGroupRef } from '../bindings';import type { ProviderGroupDirectory } from '../directory';import { createProviderGroupRouter } from '../router';import {createProviderGroupService,+ PROVIDER_GROUP_ADOPT_TIMEOUT_MS,PROVIDER_GROUP_BEFORE_SEND_TIMEOUT_MS,PROVIDER_GROUP_UNAVAILABLE_ERROR,type ProviderGroupRemoteGroups,@@ -44,6 +45,8 @@ function harness(options: {: { strategy: 'least', autoSwitch: true, members: [OWNER_LOCAL, SELF, STUDIO, SHARED] };const picks = [...(options.picks ?? [STUDIO])];const bindings = new Map<string, ProviderGroupBinding>();+ /** 因组内电脑被移出或组被删除而解除过的任务 → 那个组。 */+ const released = new Map<string, ProviderGroupRef>();const directory: ProviderGroupDirectory = {resolveMembers: async () => [],listCandidates: async () => [],@@ -105,6 +108,13 @@ function harness(options: {if (binding) bindings.set(id, { providerId: binding.providerId, memberKey: binding.memberKey, ...(binding.groupDeviceId ? { groupDeviceId: binding.groupDeviceId } : {}), at: 1 });else bindings.delete(id);}),+ isReleased: (id: string, group: ProviderGroupRef) => {+ const entry = released.get(id);+ return entry?.providerId === group.providerId && (entry.groupDeviceId ?? null) === (group.groupDeviceId ?? null);+ },+ markReleased: vi.fn(async (id: string, group: ProviderGroupRef) => {+ released.set(id, group);+ }),readSessionRow: vi.fn(async () => row),resolveImplicitProvider: vi.fn(async () => 'anthropic'),persistRoute: vi.fn(async (_id: string, route: { agentDeviceId: string | null; providerId: string | null }) => {@@ -128,7 +138,7 @@ function harness(options: {now: () => 1_000,log: { info: vi.fn(), warn: vi.fn() },} satisfies ProviderGroupServiceDeps;- return { service: createProviderGroupService(deps), deps, remote, row, bindings };+ return { service: createProviderGroupService(deps), deps, remote, row, bindings, released };}async function flush() {@@ -178,11 +188,58 @@ describe('assigning through a group on another computer', () => {await expect(h.service.assignBeforeStart(START)).rejects.toThrow(PROVIDER_GROUP_UNAVAILABLE_ERROR);});- it('never moves a task that already ran on the group computer, and leaves shares alone', async () => {- for (const row of [{ sdkSessionId: 'native-1' }, { agentDeviceId: 'share:s9' }, { providerId: null }]) {+ it('takes in a task that already ran on the group computer without moving it, and leaves shares alone', async () => {+ const ran = harness({ row: { sdkSessionId: 'native-1' } });+ expect(await ran.service.assignBeforeStart(START)).toBeNull();+ expect(ran.remote.pick).not.toHaveBeenCalled();+ expect(ran.deps.persistRoute).not.toHaveBeenCalled();+ expect(ran.bindings.get('s1')).toMatchObject({ providerId: 'anthropic', memberKey: OWNER_LOCAL.key, groupDeviceId: OWNER });++ // 运行过之后才换到组那一项的老任务(换过去后还没有原生会话,但已经有过回复)也一样。+ const switchedIn = harness();+ switchedIn.deps.hasAssistantHistory.mockResolvedValue(true);+ expect(await switchedIn.service.assignBeforeStart(START)).toBeNull();+ expect(switchedIn.remote.pick).not.toHaveBeenCalled();+ expect(switchedIn.bindings.get('s1')).toMatchObject({ memberKey: OWNER_LOCAL.key, groupDeviceId: OWNER });++ for (const row of [{ agentDeviceId: 'share:s9' }, { providerId: null }]) {const h = harness({ row });expect(await h.service.assignBeforeStart(START)).toBeNull();expect(h.remote.pick).not.toHaveBeenCalled();+ expect(h.bindings.size).toBe(0);+ }+ });++ it('leaves an old task alone when the computer has no group, cannot answer, or the task was released from it', async () => {+ for (const options of [{ config: null }, { config: undefined }]) {+ const h = harness({ ...options, row: { sdkSessionId: 'native-1' } });+ expect(await h.service.assignBeforeStart(START)).toBeNull();+ expect(h.bindings.size).toBe(0);+ }+ const released = harness({ row: { sdkSessionId: 'native-1' } });+ released.released.set('s1', { providerId: 'anthropic', groupDeviceId: OWNER });+ expect(await released.service.assignBeforeStart(START)).toBeNull();+ expect(released.bindings.size).toBe(0);+ expect(released.remote.readGroup).not.toHaveBeenCalled();+ // 解除的是别的组:不影响这个组。+ const otherGroup = harness({ row: { sdkSessionId: 'native-1' } });+ otherGroup.released.set('s1', { providerId: 'anthropic', groupDeviceId: null });+ await otherGroup.service.assignBeforeStart(START);+ expect(otherGroup.bindings.get('s1')).toMatchObject({ groupDeviceId: OWNER });+ });++ it('starts as usual without waiting when the group computer does not answer in time for an old task', async () => {+ vi.useFakeTimers();+ try {+ const h = harness({ row: { sdkSessionId: 'native-1' } });+ h.remote.readGroup.mockImplementation(() => new Promise(() => undefined));+ const done = vi.fn();+ void h.service.assignBeforeStart(START).then(done);+ await vi.advanceTimersByTimeAsync(PROVIDER_GROUP_ADOPT_TIMEOUT_MS);+ expect(done).toHaveBeenCalledWith(null);+ expect(h.bindings.size).toBe(0);+ } finally {+ vi.useRealTimers();}});@@ -264,6 +321,15 @@ describe('switching computers within a group on another computer', () => {expect(failing.bindings.has('s1')).toBe(false);expect(failing.deps.switchAgentLocation).not.toHaveBeenCalled();expect(failing.deps.fallback).toHaveBeenCalled();+ expect(failing.released.get('s1')).toEqual({ providerId: 'anthropic', groupDeviceId: OWNER });+ // 重建同一个组后,即使任务挪到了组那一项,也不再自动纳入(§9.4)。+ failing.remote.readGroup.mockResolvedValue({ strategy: 'least', autoSwitch: true, members: [OWNER_LOCAL, STUDIO] });+ Object.assign(failing.row, { agentDeviceId: OWNER, providerId: 'anthropic' });+ failing.service.onTurnError('s1', { sdkError: 'rate_limit' }, 4);+ await flush();+ expect(failing.bindings.has('s1')).toBe(false);+ expect(failing.deps.switchAgentLocation).not.toHaveBeenCalled();+ expect(failing.deps.fallback).toHaveBeenCalledTimes(2);const sending = bound({ config: null });await sending.service.beforeSend('s1');@@ -294,6 +360,18 @@ describe('switching computers within a group on another computer', () => {expect(h.bindings.has('s1')).toBe(false);expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();expect(h.deps.fallback).toHaveBeenCalled();+ // 挪到组外不算解除:挪回组那一项时照常纳入。+ expect(h.released.has('s1')).toBe(false);+ });++ it('does not take a task back once its computer was removed from the group', async () => {+ const h = bound({ config: { strategy: 'least', autoSwitch: true, members: [OWNER_LOCAL, SELF] } });+ h.service.onTurnError('s1', { sdkError: 'rate_limit' }, 3);+ await flush();+ expect(h.bindings.has('s1')).toBe(false);+ expect(h.released.get('s1')).toEqual({ providerId: 'anthropic', groupDeviceId: OWNER });+ expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();+ expect(h.deps.fallback).toHaveBeenCalled();});it('moves the task before sending when the group computer says its computer is offline', async () => {@@ -309,3 +387,46 @@ describe('switching computers within a group on another computer', () => {expect(healthy.deps.switchAgentLocation).not.toHaveBeenCalled();});});++describe('old tasks already running on the group computer', () => {+ it('takes the task in when it hits the usage limit there, then moves it and continues', async () => {+ const h = harness({ row: { sdkSessionId: 'native-1' }, picks: [STUDIO] });+ h.service.onTurnError('s1', { sdkError: 'rate_limit' }, 3);+ await flush();+ expect(h.remote.cool).toHaveBeenCalledWith(OWNER, { providerId: 'anthropic', memberKey: OWNER_LOCAL.key, cause: 'usage-limit', resetAt: 5_000 });+ expect(h.deps.switchAgentLocation).toHaveBeenCalledWith(+ 's1',+ expect.objectContaining({ agentDeviceId: 'studio', providerId: STUDIO.providerId }),+ expect.anything(),+ );+ expect(h.deps.continueSession).toHaveBeenCalledWith('s1', 7, expect.objectContaining({+ agentSwitch: { from: 'Mac Mini', to: 'Studio', cause: 'usage-limit' },+ }));+ expect(h.bindings.get('s1')).toMatchObject({ memberKey: STUDIO.key, groupDeviceId: OWNER });+ expect(h.deps.fallback).not.toHaveBeenCalled();+ });++ it('hands the error back when the task is not on the group, was released, or is not eligible', async () => {+ const noGroup = harness({ config: null, row: { sdkSessionId: 'native-1' } });+ const released = harness({ row: { sdkSessionId: 'native-1' } });+ released.released.set('s1', { providerId: 'anthropic', groupDeviceId: OWNER });+ const ineligible = harness({ row: { sdkSessionId: 'native-1' } });+ ineligible.deps.isFailoverEligible.mockResolvedValue(false);+ for (const h of [noGroup, released, ineligible]) {+ h.service.onTurnError('s1', { sdkError: 'rate_limit' }, 3);+ await flush();+ expect(h.bindings.size).toBe(0);+ expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();+ expect(h.deps.fallback).toHaveBeenCalledWith('s1', { sdkError: 'rate_limit' }, 3);+ }+ });++ it('does not take the task in for failures any computer would hit', async () => {+ const h = harness({ row: { sdkSessionId: 'native-1' } });+ h.service.onTurnError('s1', { message: 'prompt is too long', sdkError: 'invalid_request' }, 3);+ await flush();+ expect(h.remote.readGroup).not.toHaveBeenCalled();+ expect(h.bindings.size).toBe(0);+ expect(h.deps.fallback).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/main/provider-group/__tests__/service.test.ts b/apps/desktop/src/main/provider-group/__tests__/service.test.tsindex 07417ef4dc..f0ae7da2a6 100644--- a/apps/desktop/src/main/provider-group/__tests__/service.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/service.test.ts@@ -8,7 +8,7 @@ import type { ProviderView } from '@cindy/model-providers';import { describe, expect, it, vi } from 'vitest';import type { ProviderGroupConfig, ProviderGroupMember } from '../../../shared/providerGroup';-import type { ProviderGroupBinding } from '../bindings';+import type { ProviderGroupBinding, ProviderGroupRef } 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';@@ -59,6 +59,8 @@ function harness(options: {};const offline = new Set(options.offline ?? []);const bindings = new Map<string, ProviderGroupBinding>();+ /** 因组内电脑被移出或组被删除而解除过的任务 → 那个组。 */+ const released = new Map<string, ProviderGroupRef>();const directory: ProviderGroupDirectory = {async resolveMembers(_providerId, current) {return current.members.map((m): ResolvedProviderGroupMember => offline.has(m.key)@@ -100,6 +102,13 @@ function harness(options: {if (binding) bindings.set(id, { ...binding, at: now });else bindings.delete(id);}),+ isReleased: (id: string, group: ProviderGroupRef) => {+ const entry = released.get(id);+ return entry?.providerId === group.providerId && (entry.groupDeviceId ?? null) === (group.groupDeviceId ?? null);+ },+ markReleased: vi.fn(async (id: string, group: ProviderGroupRef) => {+ released.set(id, group);+ }),readSessionRow: vi.fn(async () => row),resolveImplicitProvider: vi.fn(async () => 'anthropic'),persistRoute: vi.fn(async (_id: string, route: { agentDeviceId: string | null; providerId: string | null }) => {@@ -124,7 +133,7 @@ function harness(options: {log: { info: vi.fn(), warn: vi.fn() },} satisfies ProviderGroupServiceDeps;const service = createProviderGroupService(deps);- return { service, deps, row, bindings, router, config, offline, advance: (ms: number) => { now += ms; } };+ return { service, deps, row, bindings, released, router, config, offline, advance: (ms: number) => { now += ms; } };}async function flush() {@@ -169,6 +178,14 @@ describe('assignBeforeStart', () => {expect(h.bindings.get('s1')?.memberKey).toBe('local');});+ it('does not take back a task released when this computer left the group or the group was deleted', async () => {+ const h = harness();+ h.deps.hasAssistantHistory.mockResolvedValue(true);+ h.released.set('s1', { providerId: 'anthropic', groupDeviceId: null });+ expect(await h.service.assignBeforeStart({ sessionId: 's1', agentKind: 'claude-code', model: MODEL })).toBeNull();+ expect(h.bindings.has('s1')).toBe(false);+ });+it('does nothing for providers without a group', async () => {const h = harness({ row: { providerId: 'openai' } });expect(await h.service.assignBeforeStart({ sessionId: 's1', agentKind: 'claude-code', model: MODEL })).toBeNull();@@ -208,6 +225,16 @@ describe('assignBeforeStart', () => {h.bindings.set('s1', { providerId: 'anthropic', memberKey: MINI.key, at: 1 });expect(await h.service.assignBeforeStart({ sessionId: 's1', agentKind: 'claude-code', model: MODEL })).toBeNull();expect(h.bindings.has('s1')).toBe(false);+ // 挪到组外不算解除:挪回组那一项时照常纳入。+ expect(h.released.size).toBe(0);+ });++ it('remembers a task whose computer was removed from the group, so it is not taken back', async () => {+ const h = harness({ members: [LOCAL, STUDIO], row: { agentDeviceId: 'mini', providerId: MINI.providerId, sdkSessionId: 'x' } });+ h.bindings.set('s1', { providerId: 'anthropic', memberKey: MINI.key, at: 1 });+ expect(await h.service.assignBeforeStart({ sessionId: 's1', agentKind: 'claude-code', model: MODEL })).toBeNull();+ expect(h.bindings.has('s1')).toBe(false);+ expect(h.released.get('s1')).toEqual({ providerId: 'anthropic', groupDeviceId: null });});});@@ -288,12 +315,43 @@ describe('onTurnError (automatic switch)', () => {expect(off.deps.fallback).toHaveBeenCalledTimes(1);});- it('leaves tasks that are not group-bound to the existing handling', async () => {- const h = harness();- h.service.onTurnError('s1', { sdkError: 'rate_limit' }, 1);+ it('leaves tasks that are not in any group to the existing handling', async () => {+ for (const row of [{ providerId: 'openai' }, { agentDeviceId: 'other', providerId: 'anthropic' }]) {+ const h = harness({ row });+ h.service.onTurnError('s1', { sdkError: 'rate_limit' }, 1);+ await flush();+ expect(h.deps.fallback).toHaveBeenCalledTimes(1);+ expect(h.deps.leaseRecovery).not.toHaveBeenCalled();+ expect(h.bindings.size).toBe(0);+ }+ });++ it('takes in a task that was already running here before the group existed, then moves it', async () => {+ const h = harness({ row: { sdkSessionId: 'native-1' } });+ h.service.onTurnError('s1', { sdkError: 'rate_limit' }, 7);await flush();- expect(h.deps.fallback).toHaveBeenCalledTimes(1);- expect(h.deps.leaseRecovery).not.toHaveBeenCalled();+ expect(h.router.coolingUntil('anthropic', 'local')).not.toBeNull();+ expect(h.deps.switchAgentLocation).toHaveBeenCalledWith(+ 's1',+ expect.objectContaining({ agentDeviceId: 'mini', providerId: MINI.providerId }),+ expect.anything(),+ );+ expect(h.bindings.get('s1')?.memberKey).toBe(MINI.key);+ expect(h.deps.fallback).not.toHaveBeenCalled();+ });++ it('does not take in a released or ineligible task when it fails', async () => {+ const released = harness({ row: { sdkSessionId: 'native-1' } });+ released.released.set('s1', { providerId: 'anthropic', groupDeviceId: null });+ const ineligible = harness({ row: { sdkSessionId: 'native-1' } });+ ineligible.deps.isFailoverEligible.mockResolvedValue(false);+ for (const h of [released, ineligible]) {+ h.service.onTurnError('s1', { sdkError: 'rate_limit' }, 1);+ await flush();+ expect(h.bindings.size).toBe(0);+ expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();+ expect(h.deps.fallback).toHaveBeenCalledTimes(1);+ }});it('does nothing when the user already took over the error', async () => {diff --git a/apps/desktop/src/main/provider-group/__tests__/stores.test.ts b/apps/desktop/src/main/provider-group/__tests__/stores.test.tsindex 531551506b..d53489b608 100644--- a/apps/desktop/src/main/provider-group/__tests__/stores.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/stores.test.ts@@ -93,6 +93,45 @@ describe('provider group bindings', () => {expect(bindings.readProviderGroupBinding('c')).not.toBeNull();});+ it('remembers, per group, the tasks released by removing a computer or deleting the group', async () => {+ await bindings.writeProviderGroupBinding('x1', { providerId: 'anthropic', memberKey: 'device:mini:x' }, 1);+ await bindings.writeProviderGroupBinding('x2', { providerId: 'anthropic', memberKey: 'local' }, 2);+ await bindings.pruneProviderGroupBindings('anthropic', new Set(['local']), 10);+ expect(bindings.isProviderGroupReleased('x1', { providerId: 'anthropic' })).toBe(true);+ expect(bindings.isProviderGroupReleased('x1', { providerId: 'anthropic', groupDeviceId: 'mini' })).toBe(false);+ expect(bindings.isProviderGroupReleased('x1', { providerId: 'openai' })).toBe(false);+ expect(bindings.isProviderGroupReleased('x2', { providerId: 'anthropic' })).toBe(false);++ await bindings.markProviderGroupReleased('x3', { providerId: 'anthropic', groupDeviceId: 'mini' }, 11);+ expect(bindings.isProviderGroupReleased('x3', { providerId: 'anthropic', groupDeviceId: 'mini' })).toBe(true);+ expect(bindings.isProviderGroupReleased('x3', { providerId: 'anthropic', groupDeviceId: null })).toBe(false);+ // 单独一个文件:旧版本只读绑定文件,读不到也改写不到它。+ expect(fs.existsSync(path.join(tmpDir, 'provider-group-released.json'))).toBe(true);++ // 由同一个组重新分配(例如清空后当作新任务)时作废;别的组的分配不影响。+ await bindings.writeProviderGroupBinding('x1', { providerId: 'openai', memberKey: 'local' }, 12);+ expect(bindings.isProviderGroupReleased('x1', { providerId: 'anthropic' })).toBe(true);+ await bindings.writeProviderGroupBinding('x1', { providerId: 'anthropic', memberKey: 'local' }, 13);+ expect(bindings.isProviderGroupReleased('x1', { providerId: 'anthropic' })).toBe(false);+ });++ it('keeps only well-formed release records', () => {+ expect(bindings.__testing.normalizeReleased({+ sessions: {+ a: { providerId: 'anthropic', at: 1 },+ b: { providerId: 'anthropic', groupDeviceId: 'mini', at: 2 },+ c: { providerId: 'bad id', at: 3 },+ d: { providerId: 'anthropic', groupDeviceId: 'bad id', at: 4 },+ 'e e': { providerId: 'anthropic', at: 5 },+ },+ })).toEqual({+ sessions: {+ a: { providerId: 'anthropic', at: 1 },+ b: { providerId: 'anthropic', groupDeviceId: 'mini', at: 2 },+ },+ });+ });+it('keeps bindings to a group on another computer in their own file, one group per task', async () => {await bindings.writeProviderGroupBinding('r1', { providerId: 'anthropic', memberKey: 'local', groupDeviceId: 'mini' }, 7);expect(bindings.readProviderGroupBinding('r1')).toEqual({ providerId: 'anthropic', memberKey: 'local', groupDeviceId: 'mini', at: 7 });diff --git a/apps/desktop/src/main/provider-group/bindings.ts b/apps/desktop/src/main/provider-group/bindings.tsindex ca58baea5e..e26974ac79 100644--- a/apps/desktop/src/main/provider-group/bindings.ts+++ b/apps/desktop/src/main/provider-group/bindings.ts@@ -8,6 +8,9 @@* 两份文件:本机的组(`provider-group-bindings.json`)与同账号另一台电脑上的组* (`provider-group-remote-bindings.json`,多记组所在电脑)。分开存放,降级到旧版本时旧版本只读得到* 本机的那份,不会把另一台电脑上的组误当成本机的同名组。+ *+ * 另记一份「因组内电脑被移出或组被删除而解除过」的任务(`provider-group-released.json`):没归过组、+ * 正用着组那一项的老任务会被纳入组(service.ts),这些任务不纳入(§9.4)。旧版本不读它,也不改写它。*/import { activeOwnerScopeKey, ownerScopedUserDataPath } from '../appSessionState.js';import { desktopMakerLogger } from '../maker-host/logger-adapter.js';@@ -29,6 +32,23 @@ interface BindingFile {sessions: Record<string, ProviderGroupBinding>;}+/** 哪个组:组所属的供应商,组在另一台电脑上时再加那台的设备 id(本机的组为 null)。 */+export interface ProviderGroupRef {+ providerId: string;+ groupDeviceId?: string | null;+}++/** 一个任务因组内电脑被移出或组被删除而解除了哪个组的绑定。 */+export interface ProviderGroupRelease {+ providerId: string;+ groupDeviceId?: string;+ at: number;+}++interface ReleaseFile {+ sessions: Record<string, ProviderGroupRelease>;+}+const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;const MEMBER_KEY_PATTERN = /^[A-Za-z0-9_.:-]{1,300}$/;const DEVICE_ID_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/;@@ -46,7 +66,17 @@ function normalizeBinding(raw: unknown, remote: boolean): ProviderGroupBinding |return { providerId: value.providerId, memberKey: value.memberKey, groupDeviceId: value.groupDeviceId, at };}-function prune(sessions: Record<string, ProviderGroupBinding>): Record<string, ProviderGroupBinding> {+function normalizeRelease(raw: unknown): ProviderGroupRelease | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const value = raw as Record<string, unknown>;+ if (!isProviderGroupProviderId(value.providerId)) return null;+ const at = typeof value.at === 'number' && Number.isFinite(value.at) && value.at > 0 ? value.at : 0;+ if (value.groupDeviceId === undefined) return { providerId: value.providerId, at };+ if (typeof value.groupDeviceId !== 'string' || !DEVICE_ID_PATTERN.test(value.groupDeviceId)) return null;+ return { providerId: value.providerId, groupDeviceId: value.groupDeviceId, at };+}++function prune<T extends { at: number }>(sessions: Record<string, T>): Record<string, T> {const entries = Object.entries(sessions);if (entries.length <= MAX_PROVIDER_GROUP_BINDINGS) return sessions;entries.sort((a, b) => b[1].at - a[1].at);@@ -68,6 +98,22 @@ function normalizeFile(raw: unknown, remote: boolean): BindingFile {const normalize = (raw: unknown) => normalizeFile(raw, false);const normalizeRemote = (raw: unknown) => normalizeFile(raw, true);+function normalizeReleased(raw: unknown): ReleaseFile {+ const sessions = (raw as Partial<ReleaseFile> | null)?.sessions;+ if (!sessions || typeof sessions !== 'object' || Array.isArray(sessions)) return { sessions: {} };+ const out: Record<string, ProviderGroupRelease> = {};+ for (const [sessionId, value] of Object.entries(sessions)) {+ if (!SESSION_ID_PATTERN.test(sessionId)) continue;+ const release = normalizeRelease(value);+ if (release) out[sessionId] = release;+ }+ return { sessions: prune(out) };+}++function sameGroup(release: ProviderGroupRelease, group: ProviderGroupRef): boolean {+ return release.providerId === group.providerId && (release.groupDeviceId ?? null) === (group.groupDeviceId ?? null);+}+const log = desktopMakerLogger.child('provider-group-bindings');const store = createOverrideSettingsFile<BindingFile>({filePath: () => ownerScopedUserDataPath('provider-group-bindings.json'),@@ -89,6 +135,16 @@ const remoteStore = createOverrideSettingsFile<BindingFile>({maxBytes: 2 * 1024 * 1024,logLoadedValue: false,});+const releasedStore = createOverrideSettingsFile<ReleaseFile>({+ filePath: () => ownerScopedUserDataPath('provider-group-released.json'),+ scopeKey: activeOwnerScopeKey,+ defaults: { sessions: {} },+ normalize: normalizeReleased,+ log,+ label: 'provider-group-released',+ maxBytes: 2 * 1024 * 1024,+ logLoadedValue: false,+});/** 这个任务的绑定(本机的组或另一台电脑上的组,至多一个)。 */export function readProviderGroupBinding(sessionId: string): ProviderGroupBinding | null {@@ -135,6 +191,44 @@ export async function writeProviderGroupBinding(if (binding && !normalized) throw new Error('Invalid provider group binding');await writeIn(remote ? remoteStore : store, sessionId, normalized);await writeIn(remote ? store : remoteStore, sessionId, null);+ // 重新由同一个组分配(例如清空后当作新任务):之前解除过的记录作废。+ const release = normalized ? releasedStore.read().sessions[sessionId] : undefined;+ if (normalized && release && sameGroup(release, normalized)) {+ await releasedStore.updateAtomic(({ value }) => {+ const current = value.sessions[sessionId];+ if (!current || !sameGroup(current, normalized)) return {};+ const sessions = { ...value.sessions };+ delete sessions[sessionId];+ return { sessions };+ });+ }+}++/** 这个任务曾因组内电脑被移出或这个组被删除而解除过这个组的绑定:不再自动纳入这个组(§9.4)。 */+export function isProviderGroupReleased(sessionId: string, group: ProviderGroupRef): boolean {+ if (!SESSION_ID_PATTERN.test(sessionId)) return false;+ const release = releasedStore.read().sessions[sessionId];+ return release !== undefined && sameGroup(release, group);+}++async function writeReleases(sessionIds: readonly string[], group: ProviderGroupRef, now: number): Promise<void> {+ const release = normalizeRelease({ ...group, groupDeviceId: group.groupDeviceId ?? undefined, at: now });+ const ids = sessionIds.filter((id) => SESSION_ID_PATTERN.test(id));+ if (!release || ids.length === 0) return;+ await releasedStore.updateAtomic(({ value }) => {+ const sessions = { ...value.sessions };+ for (const id of ids) sessions[id] = release;+ return { sessions: prune(sessions) };+ });+}++/** 记下这个任务因组内电脑被移出或组被删除而解除了这个组的绑定。 */+export async function markProviderGroupReleased(+ sessionId: string,+ group: ProviderGroupRef,+ now: number = Date.now(),+): Promise<void> {+ await writeReleases([sessionId], group, now);}/**@@ -145,18 +239,21 @@ export async function writeProviderGroupBinding(export async function pruneProviderGroupBindings(providerId: string,keepMemberKeys: ReadonlySet<string> | null,+ now: number = Date.now(),): Promise<void> {+ const released: string[] = [];await store.updateAtomic(({ value }) => {const sessions = { ...value.sessions };- let changed = false;+ released.length = 0;for (const [sessionId, binding] of Object.entries(sessions)) {if (binding.providerId !== providerId) continue;if (keepMemberKeys?.has(binding.memberKey)) continue;delete sessions[sessionId];- changed = true;+ released.push(sessionId);}- return changed ? { sessions } : {};+ return released.length > 0 ? { sessions } : {};});+ await writeReleases(released, { providerId }, now);}-export const __testing = { normalize, normalizeRemote, prune };+export const __testing = { normalize, normalizeRemote, normalizeReleased, prune };diff --git a/apps/desktop/src/main/provider-group/service.ts b/apps/desktop/src/main/provider-group/service.tsindex 789331ae52..a3c6ea6c57 100644--- a/apps/desktop/src/main/provider-group/service.ts+++ b/apps/desktop/src/main/provider-group/service.ts@@ -7,6 +7,9 @@* 同一轮每台最多试一次,全部失败才交回原有的报错 / 等额度重置流程。* 3. **发送前**:已归组的任务所在那台现在不能用时,先交接到下一台,这条消息直接发到新电脑。*+ * 没归过组、但正用着组那一项的老任务(建组前就在用,或运行过之后才换到组那一项)在启动 Agent 前纳入组,+ * 不挪动它;当时没纳入的(一直开着、或启动时问不到组所在电脑)出错时再补上,然后照常换电脑。+ ** 组可以在本机,也可以在同账号的另一台电脑上(§4「同账号直连」):任务选了另一台电脑的某个供应商、* 而那台把它建成了组时,选哪台由组所在电脑决定,这台电脑直接连到选中的那台运行;那台出问题时由* 这台电脑(任务所在、看得到错误、有对话记录)换电脑,并把需要冷却的电脑报告给组所在电脑。两种组共用@@ -30,7 +33,7 @@ import type {import { providerGroupMemberKey } from '../../shared/providerGroup.js';import { isProviderShareAgentDeviceId } from '../../shared/providerShare.js';import type { InterruptedTurnErrorSignals } from '../maker-ipc/interruptedTurnAutoResume.js';-import type { ProviderGroupBinding } from './bindings.js';+import type { ProviderGroupBinding, ProviderGroupRef } from './bindings.js';import type { ProviderGroupDirectory } from './directory.js';import type { ProviderGroupGuestSwitch } from './guestSwitch.js';import {@@ -123,6 +126,10 @@ export interface ProviderGroupServiceDeps {sessionId: string,binding: { providerId: string; memberKey: string; groupDeviceId?: string | null } | null,): Promise<void>;+ /** 这个任务曾因组内电脑被移出或这个组被删除而解除过这个组的绑定(§9.4):不再自动纳入这个组。 */+ isReleased(sessionId: string, group: ProviderGroupRef): boolean;+ /** 记下这个任务因组内电脑被移出或组被删除而解除了这个组的绑定。 */+ markReleased(sessionId: string, group: ProviderGroupRef): Promise<void>;readSessionRow(sessionId: string): Promise<ProviderGroupSessionRow | null>;/** 隐式来源(provider_id 为空)时本机实际会用的来源。 */resolveImplicitProvider(agentKind: AgentKind, model: string): Promise<string | null>;@@ -194,6 +201,9 @@ export interface ProviderGroupService {/** 发送前检查组内电脑状态的上限:读不到就照常发送,不让一台卡住的电脑拖慢每次发送。 */export const PROVIDER_GROUP_BEFORE_SEND_TIMEOUT_MS = 3_000;+/** 纳入老任务时问组所在电脑的上限:读不到就照常启动 / 交回原有处理,出错时再补。 */+export const PROVIDER_GROUP_ADOPT_TIMEOUT_MS = 3_000;+function errorText(error: unknown): string {return error instanceof Error ? error.message : typeof error === 'string' ? error : '';}@@ -373,6 +383,19 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Provreturn { providerId, memberKey, ...(source.ownerDeviceId ? { groupDeviceId: source.ownerDeviceId } : {}) };}+ function groupOf(source: GroupSource, providerId: string): ProviderGroupRef {+ return { providerId, groupDeviceId: source.ownerDeviceId };+ }++ /** 任务记录里 Agent 所在位置换成组里的键(组所在电脑视角),不看它还在不在组里;SSH 远端任务返回 null。 */+ async function locatedMemberKey(+ source: GroupSource,+ groupProviderId: string,+ row: ProviderGroupSessionRow,+ ): Promise<string | null> {+ return row.remoteHostId ? null : source.memberKeyOf(groupProviderId, row);+ }+/** 任务记录里 Agent 实际所在位置对应的组内电脑键;不在组里返回 null。 */async function actualMemberKey(source: GroupSource,@@ -380,8 +403,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Provconfig: ProviderGroupConfig,row: ProviderGroupSessionRow,): Promise<string | null> {- if (row.remoteHostId) return null;- const key = await source.memberKeyOf(groupProviderId, row);+ const key = await locatedMemberKey(source, groupProviderId, row);return key !== null && config.members.some((m) => m.key === key) ? key : null;}@@ -396,9 +418,13 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Provconfig: ProviderGroupConfig | null,row: ProviderGroupSessionRow,): Promise<ProviderGroupMember | null> {- const key = config ? await actualMemberKey(source, binding.providerId, config, row) : null;+ const located = await locatedMemberKey(source, binding.providerId, row);+ const key = located !== null && config?.members.some((m) => m.key === located) ? located : null;if (key === null) {await deps.writeBinding(sessionId, null);+ // 任务还在原来那台、那台却已被移出组(或组已删除):之后同一台重新加入、重建同一个组都不再纳入(§9.4)。+ // 用户把任务挪到组外不记:挪回组那一项时照常纳入。+ if (!config || located === binding.memberKey) await deps.markReleased(sessionId, groupOf(source, binding.providerId));return null;}if (key !== binding.memberKey) {@@ -455,11 +481,58 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov* 组所在电脑确认组已删除(读到了、没有这个组)时立即解除绑定,任务成为普通的(远程)任务——之后重建同一个组也不会* 恢复自动换电脑(§9.4)。读不到(undefined)的情况 loadBound 已经挡掉,绑定不动。*/- async function releaseDeletedGroup(sessionId: string): Promise<void> {+ async function releaseDeletedGroup(sessionId: string, group: ProviderGroupRef): Promise<void> {await deps.writeBinding(sessionId, null);+ await deps.markReleased(sessionId, group);deps.log.info('provider group: group no longer exists; released the task', { sessionId });}+ /** 把正用着组里某一项的任务纳入组(不挪动它);曾因组内电脑被移出或组被删除而解除过的不纳入(§9.4)。 */+ async function adopt(sessionId: string, source: GroupSource, groupProviderId: string, memberKey: string): Promise<boolean> {+ if (deps.isReleased(sessionId, groupOf(source, groupProviderId))) return false;+ await deps.writeBinding(sessionId, bindingFor(source, groupProviderId, memberKey));+ deps.log.info('provider group: took in a task already running in the group', {+ sessionId,+ groupProviderId,+ member: memberKey,+ remote: source.ownerDeviceId !== null,+ });+ return true;+ }++ /**+ * 还没归组、但正用着组那一项的老任务纳入组,不挪动它(§6):用着本机建了组的供应商,或用着同账号另一台电脑上+ * 建了组的那个供应商(在组所在电脑本身运行)。直接选组里某台电脑、分享来的供应商不算:用的不是组那一项(§4)。+ * 返回是否纳入。+ */+ async function adoptRunningTask(sessionId: string, row: ProviderGroupSessionRow): Promise<boolean> {+ if (row.remoteHostId) return false;+ if (!row.agentDeviceId) {+ const groupProviderId = row.providerId+ ?? (row.model ? await deps.resolveImplicitProvider(row.agentKind, row.model) : null);+ const config = groupProviderId ? deps.readGroup(groupProviderId) : null;+ if (!groupProviderId || !config?.members.some((m) => m.kind === 'local')) return false;+ return adopt(sessionId, localSource, groupProviderId, providerGroupMemberKey(null, groupProviderId));+ }+ if (!deps.remote || isProviderShareAgentDeviceId(row.agentDeviceId) || !row.providerId) return false;+ const source = remoteSource(row.agentDeviceId);+ const groupProviderId = row.providerId;+ // 先看本地记录,解除过的不再问组所在电脑。+ if (deps.isReleased(sessionId, groupOf(source, groupProviderId))) return false;+ const config = await source.readGroup(groupProviderId).catch(() => undefined);+ if (!config) return false;+ const key = await actualMemberKey(source, groupProviderId, config, row);+ return key !== null && adopt(sessionId, source, groupProviderId, key);+ }++ /** 出错时还没归组:老任务正用着组那一项时先纳入组,再照常换电脑(一直开着的老任务不用等重新打开)。 */+ async function adoptOnFailure(sessionId: string): Promise<boolean> {+ const row = await deps.readSessionRow(sessionId);+ if (!row?.model || row.remoteHostId || isProviderShareAgentDeviceId(row.agentDeviceId)) return false;+ if (!(await deps.isFailoverEligible(sessionId))) return false;+ return (await withTimeout(adoptRunningTask(sessionId, row), PROVIDER_GROUP_ADOPT_TIMEOUT_MS)) === true;+ }+/*** 登记一次进行中的换电脑:用户在途中接手(重试、发消息、换模型)或那次错误已不是当前状态时,之后的每一步都停手。* `handBack` 在不再换电脑时交回原有的报错与额度重置后自动继续;之前的交接若已关掉旧会话,换一个对当前状态@@ -497,12 +570,14 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Provasync 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);+ if (!deps.readBinding(sessionId) && !(await adoptOnFailure(sessionId))) {+ return guestFailover(sessionId, signals, token, cause);+ }const bound = await loadBound(sessionId);if (!bound) return false;const { binding, source, config } = bound;if (!config) {- await releaseDeletedGroup(sessionId);+ await releaseDeletedGroup(sessionId, groupOf(source, binding.providerId));return false;}if (!config.autoSwitch) return false;@@ -673,8 +748,12 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov): Promise<ProviderGroupStartContext | null> {const ownerDeviceId = row.agentDeviceId;if (!deps.remote || !ownerDeviceId || isProviderShareAgentDeviceId(ownerDeviceId) || !row.providerId) return null;- // 只给从没运行过的任务选电脑;已经在那台运行过的留在那台(原生会话在那里)。- if (row.sdkSessionId || (await deps.hasAssistantHistory(sessionId))) return null;+ // 只给从没运行过的任务选电脑;已经在那台运行过的留在那台(原生会话在那里),正用着组那一项时纳入组。+ // 问不到组所在电脑时照常启动,出错时再补。+ if (row.sdkSessionId || (await deps.hasAssistantHistory(sessionId))) {+ await withTimeout(adoptRunningTask(sessionId, row), PROVIDER_GROUP_ADOPT_TIMEOUT_MS);+ return null;+ }const source = remoteSource(ownerDeviceId);const groupProviderId = row.providerId;const config = await source.readGroup(groupProviderId).catch(() => undefined);@@ -740,14 +819,11 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Provconst groupProviderId = row.providerId ?? (await deps.resolveImplicitProvider(agentKind, model));const config = groupProviderId ? deps.readGroup(groupProviderId) : null;if (!groupProviderId || !config) return null;- // 已经运行过的任务(回退、清空等清掉了原生会话)不按策略挪走:留在本机并纳入组,之后出问题时+ // 已经运行过的任务(建组前就在用、回退或清空等清掉了原生会话)不按策略挪走:留在本机并纳入组,之后出问题时// 照常自动换电脑。if (row.sdkSessionId || (await deps.hasAssistantHistory(sessionId))) {if (config.members.some((m) => m.kind === 'local')) {- await deps.writeBinding(sessionId, {- providerId: groupProviderId,- memberKey: providerGroupMemberKey(null, groupProviderId),- });+ await adopt(sessionId, localSource, groupProviderId, providerGroupMemberKey(null, groupProviderId));}return null;}@@ -782,7 +858,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Provconst config = await source.readGroup(context.groupProviderId).catch(() => undefined);// 启动阶段同样:组所在电脑确认组已删除时立即解除绑定,读不到不动。if (config === null) {- await releaseDeletedGroup(context.sessionId);+ await releaseDeletedGroup(context.sessionId, groupOf(source, context.groupProviderId));return null;}if (!config?.autoSwitch) return null;@@ -830,7 +906,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Provif (!bound) return;const { binding, source, config } = bound;if (!config) {- await releaseDeletedGroup(sessionId);+ await releaseDeletedGroup(sessionId, groupOf(source, binding.providerId));return;}if (!config.autoSwitch) return;diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 6575b57358..bb022e7a03 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -762,7 +762,9 @@ B 上的 Worker 是一条普通任务,`sessions.orca_remote_lead`(migration 01- **远程 Agent open 载荷新增可选 `groupAssigned: true`**(`remote-agent/wire.ts`):任务由供应商组分配到这台(本机的组或另一台的组),这台直接运行、不再进入它自己的组(防转圈)。旧被控端解码时丢弃(它本来没有组)。- **本地数据**:C 上经另一台电脑的组分配的任务绑定存 `provider-group-remote-bindings.json`(按账号,与本机组的- `provider-group-bindings.json` 分开,降级后旧版本读不到它,不会误认成本机的同名组)。不改数据库与服务端。+ `provider-group-bindings.json` 分开,降级后旧版本读不到它,不会误认成本机的同名组)。因组内电脑被移出或组被删除而+ 解除过绑定的任务按组记在 `provider-group-released.json`(按账号,2026-10-10),老任务纳入组时据此跳过(provider-groups.md+ §6、§9.4);旧版本不读也不改写它,降级再升级后记录仍在。不改数据库与服务端。- 实现:`apps/desktop/src/main/provider-group/`(`remoteHandler.ts`、`remoteClient.ts`、`externalLoad.ts`、`leaseReporter.ts`、`service.ts` 的组来源);回归见同目录 `__tests__/remoteGroup.test.ts`、`remoteHandler.test.ts`、`leaseReporter.test.ts`,`device-link/__tests__/providerShareDispatch.test.ts`(受邀者拒绝与不泄露组摘要)。diff --git a/docs/product-rules/provider-groups.md b/docs/product-rules/provider-groups.mdindex 9eee268819..539233707a 100644--- a/docs/product-rules/provider-groups.md+++ b/docs/product-rules/provider-groups.md@@ -136,10 +136,18 @@- 任务第一次在组里运行时选定一台组内电脑,之后固定在这台:对话记录保存在那台电脑上。只有正常运行时才保持固定;那台电脑出问题时按下面的规则**自动换电脑**,不需要用户操作。- 正在正常运行的任务不会因为组策略变化或其他电脑空闲而迁移。-- 只给从没运行过的任务按策略选电脑。建组前就在本机运行过的任务、回退或清空后原生会话被清掉的任务,不按策略挪走:- 留在本机并纳入组,之后出问题时照常自动换电脑。+- 只给从没运行过的任务按策略选电脑。已经运行过、正用着组那一项的任务不按策略挪走:留在原处并纳入组,之后出问题时+ 照常自动换电脑(2026-10-10 用户要求:老任务也要生效)。包括:+ - 建组前就在用这个供应商的任务、回退或清空后原生会话被清掉的任务;+ - 运行过之后才在模型选择里换到组那一项的任务;+ - 同账号其他电脑上的老任务:用着另一台电脑上建了组的那个供应商(在组所在电脑本身运行),由任务所在的电脑问组所在电脑+ 确认它在组里。+ - 纳入的时机:启动 Agent 时(问组所在电脑最多等 3 秒,问不到就照常启动);当时没纳入的(一直开着没重新启动、+ 或启动时问不到)在因 §6.1 的原因失败时先纳入,再照常换电脑,所以已经开着的老任务点重试也会换。+ - 不纳入:直接选组里某台电脑或分享来的供应商的任务(用的不是组那一项,§4);因组内电脑被移出、或组被删除而解除过+ 这个组的任务(§9.4,任务所在的电脑按组记下,之后同一台重新加入、或重建同一个组也不纳入)。- 用户在模型选择里把任务挪到组外的电脑或换成别的供应商,任务即退出组:之后不再自动换电脑,也不把那台的失败- 记到组内电脑头上。挪到组里另一台时绑定跟着更新。+ 记到组内电脑头上。挪到组里另一台时绑定跟着更新;之后再挪回组那一项时按上一条重新纳入。### 6.1 自动换电脑