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。

refactor(device-link): 归并桌面和手机的恢复调度与请求策略 (#4443)

Dash5a8e74a6bad3
diff --git a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
index 970ab8d5c4..c5fb6018cd 100644
--- a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
@@ -375,8 +375,8 @@ describe('active runtime summary projection', () => {
describe('schedule sidebar index tunnel cap', () => {
it('coalesces the schedule index channel with other listing reads', () => {
- expect(__testing.coalesceRemoteInvokeChannels.has('maker:schedule:list-sidebar-index-runs')).toBe(true);
- expect(__testing.coalesceRemoteInvokeChannels.has('local-db:sessions:list')).toBe(true);
+ expect(__testing.canCoalesceRemoteListing({ channel: 'maker:schedule:list-sidebar-index-runs', args: [] })).toBe(true);
+ expect(__testing.canCoalesceRemoteListing({ channel: 'local-db:sessions:list', args: [] })).toBe(true);
});
it('keeps the newest mapping when the snapshot exceeds the tunnel budget', () => {
diff --git a/apps/desktop/src/main/device-link/__tests__/subscriptionReplayScheduler.test.ts b/apps/desktop/src/main/device-link/__tests__/subscriptionReplayScheduler.test.ts
index 6e82431477..90ef7a21e4 100644
--- a/apps/desktop/src/main/device-link/__tests__/subscriptionReplayScheduler.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/subscriptionReplayScheduler.test.ts
@@ -219,7 +219,7 @@ describe('subscription replay scheduler', () => {
expect(calls).toEqual([['session:one'], ['session:one', 'session:two']]);
});
- it('does not let an old request clear a new generation after teardown and reacquire', async () => {
+ it('serializes reacquired work behind the cancelled request without losing the new generation', async () => {
const deviceId = 'device-a';
const first = deferred<unknown>();
const second = deferred<unknown>();
@@ -242,7 +242,7 @@ describe('subscription replay scheduler', () => {
scheduler.replay('ws-online');
scheduler.teardown();
scheduler.replay('ws-online-reacquire');
- expect(remoteSubscribe).toHaveBeenCalledTimes(2);
+ expect(remoteSubscribe).toHaveBeenCalledTimes(1);
first.resolve(undefined);
await Promise.resolve();
@@ -255,6 +255,32 @@ describe('subscription replay scheduler', () => {
expect(remoteSubscribe).toHaveBeenCalledTimes(2);
});
+ it('bounds reconnect replay and rechecks subscriptions when queued peers get a slot', async () => {
+ let refs = Array.from({ length: 8 }, (_, index) => ({ deviceId: `peer-${index}`, topics: ['sessions'] }));
+ const pending = deferred<unknown>();
+ const remoteSubscribe = vi.fn().mockReturnValue(pending.promise);
+ const scheduler = createSubscriptionReplayScheduler({
+ snapshotSubscriptions: (id) => refs.filter((ref) => !id || id === ref.deviceId),
+ remoteSubscribe,
+ isLinkTornDown: () => false,
+ isRelayOnline: () => true,
+ isDeviceUnresponsive: () => false,
+ getPresenceAvailability: () => true,
+ isPermanentError: () => false,
+ log: { debug: vi.fn(), warn: vi.fn() },
+ });
+ scheduler.replay('ws-online');
+ expect(remoteSubscribe).toHaveBeenCalledTimes(6);
+ refs = refs.filter((ref) => ref.deviceId !== 'peer-6');
+ refs.find((ref) => ref.deviceId === 'peer-7')!.topics = ['session:new'];
+ pending.resolve(undefined);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(remoteSubscribe).toHaveBeenCalledTimes(7);
+ expect(remoteSubscribe).toHaveBeenLastCalledWith('peer-7', ['session:new']);
+ scheduler.teardown();
+ });
+
it('invalidates retry timers from an old generation', async () => {
vi.useFakeTimers();
try {
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 1071c8c373..a655beff24 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -21,6 +21,7 @@
import {
computeAllowlistHash,
+ canCoalesceRemoteListing,
INVOKE_TIMEOUT_OVERRIDES_MS,
MAX_FRAME_BYTES,
PROTOCOL_VERSION,
@@ -638,19 +639,12 @@ type RemoteInvokeBusyChangedListener = (busy: boolean) => void;
let onRemoteInvokeBusyChanged: RemoteInvokeBusyChangedListener | null = null;
let inFlightRemoteInvokeCount = 0;
const REMOTE_INVOKE_IN_FLIGHT_LIMIT = 64;
-/**
- * 控制端周期对账 / 熔断探测会用新 requestId 连打相同 listing。按 requestId 去重
- * 拦不住,16 条并发 sessions:list 会把单线程 DB worker 打到 128/512 硬顶。
- * 同一控制端、同一 channel+args 的只读 listing 合并成一次执行。
- */
-const COALESCE_REMOTE_INVOKE_CHANNELS: ReadonlySet<string> = new Set([
+/** Host DB admission is independent of whether a read can share an in-flight snapshot. */
+const BACKGROUND_REMOTE_INVOKE_CHANNELS: ReadonlySet<string> = new Set([
'local-db:sessions:list',
- // sessions:get 是写后权威回读(mobile 设置失败恢复会复用同一参数),
- // 不能并进仍停在投影 await 的写前查询。
'maker:get-capabilities',
'maker:provider:list',
'maker:git-safety:get',
- // Studio/手机周期对账会连打这条;不合并就会把单线程 DB worker 打满。
'maker:schedule:list-sidebar-index-runs',
]);
/** 隧道回包必须低于 4MB 传输上限与 per-controller 4MB 准入;2MB 给 envelope 留余量。 */
@@ -2668,19 +2662,6 @@ function currentRemoteInvokeAdmissionFailure(src: string): InvokeResultPayload |
return null;
}
-function isFreshSessionListInvoke(payload: InvokePayload): boolean {
- if (payload.channel !== 'local-db:sessions:list') return false;
- const options = payload.args?.[2];
- return !!(options && typeof options === 'object' && !Array.isArray(options)
- && (options as { fresh?: unknown }).fresh === true);
-}
-
-function canCoalesceRemoteListing(payload: InvokePayload | undefined): payload is InvokePayload {
- return !!payload
- && COALESCE_REMOTE_INVOKE_CHANNELS.has(payload.channel)
- && !isFreshSessionListInvoke(payload);
-}
-
function remoteListingFlightKey(src: string, payload: InvokePayload): string {
return `${src}\u0000${payload.channel}\u0000${JSON.stringify(payload.args ?? [])}`;
}
@@ -3734,7 +3715,7 @@ export async function runInvoke(
payload.channel,
payload.channel === 'maker:provider:list' ? [] : args,
);
- return COALESCE_REMOTE_INVOKE_CHANNELS.has(payload.channel)
+ return BACKGROUND_REMOTE_INVOKE_CHANNELS.has(payload.channel)
? runAsBackgroundDbRpc(invoke)
: invoke();
},
@@ -3878,7 +3859,7 @@ export const __testing = {
projectInvokeResultForTunnel,
capScheduleSidebarIndexForTunnel,
remoteScheduleIndexMaxBytes: REMOTE_SCHEDULE_INDEX_MAX_BYTES,
- coalesceRemoteInvokeChannels: COALESCE_REMOTE_INVOKE_CHANNELS,
+ canCoalesceRemoteListing,
remoteInvokeInFlightLimit: REMOTE_INVOKE_IN_FLIGHT_LIMIT,
remoteInvokeInFlightPerControllerLimit: REMOTE_INVOKE_IN_FLIGHT_PER_CONTROLLER_LIMIT,
remoteInvokeOrphanTimeoutMs: REMOTE_INVOKE_ORPHAN_TIMEOUT_MS,
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index a8dd5d292e..b4d03cb9b7 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -38,7 +38,7 @@ import {
type Envelope,
type PushPayload,
DeviceLinkError,
- INVOKE_TIMEOUT_OVERRIDES_MS,
+ resolveRemoteInvokeTimeoutMs,
} from '@cindy/device-link';
import { DEVICE_LINK_VOICE_DICTIONARY_SNAPSHOT_CHANNEL } from '@cindy/maker-shared/device-link-contract';
import * as authManager from '../authManager';
@@ -700,7 +700,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
probeInvoke: (deviceId, channel, args) => {
if (!client)
throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');
- return client.invoke(deviceId, { channel, args }, INVOKE_TIMEOUT_OVERRIDES_MS[channel]);
+ return client.invoke(deviceId, { channel, args }, resolveRemoteInvokeTimeoutMs(channel, args, 'desktop'));
},
onUnresponsiveChanged: (deviceId, unresponsive) => {
broadcast(DEVICE_LINK_PUSH.RESPONSIVENESS_CHANGED, { deviceId, unresponsive });
@@ -1703,7 +1703,7 @@ export async function remoteInvoke(
assertLinkNotClosedSinceStart();
options?.preSend?.();
if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');
- return client.invoke(deviceId, { channel, args }, INVOKE_TIMEOUT_OVERRIDES_MS[channel]);
+ return client.invoke(deviceId, { channel, args }, resolveRemoteInvokeTimeoutMs(channel, args, 'desktop'));
};
const run = (): Promise<InvokeResultPayload> =>
invokeWithClosedLinkRecovery(
diff --git a/apps/desktop/src/main/device-link/subscriptionReplayScheduler.ts b/apps/desktop/src/main/device-link/subscriptionReplayScheduler.ts
index 7bd1db7dbd..4b93b9d3e4 100644
--- a/apps/desktop/src/main/device-link/subscriptionReplayScheduler.ts
+++ b/apps/desktop/src/main/device-link/subscriptionReplayScheduler.ts
@@ -1,4 +1,4 @@
-import { DeviceLinkError } from '@cindy/device-link';
+import { DeviceLinkError, PeerRecoveryScheduler } from '@cindy/device-link';
const PERMANENT_SUBSCRIPTION_REPLAY_CODES: ReadonlySet<string> = new Set([
'VERSION_MISMATCH',
@@ -34,8 +34,6 @@ export type SubscriptionReplayScheduler = {
teardown(): void;
};
-type Timer = ReturnType<typeof setTimeout>;
-
type SubscriptionReplaySchedulerOptions = {
snapshotSubscriptions: (deviceId?: string) => SubscriptionReplayRef[];
remoteSubscribe: (deviceId: string, topics: string[]) => Promise<unknown>;
@@ -63,112 +61,43 @@ type SubscriptionReplaySchedulerOptions = {
export function createSubscriptionReplayScheduler(
options: SubscriptionReplaySchedulerOptions,
): SubscriptionReplayScheduler {
- const retryBaseMs = options.retryBaseMs ?? 3_000;
- const retryMaxMs = options.retryMaxMs ?? 30_000;
- const retryTimers = new Map<string, Timer>();
- const inFlight = new Map<string, symbol>();
- const pendingReruns = new Map<string, string>();
- const generations = new Map<string, number>();
-
- const currentGeneration = (deviceId: string): number => generations.get(deviceId) ?? 0;
-
- const clearTimer = (deviceId: string): void => {
- const timer = retryTimers.get(deviceId);
- if (!timer) return;
- clearTimeout(timer);
- retryTimers.delete(deviceId);
- };
-
- const replayDevice = (
- deviceId: string,
- topics: string[],
- reason: string,
- attempt: number,
- generation?: number,
- ): void => {
- if (inFlight.has(deviceId)) {
- pendingReruns.set(deviceId, reason);
- return;
- }
-
- const gen = generation ?? currentGeneration(deviceId) + 1;
- if (generation === undefined) generations.set(deviceId, gen);
- clearTimer(deviceId);
-
- const requestToken = Symbol(deviceId);
- inFlight.set(deviceId, requestToken);
- void options.remoteSubscribe(deviceId, topics).catch((error: unknown) => {
- if (currentGeneration(deviceId) !== gen) return;
- if (options.isPermanentError(error, deviceId)) {
- options.log.warn(
- `device-link replay subscriptions failed (${reason}) for ${deviceId.slice(0, 8)}, permanent, giving up: ${String(error)}`,
- );
- return;
- }
-
- const delay = Math.min(retryBaseMs * 2 ** attempt, retryMaxMs);
+ // Reuse Mobile's per-peer serialization, cancellation and retry accounting.
+ // The adapter owns only Desktop's subscription snapshot and availability gates.
+ const scheduler = new PeerRecoveryScheduler(async (deviceId) => {
+ if (options.isLinkTornDown() || !options.isRelayOnline()) return { retry: false };
+ if (options.isDeviceUnresponsive(deviceId)) return { retry: false };
+ if (options.getPresenceAvailability(deviceId) === false) return { retry: false };
+ const current = options.snapshotSubscriptions(deviceId)
+ .find((ref) => ref.deviceId === deviceId);
+ if (!current || current.topics.length === 0) return { retry: false };
+ try {
+ await options.remoteSubscribe(deviceId, current.topics);
+ return { retry: false };
+ } catch (error) {
+ const retry = !options.isPermanentError(error, deviceId);
options.log.warn(
- `device-link replay subscriptions failed (${reason}) for ${deviceId.slice(0, 8)}, retrying in ${delay}ms: ${String(error)}`,
+ `device-link replay subscriptions failed for ${deviceId.slice(0, 8)}, ` +
+ `${retry ? 'retrying with backoff' : 'permanent, giving up'}: ${String(error)}`,
);
- const timer = setTimeout(() => {
- retryTimers.delete(deviceId);
- if (currentGeneration(deviceId) !== gen) return;
- if (options.isLinkTornDown() || !options.isRelayOnline()) return;
- if (options.isDeviceUnresponsive(deviceId)) return;
- // Presence is incremental and resets on reconnect. Unknown must keep the
- // existing backoff alive; only an explicit offline/disabled verdict stops it.
- if (options.getPresenceAvailability(deviceId) === false) return;
- const current = options
- .snapshotSubscriptions(deviceId)
- .find((ref) => ref.deviceId === deviceId);
- if (!current || current.topics.length === 0) return;
- replayDevice(deviceId, current.topics, `${reason}-retry`, attempt + 1, gen);
- }, delay);
- timer.unref?.();
- retryTimers.set(deviceId, timer);
- }).finally(() => {
- // A teardown/re-acquire can start a new request before an old one settles.
- // Only the request that registered the token may clear in-flight state.
- if (inFlight.get(deviceId) !== requestToken) return;
- inFlight.delete(deviceId);
- const pendingReason = pendingReruns.get(deviceId);
- if (!pendingReason) return;
- pendingReruns.delete(deviceId);
- if (options.isLinkTornDown() || !options.isRelayOnline()) return;
- replay(pendingReason + '-pending', deviceId);
- });
- };
-
- const replay = (reason: string, deviceId?: string): void => {
- const refs = options.snapshotSubscriptions(deviceId);
- if (refs.length === 0) return;
- const topicCount = refs.reduce((sum, item) => sum + item.topics.length, 0);
- options.log.debug(
- `device-link replay subscriptions (${reason}): devices=${refs.length} topics=${topicCount}`,
- );
- for (const ref of refs) replayDevice(ref.deviceId, ref.topics, reason, 0);
- };
-
- const cancel = (deviceId: string): void => {
- generations.set(deviceId, currentGeneration(deviceId) + 1);
- clearTimer(deviceId);
- pendingReruns.delete(deviceId);
- };
-
- const teardown = (): void => {
- const devices = new Set([
- ...retryTimers.keys(),
- ...inFlight.keys(),
- ...pendingReruns.keys(),
- ...generations.keys(),
- ]);
- for (const deviceId of devices) {
- generations.set(deviceId, currentGeneration(deviceId) + 1);
- clearTimer(deviceId);
- pendingReruns.delete(deviceId);
+ return { retry };
}
- inFlight.clear();
+ }, {
+ unrefRetryTimers: true,
+ retryBaseMs: options.retryBaseMs ?? 3_000,
+ retryMaxMs: options.retryMaxMs ?? 30_000,
+ });
+
+ return {
+ replay(reason, deviceId) {
+ const refs = options.snapshotSubscriptions(deviceId);
+ if (refs.length === 0) return;
+ options.log.debug(
+ `device-link replay subscriptions (${reason}): devices=${refs.length} ` +
+ `topics=${refs.reduce((sum, ref) => sum + ref.topics.length, 0)}`,
+ );
+ scheduler.requestMany(refs.map((ref) => ref.deviceId));
+ },
+ cancel(deviceId) { scheduler.cancel(deviceId); },
+ teardown() { scheduler.clear(); },
};
-
- return { replay, cancel, teardown };
}
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index 50f9d253df..e21b48f430 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -2087,7 +2087,7 @@ describe('new session worktree wiring (source locks)', () => {
expect(newSource).not.toContain('return false;\n }\n },\n shouldDefer:');
});
- it('applies the protocol timeout override map to mobile invokes (worktree:create needs 60s)', () => {
+ it('applies the protocol timeout override map to mobile invokes (worktree:create needs 60s)', async () => {
// 2026-07-29 与 main 合并后,移动端逐通道超时统一走 invokeTimeouts 的
// resolveMobileInvokeTimeoutMs(mobile 专属表 → 协议契约表 INVOKE_TIMEOUT_OVERRIDES_MS
// 兜底),worktree:create 的 60s 预算经协议表兜底生效——两层缺一都会让
@@ -2097,11 +2097,8 @@ describe('new session worktree wiring (source locks)', () => {
'utf8',
);
expect(contextSource).toContain('resolveMobileInvokeTimeoutMs(channel, args)');
- const timeoutsSource = readTextLf(
- resolve(process.cwd(), 'src/device-link/invokeTimeouts.ts'),
- 'utf8',
- );
- expect(timeoutsSource).toContain('INVOKE_TIMEOUT_OVERRIDES_MS[channel]');
+ const { resolveMobileInvokeTimeoutMs } = await import('@/device-link/invokeTimeouts');
+ expect(resolveMobileInvokeTimeoutMs('worktree:create')).toBe(60_000);
});
});
diff --git a/apps/mobile/src/__tests__/peerRecoveryScheduler.test.ts b/apps/mobile/src/__tests__/peerRecoveryScheduler.test.ts
index 6e034975e1..12aefc23e7 100644
--- a/apps/mobile/src/__tests__/peerRecoveryScheduler.test.ts
+++ b/apps/mobile/src/__tests__/peerRecoveryScheduler.test.ts
@@ -1,7 +1,6 @@
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import { resolveHomeConnectionFeedback } from '@/components/connectionBannerVisibility';
import {
- PeerRecoveryOpenIntentRegistry,
PeerRecoveryScheduler,
} from '@/device-link/peerRecoveryScheduler';
@@ -41,184 +40,4 @@ describe('PeerRecoveryScheduler', () => {
expect(feedback().deviceRecovery).toBe(false);
expect(resolveHomeConnectionFeedback(null, syncing).error).toBeNull();
});
- it('publishes stable active snapshots across queue, retry, completion and cancellation', async () => {
- vi.useFakeTimers();
- try {
- const first = deferred<{ retry: boolean }>();
- const scheduler = new PeerRecoveryScheduler(() => first.promise, { maxConcurrent: 1 });
- const changed = vi.fn();
- const off = scheduler.subscribe(changed);
- const initial = scheduler.getActiveDeviceIds();
- scheduler.requestMany(['a', 'b']);
- expect([...scheduler.getActiveDeviceIds()]).toEqual(['a', 'b']);
- expect(initial.size).toBe(0);
- const active = scheduler.getActiveDeviceIds();
- first.resolve({ retry: true });
- await flush();
- expect(scheduler.getActiveDeviceIds()).toBe(active);
- scheduler.cancel('a');
- expect([...scheduler.getActiveDeviceIds()]).toEqual(['b']);
- scheduler.pause();
- expect(scheduler.getActiveDeviceIds().size).toBe(0);
- const calls = changed.mock.calls.length;
- off();
- scheduler.clear();
- expect(changed).toHaveBeenCalledTimes(calls);
- } finally { vi.useRealTimers(); }
- });
-
- it('keeps a re-request visible while a cancelled generation settles', async () => {
- const old = deferred<{ retry: boolean }>();
- const next = deferred<{ retry: boolean }>();
- const run = vi.fn().mockReturnValueOnce(old.promise).mockReturnValueOnce(next.promise);
- const scheduler = new PeerRecoveryScheduler(run);
- scheduler.request('a');
- scheduler.cancel('a');
- expect(scheduler.getActiveDeviceIds().size).toBe(0);
- scheduler.request('a');
- expect(scheduler.getActiveDeviceIds().has('a')).toBe(true);
- old.resolve({ retry: false });
- await flush();
- expect(scheduler.getActiveDeviceIds().has('a')).toBe(true);
- next.resolve({ retry: false });
- await flush();
- expect(scheduler.getActiveDeviceIds().size).toBe(0);
- });
- it('does not let an old forced-open completion clear a newer intent for the same peer', () => {
- const intents = new PeerRecoveryOpenIntentRegistry();
- const first = intents.request('desktop-a');
- intents.cancel('desktop-a');
- const second = intents.request('desktop-a');
-
- expect(second).toBeGreaterThan(first);
- expect(intents.complete('desktop-a', first)).toBe(false);
- expect(intents.has('desktop-a')).toBe(true);
- expect(intents.complete('desktop-a', second)).toBe(true);
- expect(intents.has('desktop-a')).toBe(false);
- });
-
- it('runs up to six peer recoveries by default', () => {
- const started: string[] = [];
- const scheduler = new PeerRecoveryScheduler((deviceId) => {
- started.push(deviceId);
- return deferred<{ retry: boolean }>().promise;
- });
-
- scheduler.requestMany(['a', 'b', 'c', 'd', 'e', 'f', 'g']);
-
- expect(started).toEqual(['a', 'b', 'c', 'd', 'e', 'f']);
- expect(scheduler.getSnapshot('g').phase).toBe('queued');
- });
-
- it('lets healthy peers recover while one peer is stalled', async () => {
- const stalled = deferred<{ retry: boolean }>();
- const completed: string[] = [];
- const scheduler = new PeerRecoveryScheduler(
- async (deviceId) => {
- if (deviceId === 'desktop-a') return stalled.promise;
- completed.push(deviceId);
- return { retry: false };
- },
- { maxConcurrent: 3 },
- );
-
- scheduler.requestMany(['desktop-a', 'desktop-b', 'desktop-c']);
- await flush();
-
- expect(completed).toEqual(['desktop-b', 'desktop-c']);
- expect(scheduler.getSnapshot('desktop-a').phase).toBe('running');
- expect(scheduler.getSnapshot('desktop-b').phase).toBe('idle');
- stalled.resolve({ retry: true });
- await flush();
- });
-
- it('bounds recovery concurrency without making peers share lifecycle state', async () => {
- const releases = new Map<string, ReturnType<typeof deferred<{ retry: boolean }>>>();
- const started: string[] = [];
- const scheduler = new PeerRecoveryScheduler(
- (deviceId) => {
- started.push(deviceId);
- const run = deferred<{ retry: boolean }>();
- releases.set(deviceId, run);
- return run.promise;
- },
- { maxConcurrent: 2 },
- );
-
- scheduler.requestMany(['a', 'b', 'c']);
- expect(started).toEqual(['a', 'b']);
- expect(scheduler.getSnapshot('c').phase).toBe('queued');
-
- releases.get('b')?.resolve({ retry: false });
- await flush();
- expect(started).toEqual(['a', 'b', 'c']);
- expect(scheduler.getSnapshot('a').phase).toBe('running');
- });
-
- it('keeps retry backoff per peer', async () => {
- vi.useFakeTimers();
- const calls: string[] = [];
- const scheduler = new PeerRecoveryScheduler(
- async (deviceId) => {
- calls.push(deviceId);
- return { retry: deviceId === 'a' };
- },
- { retryBaseMs: 2_000, retryMaxMs: 30_000 },
- );
-
- scheduler.requestMany(['a', 'b']);
- await flush();
- expect(scheduler.getSnapshot('a')).toMatchObject({
- phase: 'waiting-retry',
- retryAttempt: 1,
- });
- expect(scheduler.getSnapshot('b').phase).toBe('idle');
-
- await vi.advanceTimersByTimeAsync(2_000);
- expect(calls).toEqual(['a', 'b', 'a']);
- expect(scheduler.getSnapshot('a').retryAttempt).toBe(2);
- expect(scheduler.getSnapshot('b').retryAttempt).toBe(0);
- scheduler.clear();
- vi.useRealTimers();
- });
-
- it('cancels only the selected peer and ignores its late result', async () => {
- const a = deferred<{ retry: boolean }>();
- const b = deferred<{ retry: boolean }>();
- const scheduler = new PeerRecoveryScheduler((deviceId) => (
- deviceId === 'a' ? a.promise : b.promise
- ));
-
- scheduler.requestMany(['a', 'b']);
- scheduler.cancel('a');
- a.resolve({ retry: true });
- b.resolve({ retry: false });
- await flush();
-
- expect(scheduler.getSnapshot('a')).toEqual({
- deviceId: 'a',
- phase: 'idle',
- retryAttempt: 0,
- });
- expect(scheduler.getSnapshot('b').phase).toBe('idle');
- });
-
- it('reruns only the peer requested during its in-flight recovery', async () => {
- const firstA = deferred<{ retry: boolean }>();
- const calls: string[] = [];
- const scheduler = new PeerRecoveryScheduler(async (deviceId) => {
- calls.push(deviceId);
- if (deviceId === 'a' && calls.filter((item) => item === 'a').length === 1) {
- return firstA.promise;
- }
- return { retry: false };
- });
-
- scheduler.requestMany(['a', 'b']);
- scheduler.request('a');
- firstA.resolve({ retry: false });
- await flush();
-
- expect(calls).toEqual(['a', 'b', 'a']);
- });
});
diff --git a/apps/mobile/src/device-link/invokeTimeouts.ts b/apps/mobile/src/device-link/invokeTimeouts.ts
index 0459c5ed48..d0de08d996 100644
--- a/apps/mobile/src/device-link/invokeTimeouts.ts
+++ b/apps/mobile/src/device-link/invokeTimeouts.ts
@@ -1,81 +1,6 @@
-import { INVOKE_TIMEOUT_OVERRIDES_MS } from '@cindy/device-link';
-
-/**
- * mobile 侧 invoke 超时解析(优先级:mobile 精确表 → schedule 前缀规则 →
- * 协议契约表 → undefined = client 默认 15s)。
- *
- * 背景:mobile 把默认请求超时从 30s 收紧到 15s 后,凡是桌面端有更长执行预算的
- * 通道都必须在这里保住原有窗口,否则合法慢操作会被提前掐断(review 三轮反馈):
- * - media:fetch:桌面拉文件传 OSS,最大 2GB;
- * - file-browser:remote-op:searchCollect 桌面执行预算 20s(SEARCH_COLLECT_TIMEOUT_MS);
- * - maker:schedule:*:桌面 handler 会等 scheduler 就绪(READINESS_TIMEOUT_MS=30s,
- * 冷启动 / 登出登录窗口内就绪可能落在 15-30s),40s = 就绪上限 + 执行余量;
- * - voice:dictionary-learning:桌面 advisor 走 managed refiner,单次尝试空闲窗
- * 12s(VOICE_INPUT_MANAGED_REFINER_IDLE_TIMEOUT_MS)且主模型卡住会换备选
- * profile 再试,合法执行可超 15s;误超时会让后台学习白白计入熔断失败;
- * - voice:transcribe:桌面端先 downloadToBuffer 从 OSS 拉音频再走批量网关转写,
- * 两段都无更短的执行 deadline,中速/慢网络下合法执行可超 15s,且连续几条
- * 语音误超时就会错误打开设备级熔断;
- * - maker:fork:桌面端 forkSessionAtMessage 载入完整可见消息前缀 + SDK fork +
- * 事务内批量拷贝,大会话可落在 15-30s;且该操作**非幂等**——误超时后桌面端
- * 仍会建出并广播新会话,用户重试会分叉出重复副本;
- * - maker:rewind:commit:transcript/DB 读 + SDK/Codex 线程回滚 + Git 文件回退 +
- * 收尾 SQLite 事务,同样非幂等——误超时后对话与文件已被回退,重试会作用在
- * 已变更的历史上;
- * - maker:get-context-usage:非运行中会话走 lazy-create 分支
- * (ensureRemoteReadyForSessionStart + bootstrapSession),SSH 工作区仅就绪
- * 等待就允许 20s,再叠会话拉起;15s 会在桌面端继续启动时提前掐断,反复
- * 尝试还会误开设备级熔断;
- * - maker:usage:codex-rate-limits / codex-rate-limit-reset:账号 app-server
- * 冷启动或 RPC 慢时无更短 deadline;reset 还串行做消耗 + 身份校验 + 额度
- * 刷新且有真实副作用,误超时后桌面会继续完成消耗,重试有重复扣减风险;
- * - maker:send:makerSendTransaction 接收消息前会等
- * ensureRemoteReadyForSessionStart(SSH 就绪窗口 20s)再落库/派发;误超时后
- * 桌面仍会接收并发出该消息,用户重试会把同一条消息发两遍;
- * - maker:regenerate-title:桌面路径先 getValidClaudeAiOAuth(刷新最长 ~10s)
- * 再发标题请求(自身 TITLE_TIMEOUT_MS=12s),合法总预算 ~22s;
- * - maker:create-session:桌面 await maker.createSession → agent.startSession /
- * Codex host.ensureStarted,冷启动 app-server 无更短 deadline;goal 路径无
- * 稳定的客户端会话 id,误超时后重试会建出第二个会话;
- * - maker:message:delete:桌面提交删除前先读 handoff 历史并 await
- * maker.closeSession(Claude 远端 close 的 cc-manager RPC 自带 15s 超时),
- * 合法可贴着 15s 边界;破坏性操作,误超时后删除实际已生效,mobile 却报失败;
- * - maker:goal:set / goal:resume:GoalController.ensureSession 的
- * restoreSessionForGoal 同样 await createSession 重启持久化 agent,冷启动
- * 可超 15s;两者都有真实副作用(set 落库目标并发首轮,resume 先标 active),
- * 误超时后重试会改动/重启已在跑的 goal。
- * 新增合法慢通道优先登记协议契约表(桌面控制端共用),仅 mobile 特有差异放这里。
- */
-export const MOBILE_INVOKE_TIMEOUT_OVERRIDES_MS: Record<string, number> = {
- // Even a small row count can contain one large message: the Android weak-link
- // regression took ~18s to deliver 200KB. Do not enqueue another copy at 15s.
- 'local-db:messages:list': 30_000,
- 'device-link:media:fetch': 30_000,
- 'device-link:voice:dictionary-learning': 30_000,
- 'device-link:voice:transcribe': 30_000,
- 'file-browser:remote-op': 30_000,
- 'maker:create-session': 30_000,
- 'maker:fork': 30_000,
- 'maker:get-context-usage': 30_000,
- 'maker:goal:resume': 30_000,
- 'maker:goal:set': 30_000,
- 'maker:message:delete': 30_000,
- 'maker:regenerate-title': 30_000,
- 'maker:rewind:commit': 30_000,
- 'maker:send': 30_000,
- 'maker:usage:codex-rate-limit-reset': 30_000,
- 'maker:usage:codex-rate-limits': 30_000,
-};
-
-export const MOBILE_SCHEDULE_CHANNEL_TIMEOUT_MS = 40_000;
+import { resolveRemoteInvokeTimeoutMs } from '@cindy/device-link';
+export { MOBILE_INVOKE_TIMEOUT_OVERRIDES_MS, MOBILE_SCHEDULE_CHANNEL_TIMEOUT_MS } from '@cindy/device-link';
export function resolveMobileInvokeTimeoutMs(channel: string, args?: unknown[]): number | undefined {
- // Renewals must settle before the 12s lease, independently of slow media offers.
- const request = args?.[0];
- if (channel === 'device-link:remote-desktop:v1' && request &&
- typeof request === 'object' && 'op' in request && request.op === 'heartbeat') return 5_000;
- const exact = MOBILE_INVOKE_TIMEOUT_OVERRIDES_MS[channel];
- if (exact !== undefined) return exact;
- if (channel.startsWith('maker:schedule:')) return MOBILE_SCHEDULE_CHANNEL_TIMEOUT_MS;
- return INVOKE_TIMEOUT_OVERRIDES_MS[channel];
+ return resolveRemoteInvokeTimeoutMs(channel, args, 'mobile');
}
diff --git a/apps/mobile/src/device-link/peerRecoveryScheduler.ts b/apps/mobile/src/device-link/peerRecoveryScheduler.ts
index f8687b2f67..be70d9f74a 100644
--- a/apps/mobile/src/device-link/peerRecoveryScheduler.ts
+++ b/apps/mobile/src/device-link/peerRecoveryScheduler.ts
@@ -1,327 +1,5 @@
-export type PeerRecoveryPhase = 'idle' | 'queued' | 'running' | 'waiting-retry';
-
-export interface PeerRecoveryResult {
- /** True when this peer still has transient work and needs a later retry. */
- retry: boolean;
-}
-
-export interface PeerRecoverySchedulerOptions {
- maxConcurrent?: number;
- retryBaseMs?: number;
- retryMaxMs?: number;
- onError?(deviceId: string, error: unknown): void;
-}
-
-export interface PeerRecoverySnapshot {
- deviceId: string;
- phase: PeerRecoveryPhase;
- retryAttempt: number;
-}
-
-interface PeerRecoveryEntry {
- phase: PeerRecoveryPhase;
- generation: number;
- running: boolean;
- rerun: boolean;
- retryAttempt: number;
- retryTimer: ReturnType<typeof setTimeout> | null;
-}
-
-const DEFAULT_MAX_CONCURRENT = 6;
-const DEFAULT_RETRY_BASE_MS = 2_000;
-const DEFAULT_RETRY_MAX_MS = 30_000;
-
-/**
- * Transient open intent created by a peer-level transport reset. Generations never reuse
- * within this provider lifetime, so an old A recovery cannot clear a newer A intent after
- * cancel → reacquire (the same ABA fence used by the scheduler itself).
- */
-export class PeerRecoveryOpenIntentRegistry {
- private readonly generations = new Map<string, number>();
- private nextGeneration = 0;
-
- request(deviceId: string): number {
- if (!deviceId) return 0;
- const generation = ++this.nextGeneration;
- this.generations.set(deviceId, generation);
- return generation;
- }
-
- getGeneration(deviceId: string): number | undefined {
- return this.generations.get(deviceId);
- }
-
- has(deviceId: string): boolean {
- return this.generations.has(deviceId);
- }
-
- complete(deviceId: string, generation: number): boolean {
- if (this.generations.get(deviceId) !== generation) return false;
- this.generations.delete(deviceId);
- return true;
- }
-
- cancel(deviceId: string): void {
- this.generations.delete(deviceId);
- }
-
- clear(): void {
- // Keep nextGeneration monotonic: a settling pre-clear run must never collide with a
- // post-clear intent if the provider/client is replaced while its promise unwinds.
- this.generations.clear();
- }
-
- deviceIds(): string[] {
- return [...this.generations.keys()];
- }
-}
-
-/**
- * Runs recovery independently per remote device while sharing a small global
- * concurrency budget. A slow peer occupies at most one slot, so it cannot hold
- * every other desktop behind its timeout. Each peer owns its own rerun flag,
- * retry attempt and timer.
- */
-export class PeerRecoveryScheduler {
- private readonly runPeer: (deviceId: string) => Promise<PeerRecoveryResult>;
- private readonly onError?: PeerRecoverySchedulerOptions['onError'];
- private readonly maxConcurrent: number;
- private readonly retryBaseMs: number;
- private readonly retryMaxMs: number;
- private readonly entries = new Map<string, PeerRecoveryEntry>();
- private readonly queue: string[] = [];
- private readonly queued = new Set<string>();
- private active = 0;
- private paused = false;
- private activeDeviceIds: ReadonlySet<string> = new Set();
- private readonly listeners = new Set<() => void>();
-
- /** Cached read-only UI projection; it never schedules recovery work. */
- getActiveDeviceIds = (): ReadonlySet<string> => this.activeDeviceIds;
-
- subscribe = (listener: () => void): (() => void) => {
- this.listeners.add(listener);
- return () => { this.listeners.delete(listener); };
- };
-
- private publishActiveDeviceIds(): void {
- const next = new Set<string>();
- for (const [deviceId, entry] of this.entries) {
- if (entry.phase !== 'idle' || entry.rerun) next.add(deviceId);
- }
- if (next.size === this.activeDeviceIds.size && [...next].every((id) => this.activeDeviceIds.has(id))) return;
- this.activeDeviceIds = next;
- for (const listener of this.listeners) {
- try { listener(); } catch { /* UI observers must not affect recovery scheduling. */ }
- }
- }
-
- constructor(
- run: (deviceId: string) => Promise<PeerRecoveryResult>,
- options: PeerRecoverySchedulerOptions = {},
- ) {
- this.runPeer = run;
- this.onError = options.onError;
- this.maxConcurrent = normalizePositiveInteger(
- options.maxConcurrent,
- DEFAULT_MAX_CONCURRENT,
- );
- this.retryBaseMs = normalizePositiveInteger(
- options.retryBaseMs,
- DEFAULT_RETRY_BASE_MS,
- );
- this.retryMaxMs = Math.max(
- this.retryBaseMs,
- normalizePositiveInteger(options.retryMaxMs, DEFAULT_RETRY_MAX_MS),
- );
- }
-
- request(deviceId: string): void {
- if (!deviceId) return;
- const entry = this.getOrCreateEntry(deviceId);
- if (entry.retryTimer) {
- clearTimeout(entry.retryTimer);
- entry.retryTimer = null;
- }
- // A cancelled generation may still be settling. Keep the next generation
- // serialized behind it so one peer never has two recovery runs in flight.
- if (entry.running) {
- entry.rerun = true;
- this.publishActiveDeviceIds();
- return;
- }
- this.enqueue(deviceId, entry);
- }
-
- requestMany(deviceIds: Iterable<string>): void {
- for (const deviceId of deviceIds) this.request(deviceId);
- }
-
- /** Cancels one peer without touching any other peer's timers or work. */
- cancel(deviceId: string, resetAttempt = true): void {
- const entry = this.entries.get(deviceId);
- if (!entry) return;
- entry.generation += 1;
- entry.rerun = false;
- if (resetAttempt) entry.retryAttempt = 0;
- if (entry.retryTimer) {
- clearTimeout(entry.retryTimer);
- entry.retryTimer = null;
- }
- if (this.queued.delete(deviceId)) {
- const index = this.queue.indexOf(deviceId);
- if (index >= 0) this.queue.splice(index, 1);
- }
- entry.phase = 'idle';
- this.publishActiveDeviceIds();
- }
-
- /**
- * Relay/background lifecycle gate. In-flight promises cannot be force-cancelled,
- * but generation fencing makes their late scheduling result inert.
- */
- pause(): void {
- if (this.paused) return;
- this.paused = true;
- this.cancelAll(true);
- }
-
- resume(): void {
- if (!this.paused) {
- this.drain();
- return;
- }
- this.paused = false;
- this.drain();
- }
-
- /** Clears all queued/timed work while retaining safe fences for settling runs. */
- clear(): void {
- this.cancelAll(true);
- for (const [deviceId, entry] of this.entries) {
- if (!entry.running) this.entries.delete(deviceId);
- }
- }
-
- getSnapshot(deviceId: string): PeerRecoverySnapshot {
- const entry = this.entries.get(deviceId);
- return {
- deviceId,
- phase: entry?.phase ?? 'idle',
- retryAttempt: entry?.retryAttempt ?? 0,
- };
- }
-
- private cancelAll(resetAttempts: boolean): void {
- this.queue.length = 0;
- this.queued.clear();
- for (const [deviceId] of this.entries) this.cancel(deviceId, resetAttempts);
- }
-
- private getOrCreateEntry(deviceId: string): PeerRecoveryEntry {
- let entry = this.entries.get(deviceId);
- if (!entry) {
- entry = {
- phase: 'idle',
- generation: 0,
- running: false,
- rerun: false,
- retryAttempt: 0,
- retryTimer: null,
- };
- this.entries.set(deviceId, entry);
- }
- return entry;
- }
-
- private enqueue(deviceId: string, entry: PeerRecoveryEntry): void {
- if (this.queued.has(deviceId)) return;
- entry.phase = 'queued';
- this.queued.add(deviceId);
- this.queue.push(deviceId);
- this.publishActiveDeviceIds();
- this.drain();
- }
-
- private drain(): void {
- if (this.paused) return;
- while (this.active < this.maxConcurrent && this.queue.length > 0) {
- const deviceId = this.queue.shift()!;
- this.queued.delete(deviceId);
- const entry = this.entries.get(deviceId);
- if (!entry || entry.phase !== 'queued' || entry.running) continue;
- this.start(deviceId, entry);
- }
- }
-
- private start(deviceId: string, entry: PeerRecoveryEntry): void {
- const generation = entry.generation;
- entry.phase = 'running';
- entry.running = true;
- entry.rerun = false;
- this.active += 1;
-
- let run: Promise<PeerRecoveryResult>;
- try {
- run = this.runPeer(deviceId);
- } catch (error) {
- try {
- this.onError?.(deviceId, error);
- } catch {
- // Diagnostics must never strand the scheduler's active-slot accounting.
- }
- this.finish(deviceId, entry, generation, { retry: true });
- return;
- }
- void run.then(
- (result) => this.finish(deviceId, entry, generation, result),
- (error: unknown) => {
- try {
- this.onError?.(deviceId, error);
- } catch {
- // Diagnostics must never strand the scheduler's active-slot accounting.
- }
- this.finish(deviceId, entry, generation, { retry: true });
- },
- );
- }
-
- private finish(
- deviceId: string,
- entry: PeerRecoveryEntry,
- generation: number,
- result: PeerRecoveryResult,
- ): void {
- if (entry.generation === generation && !entry.rerun) {
- if (!result.retry) {
- entry.retryAttempt = 0;
- entry.phase = 'idle';
- } else {
- const delay = Math.min(
- this.retryBaseMs * 2 ** entry.retryAttempt,
- this.retryMaxMs,
- );
- entry.retryAttempt += 1;
- entry.phase = 'waiting-retry';
- entry.retryTimer = setTimeout(() => {
- entry.retryTimer = null;
- if (entry.generation !== generation) return;
- this.enqueue(deviceId, entry);
- }, delay);
- }
- }
- entry.running = false;
- this.active -= 1;
- if (entry.rerun) {
- entry.rerun = false;
- this.enqueue(deviceId, entry);
- }
- this.drain();
- this.publishActiveDeviceIds();
- }
-}
-
-function normalizePositiveInteger(value: number | undefined, fallback: number): number {
- if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return fallback;
- return Math.max(1, Math.floor(value));
-}
+// Keep the Mobile import path stable; both controllers use the same scheduler.
+export { PeerRecoveryScheduler, PeerRecoveryOpenIntentRegistry,
+ type PeerRecoveryPhase, type PeerRecoveryResult, type PeerRecoverySchedulerOptions,
+ type PeerRecoverySnapshot,
+} from '@cindy/device-link';
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index dee1cd9c5d..60baac9cc3 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -68,6 +68,23 @@ relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即
一起打掉线,由 #1405 收窄止损半径修复。协议兼容、allowlist、单测三层防线对这类问题
全部免疫,只有 review 时点名问「半径」才拦得住。
+## 共享恢复与请求策略
+
+Desktop 和 Mobile 的按设备排队、并发上限、退避、取消代次由
+`packages/device-link/src/peerRecoveryScheduler.ts` 统一维护。Desktop 的订阅快照与
+在线判断、Mobile 的后台生命周期与页面恢复仍由各端适配器负责。同一设备取消后重新
+请求恢复,须等待旧请求结算;旧结果不能取消新请求,也不能恢复已取消的重试。
+
+`packages/device-link/src/invokePolicy.ts` 集中维护请求策略,三个边界独立判断:
+
+- 通道执行预算:保留 Desktop / Mobile 的超时差异,超时不代表主机操作未执行。
+- peer reset 后可重试的读取:显式列举,不按名字推断写操作可以重试。
+- 可共享在途结果的 listing:不能从“可重试”推导。`sessions:get` 与要求 `fresh` 的
+ `sessions:list` 必须重新读取,避免复用写入之前开始的快照。
+
+主机数据库后台准入是独立的资源分配策略,不能直接复用上述 listing 集合作为分类依据。
+这些策略不改变 wire 格式或通道权限;权限仍以 allowlist 为准。
+
## 模块通过 Remote Resource 接入移动端
面向移动端新增独立产品入口时,默认通过 `@cindy/device-link` 的 Remote Resource
diff --git a/packages/device-link/src/__tests__/invokePolicy.test.ts b/packages/device-link/src/__tests__/invokePolicy.test.ts
new file mode 100644
index 0000000000..578badd3c7
--- /dev/null
+++ b/packages/device-link/src/__tests__/invokePolicy.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+import {
+ canCoalesceRemoteListing,
+ isPeerResetRetryableReadChannel,
+ resolveRemoteInvokeTimeoutMs,
+} from '../index.js';
+
+describe('remote invoke policy boundaries', () => {
+ it('allows retrying a read without sharing a snapshot from before a write', () => {
+ expect(isPeerResetRetryableReadChannel('local-db:sessions:get')).toBe(true);
+ expect(canCoalesceRemoteListing({ channel: 'local-db:sessions:get', args: ['id'] })).toBe(false);
+ expect(isPeerResetRetryableReadChannel('local-db:sessions:list')).toBe(true);
+ expect(canCoalesceRemoteListing({ channel: 'local-db:sessions:list', args: [] })).toBe(true);
+ expect(canCoalesceRemoteListing({ channel: 'local-db:sessions:list', args: [null, null, { fresh: true }] })).toBe(false);
+ });
+
+ it.each(['maker:send', 'maker:create-session', 'maker:schedule:mark-run-read', 'unknown:read'])(
+ 'does not infer retry or coalescing permission from %s', (channel) => {
+ expect(isPeerResetRetryableReadChannel(channel)).toBe(false);
+ expect(canCoalesceRemoteListing({ channel, args: [] })).toBe(false);
+ },
+ );
+
+ it('preserves schedule index coalescing without enabling peer-reset retries', () => {
+ const channel = 'maker:schedule:list-sidebar-index-runs';
+ expect(canCoalesceRemoteListing({ channel, args: [] })).toBe(true);
+ expect(isPeerResetRetryableReadChannel(channel)).toBe(false);
+ });
+
+ it('keeps mobile execution budgets and desktop defaults separate', () => {
+ expect(resolveRemoteInvokeTimeoutMs('maker:send', [], 'mobile')).toBe(30_000);
+ expect(resolveRemoteInvokeTimeoutMs('maker:send', [], 'desktop')).toBeUndefined();
+ expect(resolveRemoteInvokeTimeoutMs('maker:schedule:list', [], 'mobile')).toBe(40_000);
+ expect(resolveRemoteInvokeTimeoutMs('device-link:remote-desktop:v1', [{ op: 'heartbeat' }], 'mobile')).toBe(5_000);
+ expect(resolveRemoteInvokeTimeoutMs('device-link:remote-desktop:v1', [{ op: 'heartbeat' }], 'desktop')).toBe(59_000);
+ expect(resolveRemoteInvokeTimeoutMs('unknown:read', [], 'mobile')).toBeUndefined();
+ });
+});
diff --git a/packages/device-link/src/__tests__/peerRecoveryScheduler.test.ts b/packages/device-link/src/__tests__/peerRecoveryScheduler.test.ts
new file mode 100644
index 0000000000..65cdc57bc6
--- /dev/null
+++ b/packages/device-link/src/__tests__/peerRecoveryScheduler.test.ts
@@ -0,0 +1,202 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ PeerRecoveryOpenIntentRegistry,
+ PeerRecoveryScheduler,
+} from '../peerRecoveryScheduler.js';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+async function flush(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+describe('PeerRecoveryScheduler', () => {
+ it('publishes stable active snapshots across queue, retry, completion and cancellation', async () => {
+ vi.useFakeTimers();
+ try {
+ const first = deferred<{ retry: boolean }>();
+ const scheduler = new PeerRecoveryScheduler(() => first.promise, { maxConcurrent: 1 });
+ const changed = vi.fn();
+ const off = scheduler.subscribe(changed);
+ const initial = scheduler.getActiveDeviceIds();
+ scheduler.requestMany(['a', 'b']);
+ expect([...scheduler.getActiveDeviceIds()]).toEqual(['a', 'b']);
+ expect(initial.size).toBe(0);
+ const active = scheduler.getActiveDeviceIds();
+ first.resolve({ retry: true });
+ await flush();
+ expect(scheduler.getActiveDeviceIds()).toBe(active);
+ scheduler.cancel('a');
+ expect([...scheduler.getActiveDeviceIds()]).toEqual(['b']);
+ scheduler.pause();
+ expect(scheduler.getActiveDeviceIds().size).toBe(0);
+ const calls = changed.mock.calls.length;
+ off();
+ scheduler.clear();
+ expect(changed).toHaveBeenCalledTimes(calls);
+ } finally { vi.useRealTimers(); }
+ });
+
+ it('keeps a re-request visible while a cancelled generation settles', async () => {
+ const old = deferred<{ retry: boolean }>();
+ const next = deferred<{ retry: boolean }>();
+ const run = vi.fn().mockReturnValueOnce(old.promise).mockReturnValueOnce(next.promise);
+ const scheduler = new PeerRecoveryScheduler(run);
+ scheduler.request('a');
+ scheduler.cancel('a');
+ expect(scheduler.getActiveDeviceIds().size).toBe(0);
+ scheduler.request('a');
+ expect(scheduler.getActiveDeviceIds().has('a')).toBe(true);
+ old.resolve({ retry: false });
+ await flush();
+ expect(scheduler.getActiveDeviceIds().has('a')).toBe(true);
+ next.resolve({ retry: false });
+ await flush();
+ expect(scheduler.getActiveDeviceIds().size).toBe(0);
+ });
+ it('does not let an old forced-open completion clear a newer intent for the same peer', () => {
+ const intents = new PeerRecoveryOpenIntentRegistry();
+ const first = intents.request('desktop-a');
+ intents.cancel('desktop-a');
+ const second = intents.request('desktop-a');
+
+ expect(second).toBeGreaterThan(first);
+ expect(intents.complete('desktop-a', first)).toBe(false);
+ expect(intents.has('desktop-a')).toBe(true);
+ expect(intents.complete('desktop-a', second)).toBe(true);
+ expect(intents.has('desktop-a')).toBe(false);
+ });
+
+ it('runs up to six peer recoveries by default', () => {
+ const started: string[] = [];
+ const scheduler = new PeerRecoveryScheduler((deviceId) => {
+ started.push(deviceId);
+ return deferred<{ retry: boolean }>().promise;
+ });
+
+ scheduler.requestMany(['a', 'b', 'c', 'd', 'e', 'f', 'g']);
+
+ expect(started).toEqual(['a', 'b', 'c', 'd', 'e', 'f']);
+ expect(scheduler.getSnapshot('g').phase).toBe('queued');
+ });
+
+ it('lets healthy peers recover while one peer is stalled', async () => {
+ const stalled = deferred<{ retry: boolean }>();
+ const completed: string[] = [];
+ const scheduler = new PeerRecoveryScheduler(
+ async (deviceId) => {
+ if (deviceId === 'desktop-a') return stalled.promise;
+ completed.push(deviceId);
+ return { retry: false };
+ },
+ { maxConcurrent: 3 },
+ );
+
+ scheduler.requestMany(['desktop-a', 'desktop-b', 'desktop-c']);
+ await flush();
+
+ expect(completed).toEqual(['desktop-b', 'desktop-c']);
+ expect(scheduler.getSnapshot('desktop-a').phase).toBe('running');
+ expect(scheduler.getSnapshot('desktop-b').phase).toBe('idle');
+ stalled.resolve({ retry: true });
+ await flush();
+ scheduler.clear();
+ });
+
+ it('bounds recovery concurrency without making peers share lifecycle state', async () => {
+ const releases = new Map<string, ReturnType<typeof deferred<{ retry: boolean }>>>();
+ const started: string[] = [];
+ const scheduler = new PeerRecoveryScheduler(
+ (deviceId) => {
+ started.push(deviceId);
+ const run = deferred<{ retry: boolean }>();
+ releases.set(deviceId, run);
+ return run.promise;
+ },
+ { maxConcurrent: 2 },
+ );
+
+ scheduler.requestMany(['a', 'b', 'c']);
+ expect(started).toEqual(['a', 'b']);
+ expect(scheduler.getSnapshot('c').phase).toBe('queued');
+
+ releases.get('b')?.resolve({ retry: false });
+ await flush();
+ expect(started).toEqual(['a', 'b', 'c']);
+ expect(scheduler.getSnapshot('a').phase).toBe('running');
+ });
+
+ it('keeps retry backoff per peer', async () => {
+ vi.useFakeTimers();
+ const calls: string[] = [];
+ const scheduler = new PeerRecoveryScheduler(
+ async (deviceId) => {
+ calls.push(deviceId);
+ return { retry: deviceId === 'a' };
+ },
+ { retryBaseMs: 2_000, retryMaxMs: 30_000 },
+ );
+
+ scheduler.requestMany(['a', 'b']);
+ await flush();
+ expect(scheduler.getSnapshot('a')).toMatchObject({
+ phase: 'waiting-retry',
+ retryAttempt: 1,
+ });
+ expect(scheduler.getSnapshot('b').phase).toBe('idle');
+
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(calls).toEqual(['a', 'b', 'a']);
+ expect(scheduler.getSnapshot('a').retryAttempt).toBe(2);
+ expect(scheduler.getSnapshot('b').retryAttempt).toBe(0);
+ scheduler.clear();
+ vi.useRealTimers();
+ });
+
+ it('cancels only the selected peer and ignores its late result', async () => {
+ const a = deferred<{ retry: boolean }>();
+ const b = deferred<{ retry: boolean }>();
+ const scheduler = new PeerRecoveryScheduler((deviceId) => (
+ deviceId === 'a' ? a.promise : b.promise
+ ));
+
+ scheduler.requestMany(['a', 'b']);
+ scheduler.cancel('a');
+ a.resolve({ retry: true });
+ b.resolve({ retry: false });
+ await flush();
+
+ expect(scheduler.getSnapshot('a')).toEqual({
+ deviceId: 'a',
+ phase: 'idle',
+ retryAttempt: 0,
+ });
+ expect(scheduler.getSnapshot('b').phase).toBe('idle');
+ });
+
+ it('reruns only the peer requested during its in-flight recovery', async () => {
+ const firstA = deferred<{ retry: boolean }>();
+ const calls: string[] = [];
+ const scheduler = new PeerRecoveryScheduler(async (deviceId) => {
+ calls.push(deviceId);
+ if (deviceId === 'a' && calls.filter((item) => item === 'a').length === 1) {
+ return firstA.promise;
+ }
+ return { retry: false };
+ });
+
+ scheduler.requestMany(['a', 'b']);
+ scheduler.request('a');
+ firstA.resolve({ retry: false });
+ await flush();
+
+ expect(calls).toEqual(['a', 'b', 'a']);
+ });
+});
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 4519b15b8b..165359098b 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -1,3 +1,4 @@
+import { isPeerResetRetryableReadChannel } from './invokePolicy.js';
import { CongestionSendBudget } from './congestionSendBudget.js';
import { PUSH_FORWARD_ALLOWLIST, REMOTE_INVOKE_ALLOWLIST } from './allowlist.js';
import {
@@ -486,32 +487,11 @@ interface PendingRequest {
retryAfterPeerReset?: () => void;
}
-const PEER_RESET_RETRYABLE_READ_CHANNELS = new Set([
- 'local-db:sessions:list',
- 'local-db:sessions:get',
- 'local-db:conversations:search',
- 'local-db:history:messages',
- 'local-db:messages:list',
- 'local-db:messages:view',
- 'local-db:messages:work-details',
- 'local-db:messages:around',
- 'local-db:messages:around-client-id',
- 'local-db:messages:estimatedSessionValue',
- 'local-db:recent-workdirs:list',
- 'local-db:subagent-runs:list',
- 'local-db:subagent-runs:detail',
- 'local-db:subagent-runs:transcript',
- 'local-db:bots:list',
- 'local-db:bots:get',
- 'local-db:orca-workflows:get-by-lead',
- 'local-db:orca-workflows:get-by-worker-session',
- 'local-db:orca-workflows:list-workers-by-lead',
-]);
function isPeerResetRetryableRead(env: Omit<Envelope, 'id'>): boolean {
if (env.kind !== 'invoke') return false;
const channel = (env.payload as InvokePayload | undefined)?.channel;
- return typeof channel === 'string' && PEER_RESET_RETRYABLE_READ_CHANNELS.has(channel);
+ return typeof channel === 'string' && isPeerResetRetryableReadChannel(channel);
}
interface PendingReliableMessage {
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 38da6a9791..50c4d33f58 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -25,3 +25,5 @@ export * from './remoteDesktopIce.js';
export * from './remoteDesktopIceConfig.js';
export * from './remoteClipboard.js';
export * from './remoteCursor.js';
+export * from './peerRecoveryScheduler.js';
+export * from './invokePolicy.js';
diff --git a/packages/device-link/src/invokePolicy.ts b/packages/device-link/src/invokePolicy.ts
new file mode 100644
index 0000000000..dc1514f55e
--- /dev/null
+++ b/packages/device-link/src/invokePolicy.ts
@@ -0,0 +1,135 @@
+import { INVOKE_TIMEOUT_OVERRIDES_MS } from './allowlist.js';
+import type { InvokePayload } from './protocol.js';
+
+/**
+ * mobile 侧 invoke 超时解析(优先级:mobile 精确表 → schedule 前缀规则 →
+ * 协议契约表 → undefined = client 默认 15s)。
+ *
+ * 背景:mobile 把默认请求超时从 30s 收紧到 15s 后,凡是桌面端有更长执行预算的
+ * 通道都必须在这里保住原有窗口,否则合法慢操作会被提前掐断(review 三轮反馈):
+ * - media:fetch:桌面拉文件传 OSS,最大 2GB;
+ * - file-browser:remote-op:searchCollect 桌面执行预算 20s(SEARCH_COLLECT_TIMEOUT_MS);
+ * - maker:schedule:*:桌面 handler 会等 scheduler 就绪(READINESS_TIMEOUT_MS=30s,
+ * 冷启动 / 登出登录窗口内就绪可能落在 15-30s),40s = 就绪上限 + 执行余量;
+ * - voice:dictionary-learning:桌面 advisor 走 managed refiner,单次尝试空闲窗
+ * 12s(VOICE_INPUT_MANAGED_REFINER_IDLE_TIMEOUT_MS)且主模型卡住会换备选
+ * profile 再试,合法执行可超 15s;误超时会让后台学习白白计入熔断失败;
+ * - voice:transcribe:桌面端先 downloadToBuffer 从 OSS 拉音频再走批量网关转写,
+ * 两段都无更短的执行 deadline,中速/慢网络下合法执行可超 15s,且连续几条
+ * 语音误超时就会错误打开设备级熔断;
+ * - maker:fork:桌面端 forkSessionAtMessage 载入完整可见消息前缀 + SDK fork +
+ * 事务内批量拷贝,大会话可落在 15-30s;且该操作**非幂等**——误超时后桌面端
+ * 仍会建出并广播新会话,用户重试会分叉出重复副本;
+ * - maker:rewind:commit:transcript/DB 读 + SDK/Codex 线程回滚 + Git 文件回退 +
+ * 收尾 SQLite 事务,同样非幂等——误超时后对话与文件已被回退,重试会作用在
+ * 已变更的历史上;
+ * - maker:get-context-usage:非运行中会话走 lazy-create 分支
+ * (ensureRemoteReadyForSessionStart + bootstrapSession),SSH 工作区仅就绪
+ * 等待就允许 20s,再叠会话拉起;15s 会在桌面端继续启动时提前掐断,反复
+ * 尝试还会误开设备级熔断;
+ * - maker:usage:codex-rate-limits / codex-rate-limit-reset:账号 app-server
+ * 冷启动或 RPC 慢时无更短 deadline;reset 还串行做消耗 + 身份校验 + 额度
+ * 刷新且有真实副作用,误超时后桌面会继续完成消耗,重试有重复扣减风险;
+ * - maker:send:makerSendTransaction 接收消息前会等
+ * ensureRemoteReadyForSessionStart(SSH 就绪窗口 20s)再落库/派发;误超时后
+ * 桌面仍会接收并发出该消息,用户重试会把同一条消息发两遍;
+ * - maker:regenerate-title:桌面路径先 getValidClaudeAiOAuth(刷新最长 ~10s)
+ * 再发标题请求(自身 TITLE_TIMEOUT_MS=12s),合法总预算 ~22s;
+ * - maker:create-session:桌面 await maker.createSession → agent.startSession /
+ * Codex host.ensureStarted,冷启动 app-server 无更短 deadline;goal 路径无
+ * 稳定的客户端会话 id,误超时后重试会建出第二个会话;
+ * - maker:message:delete:桌面提交删除前先读 handoff 历史并 await
+ * maker.closeSession(Claude 远端 close 的 cc-manager RPC 自带 15s 超时),
+ * 合法可贴着 15s 边界;破坏性操作,误超时后删除实际已生效,mobile 却报失败;
+ * - maker:goal:set / goal:resume:GoalController.ensureSession 的
+ * restoreSessionForGoal 同样 await createSession 重启持久化 agent,冷启动
+ * 可超 15s;两者都有真实副作用(set 落库目标并发首轮,resume 先标 active),
+ * 误超时后重试会改动/重启已在跑的 goal。
+ * 新增合法慢通道优先登记协议契约表(桌面控制端共用),仅 mobile 特有差异放这里。
+ */
+export const MOBILE_INVOKE_TIMEOUT_OVERRIDES_MS: Record<string, number> = {
+ // Even a small row count can contain one large message: the Android weak-link
+ // regression took ~18s to deliver 200KB. Do not enqueue another copy at 15s.
+ 'local-db:messages:list': 30_000,
+ 'device-link:media:fetch': 30_000,
+ 'device-link:voice:dictionary-learning': 30_000,
+ 'device-link:voice:transcribe': 30_000,
+ 'file-browser:remote-op': 30_000,
+ 'maker:create-session': 30_000,
+ 'maker:fork': 30_000,
+ 'maker:get-context-usage': 30_000,
+ 'maker:goal:resume': 30_000,
+ 'maker:goal:set': 30_000,
+ 'maker:message:delete': 30_000,
+ 'maker:regenerate-title': 30_000,
+ 'maker:rewind:commit': 30_000,
+ 'maker:send': 30_000,
+ 'maker:usage:codex-rate-limit-reset': 30_000,
+ 'maker:usage:codex-rate-limits': 30_000,
+};
+
+export const MOBILE_SCHEDULE_CHANNEL_TIMEOUT_MS = 40_000;
+
+export function resolveRemoteInvokeTimeoutMs(
+ channel: string,
+ args?: unknown[],
+ platform: 'desktop' | 'mobile' = 'desktop',
+): number | undefined {
+ if (platform === 'desktop') return INVOKE_TIMEOUT_OVERRIDES_MS[channel];
+ // Renewals must settle before the 12s lease, independently of slow media offers.
+ const request = args?.[0];
+ if (channel === 'device-link:remote-desktop:v1' && request &&
+ typeof request === 'object' && 'op' in request && request.op === 'heartbeat') return 5_000;
+ const exact = MOBILE_INVOKE_TIMEOUT_OVERRIDES_MS[channel];
+ if (exact !== undefined) return exact;
+ if (channel.startsWith('maker:schedule:')) return MOBILE_SCHEDULE_CHANNEL_TIMEOUT_MS;
+ return INVOKE_TIMEOUT_OVERRIDES_MS[channel];
+}
+
+const PEER_RESET_RETRYABLE_READ_CHANNELS = new Set([
+ 'local-db:sessions:list',
+ 'local-db:sessions:get',
+ 'local-db:conversations:search',
+ 'local-db:history:messages',
+ 'local-db:messages:list',
+ 'local-db:messages:view',
+ 'local-db:messages:work-details',
+ 'local-db:messages:around',
+ 'local-db:messages:around-client-id',
+ 'local-db:messages:estimatedSessionValue',
+ 'local-db:recent-workdirs:list',
+ 'local-db:subagent-runs:list',
+ 'local-db:subagent-runs:detail',
+ 'local-db:subagent-runs:transcript',
+ 'local-db:bots:list',
+ 'local-db:bots:get',
+ 'local-db:orca-workflows:get-by-lead',
+ 'local-db:orca-workflows:get-by-worker-session',
+ 'local-db:orca-workflows:list-workers-by-lead',
+]);
+
+/** Safe to retry after a peer reset; this does not grant permission or allow coalescing. */
+export function isPeerResetRetryableReadChannel(channel: string): boolean {
+ return PEER_RESET_RETRYABLE_READ_CHANNELS.has(channel);
+}
+
+const COALESCIBLE_LISTING_CHANNELS: ReadonlySet<string> = new Set([
+ 'local-db:sessions:list',
+ 'maker:get-capabilities',
+ 'maker:provider:list',
+ 'maker:git-safety:get',
+ 'maker:schedule:list-sidebar-index-runs',
+]);
+
+/**
+ * Read freshness is independent of retry safety and Host background admission.
+ * sessions:get is a read-after-write recovery boundary, so it never shares an
+ * earlier read. A fresh list likewise must not join a snapshot begun before a write.
+ */
+export function canCoalesceRemoteListing(payload: InvokePayload | undefined): payload is InvokePayload {
+ if (!payload || !COALESCIBLE_LISTING_CHANNELS.has(payload.channel)) return false;
+ const options = payload.args?.[2];
+ return !(payload.channel === 'local-db:sessions:list'
+ && options && typeof options === 'object' && !Array.isArray(options)
+ && (options as { fresh?: unknown }).fresh === true);
+}
diff --git a/packages/device-link/src/peerRecoveryScheduler.ts b/packages/device-link/src/peerRecoveryScheduler.ts
new file mode 100644
index 0000000000..6b046f9970
--- /dev/null
+++ b/packages/device-link/src/peerRecoveryScheduler.ts
@@ -0,0 +1,334 @@
+export type PeerRecoveryPhase = 'idle' | 'queued' | 'running' | 'waiting-retry';
+
+export interface PeerRecoveryResult {
+ /** True when this peer still has transient work and needs a later retry. */
+ retry: boolean;
+}
+
+export interface PeerRecoverySchedulerOptions {
+ maxConcurrent?: number;
+ /** Desktop retries must not keep the Node process alive. */
+ unrefRetryTimers?: boolean;
+ retryBaseMs?: number;
+ retryMaxMs?: number;
+ onError?(deviceId: string, error: unknown): void;
+}
+
+export interface PeerRecoverySnapshot {
+ deviceId: string;
+ phase: PeerRecoveryPhase;
+ retryAttempt: number;
+}
+
+interface PeerRecoveryEntry {
+ phase: PeerRecoveryPhase;
+ generation: number;
+ running: boolean;
+ rerun: boolean;
+ retryAttempt: number;
+ retryTimer: ReturnType<typeof setTimeout> | null;
+}
+
+const DEFAULT_MAX_CONCURRENT = 6;
+const DEFAULT_RETRY_BASE_MS = 2_000;
+const DEFAULT_RETRY_MAX_MS = 30_000;
+
+/**
+ * Transient open intent created by a peer-level transport reset. Generations never reuse
+ * within this provider lifetime, so an old A recovery cannot clear a newer A intent after
+ * cancel → reacquire (the same ABA fence used by the scheduler itself).
+ */
+export class PeerRecoveryOpenIntentRegistry {
+ private readonly generations = new Map<string, number>();
+ private nextGeneration = 0;
+
+ request(deviceId: string): number {
+ if (!deviceId) return 0;
+ const generation = ++this.nextGeneration;
+ this.generations.set(deviceId, generation);
+ return generation;
+ }
+
+ getGeneration(deviceId: string): number | undefined {
+ return this.generations.get(deviceId);
+ }
+
+ has(deviceId: string): boolean {
+ return this.generations.has(deviceId);
+ }
+
+ complete(deviceId: string, generation: number): boolean {
+ if (this.generations.get(deviceId) !== generation) return false;
+ this.generations.delete(deviceId);
+ return true;
+ }
+
+ cancel(deviceId: string): void {
+ this.generations.delete(deviceId);
+ }
+
+ clear(): void {
+ // Keep nextGeneration monotonic: a settling pre-clear run must never collide with a
+ // post-clear intent if the provider/client is replaced while its promise unwinds.
+ this.generations.clear();
+ }
+
+ deviceIds(): string[] {
+ return [...this.generations.keys()];
+ }
+}
+
+/**
+ * Runs recovery independently per remote device while sharing a small global
+ * concurrency budget. A slow peer occupies at most one slot, so it cannot hold
+ * every other desktop behind its timeout. Each peer owns its own rerun flag,
+ * retry attempt and timer.
+ */
+export class PeerRecoveryScheduler {
+ private readonly runPeer: (deviceId: string) => Promise<PeerRecoveryResult>;
+ private readonly onError?: PeerRecoverySchedulerOptions['onError'];
+ private readonly maxConcurrent: number;
+ private readonly unrefRetryTimers: boolean;
+ private readonly retryBaseMs: number;
+ private readonly retryMaxMs: number;
+ private readonly entries = new Map<string, PeerRecoveryEntry>();
+ private readonly queue: string[] = [];
+ private readonly queued = new Set<string>();
+ private active = 0;
+ private paused = false;
+ private activeDeviceIds: ReadonlySet<string> = new Set();
+ private readonly listeners = new Set<() => void>();
+
+ /** Cached read-only UI projection; it never schedules recovery work. */
+ getActiveDeviceIds = (): ReadonlySet<string> => this.activeDeviceIds;
+
+ subscribe = (listener: () => void): (() => void) => {
+ this.listeners.add(listener);
+ return () => { this.listeners.delete(listener); };
+ };
+
+ private publishActiveDeviceIds(): void {
+ const next = new Set<string>();
+ for (const [deviceId, entry] of this.entries) {
+ if (entry.phase !== 'idle' || entry.rerun) next.add(deviceId);
+ }
+ if (next.size === this.activeDeviceIds.size && [...next].every((id) => this.activeDeviceIds.has(id))) return;
+ this.activeDeviceIds = next;
+ for (const listener of this.listeners) {
+ try { listener(); } catch { /* UI observers must not affect recovery scheduling. */ }
+ }
+ }
+
+ constructor(
+ run: (deviceId: string) => Promise<PeerRecoveryResult>,
+ options: PeerRecoverySchedulerOptions = {},
+ ) {
+ this.runPeer = run;
+ this.onError = options.onError;
+ this.unrefRetryTimers = options.unrefRetryTimers ?? false;
+ this.maxConcurrent = normalizePositiveInteger(
+ options.maxConcurrent,
+ DEFAULT_MAX_CONCURRENT,
+ );
+ this.retryBaseMs = normalizePositiveInteger(
+ options.retryBaseMs,
+ DEFAULT_RETRY_BASE_MS,
+ );
+ this.retryMaxMs = Math.max(
+ this.retryBaseMs,
+ normalizePositiveInteger(options.retryMaxMs, DEFAULT_RETRY_MAX_MS),
+ );
+ }
+
+ request(deviceId: string): void {
+ if (!deviceId) return;
+ const entry = this.getOrCreateEntry(deviceId);
+ if (entry.retryTimer) {
+ clearTimeout(entry.retryTimer);
+ entry.retryTimer = null;
+ }
+ // A cancelled generation may still be settling. Keep the next generation
+ // serialized behind it so one peer never has two recovery runs in flight.
+ if (entry.running) {
+ entry.rerun = true;
+ this.publishActiveDeviceIds();
+ return;
+ }
+ this.enqueue(deviceId, entry);
+ }
+
+ requestMany(deviceIds: Iterable<string>): void {
+ for (const deviceId of deviceIds) this.request(deviceId);
+ }
+
+ /** Cancels one peer without touching any other peer's timers or work. */
+ cancel(deviceId: string, resetAttempt = true): void {
+ const entry = this.entries.get(deviceId);
+ if (!entry) return;
+ entry.generation += 1;
+ entry.rerun = false;
+ if (resetAttempt) entry.retryAttempt = 0;
+ if (entry.retryTimer) {
+ clearTimeout(entry.retryTimer);
+ entry.retryTimer = null;
+ }
+ if (this.queued.delete(deviceId)) {
+ const index = this.queue.indexOf(deviceId);
+ if (index >= 0) this.queue.splice(index, 1);
+ }
+ entry.phase = 'idle';
+ this.publishActiveDeviceIds();
+ }
+
+ /**
+ * Relay/background lifecycle gate. In-flight promises cannot be force-cancelled,
+ * but generation fencing makes their late scheduling result inert.
+ */
+ pause(): void {
+ if (this.paused) return;
+ this.paused = true;
+ this.cancelAll(true);
+ }
+
+ resume(): void {
+ if (!this.paused) {
+ this.drain();
+ return;
+ }
+ this.paused = false;
+ this.drain();
+ }
+
+ /** Clears all queued/timed work while retaining safe fences for settling runs. */
+ clear(): void {
+ this.cancelAll(true);
+ for (const [deviceId, entry] of this.entries) {
+ if (!entry.running) this.entries.delete(deviceId);
+ }
+ }
+
+ getSnapshot(deviceId: string): PeerRecoverySnapshot {
+ const entry = this.entries.get(deviceId);
+ return {
+ deviceId,
+ phase: entry?.phase ?? 'idle',
+ retryAttempt: entry?.retryAttempt ?? 0,
+ };
+ }
+
+ private cancelAll(resetAttempts: boolean): void {
+ this.queue.length = 0;
+ this.queued.clear();
+ for (const [deviceId] of this.entries) this.cancel(deviceId, resetAttempts);
+ }
+
+ private getOrCreateEntry(deviceId: string): PeerRecoveryEntry {
+ let entry = this.entries.get(deviceId);
+ if (!entry) {
+ entry = {
+ phase: 'idle',
+ generation: 0,
+ running: false,
+ rerun: false,
+ retryAttempt: 0,
+ retryTimer: null,
+ };
+ this.entries.set(deviceId, entry);
+ }
+ return entry;
+ }
+
+ private enqueue(deviceId: string, entry: PeerRecoveryEntry): void {
+ if (this.queued.has(deviceId)) return;
+ entry.phase = 'queued';
+ this.queued.add(deviceId);
+ this.queue.push(deviceId);
+ this.publishActiveDeviceIds();
+ this.drain();
+ }
+
+ private drain(): void {
+ if (this.paused) return;
+ while (this.active < this.maxConcurrent && this.queue.length > 0) {
+ const deviceId = this.queue.shift()!;
+ this.queued.delete(deviceId);
+ const entry = this.entries.get(deviceId);
+ if (!entry || entry.phase !== 'queued' || entry.running) continue;
+ this.start(deviceId, entry);
+ }
+ }
+
+ private start(deviceId: string, entry: PeerRecoveryEntry): void {
+ const generation = entry.generation;
+ entry.phase = 'running';
+ entry.running = true;
+ entry.rerun = false;
+ this.active += 1;
+
+ let run: Promise<PeerRecoveryResult>;
+ try {
+ run = this.runPeer(deviceId);
+ } catch (error) {
+ try {
+ this.onError?.(deviceId, error);
+ } catch {
+ // Diagnostics must never strand the scheduler's active-slot accounting.
+ }
+ this.finish(deviceId, entry, generation, { retry: true });
+ return;
+ }
+ void run.then(
+ (result) => this.finish(deviceId, entry, generation, result),
+ (error: unknown) => {
+ try {
+ this.onError?.(deviceId, error);
+ } catch {
+ // Diagnostics must never strand the scheduler's active-slot accounting.
+ }
+ this.finish(deviceId, entry, generation, { retry: true });
+ },
+ );
+ }
+
+ private finish(
+ deviceId: string,
+ entry: PeerRecoveryEntry,
+ generation: number,
+ result: PeerRecoveryResult,
+ ): void {
+ if (entry.generation === generation && !entry.rerun) {
+ if (!result.retry) {
+ entry.retryAttempt = 0;
+ entry.phase = 'idle';
+ } else {
+ const delay = Math.min(
+ this.retryBaseMs * 2 ** entry.retryAttempt,
+ this.retryMaxMs,
+ );
+ entry.retryAttempt += 1;
+ entry.phase = 'waiting-retry';
+ entry.retryTimer = setTimeout(() => {
+ entry.retryTimer = null;
+ if (entry.generation !== generation) return;
+ this.enqueue(deviceId, entry);
+ }, delay);
+ if (this.unrefRetryTimers) {
+ (entry.retryTimer as unknown as { unref?: () => void }).unref?.();
+ }
+ }
+ }
+ entry.running = false;
+ this.active -= 1;
+ if (entry.rerun) {
+ entry.rerun = false;
+ this.enqueue(deviceId, entry);
+ }
+ this.drain();
+ this.publishActiveDeviceIds();
+ }
+}
+
+function normalizePositiveInteger(value: number | undefined, fallback: number): number {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return fallback;
+ return Math.max(1, Math.floor(value));
+}
diff --git a/scripts/device-link/clientHarness.ts b/scripts/device-link/clientHarness.ts
index 9237b85b3e..ed663daca9 100644
--- a/scripts/device-link/clientHarness.ts
+++ b/scripts/device-link/clientHarness.ts
@@ -1,6 +1,7 @@
import WebSocket from "ws";
import {
DeviceLinkClient,
+ PeerRecoveryScheduler,
DeviceLinkError,
PROTOCOL_VERSION,
type DeviceLinkTiming,
@@ -8,7 +9,6 @@ import {
type InvokePayload,
type LinkOpenPayload,
} from "../../packages/device-link/src/index";
-import { PeerRecoveryScheduler } from "../../apps/mobile/src/device-link/peerRecoveryScheduler";
import { rehydrateDeviceLinkPeer } from "../../apps/mobile/src/device-link/rehydrate";
import { DeviceLinkTopicRegistry } from "../../apps/mobile/src/device-link/topicRegistry";