Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 补全远控任务的分享供应商选择 (#6040)
DavidShenXD07de0809a06f
diff --git a/apps/desktop/src/main/device-link/__tests__/providerShareCrossRegion.test.ts b/apps/desktop/src/main/device-link/__tests__/providerShareCrossRegion.test.tsindex 88820fb896..3fd73857ef 100644--- a/apps/desktop/src/main/device-link/__tests__/providerShareCrossRegion.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/providerShareCrossRegion.test.ts@@ -85,13 +85,14 @@ import {crossRegionSendRequest,getCrossRegionReceived,getConfirmedCrossRegionReceivedRegions,+ isCrossRegionReceivedReady,refreshProviderShareCrossRegion,isCrossRegionProviderShareTarget,startProviderShareCrossRegion,stopProviderShareCrossRegion,} from '../providerShareCrossRegion';import { providerShareHostPeer } from '@cindy/device-link';-import { getReceivedSharesSnapshot, refreshReceivedShares, startProviderShareGuest, stopProviderShareGuest } from '../providerShareGuest';+import { getReceivedSharesSnapshot, isReceivedSharesReady, refreshReceivedShares, startProviderShareGuest, stopProviderShareGuest } from '../providerShareGuest';const share = {shareId: 'share-x', memberId: 'member-x', providerId: 'openai', providerLabel: 'OpenAI', hostDeviceId: 'owner-pc',@@ -336,6 +337,7 @@ describe('cross-region provider share', () => {await refreshReceivedShares('test');await refreshProviderShareCrossRegion('global');const snapshot = getReceivedSharesSnapshot();+ expect(isReceivedSharesReady()).toBe(false);expect(snapshot.confirmedRegions).toEqual([failed === 'local' ? 'global' : 'cn']);expect(snapshot.received.map((item) => item.shareId)).toEqual([failed === 'local' ? 'share-x' : 'share-local']);});@@ -354,6 +356,37 @@ describe('cross-region provider share', () => {stopProviderShareCrossRegion();expect(getConfirmedCrossRegionReceivedRegions()).toEqual([]);});++ it.each([true, false])('waits for a marked peer region before reporting received shares ready (empty=%s)', async (empty) => {+ expect(isCrossRegionReceivedReady()).toBe(true);+ startProviderShareGuest({ changed: vi.fn(), settled: vi.fn() }, { userDataDir: dir });+ expect(isReceivedSharesReady()).toBe(false);+ await refreshReceivedShares('test');+ expect(isReceivedSharesReady()).toBe(true);+ expect(state.calls).toEqual([]);+ stopProviderShareGuest();++ state.responses.set('/requests', { requestId: 'r1', status: 'pending', pairingCode: '0042', expiresAt: new Date().toISOString(), requestToken: TOKEN });+ await crossRegionSendRequest('global', TOKEN);+ const session = deferred<unknown>();+ state.responses.set('/session', session.promise);+ startProviderShareGuest({ changed: vi.fn(), settled: vi.fn() }, { userDataDir: dir });+ await refreshReceivedShares('test');+ expect(getReceivedSharesSnapshot().confirmedRegions).toEqual(['cn']);+ expect(isCrossRegionReceivedReady()).toBe(false);+ expect(isReceivedSharesReady()).toBe(false);+ session.resolve({+ credential: empty ? null : CREDENTIAL,+ expiresAt: empty ? null : new Date(Date.now() + 86_400_000).toISOString(),+ shares: empty ? [] : [share],+ });+ await refreshProviderShareCrossRegion('global');+ expect(isCrossRegionReceivedReady()).toBe(true);+ expect(isReceivedSharesReady()).toBe(true);+ expect(getReceivedSharesSnapshot().received.map((item) => item.shareId))+ .toEqual(empty ? ['share-local'] : ['share-local', 'share-x']);+ });+it('only accepts the two official regions', async () => {await expect(crossRegionOfIntent({ invitation: TOKEN, server: LOCAL }, LOCAL)).resolves.toBeNull();await expect(crossRegionOfIntent({ invitation: TOKEN, server: PEER }, LOCAL)).resolves.toBe('global');diff --git a/apps/desktop/src/main/device-link/__tests__/providerShareRuntime.test.ts b/apps/desktop/src/main/device-link/__tests__/providerShareRuntime.test.tsindex d3858b8e68..275370578c 100644--- a/apps/desktop/src/main/device-link/__tests__/providerShareRuntime.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/providerShareRuntime.test.ts@@ -18,11 +18,12 @@ const state = vi.hoisted(() => ({owned: [] as ProviderShareOwned[],received: [] as ProviderShareReceived[],receivedError: false,+ boundaryPending: false,}));vi.mock('../../appSessionState.js', () => ({activeOwnerScopeKey: () => state.scope,- isAppSessionBoundaryPending: () => false,+ isAppSessionBoundaryPending: () => state.boundaryPending,getActiveDataOwnerPushStamp: () => ({ dataOwnerId: state.scope, ownerGeneration: 1 }),}));vi.mock('../../authManager.js', () => ({@@ -108,6 +109,7 @@ beforeEach(() => {state.owned = [];state.received = [];state.receivedError = false;+ state.boundaryPending = false;vi.mocked(crossRegionLeave).mockReset().mockResolvedValue(false);vi.mocked(providerShareApi.leave).mockReset().mockImplementation(async (memberId) => {state.received = state.received.filter((entry) => entry.memberId !== memberId);@@ -233,6 +235,18 @@ describe('provider share guest routing', () => {hostOnline: true, hostCapable: true,});+ it.each(['account', 'logout', 'boundary', 'stopped'])('does not expose a loaded snapshot after %s invalidation', async (reason) => {+ state.received = [received('active')];+ startProviderShareGuest({ changed: vi.fn(), settled: vi.fn() });+ await refreshReceivedShares('test');+ expect(getReceivedSharesSnapshot().received).toEqual(state.received);+ if (reason === 'account') state.scope = 'cloud:other:2';+ else if (reason === 'logout') state.authenticated = false;+ else if (reason === 'boundary') state.boundaryPending = true;+ else stopProviderShareGuest();+ expect(getReceivedSharesSnapshot().received).toEqual([]);+ });+it('keeps task ids within the device id limit and maps them to the owner computer', async () => {expect(providerShareAgentDeviceId('share-1')).toBe('share:share-1');expect(() => providerShareAgentDeviceId('x'.repeat(123))).toThrow();diff --git a/apps/desktop/src/main/device-link/providerShareCrossRegion.ts b/apps/desktop/src/main/device-link/providerShareCrossRegion.tsindex e4a74f65b6..752960de99 100644--- a/apps/desktop/src/main/device-link/providerShareCrossRegion.ts+++ b/apps/desktop/src/main/device-link/providerShareCrossRegion.ts@@ -432,6 +432,17 @@ export function getConfirmedCrossRegionReceivedRegions(): Region[] {return rt && current(rt) ? [...rt.regions.values()].filter((state) => state.loaded).map((state) => state.region) : [];}+/** 被启用的跨区标记对应的首次分享列表是否已完成。 */+export function isCrossRegionReceivedReady(): boolean {+ const rt = runtime;+ // 未启动跨区 runtime 时,当前进程没有跨区分享需要等待。+ if (!rt) return true;+ if (!current(rt)) return false;+ const region = peerRegion();+ if (!readMarkers()[rt.account]?.includes(region)) return true;+ return rt.regions.get(region)?.loaded === true;+}+function stateForShare(shareId: string): RegionState | null {for (const state of runtime?.regions.values() ?? []) {if (state.shares.some((share) => share.shareId === shareId)) return state;diff --git a/apps/desktop/src/main/device-link/providerShareGuest.ts b/apps/desktop/src/main/device-link/providerShareGuest.tsindex a7533fd83b..a1bc81c173 100644--- a/apps/desktop/src/main/device-link/providerShareGuest.ts+++ b/apps/desktop/src/main/device-link/providerShareGuest.ts@@ -35,6 +35,7 @@ import {crossRegionWithdraw,getCrossRegionReceived,getConfirmedCrossRegionReceivedRegions,+ isCrossRegionReceivedReady,ensureCrossRegionReceivedForFavorites,refreshProviderShareCrossRegion,startProviderShareCrossRegion,@@ -256,6 +257,12 @@ export function getReceivedShares(): readonly ProviderShareReceived[] {return allReceived(runtime);}+/** 首次本区及已标记跨区收到分享的拉取已完成;空列表只有在此状态下才代表真实的空结果。 */+export function isReceivedSharesReady(): boolean {+ const rt = runtime;+ return !!rt && current(rt) && rt.fetchedAt > 0 && isCrossRegionReceivedReady();+}+export function getReceivedSharesSnapshot(recovery?: ProviderShareFavoriteRecovery): ProviderShareReceivedSnapshot {const rt = runtime;const valid = !!rt && current(rt);diff --git a/apps/desktop/src/main/device-link/providerShareRuntime.ts b/apps/desktop/src/main/device-link/providerShareRuntime.tsindex 6c0bfa9aca..cc83860f09 100644--- a/apps/desktop/src/main/device-link/providerShareRuntime.ts+++ b/apps/desktop/src/main/device-link/providerShareRuntime.ts@@ -52,6 +52,7 @@ import { fetchIdentityCard, providerShareApi, providerShareLinkFor, sha256Hex }import {findReceivedShare,getReceivedShares,+ isReceivedSharesReady,getReceivedSharesSnapshot,leaveProviderShare,previewProviderShare,@@ -449,17 +450,25 @@ const LINK_TTL_SAFETY_MS = 5_000;/*** 手机(同账号)经被控电脑读取这台电脑收到的分享与各自的模型目录。目录由分享者电脑过滤为* 分享的那个供应商;读不到(离线、已暂停)时 catalog 为 null,不影响其他分享。+ * `includeCatalog: false` 只返回分享元数据,供远控候选筛选使用,避免把完整目录读取的等待+ * 传播到分享发现。*/-async function receivedCatalogs(args: unknown[]): Promise<{ shares: ProviderShareReceivedCatalog[] }> {- if (!running) return { shares: [] };+async function receivedCatalogs(args: unknown[]): Promise<{ ready: boolean; shares: ProviderShareReceivedCatalog[] }> {+ if (!running) return { ready: false, shares: [] };const invoke = shareInvoke;const listArgs = Array.isArray(args) ? args.slice(0, 1) : [];- const shares = getReceivedShares();+ const includeCatalog = !(+ listArgs[0] && typeof listArgs[0] === 'object' && !Array.isArray(listArgs[0])+ && (listArgs[0] as { includeCatalog?: unknown }).includeCatalog === false+ );+ // 未全部就绪时也返回已加载的区域,但账号切换期间不得返回旧账号名单。+ const shares = getReceivedSharesSnapshot().received;return {+ ready: isReceivedSharesReady(),shares: await Promise.all(shares.map(async (share): Promise<ProviderShareReceivedCatalog> => {const agentDeviceId = `share:${share.shareId}`;let catalog: unknown = null;- if (invoke && share.status === 'active') {+ if (includeCatalog && invoke && share.status === 'active') {let timer: ReturnType<typeof setTimeout> | undefined;try {const result = await Promise.race([diff --git a/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/snapshot.test.ts b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/snapshot.test.tsindex 973d6b5d9f..5c5cd3f04b 100644--- a/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/snapshot.test.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/snapshot.test.ts@@ -558,6 +558,13 @@ describe('snapshotRealProfile', () => {const destDir = realProfileDestDir(path.join(makeTempDir(), 'runtime'));const db = new DatabaseSync(path.join(source.userDataDir, 'Profile 6', 'Cookies'));db.exec('PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE;');+ const realExec = DatabaseSync.prototype.exec;+ // Keep the real exclusive-lock conflict, but do not spend the production+ // busy timeout waiting for a lock this test only releases in finally.+ const exec = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) {+ if (sql === 'BEGIN') realExec.call(this, 'PRAGMA busy_timeout = 0');+ return realExec.call(this, sql);+ });try {await expect(snapshotRealProfile({ source, destDir, platform: 'darwin' }),@@ -565,6 +572,7 @@ describe('snapshotRealProfile', () => {expect(fs.existsSync(destDir)).toBe(false);expect(leftoverStagingNames(destDir)).toEqual([]);} finally {+ exec.mockRestore();db.close();}}, 10_000);diff --git a/apps/desktop/src/main/remote-agent/__tests__/hostedProviderRouting.test.ts b/apps/desktop/src/main/remote-agent/__tests__/hostedProviderRouting.test.tsindex 84b472a00d..89a4c71afb 100644--- a/apps/desktop/src/main/remote-agent/__tests__/hostedProviderRouting.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/hostedProviderRouting.test.ts@@ -4,6 +4,7 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';+import type { RemoteAgentPollResult } from '@cindy/device-link';import type { AgentEvent, AgentSessionHandle } from '@cindy/maker-core';import { buildUserProvider } from '@cindy/model-providers';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -20,6 +21,7 @@ import { setCustomProviders } from '../../maker-host/active-catalog';import { createModelRoutingTransform, setClaudeProxyGatewayKeyReader, setClaudeProxySessionIdResolver } from '../../maker-host/anthropic-compat-proxy-host';import { resolveSessionRouteDecision, setCustomProviderKeyReader } from '../../maker-host/provider-route';import { bindHostedSessionProvider, clearAllSessionProviders, getSessionProvider, hasSessionProvider } from '../../maker-host/session-provider-store';+import { LineSplitter } from '../eventLog';import { createRemoteAgentHost, hostSessionIdFor, type HostedStartInput } from '../host/runHost';const MODEL = 'gpt-6-astra';@@ -29,6 +31,12 @@ let root: string;let host: ReturnType<typeof createRemoteAgentHost>;let shadowRoots: Set<string>;let releaseGates: Array<() => void>;+const eventStreams = new Map<string, {+ cursor: number;+ splitter: LineSplitter;+ received: Array<Record<string, unknown>>;+ done: boolean;+}>();function deferred() {let resolve!: () => void;@@ -41,6 +49,7 @@ beforeEach(() => {root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-hosted-route-')));shadowRoots = new Set();releaseGates = [];+ eventStreams.clear();clearAllSessionProviders();setCustomProviders(['fp', 'other'].map((id) => buildUserProvider({id, name: id,@@ -127,18 +136,30 @@ async function open(providerId: string | null = 'fp', sessionId = 'task-1', contreturn runId;}-async function events(runId: string, controller = OWNER): Promise<Array<Record<string, unknown>>> {- const poll = await host.handle(controller, { op: 'poll', runs: [{ runId, cursor: 0 }], waitMs: 0 }) as { runs: Array<{ data?: string }> };- return Buffer.from(poll.runs[0]?.data ?? '', 'base64').toString('utf8').split('\n').filter(Boolean).map((line) => JSON.parse(line));-}-async function waitForEvent(runId: string, type: string, callId?: string, controller = OWNER) {- let found: Record<string, unknown> | undefined;- await vi.waitFor(async () => {- found = (await events(runId, controller)).find((event) => event.t === type && (!callId || event.callId === callId));- expect(found).toBeDefined();- });- return found!;+ let stream = eventStreams.get(runId);+ if (!stream) {+ stream = { cursor: 0, splitter: new LineSplitter(1024 * 1024), received: [], done: false };+ eventStreams.set(runId, stream);+ }+ // 用协议长轮询等事件到达,避免 vi.waitFor 默认 1 秒给磁盘/隧道启动加上额外期限。+ // 总等待仍受用例超时约束;保留已收事件,避免同批返回的后续 result 被游标确认丢弃。+ for (;;) {+ const found = stream.received.find((event) => event.t === type && (!callId || event.callId === callId));+ if (found) return found;+ expect(stream.done, `Run ended before ${type}: ${JSON.stringify(stream.received)}`).toBe(false);+ const poll = await host.handle(controller, {+ op: 'poll', runs: [{ runId, cursor: stream.cursor }], waitMs: 1_000,+ }) as RemoteAgentPollResult;+ const chunk = poll.runs[0];+ if (!chunk) continue;+ expect(chunk.missing, `Run missing while waiting for ${type}`).not.toBe(true);+ stream.cursor = chunk.cursor;+ stream.done = chunk.done === true;+ if (chunk.data) {+ stream.received.push(...stream.splitter.push(Buffer.from(chunk.data, 'base64')).map((line) => JSON.parse(line)));+ }+ }}async function switchProvider(runId: string, providerId?: string | null) {diff --git a/apps/desktop/src/renderer/__tests__/controlledDraftRemoteAgentWiring.test.ts b/apps/desktop/src/renderer/__tests__/controlledDraftRemoteAgentWiring.test.tsindex e11869ee16..a56d738487 100644--- a/apps/desktop/src/renderer/__tests__/controlledDraftRemoteAgentWiring.test.ts+++ b/apps/desktop/src/renderer/__tests__/controlledDraftRemoteAgentWiring.test.ts@@ -38,7 +38,7 @@ describe('草稿页:建到被控电脑的任务也能选第三台电脑', () =>expect(agentBlock).toContain('(!effectiveDeviceLinkDeviceId || deviceLinkRemoteAgentSupported)');});- it('候选电脑去掉被控电脑本身,不并入本机收到的分享;不支持时不传', () => {+ it('候选电脑去掉被控电脑本身,并入同账号可用分享;不支持时不传', () => {const start = draftRouteSource.indexOf('const remoteAgentDevices = useMemo(() => {');expect(start).toBeGreaterThan(0);const branchEnd = draftRouteSource.indexOf(': undefined;', start);@@ -46,7 +46,8 @@ describe('草稿页:建到被控电脑的任务也能选第三台电脑', () =>expect(controlledBranch).toContain('if (effectiveDeviceLinkDeviceId) {');expect(controlledBranch).toContain('selectControlledTaskAgentDevices({');expect(controlledBranch).toContain('controlledDeviceId: effectiveDeviceLinkDeviceId,');- expect(controlledBranch).not.toContain('providerShareDevices');+ expect(controlledBranch).toContain('shareDevices: providerShareDevices,');+ expect(draftRouteSource).toContain('useProviderShareAgentDevices([effectiveAgentDeviceId], effectiveDeviceLinkDeviceId)');});it('选了另一台电脑时模型目录跟着那台', () => {diff --git a/apps/desktop/src/renderer/__tests__/controlledTaskRemoteAgentPanel.test.tsx b/apps/desktop/src/renderer/__tests__/controlledTaskRemoteAgentPanel.test.tsxindex 27bd27556e..95eb60f427 100644--- a/apps/desktop/src/renderer/__tests__/controlledTaskRemoteAgentPanel.test.tsx+++ b/apps/desktop/src/renderer/__tests__/controlledTaskRemoteAgentPanel.test.tsx@@ -214,6 +214,23 @@ describe('被控电脑上的任务:模型面板列出第三台电脑的远程供expect(screen.queryByRole('button', { name: 'C Closed · Studio' })).toBeNull();});+ it('任务仍用 B 本机模型、没有第三台电脑时,也能选择尚未用过的分享供应商', async () => {+ const shareDevice = { deviceId: 'share:abc', name: '来自 Magi 的分享' };+ const { onRelocate, onProviderChange } = renderControlledTaskPanel({ devices: [shareDevice] });+ expect(within(list()).getByText('B Model')).toBeTruthy();+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'S Shared · 来自 Magi 的分享' }));+ });+ expect(within(list()).queryByText('B Model')).toBeNull();+ await act(async () => {+ fireEvent.click(within(list()).getByText('S Model').closest('[data-unified-anchor]')!);+ });+ expect(onRelocate).toHaveBeenCalledWith(expect.objectContaining({+ providerId: 's-shared', modelId: 's-model', agent: 'claude-code', agentDevice: shareDevice,+ }));+ expect(onProviderChange).not.toHaveBeenCalled();+ });+it('浏览第三台电脑的目录,选中那里的模型 = 带着那台电脑换 Agent 位置', async () => {const { onRelocate, onProviderChange } = renderControlledTaskPanel();await act(async () => {@@ -367,6 +384,21 @@ describe('远程控制下新建任务:草稿的模型面板同样列出第三台expect(onProviderChange).not.toHaveBeenCalled();});+ it('新建到 B 的任务可直接选分享模型,提交分享身份供 B 创建远程 Agent', async () => {+ const shareDevice = { deviceId: 'share:abc', name: '来自 Magi 的分享' };+ const { onUnifiedSelect, onProviderChange } = renderControlledDraftPanel({ devices: [shareDevice] });+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'S Shared · 来自 Magi 的分享' }));+ });+ await act(async () => {+ fireEvent.click(within(list()).getByText('S Model').closest('[data-unified-anchor]')!);+ });+ expect(onUnifiedSelect).toHaveBeenCalledWith(expect.objectContaining({+ providerId: 's-shared', modelId: 's-model', engine: 'cc', agentDevice: shareDevice,+ }));+ expect(onProviderChange).not.toHaveBeenCalled();+ });+it('Agent 已选在第三台电脑:选回被控电脑的模型带 agentDevice: null', async () => {const { onUnifiedSelect } = renderControlledDraftPanel({ selectedDeviceId: 'device-c' },diff --git a/apps/desktop/src/renderer/__tests__/remoteAgentRelocationWiring.test.ts b/apps/desktop/src/renderer/__tests__/remoteAgentRelocationWiring.test.tsindex 0c105a3b7b..e1c1e3d3fb 100644--- a/apps/desktop/src/renderer/__tests__/remoteAgentRelocationWiring.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteAgentRelocationWiring.test.ts@@ -141,7 +141,7 @@ describe('被控电脑上的任务:换 Agent 所在电脑', () => {expect(chatInputSource).toContain('device: deviceLinkDeviceName || deviceLinkDeviceId,');});- it('会话视图:候选电脑去掉被控电脑本身,不并入本机收到的分享;目录跟随 Agent 所在电脑', () => {+ it('会话视图:候选电脑去掉被控电脑本身,并入全部可用分享;目录跟随 Agent 所在电脑', () => {expect(sessionViewSource).toContain('controlledTaskSupportsAgentLocation(session) &&');expect(sessionViewSource).toContain('!isSharedTaskPeer(remoteDeviceId) &&');const branch = sessionViewSource.indexOf(@@ -153,14 +153,14 @@ describe('被控电脑上的任务:换 Agent 所在电脑', () => {sessionViewSource.indexOf(': undefined;', branch),);expect(remoteBranch).toContain('selectControlledTaskAgentDevices({');- expect(remoteBranch).not.toContain('providerShareDevices');+ expect(remoteBranch).toContain('shareDevices: providerShareDevices,');expect(sessionViewSource).toContain('const catalogDeviceId = controlledAgentDeviceId ?? remoteDeviceId ?? agentDeviceId;',);expect(sessionViewSource).toContain('deviceLinkDeviceName={controlledDeviceName}');});- it('Agent 在本机也收到了的分享上:按分享目录显示,只把那一条分享并进候选', () => {+ it('Agent 在分享上:按分享目录显示,暂停的当前位置仍保留,其他可用分享也能选', () => {// 2026-10-10 用户反馈:A 远控 B 上用分享供应商的任务,模型按钮显示「模型信息暂不可用」。const start = sessionViewSource.indexOf('const controlledShareIds = useMemo(');expect(start).toBeGreaterThan(0);@@ -178,7 +178,8 @@ describe('被控电脑上的任务:换 Agent 所在电脑', () => {branch,sessionViewSource.indexOf(': undefined;', branch),);- expect(remoteBranch).toContain('shareDevices: [...(controlledShareIds ?? [])]');+ expect(remoteBranch).toContain('shareDevices: providerShareDevices,');+ expect(sessionViewSource).toContain('useProviderShareAgentDevices([session?.agentDeviceId, pendingAgentDeviceId], remoteDeviceId)');// ChatInput 只认调用方放进候选的分享。const inputStart = chatInputSource.indexOf('const deviceLinkAgentLocation =');expect(chatInputSource.slice(inputStart, inputStart + 800)).toContain(diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 45e5023b51..200a8c544a 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -2101,7 +2101,7 @@ function CCAgentSessionContent({devices: providerShareDevices,nameFor: providerShareDeviceName,isReceived: isReceivedProviderShare,- } = useProviderShareAgentDevices([agentDeviceId, pendingAgentDeviceId]);+ } = useProviderShareAgentDevices([session?.agentDeviceId, pendingAgentDeviceId], remoteDeviceId);// 被控电脑上的任务 Agent 现在 / 挂着的位置是分享时:分享按账号授予,本机也收到了同一条就经本机// 的分享通道读它的目录,模型按钮按分享显示(否则只能读到被控电脑自己的目录,显示「模型信息暂// 不可用」)。本机没收到的分享读不到,维持原样。@@ -2142,10 +2142,8 @@ function CCAgentSessionContent({devices: selectableDevices,controlledDeviceId: remoteDeviceId,keepDeviceIds: [controlledAgentDeviceId, pendingAgentDeviceId],- shareDevices: [...(controlledShareIds ?? [])].map((deviceId) => ({- deviceId,- name: providerShareDeviceName(deviceId) ?? deviceId,- })),+ // 新分享落点须由被控端名单确认;不要求任务先使用它。+ shareDevices: providerShareDevices,}): undefined;}diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex e43d288fad..9b892e469f 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -966,16 +966,17 @@ export function NewMakerDraftRoute() {*/// 供应商分享:别人分享给我的供应商(`share:<id>`)同样是落点,只并进模型选择器,不进设备切换器。const { devices: providerShareDevices } =- useProviderShareAgentDevices([effectiveAgentDeviceId]);+ useProviderShareAgentDevices([effectiveAgentDeviceId], effectiveDeviceLinkDeviceId);const remoteAgentDevices = useMemo(() => {if (effectiveDeviceLinkDeviceId) {- // 建到被控电脑的任务:候选去掉被控电脑本身;本机收到的分享被控电脑用不了,不并入。+ // 建到被控电脑的任务:候选去掉被控电脑本身,分享需在两端名单中可用。// 被控电脑不支持时不传,模型面板维持只列被控电脑的目录。return deviceLinkRemoteAgentSupported? selectControlledTaskAgentDevices({devices: selectableDevices,controlledDeviceId: effectiveDeviceLinkDeviceId,keepDeviceIds: [effectiveAgentDeviceId],+ shareDevices: providerShareDevices,}): undefined;}diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/useWorkerAgentDevices.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/useWorkerAgentDevices.test.tsxindex 29c02e7e6e..97c962cb1b 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/useWorkerAgentDevices.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/useWorkerAgentDevices.test.tsx@@ -76,7 +76,7 @@ describe('useWorkerAgentDevices', () => {).result.current).toEqual({ leadAgentDeviceId: null, devices: undefined });});- it('lists other computers and the readable share for a controlled Lead', () => {+ it.each([null, 'share:s1'])('lists all received shares for a controlled Lead running at %s', (lead) => {mocks.devices = [{ deviceId: 'host', name: 'Host', online: true },{ deviceId: 'office', name: 'Office', online: true },@@ -86,13 +86,14 @@ describe('useWorkerAgentDevices', () => {{ deviceId: 'share:s2', name: 'OpenAI · Bob' },];const { result } = renderHook(() =>- useWorkerAgentDevices({ controlledDeviceId: 'host', leadAgentDeviceId: 'share:s1' }),+ useWorkerAgentDevices({ controlledDeviceId: 'host', leadAgentDeviceId: lead }),);expect(result.current).toEqual({- leadAgentDeviceId: 'share:s1',+ leadAgentDeviceId: lead,devices: [{ deviceId: 'office', name: 'Office' },{ deviceId: 'share:s1', name: 'Anthropic · Alice' },+ { deviceId: 'share:s2', name: 'OpenAI · Bob' },],});});diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useWorkerAgentDevices.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useWorkerAgentDevices.tsindex 861ec7798b..222b1f2cfb 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useWorkerAgentDevices.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useWorkerAgentDevices.ts@@ -2,8 +2,8 @@* 协同 Worker 可以放 Agent 的其他电脑与分享(远程供应商),给「创建 Worker」面板的模型选择器用。** 与任务输入框同一套候选:本机 Lead 列在线的同账号电脑(当前位置掉线也保留)与收到的分享;远程- * 控制的被控电脑上的 Lead 列被控电脑之外的同账号电脑,分享只保留 Lead 当前所在、本机也收到的那条- * (被控电脑收到的分享控制端读不到,不作为新的落点)。+ * 控制的被控电脑上的 Lead 列被控电脑之外的同账号电脑与两端都可用的分享。分享按账号授予,+ * 不要求 Lead 已经在该分享上运行;暂停或已删除的分享只保留当前位置。* 远程控制时 Lead 的 Agent 在控制端读不到目录的地方(控制端自己、只有被控电脑收到的分享):与任务输入框* 一样维持被控电脑的目录、不列远程供应商,Worker 跟 Lead(返回的 leadAgentDeviceId 为 null)。* devices 为 undefined = 不提供(Lead 归属未解析、SSH Lead、上面这种读不到的情况)。@@ -36,7 +36,7 @@ export function useWorkerAgentDevices(input: {const lead = input.leadAgentDeviceId ?? null;const { deviceId: selfDeviceId } = useAuth();const { devices: selectableDevices } = useSelectableDevices();- const { devices: shareDevices, isReceived } = useProviderShareAgentDevices([lead]);+ const { devices: shareDevices, isReceived } = useProviderShareAgentDevices([lead], controlledDeviceId);return useMemo(() => {if (controlledDeviceId === undefined || sshRemote) return { leadAgentDeviceId: lead, devices: undefined };if (controlledDeviceId) {@@ -58,7 +58,7 @@ export function useWorkerAgentDevices(input: {devices: selectableDevices,controlledDeviceId,keepDeviceIds: [lead],- shareDevices: shareDevices.filter((device) => readableShareIds?.has(device.deviceId) === true),+ shareDevices,}),};}diff --git a/apps/desktop/src/renderer/features/provider-share/__tests__/useProviderShareAgentDevices.test.tsx b/apps/desktop/src/renderer/features/provider-share/__tests__/useProviderShareAgentDevices.test.tsxindex 9a609a4db7..dde0cb3d82 100644--- a/apps/desktop/src/renderer/features/provider-share/__tests__/useProviderShareAgentDevices.test.tsx+++ b/apps/desktop/src/renderer/features/provider-share/__tests__/useProviderShareAgentDevices.test.tsx@@ -3,6 +3,8 @@ import { act, cleanup, renderHook, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { ProviderShareReceived } from '@cindy/device-link';+import { PROVIDER_SHARE_RECEIVED_CATALOGS_CHANNEL } from '@cindy/device-link';+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';import { resetProviderShareStoreForTests } from '../providerShareStore';import { useProviderShareAgentDevices } from '../useProviderShareAgentDevices';@@ -45,6 +47,21 @@ function share(partial: Partial<ProviderShareReceived>): ProviderShareReceived {let push: ((list: ProviderShareReceived[]) => void) | null = null;let initial: ProviderShareReceived[] = [];+let linkStatus: ((payload: { status: 'online' | 'connecting' | 'stopped' }) => void) | null = null;+let linkPresence: ((payload: { deviceId: string; online: boolean; remoteControlEnabled: boolean }) => void) | null = null;+let linkPeerReset: ((payload: { deviceId: string }) => void) | null = null;+let linkControlTarget: ((payload: { deviceId: string; enabled: boolean; disabledControlDeviceIds: string[] }) => void) | null = null;+const invoke = vi.fn();+const unavailablePresence = [+ { label: 'offline', online: false, remoteControlEnabled: true },+ { label: 'remote control disabled', online: true, remoteControlEnabled: false },+];++function hostShares(...entries: Array<{ shareId: string; status?: 'active' | 'paused' }>) {+ return { shares: entries.map((entry) => ({+ ...share(entry), agentDeviceId: `share:${entry.shareId}`, catalog: null,+ })) };+}beforeEach(() => {resetProviderShareStoreForTests();@@ -52,8 +69,33 @@ beforeEach(() => {catalog.cached.clear();push = null;initial = [];+ linkStatus = null;+ linkPresence = null;+ linkPeerReset = null;+ linkControlTarget = null;+ invoke.mockReset().mockResolvedValue(hostShares());+ setDataOwnerGeneration('owner', 1);Object.assign(window, {electronAPI: {+ deviceLink: {+ invoke,+ onStatusChanged: (callback: typeof linkStatus) => {+ linkStatus = callback;+ return () => { linkStatus = null; };+ },+ onPresenceChanged: (callback: typeof linkPresence) => {+ linkPresence = callback;+ return () => { linkPresence = null; };+ },+ onPeerLinkReset: (callback: typeof linkPeerReset) => {+ linkPeerReset = callback;+ return () => { linkPeerReset = null; };+ },+ onControlTargetChanged: (callback: typeof linkControlTarget) => {+ linkControlTarget = callback;+ return () => { linkControlTarget = null; };+ },+ },providerShare: {command: vi.fn(async () => initial),onReceivedChanged: (cb: (list: ProviderShareReceived[]) => void) => {@@ -68,6 +110,373 @@ beforeEach(() => {afterEach(() => cleanup());describe('useProviderShareAgentDevices', () => {+ it('only offers new shares that the controlled host has loaded, even if the controller has more cross-region shares', async () => {+ initial = [share({ shareId: 'both' }), share({ shareId: 'controller-only' })];+ invoke.mockResolvedValue(hostShares({ shareId: 'both' }, { shareId: 'host-only' }));+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await waitFor(() => expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:both']));+ expect(invoke).toHaveBeenCalledWith('host-b', PROVIDER_SHARE_RECEIVED_CATALOGS_CHANNEL, [+ { includeCatalog: false },+ ]);+ // host 的目录暂时读不到(catalog: null)不等于 host 没有加载分享;目录仍走既有分享读取。+ expect(result.current.isReceived('share:controller-only')).toBe(true);+ });++ it('retries a not-yet-ready controlled host instead of caching its transient empty list', async () => {+ initial = [share({ shareId: 'both' })];+ invoke.mockResolvedValueOnce({ ready: false, shares: [] }).mockResolvedValueOnce(hostShares({ shareId: 'both' }));+ vi.useFakeTimers();+ try {+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ expect(result.current.devices).toEqual([]);+ await act(async () => { await vi.advanceTimersByTimeAsync(250); });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:both']);+ expect(invoke).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps controlled-host shares past the 64-entry catalog limit', async () => {+ initial = Array.from({ length: 130 }, (_, i) => share({ shareId: `s${i}` }));+ invoke.mockResolvedValue(hostShares(+ ...initial.slice(0, 129).map(({ shareId }, i) => ({ shareId, status: i === 65 ? 'paused' as const : 'active' as const })),+ { shareId: 'host-only' },+ ));+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await waitFor(() => expect(result.current.devices.map((d) => d.deviceId)).toEqual(+ initial.slice(0, 129).filter((_, i) => i !== 65).map(({ shareId }) => `share:${shareId}`),+ ));+ expect(invoke).toHaveBeenCalledTimes(1);+ });++ it('uses only known active share identities and never reads the host catalog', async () => {+ initial = ['valid', 'paused', 'unknown-status', 'mismatched', 'missing-status', 'controller-only']+ .map((shareId) => share({ shareId }));+ const readCatalog = vi.fn(() => { throw new Error('Catalog must not be read for identity discovery'); });+ const valid = { shareId: 'valid', agentDeviceId: 'share:valid', status: 'active' };+ Object.defineProperty(valid, 'catalog', { get: readCatalog });+ invoke.mockResolvedValue({ ready: true, shares: [+ null, [], 42, {}, valid,+ { shareId: 'paused', agentDeviceId: 'share:paused', status: 'paused' },+ { shareId: 'unknown-status', agentDeviceId: 'share:unknown-status', status: 'unknown' },+ { shareId: 'mismatched', agentDeviceId: 'share:valid', status: 'active' },+ { shareId: 'missing-status', agentDeviceId: 'share:missing-status' },+ { shareId: 'host-only', agentDeviceId: 'share:host-only', status: 'active' },+ ] });+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await waitFor(() => expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:valid']));+ expect(readCatalog).not.toHaveBeenCalled();+ });++ it('caps readiness backoff and clears the pending retry after recovery', async () => {+ initial = [share({ shareId: 'both' })];+ invoke.mockResolvedValue({ ready: false, shares: [] });+ vi.useFakeTimers();+ try {+ const { result, unmount } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ expect(invoke).toHaveBeenCalledTimes(1);+ let calls = 1;+ for (const delay of [250, 500, 1000, 2000, 4000, 8000, 16000, 30000, 30000]) {+ await act(async () => { await vi.advanceTimersByTimeAsync(delay - 1); });+ expect(invoke).toHaveBeenCalledTimes(calls);+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });+ expect(invoke).toHaveBeenCalledTimes(++calls);+ }+ invoke.mockResolvedValue(hostShares({ shareId: 'both' }));+ await act(async () => { window.dispatchEvent(new Event('focus')); });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:both']);+ expect(invoke).toHaveBeenCalledTimes(++calls);+ await act(async () => { await vi.advanceTimersByTimeAsync(30000); });+ expect(invoke).toHaveBeenCalledTimes(calls);++ invoke.mockResolvedValue({ ready: false, shares: [] });+ await act(async () => { window.dispatchEvent(new Event('focus')); });+ expect(invoke).toHaveBeenCalledTimes(++calls);+ await act(async () => { await vi.advanceTimersByTimeAsync(249); });+ expect(invoke).toHaveBeenCalledTimes(calls);+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });+ expect(invoke).toHaveBeenCalledTimes(++calls);+ act(() => linkStatus?.({ status: 'stopped' }));+ await act(async () => { await vi.advanceTimersByTimeAsync(30000); });+ expect(invoke).toHaveBeenCalledTimes(calls);+ await act(async () => { linkStatus?.({ status: 'online' }); });+ expect(invoke).toHaveBeenCalledTimes(++calls);+ unmount();+ await act(async () => { await vi.advanceTimersByTimeAsync(30000); });+ expect(invoke).toHaveBeenCalledTimes(calls);+ } finally {+ cleanup();+ vi.useRealTimers();+ }+ });++ it.each(['local', 'cross-region'])('offers loaded %s shares while another region is not ready', async (available) => {+ const delayed = available === 'local' ? 'cross-region' : 'local';+ initial = [available, delayed, 'controller-only', 'paused'].map((shareId) => share({ shareId }));+ invoke.mockResolvedValue({+ ready: false,+ ...hostShares({ shareId: available }, { shareId: 'paused', status: 'paused' }),+ });+ vi.useFakeTimers();+ try {+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:' + available]);+ await act(async () => { await vi.advanceTimersByTimeAsync(250); });+ expect(invoke).toHaveBeenCalledTimes(2);+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:' + available]);++ // A partial response still carries authoritative pause/removal updates.+ invoke.mockResolvedValue({ ready: false, ...hostShares({ shareId: available, status: 'paused' }) });+ await act(async () => { await vi.advanceTimersByTimeAsync(500); });+ expect(result.current.devices).toEqual([]);+ invoke.mockResolvedValue({ ready: true, ...hostShares({ shareId: delayed }) });+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:' + delayed]);+ await act(async () => { await vi.advanceTimersByTimeAsync(30000); });+ expect(invoke).toHaveBeenCalledTimes(4);+ } finally {+ cleanup();+ vi.useRealTimers();+ }+ });++ it('keeps current/pending shares while excluding new shares paused or unknown on the controlled host', async () => {+ initial = ['current', 'pending', 'paused', 'unknown'].map((shareId) => share({ shareId }));+ invoke.mockResolvedValue(hostShares({ shareId: 'paused', status: 'paused' }));+ const { result } = renderHook(() => useProviderShareAgentDevices(['share:current', 'share:pending'], 'host-b'));+ await waitFor(() => expect(invoke).toHaveBeenCalled());+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:current', 'share:pending']);+ });++ it.each(['DEVICE_LINK_CHANNEL_NOT_ALLOWED', 'DEVICE_LINK_NOT_CONNECTED'])('does not fall back to controller shares after %s; retries on focus', async (code) => {+ initial = [share({ shareId: 'both' })];+ invoke.mockRejectedValueOnce(new Error(`[${code}] host unavailable`));+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await waitFor(() => expect(invoke).toHaveBeenCalledTimes(1));+ expect(result.current.devices).toEqual([]);+ invoke.mockResolvedValue(hostShares({ shareId: 'both' }));+ act(() => window.dispatchEvent(new Event('focus')));+ await waitFor(() => expect(result.current.devices).toHaveLength(1));+ invoke.mockResolvedValue(hostShares());+ act(() => push?.([...initial]));+ await waitFor(() => expect(result.current.devices).toEqual([]));+ });++ it('does not use another host’s result or a late disconnected response', async () => {+ initial = [share({ shareId: 'both' })];+ let finish!: (value: unknown) => void;+ invoke.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ const { result, rerender } = renderHook(({ host }) => useProviderShareAgentDevices([], host), { initialProps: { host: 'host-b' } });+ await waitFor(() => expect(invoke).toHaveBeenCalledTimes(1));+ rerender({ host: 'host-c' });+ await act(async () => finish(hostShares({ shareId: 'both' })));+ expect(result.current.devices).toEqual([]);+ invoke.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ act(() => window.dispatchEvent(new Event('focus')));+ act(() => linkStatus?.({ status: 'stopped' }));+ await act(async () => finish(hostShares({ shareId: 'both' })));+ expect(result.current.devices).toEqual([]);+ invoke.mockResolvedValue(hostShares({ shareId: 'both' }));+ act(() => linkStatus?.({ status: 'online' }));+ await waitFor(() => expect(result.current.devices).toHaveLength(1));+ });++ it.each(['DEVICE_LINK_NOT_CONNECTED', 'DEVICE_LINK_PEER_RESET'])('recovers from %s when only the controlled host comes online', async (code) => {+ initial = [share({ shareId: 'both' })];+ invoke.mockRejectedValueOnce(new Error(`[${code}] host unavailable`));+ const { result, unmount } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await waitFor(() => expect(invoke).toHaveBeenCalledTimes(1));+ expect(result.current.devices).toEqual([]);+ invoke.mockResolvedValue(hostShares({ shareId: 'both' }));+ await act(async () => {+ linkPresence?.({ deviceId: 'host-c', online: false, remoteControlEnabled: true });+ linkPresence?.({ deviceId: 'host-c', online: true, remoteControlEnabled: true });+ linkPresence?.({ deviceId: 'host-b', online: false, remoteControlEnabled: true });+ });+ expect(invoke).toHaveBeenCalledTimes(1);+ await act(async () => { linkPresence?.({ deviceId: 'host-b', online: true, remoteControlEnabled: true }); });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:both']);+ expect(invoke).toHaveBeenCalledTimes(2);+ // Busy/name updates on an already-online peer must not start another query.+ await act(async () => { linkPresence?.({ deviceId: 'host-b', online: true, remoteControlEnabled: true }); });+ expect(invoke).toHaveBeenCalledTimes(2);+ unmount();+ expect(linkPresence).toBeNull();+ expect(linkStatus).toBeNull();+ });++ it.each(unavailablePresence)('ignores an old response after the controlled host recovers from $label', async ({ online, remoteControlEnabled }) => {+ initial = [share({ shareId: 'old' }), share({ shareId: 'new' })];+ let finish!: (value: unknown) => void;+ invoke.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await waitFor(() => expect(invoke).toHaveBeenCalledTimes(1));+ act(() => linkPresence?.({ deviceId: 'host-b', online, remoteControlEnabled }));+ invoke.mockResolvedValue(hostShares({ shareId: 'new' }));+ await act(async () => { linkPresence?.({ deviceId: 'host-b', online: true, remoteControlEnabled: true }); });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:new']);+ await act(async () => finish(hostShares({ shareId: 'old' })));+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:new']);+ expect(invoke).toHaveBeenCalledTimes(2);+ });++ it.each(unavailablePresence)('pauses readiness retries while the controlled host is $label and resumes on presence', async ({ online, remoteControlEnabled }) => {+ initial = [share({ shareId: 'both' })];+ invoke.mockResolvedValue({ ready: false, ...hostShares({ shareId: 'both' }) });+ vi.useFakeTimers();+ try {+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:both']);+ act(() => linkPresence?.({ deviceId: 'host-b', online, remoteControlEnabled }));+ expect(result.current.devices).toEqual([]);+ await act(async () => {+ window.dispatchEvent(new Event('focus'));+ await vi.advanceTimersByTimeAsync(30_000);+ });+ expect(invoke).toHaveBeenCalledTimes(1);+ invoke.mockResolvedValue(hostShares({ shareId: 'both' }));+ await act(async () => { linkPresence?.({ deviceId: 'host-b', online: true, remoteControlEnabled: true }); });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:both']);+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });+ expect(invoke).toHaveBeenCalledTimes(2);+ } finally {+ cleanup();+ vi.useRealTimers();+ }+ });++ it('invalidates and reloads shares when remote control is toggled while the host stays online', async () => {+ initial = [share({ shareId: 'old' }), share({ shareId: 'new' })];+ invoke.mockResolvedValue(hostShares({ shareId: 'old' }));+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await waitFor(() => expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:old']));+ await act(async () => { linkPresence?.({ deviceId: 'host-b', online: true, remoteControlEnabled: true }); });+ invoke.mockClear();+ await act(async () => {+ linkPresence?.({ deviceId: 'host-b', online: true, remoteControlEnabled: false });+ linkPresence?.({ deviceId: 'host-b', online: true, remoteControlEnabled: false });+ window.dispatchEvent(new Event('focus'));+ });+ expect(result.current.devices).toEqual([]);+ expect(invoke).not.toHaveBeenCalled();+ invoke.mockResolvedValue(hostShares({ shareId: 'new' }));+ await act(async () => { linkPresence?.({ deviceId: 'host-b', online: true, remoteControlEnabled: true }); });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:new']);+ await act(async () => { linkPresence?.({ deviceId: 'host-b', online: true, remoteControlEnabled: true }); });+ expect(invoke).toHaveBeenCalledTimes(1);+ });++ it('rejects an in-flight result after an account generation change', async () => {+ initial = [share({ shareId: 'both' })];+ let finish!: (value: unknown) => void;+ invoke.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await waitFor(() => expect(invoke).toHaveBeenCalled());+ setDataOwnerGeneration('another-owner', 2);+ await act(async () => finish(hostShares({ shareId: 'both' })));+ expect(result.current.devices).toEqual([]);+ });++ it('retries a failed share query on peer reset without relay or presence changes', async () => {+ initial = [share({ shareId: 'both' })];+ invoke.mockRejectedValueOnce(new Error('[DEVICE_LINK_PEER_RESET] peer reset'));+ const { result, unmount } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await waitFor(() => expect(invoke).toHaveBeenCalledTimes(1));+ invoke.mockResolvedValue(hostShares({ shareId: 'both' }));+ await act(async () => {+ linkPeerReset?.({ deviceId: 'host-c' });+ linkControlTarget?.({ deviceId: 'host-c', enabled: false, disabledControlDeviceIds: ['host-c'] });+ });+ expect(invoke).toHaveBeenCalledTimes(1);+ await act(async () => { linkPeerReset?.({ deviceId: 'host-b' }); });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:both']);+ expect(invoke).toHaveBeenCalledTimes(2);+ unmount();+ expect(linkPeerReset).toBeNull();+ expect(linkControlTarget).toBeNull();+ });++ it.each(['peer reset', 'local control disabled'])('ignores an old share response after %s recovery', async (reason) => {+ initial = [share({ shareId: 'old' }), share({ shareId: 'new' })];+ let finish!: (value: unknown) => void;+ invoke.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await waitFor(() => expect(invoke).toHaveBeenCalledTimes(1));+ invoke.mockResolvedValue(hostShares({ shareId: 'new' }));+ await act(async () => {+ if (reason === 'peer reset') linkPeerReset?.({ deviceId: 'host-b' });+ else {+ linkControlTarget?.({ deviceId: 'host-b', enabled: false, disabledControlDeviceIds: ['host-b'] });+ linkControlTarget?.({ deviceId: 'host-b', enabled: true, disabledControlDeviceIds: [] });+ }+ });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:new']);+ await act(async () => finish(hostShares({ shareId: 'old' })));+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:new']);+ expect(invoke).toHaveBeenCalledTimes(2);+ });++ it('pauses queries while local control is disabled and resumes when enabled', async () => {+ initial = [share({ shareId: 'both' })];+ invoke.mockResolvedValue({ ready: false, ...hostShares({ shareId: 'both' }) });+ vi.useFakeTimers();+ try {+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:both']);+ act(() => linkControlTarget?.({ deviceId: 'host-b', enabled: false, disabledControlDeviceIds: ['host-b'] }));+ expect(result.current.devices).toEqual([]);+ await act(async () => {+ linkPeerReset?.({ deviceId: 'host-b' });+ linkPresence?.({ deviceId: 'host-b', online: true, remoteControlEnabled: true });+ linkStatus?.({ status: 'online' });+ window.dispatchEvent(new Event('focus'));+ await vi.advanceTimersByTimeAsync(30_000);+ });+ expect(invoke).toHaveBeenCalledTimes(1);+ invoke.mockResolvedValue(hostShares({ shareId: 'both' }));+ await act(async () => {+ linkControlTarget?.({ deviceId: 'host-b', enabled: true, disabledControlDeviceIds: [] });+ });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:both']);+ await act(async () => {+ linkControlTarget?.({ deviceId: 'host-b', enabled: true, disabledControlDeviceIds: [] });+ await vi.advanceTimersByTimeAsync(30_000);+ });+ expect(invoke).toHaveBeenCalledTimes(2);+ } finally {+ cleanup();+ vi.useRealTimers();+ }+ });++ it.each(['relay offline', 'peer unavailable'])('does not query on peer reset or local enable while %s', async (reason) => {+ initial = [share({ shareId: 'both' })];+ invoke.mockResolvedValue(hostShares({ shareId: 'both' }));+ const { result } = renderHook(() => useProviderShareAgentDevices([], 'host-b'));+ await waitFor(() => expect(result.current.devices).toHaveLength(1));+ await act(async () => {+ if (reason === 'relay offline') linkStatus?.({ status: 'connecting' });+ else linkPresence?.({ deviceId: 'host-b', online: false, remoteControlEnabled: true });+ linkPeerReset?.({ deviceId: 'host-b' });+ linkControlTarget?.({ deviceId: 'host-b', enabled: true, disabledControlDeviceIds: [] });+ window.dispatchEvent(new Event('focus'));+ });+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(result.current.devices).toEqual([]);+ await act(async () => {+ if (reason === 'relay offline') linkStatus?.({ status: 'online' });+ else linkPresence?.({ deviceId: 'host-b', online: true, remoteControlEnabled: true });+ });+ expect(result.current.devices.map((d) => d.deviceId)).toEqual(['share:both']);+ expect(invoke).toHaveBeenCalledTimes(2);+ });+it('names shares by owner only (numbering repeats), never by the sharer’s computer', async () => {initial = [share({ shareId: 'a' }),@@ -88,6 +497,7 @@ describe('useProviderShareAgentDevices', () => {expect(result.current.isKnown('share:zzz')).toBe(false);expect(result.current.isReceived('share:b')).toBe(true);expect(result.current.isReceived('share:zzz')).toBe(false);+ expect(invoke).not.toHaveBeenCalled();});it('keeps the current paused or removed share so the task can see and leave it', async () => {diff --git a/apps/desktop/src/renderer/features/provider-share/useControlledShareIds.ts b/apps/desktop/src/renderer/features/provider-share/useControlledShareIds.tsnew file mode 100644index 0000000000..d4a36c5f26--- /dev/null+++ b/apps/desktop/src/renderer/features/provider-share/useControlledShareIds.ts@@ -0,0 +1,161 @@+import { useEffect, useState } from 'react';+import {+ isSharedTaskPeer,+ PROVIDER_SHARE_RECEIVED_CATALOGS_CHANNEL,+ type ProviderShareReceived,+} from '@cindy/device-link';++import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';++const EMPTY_IDS: ReadonlySet<string> = new Set();+const RECEIVED_LIST_RETRY_BASE_MS = 250;+const RECEIVED_LIST_RETRY_MAX_MS = 30_000;++/** 只核对本机已收到分享的身份和状态;完整目录解析的 64 条上限不适用于这份轻量名单。 */+function readControlledShareIds(value: unknown, received: readonly ProviderShareReceived[]): ReadonlySet<string> {+ const shares = value && typeof value === 'object' && !Array.isArray(value)+ ? (value as { shares?: unknown }).shares : undefined;+ const ids = new Set<string>();+ if (!Array.isArray(shares)) return ids;+ const knownShareIds = new Set(received.map((share) => share.shareId));+ for (const raw of shares) {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue;+ const entry = raw as Record<string, unknown>;+ if (typeof entry.shareId !== 'string' || !knownShareIds.has(entry.shareId) || entry.status !== 'active') continue;+ const agentDeviceId = `share:${entry.shareId}`;+ if (entry.agentDeviceId === agentDeviceId) ids.add(agentDeviceId);+ }+ // 展示名和模型目录仍取控制端既有数据;即使旧主机附带 catalog,也不在这里解析。+ return ids;+}++/**+ * 分享授权属于账号,但跨区连接的启用标记在各电脑本地。新落点必须同时出现在被控端名单中。+ * 复用手机的只读查询,不恢复跨区连接、不修改授权;只消费名单,catalog 为 null 仍可保留。+ * 就绪后跟随已有的 received 推送刷新(包括后台轮询);首次未就绪时按有上限的指数退避重查。+ * 失败只收起新的分享落点;目标恢复可用、peer 复位或本机重新开启控制时重新查询,+ * 不重连 peer/relay,也不影响普通设备或本机供应商。+ */+export function useControlledShareIds(+ deviceId: string | null | undefined,+ received: readonly ProviderShareReceived[],+): ReadonlySet<string> {+ const owner = getDataOwnerGeneration();+ const [snapshot, setSnapshot] = useState<{+ deviceId: string;+ owner: typeof owner;+ ids: ReadonlySet<string>;+ } | null>(null);++ useEffect(() => {+ if (!deviceId || isSharedTaskPeer(deviceId) || received.length === 0) return;+ const link = window.electronAPI?.deviceLink;+ if (!link) return;+ let active = true;+ let revision = 0;+ let pending = false;+ let peerAvailable: boolean | undefined;+ let relayAvailable: boolean | undefined;+ let localControlEnabled: boolean | undefined;+ let retryTimer: ReturnType<typeof setTimeout> | null = null;+ let readinessRetryAttempt = 0;+ const invalidate = () => {+ revision += 1;+ pending = false;+ if (retryTimer) clearTimeout(retryTimer);+ retryTimer = null;+ readinessRetryAttempt = 0;+ setSnapshot(null);+ };+ const scheduleReadinessRetry = () => {+ if (retryTimer) clearTimeout(retryTimer);+ const delay = Math.min(+ RECEIVED_LIST_RETRY_MAX_MS,+ RECEIVED_LIST_RETRY_BASE_MS * 2 ** Math.min(readinessRetryAttempt, 7),+ );+ readinessRetryAttempt += 1;+ retryTimer = setTimeout(() => {+ retryTimer = null;+ void refresh();+ }, delay);+ };+ const refresh = async () => {+ if (!active || pending || peerAvailable === false || relayAvailable === false+ || localControlEnabled === false || !isDataOwnerGenerationCurrent(owner)) return;+ if (retryTimer) {+ clearTimeout(retryTimer);+ retryTimer = null;+ }+ pending = true;+ const request = ++revision;+ const current = () => active && request === revision && isDataOwnerGenerationCurrent(owner);+ try {+ // 这里只需确认被控端已加载哪些分享;不要让模型目录读取(每个分享+ // 可能等待远端供应商响应数秒)阻塞候选发现。需要目录的页面仍使用+ // `maker:provider:list` 的既有读取路径。+ const value = await link.invoke(deviceId, PROVIDER_SHARE_RECEIVED_CATALOGS_CHANNEL, [+ { includeCatalog: false },+ ]);+ if (!current()) return;+ // ready 只表示各区域名单是否完整;已返回的分享仍可立即使用。+ // 暂态空列表继续重查,不能因另一区域未就绪而丢弃已加载区域的分享。+ const ids = readControlledShareIds(value, received);+ setSnapshot({ deviceId, owner, ids });+ const ready = !(value && typeof value === 'object' && !Array.isArray(value)+ && (value as { ready?: unknown }).ready === false);+ if (!ready) {+ scheduleReadinessRetry();+ return;+ }+ readinessRetryAttempt = 0;+ } catch {+ // 旧主机、断链和读失败都不把控制端名单当成被控端可用性的证据。+ if (current()) setSnapshot(null);+ } finally {+ if (current()) pending = false;+ }+ };+ const onFocus = () => { void refresh(); };+ const unsubscribe = link.onStatusChanged?.(({ status }) => {+ relayAvailable = status === 'online';+ peerAvailable = undefined;+ invalidate();+ if (status === 'online') void refresh();+ });+ const unsubscribePresence = link.onPresenceChanged?.((presence) => {+ if (presence.deviceId !== deviceId) return;+ const available = presence.online && presence.remoteControlEnabled;+ if (available === peerAvailable) return;+ peerAvailable = available;+ // 与 main 的 presence 判定一致:掉线或关闭远控均作废旧响应并停止重试。+ invalidate();+ if (available) void refresh();+ });+ const unsubscribePeerReset = link.onPeerLinkReset?.((event) => {+ if (event.deviceId !== deviceId) return;+ // 只重查当前目标;建链与合并在途 open 仍由 main 的既有 invoke 路径处理。+ invalidate();+ void refresh();+ });+ const unsubscribeControlTarget = link.onControlTargetChanged?.((event) => {+ if (event.deviceId !== deviceId || event.enabled === localControlEnabled) return;+ localControlEnabled = event.enabled;+ invalidate();+ if (event.enabled) void refresh();+ });+ window.addEventListener('focus', onFocus);+ void refresh();+ return () => {+ active = false;+ if (retryTimer) clearTimeout(retryTimer);+ retryTimer = null;+ unsubscribe?.();+ unsubscribePresence?.();+ unsubscribePeerReset?.();+ unsubscribeControlTarget?.();+ window.removeEventListener('focus', onFocus);+ };+ }, [deviceId, owner, received]);++ return snapshot && snapshot.deviceId === deviceId && snapshot.owner === owner ? snapshot.ids : EMPTY_IDS;+}diff --git a/apps/desktop/src/renderer/features/provider-share/useProviderShareAgentDevices.ts b/apps/desktop/src/renderer/features/provider-share/useProviderShareAgentDevices.tsindex 42311c2f77..5cd12033e7 100644--- a/apps/desktop/src/renderer/features/provider-share/useProviderShareAgentDevices.ts+++ b/apps/desktop/src/renderer/features/provider-share/useProviderShareAgentDevices.ts@@ -14,6 +14,7 @@ import { isProviderShareAgentDeviceId } from '../../../shared/providerShare';import { providerShareAgentDeviceId } from './providerShareFormat';import { providerShareDisplayNames } from './providerShareNames';import { useProviderShareReceived } from './providerShareStore';+import { useControlledShareIds } from './useControlledShareIds';export interface ProviderShareAgentDevice {deviceId: string;@@ -37,10 +38,12 @@ export interface ProviderShareAgentDevices {export function useProviderShareAgentDevices(keepDeviceIds: readonly (string | null | undefined)[] = [],+ controlledDeviceId?: string | null,): ProviderShareAgentDevices {const { t } = useTranslation();const { received, loaded } = useProviderShareReceived();const keepKey = keepDeviceIds.filter(isProviderShareAgentDeviceId).join('\n');+ const controlledShareIds = useControlledShareIds(controlledDeviceId, received);const names = useMemo(() => {const byShare = providerShareDisplayNames(received, t);@@ -57,6 +60,7 @@ export function useProviderShareAgentDevices(for (const share of received) {const deviceId = providerShareAgentDeviceId(share.shareId);if (share.status !== 'active' && !keep.has(deviceId)) continue;+ if (controlledDeviceId && !controlledShareIds.has(deviceId) && !keep.has(deviceId)) continue;list.push({ deviceId, name: names.get(deviceId) ?? '' });keep.delete(deviceId);}@@ -67,7 +71,7 @@ export function useProviderShareAgentDevices(}}return list;- }, [keepKey, loaded, names, received, t]);+ }, [controlledDeviceId, controlledShareIds, keepKey, loaded, names, received, t]);const nameFor = useCallback((deviceId: string | null | undefined) => {diff --git a/apps/desktop/src/renderer/lib/controlledTaskAgentLocation.ts b/apps/desktop/src/renderer/lib/controlledTaskAgentLocation.tsindex 80b4df2983..919833f754 100644--- a/apps/desktop/src/renderer/lib/controlledTaskAgentLocation.ts+++ b/apps/desktop/src/renderer/lib/controlledTaskAgentLocation.ts@@ -83,8 +83,8 @@ export function controlledTaskAgentLocationReadable(input: {* 被控电脑上的任务(已建任务或新建任务草稿)可以让 Agent 去哪些电脑:本机的可选设备(已排除本机与* 手机)里去掉被控电脑本身,留下在线的,以及任务当前 / 挂着的 Agent 所在电脑(离线也保留,让用户* 看得到、换得回来)。- * 分享只列任务当前 / 挂着的 Agent 所在、本机也读得到的那条(shareDevices,接在最后),让模型按钮按- * 分享的目录显示、面板里看得到它;其他分享不作为新的落点列出。+ * 分享按账号授予,但跨区连接启用状态按设备保存。shareDevices 接在最后,+ * 由 useProviderShareAgentDevices 交叉核对两端名单,并保留当前 / 挂着的位置供用户换走。*/export function selectControlledTaskAgentDevices(input: {devices: readonly { deviceId: string; name: string; online: boolean }[];diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 8379f8b4de..7af4bc6a80 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -863,18 +863,20 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自`agentDeviceId`(null = A)。共享任务访客不能换电脑。桌面远程控制 A 上的已建任务(2026-10-09)与手机同口径:A 投影的任务带 `agentDeviceId` 字段(含 null)才开放,控制端直接经 device-link 读第三台电脑的 `maker:provider:list`,A 自己的目录照远程控制列全部供应商,换位置同样- 带 `agentDeviceId`(null = A),换后档位记在控制端为那台电脑单独记的一份(改回 A 时写 A 的镜像)。A 收到的分享与- 控制端自己作为新的落点暂不在桌面控制端列出;Agent 正在控制端读不到目录的位置上时维持原有的 A 目录列表。- 例外(2026-10-10):Agent 当前 / 挂着的位置是分享(`share:<id>`)、且控制端自己的已收到列表里也有这条(分享按账号- 授予,同账号电脑收到的是同一份)时,控制端经自己的分享通道读那份目录与 Agent 能力,模型按钮按分享显示,候选里- 只并进这一条分享;不经 A、不新增 channel。控制端没收到时维持原样。+ 带 `agentDeviceId`(null = A),换后档位记在控制端为那台电脑单独记的一份(改回 A 时写 A 的镜像)。+ 同账号收到的可用分享全部列为候选(2026-10-14),不要求任务已在分享上运行;已暂停或已移除的分享仅保留当前 /+ 待切换位置,沿用既有不可用提示。分享按账号授予,控制端复用自己的已收到列表、分享目录与 Agent 能力通道,+ 新落点再经既有 `maker:provider-share:received-catalogs` 核对被控端已加载且未暂停该分享;+ 跨区启用标记是设备本地状态,不能仅凭控制端名单放行,也不触发新的跨区授权。查询失败时仅保留当前 / 待切换位置。+ 创建、换位置和发送仍交给任务所在的 A 校验与执行,不新增 channel 或授权。控制端自己暂不作为新落点列出;+ Agent 正在控制端读不到目录的位置上时维持原有的 A 目录列表。控制端尚未收到的分享不凭任务记录授予访问。实现见 `apps/desktop/src/renderer/lib/controlledTaskAgentLocation.ts`,回归见`controlledTaskRemoteAgentPanel.test.tsx` 与 `remoteAgentRelocationWiring.test.ts`。桌面远程控制下新建任务(建到 A 上,2026-10-09)同样开放:判据与手机新建相同(A 的 `maker:provider:list` 带`remoteInvocationEnabled` 布尔标记,共享任务访客与 SSH 不开放),模型面板先列 A 的全部供应商、再列其他同账号电脑已开放的供应商;选中后草稿的模型目录改按那台,`maker:create-session` 带 `agentDeviceId`,权限档沿用 A 的草稿值,不把那台的模型写进 A 的新建草稿记忆;默认来源解析、提交的来源与协同 Worker 收窄都只用那台已开放的供应商。- 落点范围与已建任务相同(A 收到的分享与控制端自己暂不列出);协同草稿与它不互斥(与桌面本机新建一致)。回归见+ 落点范围与已建任务相同(包括同账号可用分享,控制端自己暂不列出);协同草稿与它不互斥(与桌面本机新建一致)。回归见`controlledDraftRemoteAgentWiring.test.ts`。Mobile 新建任务(2026-10-08)同样列出这些供应商与分享来的供应商,选中后 `maker:create-session` 带`agentDeviceId`(与桌面新建同一参数,A 已接受);只有 A 的 `maker:provider:list` 带 `remoteInvocationEnabled`diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.mdindex 1125dee97f..89fd489d72 100644--- a/docs/product-rules/provider-sharing.md+++ b/docs/product-rules/provider-sharing.md@@ -123,6 +123,15 @@Desktop 与 Mobile 使用同一写法。+同账号的桌面远控中,已建任务、新建任务与 Worker 的模型菜单都应列出可用分享,不以任务已经选用+该分享为前提。Desktop 复用控制端的已收到列表与分享读取通道,并通过既有+`maker:provider-share:received-catalogs` 核对任务所在电脑也已加载且未暂停该分享;跨区域连接的启用+标记保存在各电脑本地,不能仅凭控制端名单认定被控端可用,也不自动替被控端开启跨区连接。+本区和跨区名单独立可用:返回名单里已加载且有效的分享立即参与候选筛选;仍有区域尚未就绪时,+控制端继续有上限地退避查询,补上稍后加载的分享,不让单一区域故障阻塞另一区域。+查询失败或旧主机不支持时不新增分享候选,当前 / 待切换位置仍保留。模型选择和执行仍由任务所在电脑校验;+手机沿用被控电脑代读目录。暂停或已移除的分享只为当前 / 待切换位置保留,供用户查看状态并换走。+### 5.2 供应商设置Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 410557a080..7b562ffb32 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -2688,6 +2688,7 @@ describe('DeviceLinkClient', () => {});it('transport-timeout 通知首发失败后按退避重发;对端重开后仍同 seq 续传', async () => {+ vi.useFakeTimers();const h = makeHarness({timing: {pingIntervalMs: 60_000,@@ -2697,55 +2698,62 @@ describe('DeviceLinkClient', () => {transportMaxRetryAttempts: 2,},});- h.client.start();- await tick();- h.current().ack();- await establishInboundReliableLink(h, 'notify-retry-stream');+ try {+ h.client.start();+ await vi.advanceTimersByTimeAsync(0);+ h.current().ack();+ const initialOpen = establishInboundReliableLink(h, 'notify-retry-stream');+ await vi.advanceTimersByTimeAsync(0);+ await initialOpen;- const firstSocket = h.current();- h.client.sendInvokeResult('dev-b', 'keep-me-2', { ok: true, result: [] });- const firstReliable = firstSocket.sent.find((env) => (- env.kind === 'invoke-result' && parseTransportPayload(env.payload)- ))!;- const firstMeta = parseTransportPayload(firstReliable.payload)!.meta;+ const firstSocket = h.current();+ h.client.sendInvokeResult('dev-b', 'keep-me-2', { ok: true, result: [] });+ const firstReliable = firstSocket.sent.find((env) => (+ env.kind === 'invoke-result' && parseTransportPayload(env.payload)+ ))!;+ const firstMeta = parseTransportPayload(firstReliable.payload)!.meta;- // 让 link-close 的首次发送失败(模拟 WebSocket 背压/发送异常),后续恢复- const originalSend = firstSocket.send.bind(firstSocket);- let failedOnce = false;- firstSocket.send = (data: string) => {- const env = JSON.parse(data) as Envelope;- if (env.kind === 'link-close' && !failedOnce) {- failedOnce = true;- throw new Error('simulated send backpressure');- }- originalSend(data);- };+ // 让 link-close 的首次发送失败(模拟 WebSocket 背压/发送异常),后续恢复+ const originalSend = firstSocket.send.bind(firstSocket);+ let failedOnce = false;+ firstSocket.send = (data: string) => {+ const env = JSON.parse(data) as Envelope;+ if (env.kind === 'link-close' && !failedOnce) {+ failedOnce = true;+ throw new Error('simulated send backpressure');+ }+ originalSend(data);+ };- // 对端永不 ACK → 重试耗尽 → 首发通知失败 → 退避重发成功- await vi.waitFor(() => {+ // 对端永不 ACK → 重试耗尽 → 首发通知失败 → 退避重发成功+ await vi.advanceTimersByTimeAsync(100);expect(failedOnce).toBe(true);expect(firstSocket.sent.some((env) => (env.kind === 'link-close'&& env.dst === 'dev-b'&& (env.payload as { reason?: string } | undefined)?.reason === 'transport-timeout'))).toBe(true);- });- // 重发期间 relay 连接始终未被拆- expect(firstSocket.terminated).toBe(false);- expect(h.sockets).toHaveLength(1);+ // 重发期间 relay 连接始终未被拆+ expect(firstSocket.terminated).toBe(false);+ expect(h.sockets).toHaveLength(1);- // 对端重开 → 保留的 live invoke-result 按原 seq 重放- const sentBefore = firstSocket.sent.length;- await establishInboundReliableLink(h, 'notify-retry-stream');- const replays = firstSocket.sent.slice(sentBefore).filter((env) => (- env.kind === 'invoke-result' && parseTransportPayload(env.payload)- ));- expect(replays).toHaveLength(1);- expect(parseTransportPayload(replays[0].payload)?.meta).toMatchObject({- streamId: firstMeta.streamId,- seq: firstMeta.seq,- });- h.client.stop();+ // 只完成重开握手,不跨过下一次重传期限,避免慢机器把重传算作重放。+ const sentBefore = firstSocket.sent.length;+ const reopen = establishInboundReliableLink(h, 'notify-retry-stream');+ await vi.advanceTimersByTimeAsync(0);+ await reopen;+ const replays = firstSocket.sent.slice(sentBefore).filter((env) => (+ env.kind === 'invoke-result' && parseTransportPayload(env.payload)+ ));+ expect(replays).toHaveLength(1);+ expect(parseTransportPayload(replays[0].payload)?.meta).toMatchObject({+ streamId: firstMeta.streamId,+ seq: firstMeta.seq,+ });+ } finally {+ h.client.stop();+ vi.useRealTimers();+ }});it('入站方向 closeLink 不拆共享可靠层:在途出站请求不被拒、后续发送不报 LINK_NOT_OPEN、回包照常送达', async () => {diff --git a/packages/maker-core/src/memory/scope-resolver.test.ts b/packages/maker-core/src/memory/scope-resolver.test.tsindex c9852ad3ff..f55544f3ca 100644--- a/packages/maker-core/src/memory/scope-resolver.test.ts+++ b/packages/maker-core/src/memory/scope-resolver.test.ts@@ -15,7 +15,7 @@ import { promises as fs } from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';-import { beforeEach, describe, expect, it } from 'vitest';+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';import {__clearMemoryScopeKeyCacheForTests,@@ -301,28 +301,39 @@ describe('resolveMemoryScopeKey — fake probe 回落与缓存', () => {// 默认 unit tier 唯一一条真实 Git smoke (§3.1): 端到端打通「真实 git 探测 +// 映射」主路径。组合矩阵见 scope-resolver.git-integration.test.ts。describe.skipIf(!gitAvailable())('resolveMemoryScopeKey — 真实 Git smoke', () => {- it('linked worktree 子目录 cwd → 主仓根 + 相对子路径', async () => {- const tmpRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'scope-resolver-')));- const repoRoot = path.join(tmpRoot, 'repo');+ let tmpRoot: string | undefined;+ let repoRoot: string;+ let sub: string;++ // 建仓与清理使用独立的 hook 预算,不占用真实探测断言的 5 秒时限。+ beforeAll(async () => {+ tmpRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'scope-resolver-')));+ repoRoot = path.join(tmpRoot, 'repo');const wt = path.join(tmpRoot, 'wt');const git = (args: string[], cwd: string) =>execFileSync('git', args, { cwd, stdio: 'ignore' });+ await fs.mkdir(repoRoot, { recursive: true });+ git(['init'], repoRoot);+ git([+ '-c', '[email protected]',+ '-c', 'user.name=scope-resolver-test',+ 'commit', '--allow-empty', '-m', 'init',+ ], repoRoot);+ git(['worktree', 'add', '-b', 'wt-branch', wt], repoRoot);+ sub = path.join(wt, 'apps', 'a');+ await fs.mkdir(sub, { recursive: true });+ });++ afterAll(async () => {+ if (!tmpRoot) return;try {- await fs.mkdir(repoRoot, { recursive: true });- git(['init'], repoRoot);- git(['config', 'user.email', '[email protected]'], repoRoot);- git(['config', 'user.name', 'scope-resolver-test'], repoRoot);- git(['commit', '--allow-empty', '-m', 'init'], repoRoot);- git(['worktree', 'add', '-b', 'wt-branch', wt], repoRoot);- const sub = path.join(wt, 'apps', 'a');- await fs.mkdir(sub, { recursive: true });- expect(await resolveMemoryScopeKey(sub)).toBe(path.join(repoRoot, 'apps', 'a'));- } finally {- try {- await fs.rm(tmpRoot, { recursive: true, force: true, maxRetries: 3 });- } catch {- /* Windows 上 git 只读对象偶发 EPERM — temp 目录交给 OS 清理 */- }+ await fs.rm(tmpRoot, { recursive: true, force: true, maxRetries: 3 });+ } catch {+ /* Windows 上 git 只读对象偶发 EPERM — temp 目录交给 OS 清理 */}});++ it('linked worktree 子目录 cwd → 主仓根 + 相对子路径', async () => {+ expect(await resolveMemoryScopeKey(sub)).toBe(path.join(repoRoot, 'apps', 'a'));+ });});