Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(device-link): 合并目录刷新并提前缓解共享连接拥塞 (#4582)

Dash22b811acf46a
diff --git a/apps/mobile/src/__tests__/deviceCatalogRefresh.test.ts b/apps/mobile/src/__tests__/deviceCatalogRefresh.test.ts
new file mode 100644
index 0000000000..ff9b4d0626
--- /dev/null
+++ b/apps/mobile/src/__tests__/deviceCatalogRefresh.test.ts
@@ -0,0 +1,151 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ProviderView } from '@cindy/model-providers/registry';
+
+beforeEach(() => { vi.resetModules(); vi.useFakeTimers(); });
+afterEach(() => vi.useRealTimers());
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+}
+const catalog = (id: string) => ({ providers: [{ id } as ProviderView] });
+const flush = async () => { await vi.advanceTimersByTimeAsync(50); };
+
+describe('catalog invalidation under a slow device link', () => {
+ it('coalesces four notifications and serializes a burst during a read without committing stale results', async () => {
+ const { createDeviceCatalogRefresh } = await import('@/device-link/deviceCatalogRefresh');
+ const cache = await import('@/device-link/deviceProvidersCache');
+ const caps = await import('@/session/agentCapabilitiesCache');
+ const first = deferred<ReturnType<typeof catalog>>();
+ const last = deferred<ReturnType<typeof catalog>>();
+ const firstCaps = deferred<unknown>();
+ const readProviders = vi.fn().mockReturnValueOnce(first.promise).mockReturnValueOnce(last.promise);
+ const readCapabilities = vi.fn().mockReturnValue(firstCaps.promise);
+ const published = vi.fn();
+ cache.subscribeDeviceProviders('a', published);
+ const refresh = createDeviceCatalogRefresh({ readProviders, readCapabilities, connectionEpoch: () => 7 });
+ for (let i = 0; i < 4; i++) { refresh.notify('a'); await vi.advanceTimersByTimeAsync(2); }
+ await flush();
+ expect(readProviders).toHaveBeenCalledTimes(1);
+ expect(readCapabilities).toHaveBeenCalledTimes(3);
+ // A mounted page joins the same capability read as the push refresh.
+ const pageRead = vi.fn();
+ const joined = caps.fetchAgentCapabilities('a', 'codex', pageRead);
+ for (let i = 0; i < 10; i++) refresh.notify('a');
+ await flush();
+ expect(readProviders).toHaveBeenCalledTimes(1);
+ first.resolve(catalog('stale'));
+ await flush();
+ expect(published).not.toHaveBeenCalled();
+ expect(cache.getDeviceFetchEpoch('a')).toBeUndefined();
+ expect(readProviders).toHaveBeenCalledTimes(1); // Whole batch still settling.
+ firstCaps.resolve(null);
+ await joined;
+ await flush();
+ expect(pageRead).not.toHaveBeenCalled();
+ expect(readProviders).toHaveBeenCalledTimes(2);
+ expect(readCapabilities).toHaveBeenCalledTimes(6);
+ last.resolve(catalog('latest'));
+ await flush();
+ expect(published).toHaveBeenCalledExactlyOnceWith(catalog('latest'));
+ expect(cache.getDeviceFetchEpoch('a')).toBe(7);
+ refresh.dispose();
+ });
+
+ it('a mounted reader waits for the obsolete read instead of bypassing the refresh slot', async () => {
+ const cache = await import('@/device-link/deviceProvidersCache');
+ const old = deferred<ReturnType<typeof catalog>>();
+ const first = cache.fetchDeviceProviders('a', () => old.promise);
+ cache.invalidateDeviceProvidersForRefresh('a');
+ const fetcher = vi.fn().mockResolvedValue(catalog('latest'));
+ const reads = [cache.fetchDeviceProviders('a', fetcher), cache.fetchDeviceProviders('a', fetcher)];
+ await flush();
+ expect(fetcher).not.toHaveBeenCalled();
+ old.resolve(catalog('obsolete'));
+ await first;
+ await Promise.all(reads);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(cache.getCachedDeviceProviders('a')).toEqual(catalog('latest'));
+ });
+
+ it.each([
+ ['ordinary', 'resolve', 'background-first'], ['ordinary', 'reject', 'background-first'],
+ ['fresh', 'resolve', 'background-first'], ['fresh', 'reject', 'background-first'],
+ ['ordinary', 'resolve', 'fresh-first'], ['ordinary', 'reject', 'fresh-first'],
+ ['fresh', 'resolve', 'fresh-first'], ['fresh', 'reject', 'fresh-first'],
+ ])('shares one replacement after an obsolete %s read %ss with %s', async (kind, outcome, order) => {
+ const cache = await import('@/device-link/deviceProvidersCache');
+ const old = deferred<ReturnType<typeof catalog>>();
+ const replacement = deferred<ReturnType<typeof catalog>>();
+ const first = (kind === 'fresh' ? cache.fetchDeviceProvidersFresh : cache.fetchDeviceProviders)(
+ 'a', () => old.promise,
+ ).catch(() => undefined);
+ cache.invalidateDeviceProvidersForRefresh('a');
+ const generation = cache.getDeviceProvidersGen('a');
+ const fetcher = vi.fn(() => replacement.promise);
+ const read = () => cache.fetchDeviceProviders('a', fetcher);
+ const fresh = () => cache.fetchDeviceProvidersFresh('a', fetcher);
+ const readers = order === 'background-first' ? [read(), fresh()] : [fresh(), read()];
+ await flush();
+ expect(fetcher).not.toHaveBeenCalled();
+ if (outcome === 'reject') old.reject(new Error('timeout'));
+ else old.resolve(catalog('obsolete'));
+ await first;
+ await flush();
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(cache.getDeviceProvidersGen('a')).toBe(generation);
+ expect(cache.getCachedDeviceProviders('a')).toBeUndefined();
+ replacement.resolve(catalog('latest'));
+ expect(await Promise.all(readers)).toEqual([catalog('latest'), catalog('latest')]);
+ expect(cache.getCachedDeviceProviders('a')).toEqual(catalog('latest'));
+ });
+
+ it('failed or cancelled reads cannot block another peer or resurrect a disposed owner', async () => {
+ const { createDeviceCatalogRefresh } = await import('@/device-link/deviceCatalogRefresh');
+ const cache = await import('@/device-link/deviceProvidersCache');
+ const slow = deferred<ReturnType<typeof catalog>>();
+ const readProviders = vi.fn((id: string) => id === 'a' ? slow.promise : Promise.resolve(catalog(id)));
+ const refresh = createDeviceCatalogRefresh({ readProviders, readCapabilities: async () => null, connectionEpoch: () => 1 });
+ refresh.notify('a');
+ refresh.notify('b');
+ await flush();
+ expect(cache.getCachedDeviceProviders('b')).toEqual(catalog('b'));
+ refresh.notify('a');
+ refresh.dispose();
+ slow.resolve(catalog('old-owner'));
+ await flush();
+ expect(cache.getCachedDeviceProviders('a')).toBeUndefined();
+ expect(readProviders).toHaveBeenCalledTimes(2);
+ const nextRead = vi.fn().mockRejectedValueOnce(new Error('timeout')).mockResolvedValue(catalog('new-owner'));
+ const next = createDeviceCatalogRefresh({ readProviders: nextRead, readCapabilities: async () => null, connectionEpoch: () => 2 });
+ next.notify('a');
+ await flush();
+ expect(cache.getDeviceFetchEpoch('a')).toBeUndefined();
+ next.notify('a');
+ await flush();
+ expect(nextRead).toHaveBeenCalledTimes(2);
+ expect(cache.getCachedDeviceProviders('a')).toEqual(catalog('new-owner'));
+ expect(cache.getDeviceFetchEpoch('a')).toBe(2);
+ next.dispose();
+ });
+
+ it('capability waiters are fenced when an account changes before the old read settles', async () => {
+ const caps = await import('@/session/agentCapabilitiesCache');
+ const old = deferred<unknown>();
+ const oldRead = caps.fetchAgentCapabilities('a', 'pi', () => old.promise);
+ await flush();
+ caps.evictAgentCapabilitiesForDevice('a');
+ const staleFetcher = vi.fn();
+ const staleWaiter = caps.fetchAgentCapabilities('a', 'pi', staleFetcher).catch((e) => e.message);
+ caps.resetAgentCapabilitiesCache();
+ const freshFetcher = vi.fn().mockResolvedValue('fresh');
+ const current = caps.fetchAgentCapabilities('a', 'pi', freshFetcher);
+ old.resolve('stale');
+ await oldRead;
+ expect(await staleWaiter).toBe('Capabilities read superseded');
+ expect(await current).toBe('fresh');
+ expect(staleFetcher).not.toHaveBeenCalled();
+ expect(freshFetcher).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
index 9fbf8b021a..f784c209e1 100644
--- a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
+++ b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
@@ -374,7 +374,14 @@ describe('destructive remote history pushes', () => {
// Delete (including initial-page races) is exercised through the real store in remoteHistoryReentry.test.ts.
it.each(['clear', 'archive'])('retires old pages on %s without an unrelated activity event', async (operation) => {
const context = readFileSync(resolve(process.cwd(), 'src/device-link/DeviceLinkContext.tsx'), 'utf8');
- const body = context.slice(context.indexOf(' const historySessionId ='), context.indexOf('/** provider revision')).trim().slice(0, -1);
+ const parsed = ts.createSourceFile('context.tsx', context, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ const routeFunction = parsed.statements.find((node): node is ts.FunctionDeclaration =>
+ ts.isFunctionDeclaration(node) && node.name?.text === 'routeFrame');
+ if (!routeFunction?.body) throw new Error('Missing production routeFrame body');
+ const routeBody = routeFunction.body.getText(parsed).slice(1, -1);
+ const historyStart = routeBody.indexOf(' const historySessionId =');
+ if (historyStart < 0) throw new Error('Missing production history routing');
+ const body = routeBody.slice(historyStart);
const stale = { id: 'old', clientId: 'old', role: 'user', content: 'old', createdAt: '2026-09-08T00:00:00Z' };
const oldPage = { version: 1 as const, items: projectHistoryView([stale], false), hasMore: false, nextCursor: null };
let reads = 0;
diff --git a/apps/mobile/src/__tests__/useDeviceProviders.test.ts b/apps/mobile/src/__tests__/useDeviceProviders.test.ts
index 72a6d611db..a7bfe4c9cd 100644
--- a/apps/mobile/src/__tests__/useDeviceProviders.test.ts
+++ b/apps/mobile/src/__tests__/useDeviceProviders.test.ts
@@ -206,14 +206,12 @@ describe('useDeviceProviders deviceId-aware cache', () => {
// 无挂载 hook 的后台缓存写入路径(DeviceLinkContext provider:changed)也必须
// mark epoch——否则断线前旧目录被当「首次挂载缓存命中」采信、永不刷新
// (codex review P1)。捕获 epoch 在 fetch 前、mark 在成功后(失败不 mark)。
- expect(ctxSrc).toContain('const epochAtWrite = connectionEpoch;');
- expect(ctxSrc).toContain('markDeviceFetchEpoch(deviceId, epochAtWrite);');
+ expect(ctxSrc).toContain('connectionEpoch: () => connectionEpochRef.current');
const ctxBlock = ctxSrc.slice(
ctxSrc.indexOf('onProviderChanged: (deviceId) => {'),
ctxSrc.indexOf('onProviderChanged: (deviceId) => {') + 1400,
);
- expect(ctxBlock).toContain('.then(() => {');
- expect(ctxBlock).toContain('markDeviceFetchEpoch(deviceId, epochAtWrite);');
+ expect(ctxBlock).toContain('catalogRefresh.notify(deviceId);');
// 模块级 Map + 导出存取(跨组件卸载存活)
expect(cacheSrc).toContain('const deviceFetchEpoch = new Map<string, number>();');
expect(cacheSrc).toContain('export function markDeviceFetchEpoch(deviceId: string, epoch: number): void');
diff --git a/apps/mobile/src/__tests__/useDeviceProvidersRecovery.test.tsx b/apps/mobile/src/__tests__/useDeviceProvidersRecovery.test.tsx
index d1a851ffa9..9f3e59c4e5 100644
--- a/apps/mobile/src/__tests__/useDeviceProvidersRecovery.test.tsx
+++ b/apps/mobile/src/__tests__/useDeviceProvidersRecovery.test.tsx
@@ -8,6 +8,7 @@ import { DeviceLinkClient, PROTOCOL_VERSION, DEVICE_LINK_CAPABILITY_RELIABLE_TRA
import type { ProviderView } from '@cindy/model-providers/registry';
import { useDeviceProviders, type UseDeviceProvidersResult } from '@/device-link/useDeviceProviders';
import { clearAllDeviceProviders, evictDeviceProviders, fetchDeviceProviders, fetchDeviceProvidersFresh } from '@/device-link/deviceProvidersCache';
+import { createDeviceCatalogRefresh } from '@/device-link/deviceCatalogRefresh';
const state = vi.hoisted(() => ({
context: { connectionEpoch: 1, status: 'online', recoveringDeviceIds: new Set<string>() },
@@ -69,6 +70,35 @@ afterEach(async () => {
});
describe('model catalog failure recovery', () => {
+ it('mounted picker and fresh submit share the replacement after a burst invalidates a failed read', async () => {
+ let fail!: (error: Error) => void;
+ const read = state.makers.get('a')!.listProviders;
+ read.mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject; }));
+ await render();
+ const refreshRead = vi.fn().mockResolvedValue(catalog('latest'));
+ const refresh = createDeviceCatalogRefresh({
+ readProviders: refreshRead, readCapabilities: async () => null, connectionEpoch: () => 1,
+ });
+ let fresh!: Promise<unknown>;
+ await act(async () => {
+ for (let i = 0; i < 4; i++) refresh.notify('a');
+ fresh = fetchDeviceProvidersFresh('a', refreshRead);
+ });
+ expect(values.a.ready).toBe(false);
+ expect(read).toHaveBeenCalledTimes(1);
+ expect(refreshRead).not.toHaveBeenCalled();
+ await act(async () => {
+ fail(timeout());
+ await fresh;
+ });
+ await advance(1000);
+ expect(refreshRead).toHaveBeenCalledTimes(1);
+ expect(read).toHaveBeenCalledTimes(1);
+ expect(values.a.ready).toBe(true);
+ expect(values.a.providers[0].id).toBe('latest');
+ await act(async () => refresh.dispose());
+ });
+
it('continues recovery when an external fresh read invalidates an ordinary in-flight read', async () => {
const read = state.makers.get('a')!.listProviders;
await render();
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index bd1727d3ce..41e8eeabf6 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -42,17 +42,13 @@ import {
import {
clearAllDeviceProviders,
evictDeviceProviders,
- fetchDeviceProviders,
- markDeviceFetchEpoch,
type DeviceProvidersPayload,
} from '@/device-link/deviceProvidersCache';
import {
- commitAgentCapabilities,
evictAgentCapabilitiesForDevice,
- getAgentCapabilitiesGeneration,
resetAgentCapabilitiesCache,
} from '@/session/agentCapabilitiesCache';
-import { normalizeMobileAgentCapabilities } from '@/session/agentCapabilities';
+import { createDeviceCatalogRefresh } from '@/device-link/deviceCatalogRefresh';
import { evictComposerPaletteCacheForDevice, resetComposerPaletteCache } from '@/session/composerPaletteCache';
import { clearAllDeviceModelMeta, evictDeviceModelMeta } from '@/device-link/deviceModelMetaCache';
import { dispatchFileBrowserWatchEvent } from '@/device-link/fileBrowserWatch';
@@ -841,6 +837,16 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
},
});
clientRef.current = client;
+ const catalogRefresh = createDeviceCatalogRefresh({
+ connectionEpoch: () => connectionEpochRef.current,
+ readProviders: (deviceId) => sendInvokeWithAccessHandling<DeviceProvidersPayload>(
+ client, deviceId, 'maker:provider:list',
+ [{ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2] }],
+ ),
+ readCapabilities: (deviceId, agent) => sendInvokeWithAccessHandling<unknown>(
+ client, deviceId, 'maker:get-capabilities', [agent],
+ ),
+ });
mobileDebugLog('debug', 'device-link', 'runtime identity', {
commit: /^[a-f0-9]{7,40}$/i.test(process.env.EXPO_PUBLIC_XDT_GIT_COMMIT ?? '')
? process.env.EXPO_PUBLIC_XDT_GIT_COMMIT : 'unknown',
@@ -857,6 +863,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const offStatus = client.onStatusChange((next) => {
setStatus(next);
if (next !== 'online') {
+ catalogRefresh.clear();
openLinkInFlightRef.current.clear();
remoteSubscribedTopicsRef.current.clear();
// 掉线:所有会话的实时行都可能从此漏收,窗口连续性结论的上界不再可续算。
@@ -1003,11 +1010,13 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const offFrame = client.onFrame((env) => routeFrame(env, {
currentDataOwnerId: currentDataOwnerIdRef.current,
onAccessRevoked: (deviceId) => {
+ catalogRefresh.cancel(deviceId);
remoteSubscribedTopicsRef.current.delete(deviceId);
forcedPeerRecoveryIntentRef.current.cancel(deviceId);
peerRecoverySchedulerRef.current?.cancel(deviceId);
},
onLinkClosed: (deviceId, reason) => {
+ catalogRefresh.cancel(deviceId);
resetRemoteProjectOrderPushFence(deviceId);
updateRehydrateSuppressionOnLinkClose(
rehydrateSuppressedDeviceIds,
@@ -1056,30 +1065,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}
},
onProviderChanged: (deviceId) => {
- // provider 目录与 capabilities.availableModels 是同一份 active catalog 的两种视图。
- // 同时驱逐并后台重拉;页面保留旧画面,当前代完整快照提交后由订阅一次性更新。
- evictDeviceProviders(deviceId);
- evictAgentCapabilitiesForDevice(deviceId);
- const epochAtWrite = connectionEpoch;
- void fetchDeviceProviders(deviceId, () =>
- sendInvokeWithAccessHandling<DeviceProvidersPayload>(
- client,
- deviceId,
- 'maker:provider:list',
- [{ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2] }],
- )
- )
- .then(() => {
- // 无挂载 hook 的后台缓存写入也要标记所属连接代际(codex review P1):
- // 不 mark 则 deviceFetchEpoch 保持 undefined,断线前旧目录在重连后被
- // 当「首次挂载缓存命中」采信、永不刷新——选择器无限期展示已删供应商。
- // fetch 期间重连(epoch 变化)则 mark 的是捕获时的旧代际 → 下次 effect
- // 判 reconnected → 强制 fresh(保守正确)。失败不 mark(evict 已清缓存,
- // 无旧目录可被误采信)。
- markDeviceFetchEpoch(deviceId, epochAtWrite);
- })
- .catch(() => { /* 下次进入选择器或重连补齐时继续重试。 */ });
- void refreshDeviceCapabilities(client, deviceId);
+ catalogRefresh.notify(deviceId);
},
onAgentsChanged: (deviceId) => {
for (const listener of remoteAgentRosterListeners) listener(deviceId);
@@ -1254,6 +1240,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
offResponseEvidence();
offBeforeLink();
offFrame();
+ catalogRefresh.dispose();
offPresence();
offPeerTransportReset();
offStatus();
@@ -1512,28 +1499,6 @@ export function routeFrame(env: Envelope, handlers: {
} else if (historyView?.getSnapshot().ready && (push.channel === 'local-db:messages:created' || push.channel === 'maker:status-changed')) historyView.invalidate();
}
-/** provider revision 后并行重拉所有 agent 的能力;旧代或异常结果都不触碰当前页面。 */
-async function refreshDeviceCapabilities(
- client: DeviceLinkClient,
- deviceId: string,
-): Promise<void> {
- const generation = getAgentCapabilitiesGeneration(deviceId);
- await Promise.allSettled(
- (['claude-code', 'codex', 'pi'] as const).map(async (agentKind) => {
- const raw = await sendInvokeWithAccessHandling<unknown>(
- client,
- deviceId,
- 'maker:get-capabilities',
- [agentKind],
- );
- const normalized = normalizeMobileAgentCapabilities(raw);
- if (normalized) {
- commitAgentCapabilities(deviceId, agentKind, generation, normalized);
- }
- }),
- );
-}
-
async function rebuildSessionSnapshot(
client: DeviceLinkClient,
deviceId: string,
diff --git a/apps/mobile/src/device-link/deviceCatalogRefresh.ts b/apps/mobile/src/device-link/deviceCatalogRefresh.ts
new file mode 100644
index 0000000000..b6917427f8
--- /dev/null
+++ b/apps/mobile/src/device-link/deviceCatalogRefresh.ts
@@ -0,0 +1,83 @@
+import { PeerRecoveryScheduler } from './peerRecoveryScheduler';
+import {
+ fetchDeviceProviders, getDeviceProvidersGen, invalidateDeviceProvidersForRefresh,
+ markDeviceFetchEpoch, type DeviceProvidersPayload,
+} from './deviceProvidersCache';
+import {
+ commitAgentCapabilities, evictAgentCapabilitiesForDevice, fetchAgentCapabilities,
+ getAgentCapabilitiesGeneration,
+} from '@/session/agentCapabilitiesCache';
+import { normalizeMobileAgentCapabilities } from '@/session/agentCapabilities';
+
+/** Provider pushes are invalidations, not an instruction to start four more
+ * parallel RPCs. Reuse peer recovery's serialized rerun and cancellation rules. */
+export function createDeviceCatalogRefresh(options: {
+ readProviders(deviceId: string): Promise<DeviceProvidersPayload>;
+ readCapabilities(deviceId: string, agent: 'claude-code' | 'codex' | 'pi'): Promise<unknown>;
+ connectionEpoch(): number;
+}) {
+ let disposed = false;
+ const queued = new Map<string, ReturnType<typeof setTimeout>>();
+ const devices = new Set<string>();
+ const invalidate = (id: string) => {
+ invalidateDeviceProvidersForRefresh(id);
+ evictAgentCapabilitiesForDevice(id);
+ };
+ const scheduler = new PeerRecoveryScheduler(async (id) => {
+ const epoch = options.connectionEpoch();
+ const providerGeneration = getDeviceProvidersGen(id);
+ const generation = getAgentCapabilitiesGeneration(id);
+ const read = <T,>(fetcher: () => Promise<T>): Promise<T> => {
+ if (disposed || getAgentCapabilitiesGeneration(id) !== generation) return Promise.reject(new Error('Catalog refresh superseded'));
+ return fetcher();
+ };
+ await Promise.allSettled([
+ fetchDeviceProviders(id, () => read(() => options.readProviders(id))).then(() => {
+ if (!disposed && getDeviceProvidersGen(id) === providerGeneration) markDeviceFetchEpoch(id, epoch);
+ }),
+ ...(['claude-code', 'codex', 'pi'] as const).map(async (agent) => {
+ const raw = await fetchAgentCapabilities(id, agent, () => read(() => options.readCapabilities(id, agent)));
+ const normalized = normalizeMobileAgentCapabilities(raw);
+ if (!disposed && normalized) commitAgentCapabilities(id, agent, generation, normalized);
+ }),
+ ]);
+ // Failures use the existing picker/reconnect recovery, not another retry loop.
+ return { retry: false };
+ });
+ return {
+ notify(id: string) {
+ if (disposed) return;
+ devices.add(id);
+ invalidate(id); // Immediately fence responses already on the wire.
+ if (queued.has(id)) return;
+ // Separate socket callbacks from the same burst need a bounded batching
+ // window, not just a microtask. Further notifications never extend it.
+ queued.set(id, setTimeout(() => {
+ queued.delete(id);
+ if (disposed) return;
+ scheduler.request(id);
+ }, 50));
+ },
+ cancel(id: string) {
+ clearTimeout(queued.get(id));
+ queued.delete(id);
+ scheduler.cancel(id);
+ if (devices.delete(id)) invalidate(id);
+ },
+ clear() {
+ for (const timer of queued.values()) clearTimeout(timer);
+ queued.clear();
+ scheduler.clear();
+ for (const id of devices) invalidate(id);
+ devices.clear();
+ },
+ dispose() {
+ disposed = true;
+ for (const timer of queued.values()) clearTimeout(timer);
+ queued.clear();
+ scheduler.clear();
+ for (const id of devices) invalidate(id);
+ devices.clear();
+ },
+ };
+}
diff --git a/apps/mobile/src/device-link/deviceProvidersCache.ts b/apps/mobile/src/device-link/deviceProvidersCache.ts
index 497e11376c..4235e6d3a3 100644
--- a/apps/mobile/src/device-link/deviceProvidersCache.ts
+++ b/apps/mobile/src/device-link/deviceProvidersCache.ts
@@ -56,6 +56,7 @@ async function requestDeviceProviders(
// 缓存按被控设备隔离;代际同桌面(evict 时自增,作废在途 fetch 的回写)。
const cache = new Map<string, DeviceProvidersPayload>();
const inflight = new Map<string, Promise<DeviceProvidersPayload>>();
+const readGeneration = new WeakMap<Promise<DeviceProvidersPayload>, number>();
const deviceGen = new Map<string, number>();
const listeners = new Map<string, Set<(payload: DeviceProvidersPayload) => void>>();
const errorListeners = new Map<string, Set<(error: unknown) => void>>();
@@ -131,9 +132,9 @@ export async function fetchDeviceProviders(
// 捕获与 fresh 相同的代际,晚于 fresh 返回仍通过 isCurrent() 覆盖共享缓存。
// fresh 结果即工作站最新真相,普通读取 join 它语义正确且不会产生竞争请求。
const fp = freshInflight.get(deviceId);
- if (fp) return fp;
+ if (fp) return joinProviderRead(deviceId, fp, () => fetchDeviceProviders(deviceId, fetcher));
const ip = inflight.get(deviceId);
- if (ip) return ip;
+ if (ip) return joinProviderRead(deviceId, ip, () => fetchDeviceProviders(deviceId, fetcher));
// 捕获发起时代际;回调里若代际已变(被 evict)则认为本次请求作废,不回写 cache / 不动 inflight。
const startGen = deviceGen.get(deviceId) ?? 0;
@@ -162,9 +163,36 @@ export async function fetchDeviceProviders(
throw e;
});
inflight.set(deviceId, p);
+ readGeneration.set(p, startGen);
+ void p.finally(() => {
+ if (inflight.get(deviceId) === p) inflight.delete(deviceId);
+ }).catch(() => undefined);
return p;
}
+/** A revision retires the result, not the physical request. New readers wait for
+ * it to settle, then share one current-generation read instead of flooding the link. */
+function joinProviderRead(
+ deviceId: string,
+ pending: Promise<DeviceProvidersPayload>,
+ next: () => Promise<DeviceProvidersPayload>,
+): Promise<DeviceProvidersPayload> {
+ const generation = getDeviceProvidersGen(deviceId);
+ if (readGeneration.get(pending) === generation) return pending;
+ return pending.catch(() => undefined).then(() => {
+ if (getDeviceProvidersGen(deviceId) !== generation) throw new Error('Provider read superseded');
+ return next();
+ });
+}
+
+/** Catalog push refresh owns the replacement read; mounted hooks only retire
+ * readiness. Keep in-flight slots so a burst cannot start overlapping reads. */
+export function invalidateDeviceProvidersForRefresh(deviceId: string): void {
+ cache.delete(deviceId);
+ deviceGen.set(deviceId, getDeviceProvidersGen(deviceId) + 1);
+ notifyDeviceProvidersGen(deviceId, 'fresh-invalidate');
+}
+
/**
* 强制刷新取某被控设备的供应商目录(codex review P2):**跳过缓存命中短路**——
* 即使缓存仍存在也执行 fetcher 访问工作站,成功后回写缓存并推送 payload 订阅者。
@@ -181,7 +209,10 @@ export async function fetchDeviceProvidersFresh(
fetcher: DeviceProvidersFetcher,
): Promise<DeviceProvidersPayload> {
const fp = freshInflight.get(deviceId);
- if (fp) return fp;
+ // After an obsolete read settles, all waiters share the replacement started
+ // after this call. Re-entering fresh would invalidate a sibling waiter's new
+ // read and send a duplicate; independent fresh calls still bypass cache below.
+ if (fp) return joinProviderRead(deviceId, fp, () => fetchDeviceProviders(deviceId, fetcher));
// fresh 语义 = 强制访问工作站拿当前真相。仅当确有普通请求在途时才作废它
// (greptile/copilot/codex review P1/P2):旧普通请求若在 fresh 之后返回,仍会
@@ -191,6 +222,9 @@ export async function fetchDeviceProvidersFresh(
// 为外部驱逐而丢弃结果;仅在确有在途时推进,守卫下一轮重跑(普通在途已清)
// 即收敛,gen 保持稳定时 fetch 前后一致直接采信。
const ip = inflight.get(deviceId);
+ if (ip && readGeneration.get(ip) !== getDeviceProvidersGen(deviceId)) {
+ return joinProviderRead(deviceId, ip, () => fetchDeviceProviders(deviceId, fetcher));
+ }
if (ip) {
inflight.delete(deviceId);
deviceGen.set(deviceId, (deviceGen.get(deviceId) ?? 0) + 1);
@@ -222,6 +256,7 @@ export async function fetchDeviceProvidersFresh(
throw error;
});
freshInflight.set(deviceId, p);
+ readGeneration.set(p, startGen);
void p.finally(() => {
if (freshInflight.get(deviceId) === p) freshInflight.delete(deviceId);
}).catch(() => undefined);
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index cea34a6015..8e4f514dfb 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -4,6 +4,7 @@ import {
releasePeerMedia,
} from "./peerFileRegistry";
import { withTransientRemoteRetry } from "./remoteRetry";
+import { fetchAgentCapabilities } from "@/session/agentCapabilitiesCache";
import {
getMobileAuthOwner,
isMobileAuthOwnerCurrent,
@@ -902,7 +903,10 @@ export function createMobileMakerTransport({
return {
createSession: (opts) => call("maker:create-session", [opts]),
- getCapabilities: (agentKind) => call("maker:get-capabilities", [agentKind]),
+ getCapabilities: (agentKind) => fetchAgentCapabilities(deviceId, agentKind, () => {
+ if (!isCurrent()) throw new Error("Capabilities read superseded");
+ return call("maker:get-capabilities", [agentKind]);
+ }),
listAvailableAgents: () => call('maker:list-available-agents', []),
// Pi 原生分支树通过 device-link 复用桌面端 runtime;移动会话页只在当前会话
// 确认为 Pi 时展示入口,并在渲染前校验返回的树形状。
diff --git a/apps/mobile/src/session/agentCapabilitiesCache.ts b/apps/mobile/src/session/agentCapabilitiesCache.ts
index ff6a2904c9..de2a219a9c 100644
--- a/apps/mobile/src/session/agentCapabilitiesCache.ts
+++ b/apps/mobile/src/session/agentCapabilitiesCache.ts
@@ -12,6 +12,33 @@ import type { MobileAgentCapabilities } from '@/session/agentCapabilities';
const cache = new Map<string, MobileAgentCapabilities>();
const deviceGen = new Map<string, number>();
const listeners = new Map<string, Set<(value: MobileAgentCapabilities) => void>>();
+const inflight = new Map<string, { generation: number; promise: Promise<unknown> }>();
+
+/** Share page and push-triggered reads. A newer generation waits for the old
+ * physical read to settle, but never adopts its result or revives an old owner. */
+export function fetchAgentCapabilities(
+ deviceId: string,
+ agentKind: string,
+ fetcher: () => Promise<unknown>,
+): Promise<unknown> {
+ const key = buildAgentCapabilitiesCacheKey(deviceId, agentKind);
+ const generation = getAgentCapabilitiesGeneration(deviceId);
+ deviceGen.set(deviceId, generation);
+ const pending = inflight.get(key);
+ if (pending) {
+ if (pending.generation === generation) return pending.promise;
+ return pending.promise.catch(() => undefined).then(() => {
+ if (!isAgentCapabilitiesGenerationCurrent(deviceId, generation)) throw new Error('Capabilities read superseded');
+ return fetchAgentCapabilities(deviceId, agentKind, fetcher);
+ });
+ }
+ const promise = Promise.resolve().then(fetcher);
+ inflight.set(key, { generation, promise });
+ void promise.finally(() => {
+ if (inflight.get(key)?.promise === promise) inflight.delete(key);
+ }).catch(() => undefined);
+ return promise;
+}
export function buildAgentCapabilitiesCacheKey(deviceId: string, agentKind: string): string {
return `${deviceId} ${agentKind}`;
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index 0452d1635c..afe96f7938 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -85,6 +85,12 @@ Desktop 和 Mobile 的按设备排队、并发上限、退避、取消代次由
主机数据库后台准入是独立的资源分配策略,不能直接复用上述 listing 集合作为分类依据。
这些策略不改变 wire 格式或通道权限;权限仍以 allowlist 为准。
+Mobile 的模型目录变化通知由 `deviceCatalogRefresh.ts` 按设备合并,失效立即推进代次,
+在途读取结算后再补拉最新快照;页面与后台共享能力读取,通知不得清掉物理在途槽后重复发包。
+可靠传输在本地 WebSocket 出现积压时提前暂停数据写入,复用公平预算与短间隔 drain,
+为 ACK/握手保留硬上限之前的余量;不等待 relay 的 1013 才降速,也不对已排空的健康
+socket 固定限速。最大逻辑消息仍可在排空后原子发送,不改变可靠序号和跨版本协议。
+
## 模块通过 Remote Resource 接入移动端
面向移动端新增独立产品入口时,默认通过 `@cindy/device-link` 的 Remote Resource
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 5e00a29141..8bf7a9f832 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -6781,6 +6781,83 @@ describe('DeviceLinkClient relay 拥塞断连(close 1013)', () => {
} finally { h.client.stop(); vi.useRealTimers(); }
});
+ it('paces a slow socket before any 1013 while another peer and control ACKs keep progressing', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: { pingIntervalMs: 600_000 } });
+ try {
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(0);
+ h.current().ack();
+ for (const peer of ['a', 'b']) {
+ const opened = establishInboundReliableLink(h, `stream-${peer}`, 1, peer);
+ await vi.advanceTimersByTimeAsync(0);
+ await opened;
+ }
+ const socket = h.current();
+ socket.sent.length = 0;
+ const send = socket.send.bind(socket);
+ let peak = 0;
+ socket.send = (data) => {
+ socket.bufferedAmount += Buffer.byteLength(data);
+ peak = Math.max(peak, socket.bufferedAmount);
+ send(data);
+ };
+ // Repeat the incident's ~300KB catalog replies; a deliberately never ACKs.
+ for (let i = 0; i < 12; i++) h.client.sendInvokeResult('a', `catalog-${i}`, { ok: true, result: 'x'.repeat(295_000) });
+ const firstBurst = socket.sent.length;
+ h.client.sendInvokeResult('b', 'healthy-result', { ok: true, result: 'ok' });
+ socket.push(encodeReliableFrames({ v: 1, kind: 'push', src: 'a', payload: { channel: 'maker:event', payload: {} } }, 'stream-a', 1)[0]);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(socket.sent.some((env) => (env.payload as { channel?: string })?.channel === DEVICE_LINK_TRANSPORT_ACK_CHANNEL)).toBe(true);
+ expect(firstBurst).toBeLessThan(12);
+ for (let window = 0; window < 24; window++) {
+ socket.bufferedAmount = Math.max(0, socket.bufferedAmount - 128 * 1024);
+ await vi.advanceTimersByTimeAsync(250);
+ if (window === 3) expect(socket.sent.some((env) => env.id === 'healthy-result')).toBe(true);
+ }
+ const ids = new Set(socket.sent.filter((env) => env.dst === 'a' && env.kind === 'invoke-result').map((env) => env.id));
+ expect(ids.size).toBe(12);
+ expect(peak).toBeLessThan(1024 * 1024);
+ expect(h.client.getStatus()).toBe('online');
+ expect(socket.closed).toBeNull();
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
+ it('admits an atomic maximum-size reply after draining without pacing a fast empty socket', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: { pingIntervalMs: 600_000 } });
+ try {
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(0);
+ h.current().ack();
+ const opened = establishInboundReliableLink(h, 'stream-a', 1, 'a');
+ await vi.advanceTimersByTimeAsync(0);
+ await opened;
+ const socket = h.current();
+ socket.sent.length = 0;
+ socket.bufferedAmount = 600 * 1024;
+ h.client.sendInvokeResult('a', 'max-reply', { ok: true, result: 'x'.repeat(4 * 1024 * 1024 - 1024) });
+ expect(socket.sent).toHaveLength(0);
+ socket.bufferedAmount = 0;
+ await vi.advanceTimersByTimeAsync(250);
+ const large = socket.sent.filter((env) => env.id === 'max-reply');
+ expect(large.length).toBeGreaterThan(1);
+ const last = parseTransportPayload(large.at(-1)!.payload)!;
+ expect(large.length).toBe(last.meta.segment!.total);
+ socket.push({ v: 1, kind: 'push', src: 'a', payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: { streamId: last.meta.streamId, ackSeq: last.meta.seq },
+ } });
+ const beforeLarge = socket.sent.length;
+ h.client.sendInvokeResult('a', 'fast-large', { ok: true, result: 'x'.repeat(4 * 1024 * 1024 - 1024) });
+ expect(socket.sent.length - beforeLarge).toBe(large.length);
+ const before = socket.sent.length;
+ for (let i = 0; i < 10; i++) h.client.sendInvokeResult('a', `fast-${i}`, { ok: true, result: 'ok' });
+ expect(socket.sent.length - before).toBe(10);
+ expect(socket.closed).toBeNull();
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
it('paces all reliable sends after 1013 without starving another peer or control ACKs', async () => {
vi.useFakeTimers();
const h = makeHarness({ timing: {
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index ee268e4ad8..f5499d8db7 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -111,6 +111,12 @@ const HANDSHAKE_TIMEOUT_WIDEN_AFTER = 2;
/** 「link 未就绪收到可靠帧」通知的 per-peer 节流(见 onReliableFrameBeforeLink)。 */
const STALE_LINK_NOTIFY_THROTTLE_MS = 30_000;
const SLOW_REQUEST_WARN_MS = 1_000;
+// Stop bulk writes well before the native socket's hard limit. Control envelopes
+// retain the hard-limit headroom; healthy sockets that drain immediately stay unpaced.
+const SOCKET_DATA_HIGH_WATER_BYTES = 512 * 1024;
+const SOCKET_DATA_LOW_WATER_BYTES = 128 * 1024;
+const SOCKET_CONTROL_RESERVE_BYTES = 64 * 1024;
+const SOCKET_SEND_CREDIT_BYTES = 64 * 1024;
/**
* 接收端累计 ACK 的推进粒度。整批 drain 完成前完全不 ACK 会让发送端把
* 已成功处理的前缀也等在慢 handler 后面。小批量 ACK 让发送端及时释放
@@ -664,6 +670,8 @@ export class DeviceLinkClient {
*/
private congestionCloseStreak = 0;
private readonly congestionSendBudget = new CongestionSendBudget();
+ private localSendPressure = false;
+ private readonly localSendBudget = new CongestionSendBudget();
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectStableTimer: ReturnType<typeof setTimeout> | null = null;
private congestionStableTimer: ReturnType<typeof setTimeout> | null = null;
@@ -945,6 +953,8 @@ export class DeviceLinkClient {
this.failAllPending(new DeviceLinkError('NOT_CONNECTED', 'client stopped'));
this.clearPeerTransport();
this.congestionSendBudget.reset();
+ this.localSendPressure = false;
+ this.localSendBudget.reset();
this.pendingInboundLinkOffers.clear();
this.staleLinkNotifiedAt.clear();
this.resetLegacyInboundQueue();
@@ -1750,6 +1760,8 @@ export class DeviceLinkClient {
return;
}
this.ws = ws;
+ this.localSendPressure = false;
+ this.localSendBudget.reset();
this.armHandshakeTimeout(epoch);
ws.on('open', () => {
@@ -2976,19 +2988,40 @@ export class DeviceLinkClient {
pending.seq,
this.getTransportBaseSeq(peer),
);
+ const wireBytes = this.measureReliableFrames(frames);
+ const peers = this.getReadyReliablePeers(pending.envelope.dst!);
+ const budgetNow = this.monotonicNow();
const congestionBudget = this.congestionCloseStreak > 0 ? this.congestionSendBudget : null;
+ if (congestionBudget && !congestionBudget.canTake(
+ pending.envelope.dst!, frames.length, peers, budgetNow,
+ )) return 0;
+ // Keep hard-cap errors unchanged. Soft pressure only delays the existing
+ // bounded reliable queue, without consuming attempts or changing sequence IDs.
+ this.assertWebSocketCapacity(wireBytes);
+ if (!this.canWriteReliableBytes(wireBytes)) return 0;
+ const localBudget = this.localSendPressure ? this.localSendBudget : null;
+ const byteCredits = Math.ceil(wireBytes / SOCKET_SEND_CREDIT_BYTES);
+ if (localBudget && !localBudget.canTake(
+ pending.envelope.dst!, byteCredits, peers, budgetNow,
+ )) return 0;
if (congestionBudget) {
if (!congestionBudget.take(
- pending.envelope.dst!, frames.length, this.getReadyReliablePeers(pending.envelope.dst!), this.monotonicNow(),
+ pending.envelope.dst!, frames.length, peers, budgetNow,
)) return 0;
}
+ if (localBudget && !localBudget.take(pending.envelope.dst!, byteCredits, peers, budgetNow)) {
+ congestionBudget?.refund(pending.envelope.dst!, frames.length);
+ return 0;
+ }
let sent = 0;
+ let writtenBytes = 0;
try {
- this.assertWebSocketCapacity(this.measureReliableFrames(frames));
+ this.assertWebSocketCapacity(wireBytes);
for (const frame of frames) {
// pending 可在 link down 时入队,并在后续 link generation 才首次上网;
// 路由错误必须归属每次真实物理发送,而不是逻辑消息的入队代次。
this.sendRoutedEnvelope(frame, peer.linkGeneration);
+ writtenBytes += byteLength(JSON.stringify(frame));
pending.sent = true;
sent += 1;
}
@@ -3000,6 +3033,7 @@ export class DeviceLinkClient {
);
} finally {
congestionBudget?.refund(pending.envelope.dst!, frames.length - sent);
+ localBudget?.refund(pending.envelope.dst!, byteCredits - Math.ceil(writtenBytes / SOCKET_SEND_CREDIT_BYTES));
if (sent > 0) {
const ageMs = Math.round(this.monotonicNow() - pending.enqueuedAt);
if ((pending.envelope.kind === 'invoke' || pending.envelope.kind === 'invoke-result')
@@ -3022,6 +3056,28 @@ export class DeviceLinkClient {
return sent;
}
+ private canWriteReliableBytes(bytes: number): boolean {
+ const buffered = this.ws?.bufferedAmount ?? 0;
+ const pressured = buffered > SOCKET_DATA_LOW_WATER_BYTES
+ && (this.localSendPressure || buffered + bytes > SOCKET_DATA_HIGH_WATER_BYTES);
+ if (pressured !== this.localSendPressure) {
+ this.localSendPressure = pressured;
+ if (!pressured) this.localSendBudget.reset();
+ // Reuse the existing drain timer, accelerate only while the socket is slow.
+ for (const [id, state] of this.peerTransport) {
+ if (!state.retryTimer) continue;
+ clearInterval(state.retryTimer);
+ state.retryTimer = null;
+ this.ensureRetryTimer(id);
+ }
+ }
+ // Chunks are sent atomically. A maximum-size message must be able to progress
+ // once the socket drains, even though it exceeds the ordinary data watermark.
+ return buffered + bytes <= SOCKET_DATA_HIGH_WATER_BYTES
+ || (buffered <= SOCKET_DATA_LOW_WATER_BYTES
+ && buffered + bytes <= MAX_TRANSPORT_WEBSOCKET_BUFFERED_BYTES - SOCKET_CONTROL_RESERVE_BYTES);
+ }
+
private isOutsideReceiveWindow(peer: PeerTransportState, seq: number): boolean {
// Keep future messages at the sender until cumulative ACK advances. A
// receiver has only this many reassembly/ready slots; sending 64 pending
@@ -3876,7 +3932,7 @@ export class DeviceLinkClient {
if (peer.retryTimer) return;
peer.retryTimer = setInterval(
() => this.retryPending(dst, { ignoreInterval: false }),
- this.congestionCloseStreak > 0
+ this.congestionCloseStreak > 0 || this.localSendPressure
? Math.min(250, this.timing.transportRetryIntervalMs)
: this.timing.transportRetryIntervalMs,
);