Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(provider-groups): bound shared status capability probes
MagicLizie853b5ebbe5e
diff --git a/apps/desktop/src/main/provider-group/__tests__/sharedStatus.test.ts b/apps/desktop/src/main/provider-group/__tests__/sharedStatus.test.tsindex 98be195d9c..7eddb4bfd4 100644--- a/apps/desktop/src/main/provider-group/__tests__/sharedStatus.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/sharedStatus.test.ts@@ -3,7 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import type { RemoteAgentCaps } from '@cindy/device-link';import type { ProviderGroupConfig, ProviderGroupMemberState, ProviderGroupView } from '../../../shared/providerGroup';import type { ProviderGroupOwnerScope } from '../runtime';-import { createGuestSupportReader, readSharedGroupStatus, SHARED_GROUP_STATUS_TIMEOUT_MS } from '../sharedStatus';+import { createGuestSupportReader, readSharedGroupStatus, SHARED_GROUP_STATUS_TIMEOUT_MS, type SharedGroupStatusDeps } from '../sharedStatus';function setup(states: ProviderGroupMemberState[] = ['available', 'full', 'cooling', 'offline', 'paused', 'unavailable']) {let current = true;@@ -21,7 +21,7 @@ function setup(states: ProviderGroupMemberState[] = ['available', 'full', 'cooli})),};const router = { view: vi.fn(async () => view) };- const readCaps = vi.fn(async () => ({ virtualWorkspace: true, guestRelay: true }) as RemoteAgentCaps);+ const readCaps = vi.fn<SharedGroupStatusDeps['readCaps']>(async () => ({ virtualWorkspace: true, guestRelay: true }) as RemoteAgentCaps);const isIncapable = vi.fn(() => false);const deps = {scope: () => ({ router, isCurrent: () => current }) as unknown as ProviderGroupOwnerScope,@@ -38,7 +38,7 @@ function setup(states: ProviderGroupMemberState[] = ['available', 'full', 'cooliafterEach(() => vi.useRealTimers());describe('anonymous shared group status', () => {- it('coalesces capability reads per computer without caching across detail refreshes', async () => {+ it('coalesces capability reads per computer within an explicitly created reader', async () => {const env = setup(['available', 'available']);const member = env.view.config!.members[1];const read = createGuestSupportReader(env.readCaps);@@ -56,7 +56,139 @@ describe('anonymous shared group status', () => {expect(env.readCaps).toHaveBeenCalledTimes(1);});+ it('bounds capability probes for 512 members and shares them across concurrent refreshes', async () => {+ vi.useFakeTimers();+ const env = setup(Array.from({ length: 512 }, () => 'available'));+ let active = 0;+ let peak = 0;+ env.readCaps.mockImplementation(() => new Promise((resolve) => {+ active += 1;+ peak = Math.max(peak, active);+ setTimeout(() => {+ active -= 1;+ resolve({ virtualWorkspace: true, guestRelay: true } as RemoteAgentCaps);+ }, 1);+ }));+ const first = readSharedGroupStatus(env.deps, 'anthropic');+ const second = readSharedGroupStatus({+ ...env.deps, readCaps: (member) => env.deps.readCaps(member),+ }, 'anthropic');+ await vi.advanceTimersByTimeAsync(0);+ expect(env.readCaps).toHaveBeenCalledTimes(4);+ await vi.advanceTimersByTimeAsync(512);+ const expected = Array.from({ length: 512 }, (_, index) => index === 1 ? 'busy' : 'available');+ expect(await first).toEqual(expected);+ expect(await second).toEqual(expected);+ expect(peak).toBe(4);+ expect(active).toBe(0);+ expect(env.readCaps).toHaveBeenCalledTimes(511);+ });++ it('expires queued probes without releasing physical slots or repeating timed-out requests', async () => {+ vi.useFakeTimers();+ const env = setup(Array.from({ length: 512 }, () => 'available'));+ const finish: Array<(caps: RemoteAgentCaps) => void> = [];+ env.readCaps.mockImplementation(() => new Promise((resolve) => { finish.push(resolve); }));+ const first = readSharedGroupStatus(env.deps, 'anthropic');+ await vi.advanceTimersByTimeAsync(SHARED_GROUP_STATUS_TIMEOUT_MS);+ expect(await first).toEqual(['available', ...Array.from({ length: 511 }, () => 'unknown')]);+ expect(env.readCaps).toHaveBeenCalledTimes(4);++ await vi.advanceTimersByTimeAsync(15_000 - SHARED_GROUP_STATUS_TIMEOUT_MS);+ const second = readSharedGroupStatus(env.deps, 'anthropic');+ await vi.advanceTimersByTimeAsync(SHARED_GROUP_STATUS_TIMEOUT_MS);+ expect(await second).toEqual(await first);+ expect(env.readCaps).toHaveBeenCalledTimes(4);++ for (const resolve of finish) resolve({ virtualWorkspace: true, guestRelay: true } as RemoteAgentCaps);+ await vi.advanceTimersByTimeAsync(0);+ expect(env.readCaps).toHaveBeenCalledTimes(4);+ const third = readSharedGroupStatus(env.deps, 'anthropic');+ await vi.advanceTimersByTimeAsync(SHARED_GROUP_STATUS_TIMEOUT_MS);+ expect((await third)?.slice(0, 6)).toEqual(['available', 'busy', 'available', 'available', 'available', 'unknown']);+ expect(env.readCaps).toHaveBeenCalledTimes(8);+ expect(new Set(env.readCaps.mock.calls.map(([member]) => member.agentDeviceId)).size).toBe(8);+ });++ it('reuses completed capabilities for 15 seconds without caching live group states', async () => {+ vi.useFakeTimers();+ const env = setup(['available', 'available']);+ expect(await readSharedGroupStatus(env.deps, 'anthropic')).toEqual(['available', 'busy']);+ env.view.members[1].running = 0;+ env.readCaps.mockResolvedValue({ virtualWorkspace: true } as RemoteAgentCaps);+ await vi.advanceTimersByTimeAsync(14_999);+ expect(await readSharedGroupStatus(env.deps, 'anthropic')).toEqual(['available', 'available']);+ expect(env.readCaps).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1);+ expect(await readSharedGroupStatus(env.deps, 'anthropic')).toEqual(['available', 'needs-update']);+ expect(env.readCaps).toHaveBeenCalledTimes(2);+ });++ it('does not dispatch expired queued probes before their timeout callbacks run', async () => {+ vi.useFakeTimers();+ const env = setup(Array.from({ length: 10 }, () => 'available'));+ const finish: Array<(caps: RemoteAgentCaps) => void> = [];+ env.readCaps.mockImplementation(() => new Promise((resolve) => { finish.push(resolve); }));+ const result = readSharedGroupStatus(env.deps, 'anthropic');+ await vi.advanceTimersByTimeAsync(0);+ vi.setSystemTime(Date.now() + SHARED_GROUP_STATUS_TIMEOUT_MS);+ for (const resolve of finish) resolve({ virtualWorkspace: true, guestRelay: true } as RemoteAgentCaps);+ await vi.advanceTimersByTimeAsync(0);+ expect(env.readCaps).toHaveBeenCalledTimes(4);+ expect((await result)?.slice(0, 6)).toEqual(['available', 'busy', 'available', 'available', 'available', 'unknown']);+ });++ it.each(['throw', 'reject'])('releases physical slots after a capability %s', async (failure) => {+ vi.useFakeTimers();+ const env = setup(Array.from({ length: 10 }, () => 'available'));+ env.readCaps.mockImplementation(() => {+ if (failure === 'throw') throw new Error('Unavailable');+ return Promise.reject(new Error('Unavailable'));+ });+ expect(await readSharedGroupStatus(env.deps, 'anthropic')).toEqual([+ 'available', ...Array.from({ length: 9 }, () => 'unknown'),+ ]);+ expect(env.readCaps).toHaveBeenCalledTimes(9);+ env.readCaps.mockResolvedValue({ virtualWorkspace: true, guestRelay: true } as RemoteAgentCaps);+ await vi.advanceTimersByTimeAsync(15_000);+ expect(await readSharedGroupStatus(env.deps, 'anthropic')).toEqual([+ 'available', 'busy', ...Array.from({ length: 8 }, () => 'available'),+ ]);+ expect(env.readCaps).toHaveBeenCalledTimes(18);+ });++ it('does not start queued probes after the owner changes', async () => {+ vi.useFakeTimers();+ const env = setup(Array.from({ length: 10 }, () => 'available'));+ const finish: Array<(caps: RemoteAgentCaps) => void> = [];+ env.readCaps.mockImplementation(() => new Promise((resolve) => { finish.push(resolve); }));+ const result = readSharedGroupStatus(env.deps, 'anthropic');+ await vi.advanceTimersByTimeAsync(0);+ expect(env.readCaps).toHaveBeenCalledTimes(4);+ env.changeOwner();+ for (const resolve of finish) resolve({ virtualWorkspace: true, guestRelay: true } as RemoteAgentCaps);+ await vi.advanceTimersByTimeAsync(0);+ expect(await result).toBeNull();+ expect(env.readCaps).toHaveBeenCalledTimes(4);+ });++ it('isolates pending and cached capabilities between owner runtimes', async () => {+ vi.useFakeTimers();+ const previous = setup(['available', 'available']);+ previous.readCaps.mockImplementation(() => new Promise(() => {}));+ const stale = readSharedGroupStatus(previous.deps, 'anthropic');+ await vi.advanceTimersByTimeAsync(0);+ previous.changeOwner();+ const current = setup(['available', 'available']);+ expect(await readSharedGroupStatus(current.deps, 'anthropic')).toEqual(['available', 'busy']);+ expect(current.readCaps).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(SHARED_GROUP_STATUS_TIMEOUT_MS);+ expect(await stale).toBeNull();+ expect(previous.readCaps).toHaveBeenCalledTimes(1);+ });+it('checks guest compatibility even when the owner can use the computer', async () => {+ vi.useFakeTimers();const env = setup(['available', 'available']);env.readCaps.mockResolvedValue({ virtualWorkspace: true } as RemoteAgentCaps);expect(await readSharedGroupStatus(env.deps, 'anthropic')).toEqual(['available', 'needs-update']);@@ -64,6 +196,7 @@ describe('anonymous shared group status', () => {env.view.config!.members[1].kind = 'share';expect(await readSharedGroupStatus(env.deps, 'anthropic')).toEqual(['available', 'busy']);env.readCaps.mockResolvedValue({ guestRelay: true } as RemoteAgentCaps);+ await vi.advanceTimersByTimeAsync(15_000);expect(await readSharedGroupStatus(env.deps, 'anthropic')).toEqual(['available', 'needs-update']);});diff --git a/apps/desktop/src/main/provider-group/sharedStatus.ts b/apps/desktop/src/main/provider-group/sharedStatus.tsindex 4a46f7f4d3..30c7ee4774 100644--- a/apps/desktop/src/main/provider-group/sharedStatus.ts+++ b/apps/desktop/src/main/provider-group/sharedStatus.ts@@ -5,6 +5,8 @@ import type { ProviderGroupConfig, ProviderGroupGuestSupport, ProviderGroupMembeimport type { ProviderGroupOwnerScope } from './runtime.js';export const SHARED_GROUP_STATUS_TIMEOUT_MS = 3_000;+export const SHARED_GROUP_STATUS_CAPS_CONCURRENCY = 4;+export const SHARED_GROUP_STATUS_CAPS_CACHE_MS = 15_000;export interface SharedGroupStatusDeps {scope(): ProviderGroupOwnerScope;@@ -25,17 +27,59 @@ async function readWithin<T>(read: () => Promise<T>): Promise<T | null> {}}-/** 一次详情读取内按电脑合并能力查询;沿用真正接收分享任务时的能力条件。 */+const sharedSupportReaders = new WeakMap<ProviderGroupOwnerScope['router'], ReturnType<typeof createGuestSupportReader>>();++/** 按电脑合并有界能力探测,保留物理在途槽与短缓存;沿用真正接收分享任务时的能力条件。 */export function createGuestSupportReader(readCaps: SharedGroupStatusDeps['readCaps']) {- const caps = new Map<string, Promise<RemoteAgentCaps | null>>();+ const caps = new Map<string, { promise: Promise<RemoteAgentCaps | null>; expiresAt: number }>();+ const queued = new Set<() => void>();+ let active = 0;+ function drain() {+ for (const start of queued) {+ if (active >= SHARED_GROUP_STATUS_CAPS_CONCURRENCY) break;+ start();+ }+ }return async (member: ProviderGroupMember): Promise<ProviderGroupGuestSupport> => {if (!member.agentDeviceId) return 'supported';+ const now = Date.now();+ for (const [agentDeviceId, entry] of caps) {+ if (entry.expiresAt <= now) caps.delete(agentDeviceId);+ }let pending = caps.get(member.agentDeviceId);if (!pending) {- pending = readWithin(() => readCaps(member));+ const agentDeviceId = member.agentDeviceId;+ const promise = new Promise<RemoteAgentCaps | null>((resolve) => {+ const cancel = () => {+ queued.delete(start);+ clearTimeout(timer);+ caps.delete(agentDeviceId);+ resolve(null);+ };+ const start = () => {+ if (Date.now() >= now + SHARED_GROUP_STATUS_TIMEOUT_MS) {+ cancel();+ return;+ }+ queued.delete(start);+ clearTimeout(timer);+ active += 1;+ void Promise.resolve().then(() => readCaps(member)).catch(() => null).then(resolve).finally(() => {+ active -= 1;+ drain();+ });+ };+ const timer = setTimeout(cancel, SHARED_GROUP_STATUS_TIMEOUT_MS);+ queued.add(start);+ drain();+ });+ const entry = { promise, expiresAt: Infinity };+ void promise.then(() => { entry.expiresAt = Date.now() + SHARED_GROUP_STATUS_CAPS_CACHE_MS; });+ pending = entry;caps.set(member.agentDeviceId, pending);}- const capability = await pending;+ const promise = pending.promise;+ const capability = await readWithin(() => promise);if (!capability) return 'unknown';return capability.virtualWorkspace === true && (member.kind !== 'device' || capability.guestRelay === true)? 'supported' : 'needs-update';@@ -48,7 +92,11 @@ export async function readSharedGroupStatus(deps: SharedGroupStatusDeps, provideif (!config) return null;const view = await readWithin(() => scope.router.view(providerId));if (!scope.isCurrent()) return null;- const readSupport = createGuestSupportReader(deps.readCaps);+ const readSupport = sharedSupportReaders.get(scope.router) ?? createGuestSupportReader(async (member) => {+ if (!scope.isCurrent()) throw new Error('The account changed');+ return deps.readCaps(member);+ });+ sharedSupportReaders.set(scope.router, readSupport);const states = await Promise.all(config.members.map(async (member): Promise<ProviderShareGroupState> => {if (member.paused) return 'paused';const status = view?.members.find((item) => item.key === member.key);diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex e0c815b404..294e92218b 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -967,6 +967,9 @@ G 重新打开时换一台。G 与 O 之间新增四项可选内容,O 与 M- 由实际受邀者分配器读取组状态并按同一能力条件检查能否接分享任务,状态与能力读取各有 3 秒等待上限;超时/失败为未知,不改变分配与冷却。读取期间组设置或账号变化丢弃快照,分享撤销后不返回在途结果。`scrubSharedProvider` 在各跳按白名单重建数组;不合法的单项替换为 `unknown`,长度不符则不带字段。+- 匿名能力探测按当前账号运行期共用最多 4 个物理在途槽,同电脑跨刷新复用查询;等待超时不释放仍在途的槽,+ 未发出的排队查询 3 秒后取消。已结算的能力结果短存 15 秒,迟到结果可供下一次详情读取使用;不缓存组状态,+ 不跨账号复用或继续发出旧账号的排队查询,不改变底层 device-link 超时、重连或 wire 格式。- 兼容:旧分享者忽略查询选项,新受邀者显示未提供状态;旧受邀者不发选项、行为不变。手机沿用目录清洗但本期不增加状态入口。无组的供应商不带状态,不改服务器、relay、数据库或既有 channel 白名单。- 实现:`provider-group/sharedStatus.ts`、`guestRelay.ts`、`device-link/dispatch.ts`、diff --git a/docs/product-rules/provider-groups.md b/docs/product-rules/provider-groups.mdindex 16b787c1b2..570178af22 100644--- a/docs/product-rules/provider-groups.md+++ b/docs/product-rules/provider-groups.md@@ -419,6 +419,9 @@并反映受邀者分配器已记录的临时版本排除。满载仍能接任务,显示为忙碌;不承诺所有模型都能运行。- 详情在前台时约每 15 秒刷新,可手动刷新;关闭或切到后台暂停读取。刷新失败清掉旧的可用状态,提示刷新重试;旧分享者未提供状态时明确说明,不能猜成可用。未建组的分享保持原样。手机本期仍不增加组状态界面。+ - 匿名能力探测在当前账号的组之间共用最多 4 个物理在途槽,同一台电脑的在途查询跨刷新复用;等满 3 秒的+ 未发出查询直接取消,不在后台继续排队。已发出的慢查询直到真正结束才释放槽,能力结果短存 15 秒供下一次+ 刷新使用;组的忙闲、冷却与暂停状态仍每次现读,换账号不复用能力结果或发出旧账号的排队查询。- 查询只读,不分配任务、不改变冷却或版本排除,不开放同账号的组管理接口。实现见`apps/desktop/src/main/provider-group/sharedStatus.ts` 与`apps/desktop/src/renderer/features/provider-share/SharedProviderGroupStatus.tsx`,回归见各自同名测试。