Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): 修复远程会话同步延迟与最终收敛 (#307)
qsoyq8c4ecc5d7cd1
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 29e43e55a4..6d2c8d5c13 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -613,11 +613,10 @@ async function applyMemoryChangeWithCodexRestart<T extends object>(}// ─── Sessions push helpers ────────────────────────────────────────────────-// 同 cardActionHandler.ts / maker-host/index.ts:308 — 之所以重复一份是因为-// 跨 module 提取一个 sessions-broadcast helper 不在本次范围内。所有 caller-// 都广播 `local-db:sessions:created`, renderer sessionsStore.onCreated 收到后-// forceRefreshAll 重拉所有桶。-function broadcastSessionCreated(sessionId: string): void {+// maker-ipc 会话创建路径与 scheduler-host 共享此导出,统一广播+// `local-db:sessions:created`;renderer sessionsStore.onCreated 收到后+// forceRefreshAll 重拉所有桶。其它生命周期专属路径仍保留各自的同契约 helper。+export function broadcastSessionCreated(sessionId: string): void {tapWindowBroadcast('local-db:sessions:created', { sessionId });for (const win of BrowserWindow.getAllWindows()) {if (win.isDestroyed()) continue;diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.tsindex 1192ebc6dd..95d6fb7a70 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts@@ -492,4 +492,29 @@ describe('MakerScheduleRunner send outcome policy', () => {expect(run.resultText).toBe('done text');expect(ctx.removeAbortListener).toHaveBeenCalledTimes(1);});++ it('broadcasts a newly accepted schedule session after its user row is durable', async () => {+ const order: string[] = [];+ mocks.createMessage.mockImplementation(async () => {+ order.push('persist');+ });+ const onSessionCreated = vi.fn(() => {+ order.push('broadcast');+ });+ const h = createSessionHarness(async (_message, opts) => {+ await opts?.onAccepted?.();+ return { accepted: true };+ });+ const { runner } = createRunnerHarness(h.session, { onSessionCreated });+ const firePromise = runner.fire(baseSchedule(), createFireContext());++ await vi.waitFor(() => expect(onSessionCreated).toHaveBeenCalledWith('scheduler-session'));+ expect(order).toEqual(['persist', 'broadcast']);++ h.emit({ type: 'done', data: {} });+ await expect(firePromise).resolves.toEqual({+ sessionId: 'scheduler-session',+ resultText: undefined,+ });+ });});diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.tsindex 1ee3d10acf..2a553a6f0f 100644--- a/apps/desktop/src/main/scheduler-host/index.ts+++ b/apps/desktop/src/main/scheduler-host/index.ts@@ -26,6 +26,7 @@ import { getAgentIslandService } from '../agent-island/service.js';import { getDesktopNotificationsEnabled } from '../notificationService.js';import {applyPendingAgentSwitchForDirectSend,+ broadcastSessionCreated,enqueueSchedulerPrompt,hasQueuedSchedulerPrompt,isSchedulerPromptTracked,@@ -74,6 +75,7 @@ export async function startScheduler(deps: StartSchedulerDeps): Promise<SchedulebeforeDispatchUserTurn: deps.beforeDispatchUserTurn,onUndispatchedUserTurn: deps.onUndispatchedUserTurn,applyPendingAgentSwitch: applyPendingAgentSwitchForDirectSend,+ onSessionCreated: broadcastSessionCreated,// 心跳撞忙排队桥:实现挂在 maker-ipc/register.ts 的 coordinator 装配处// (holder 未就绪时 isSessionBusy 返回 false → runner 走原直发路径)。schedulerQueue: {diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.tsindex f37e3132c4..d058911048 100644--- a/apps/desktop/src/main/scheduler-host/runner.ts+++ b/apps/desktop/src/main/scheduler-host/runner.ts@@ -178,6 +178,8 @@ export interface MakerScheduleRunnerDeps {onUndispatchedUserTurn?: (sessionId: string) => void;/** heartbeat 直发前落实 deferred agent switch,并 bootstrap 新 live session。 */applyPendingAgentSwitch?: (sessionId: string, signal?: AbortSignal) => Promise<void>;+ /** 新建可见会话落库后通知本机窗口与 device-link 列表订阅者。 */+ onSessionCreated?: (sessionId: string) => void;/** 可选:撞忙排队桥。未注入时心跳撞忙回退为顺延(deferFire)旧行为。 */schedulerQueue?: SchedulerQueueDeps;}@@ -901,6 +903,16 @@ export class MakerScheduleRunner implements ScheduleRunner {} catch (err) {throw new SchedulerOnAcceptedError(err);}+ // 非 heartbeat 的每次 fire 都创建一条用户可见会话。必须在 source 回填和首条+ // user message 都 durable 后广播,让本机其它窗口与 device-link 控制端立即重拉;+ // heartbeat 只是在既有会话上续跑,不重复发 created。+ if (!isHeartbeat) {+ try {+ this.deps.onSessionCreated?.(session.id);+ } catch (err) {+ this.deps.logger.warn?.('[runner] session created broadcast failed (non-fatal)', err);+ }+ }if (this.deps.beforeDispatchUserTurn) {await this.deps.beforeDispatchUserTurn(session.id);baselineStarted = true;diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.tsindex c77b2a47bd..00699412bb 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts@@ -1044,6 +1044,26 @@ describe('远程交互接线不变式', () => {}});+ it('F6: scheduler 新会话在首条消息落库后广播 created 给 device-link 列表订阅者', () => {+ const runnerSrc = mainSrc('scheduler-host/runner.ts');+ const hostSrc = mainSrc('scheduler-host/index.ts');+ expect(runnerSrc).toContain('this.deps.onSessionCreated?.(session.id)');+ expect(hostSrc).toContain('onSessionCreated: broadcastSessionCreated');+ });++ it('F7: 周期 sessions:list 是有界窗口,只能 merge,不能截断远程分片', () => {+ const src = read('features/device-link/useDeviceLinkRemoteProjects.ts');+ expect(src).toContain("snapshotMode: 'merge'");+ expect(src).toContain("coalescingMode: 'weak'");+ });++ it('F8: 周期对账从实际 link status 启动,且状态 push 不被迟到快照覆盖', () => {+ const src = read('features/device-link/useDeviceLinkRemoteProjects.ts');+ expect(src).toContain('let linkOnline = false');+ expect(src).toContain("if (!linkStatusPushSeen) linkOnline = state.linkStatus === 'online'");+ expect(src).toContain('linkStatusPushSeen = true');+ });+it('F4: extraDirs 远程跳过 sessionService.update(getSessionDeviceId 守卫,避免阻断 setExtraDirs)', () => {const src = read('features/cc-agent/CCAgentSessionView.tsx');const start = src.indexOf('handleExtraDirsChange');diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.tsindex a0e8300c05..6a8ecc3e08 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts@@ -1,6 +1,40 @@-import { describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';-import { resolveIneligibleRemoteProjectAction } from '@/features/device-link/useDeviceLinkRemoteProjects';+import {+ resolveIneligibleRemoteProjectAction,+ startRemoteSessionsReconciler,+} from '@/features/device-link/useDeviceLinkRemoteProjects';++afterEach(() => {+ vi.useRealTimers();+});++describe('startRemoteSessionsReconciler', () => {+ it('periodically refreshes every eligible device and stops cleanly', async () => {+ vi.useFakeTimers();+ const eligible = new Map([+ ['dev-a', 'Mac A'],+ ['dev-b', 'Mac B'],+ ]);+ const refresh = vi.fn(async () => 'ok');+ const stop = startRemoteSessionsReconciler(() => eligible, refresh, 1_000);++ await vi.advanceTimersByTimeAsync(1_000);+ expect(refresh.mock.calls).toEqual([+ ['dev-a', 'Mac A'],+ ['dev-b', 'Mac B'],+ ]);++ eligible.delete('dev-a');+ await vi.advanceTimersByTimeAsync(1_000);+ expect(refresh).toHaveBeenLastCalledWith('dev-b', 'Mac B');+ expect(refresh).toHaveBeenCalledTimes(3);++ stop();+ await vi.advanceTimersByTimeAsync(2_000);+ expect(refresh).toHaveBeenCalledTimes(3);+ });+});describe('resolveIneligibleRemoteProjectAction', () => {it('keeps the cached shard when an eligible device goes offline even if the offline row reports remoteControlEnabled=false', () => {diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.tsindex 20be18cd54..30dfe2db27 100644--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts@@ -21,6 +21,11 @@ import {isTransientRemoteError,} from '@/features/device-link/refreshRemoteSessions';import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import {+ applyRemoteSessionActivity,+ clearRemoteSessionActivity,+ getRemoteSessionActivity,+} from '@/features/device-link/remoteSessionActivityStore';const invoke = vi.fn();let n = 0;@@ -34,11 +39,12 @@ beforeEach(() => {afterEach(() => {remoteProjectsStore.clear();+ clearRemoteSessionActivity();vi.unstubAllGlobals();});-function session(id: string): Session {- return { id } as Session;+function session(id: string, partial: Partial<Session> = {}): Session {+ return { id, ...partial } as Session;}function deferred<T>() {@@ -88,7 +94,9 @@ describe('refreshRemoteDeviceSessions retry', () => {it('永久错误(REMOTE_DISABLED)→ 不重试,立即放弃(返回 gave-up)', async () => {const d = did();invoke.mockRejectedValue(new Error('[REMOTE_DISABLED] remote control disabled'));- await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe('gave-up');+ await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(+ 'gave-up',+ );expect(invoke).toHaveBeenCalledTimes(1);expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(0);});@@ -96,7 +104,9 @@ describe('refreshRemoteDeviceSessions retry', () => {it('访问被撤销(DEVICE_LINK_ACCESS_REVOKED)→ 不重试,返回 revoked(调用方据此 handleRevoked)', async () => {const d = did();invoke.mockRejectedValue(new Error('[DEVICE_LINK_ACCESS_REVOKED] revoked'));- await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe('revoked');+ await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(+ 'revoked',+ );expect(invoke).toHaveBeenCalledTimes(1); // 终态,不重试expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(0);});@@ -143,6 +153,200 @@ describe('refreshRemoteDeviceSessions retry', () => {]);});+ it('周期有界快照更新命中行但保留 200 条窗口外的有效会话', async () => {+ const d = did();+ const recent = Array.from({ length: 200 }, (_, index) =>+ session(`recent-${index}`, { title: index === 0 ? 'new' : undefined }),+ );+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [+ session('recent-0', { title: 'old' }),+ session('outside-window'),+ ]);+ invoke+ .mockResolvedValueOnce(recent)+ .mockResolvedValueOnce(session('outside-window', { status: 'active' }));++ await refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ });++ const merged = remoteProjectsStore.getMergedRemoteSessions();+ expect(merged).toHaveLength(201);+ expect(merged.map((s) => s.id)).toContain('outside-window');+ expect(merged[0].title).toBe('new');+ expect(invoke).toHaveBeenNthCalledWith(2, d, 'local-db:sessions:get', ['outside-window']);+ });++ it('默认事件重拉也按有界快照 merge,保留 200 条窗口外的有效会话', async () => {+ const d = did();+ const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('outside-window')]);+ invoke+ .mockResolvedValueOnce(recent)+ .mockResolvedValueOnce(session('outside-window', { status: 'active' }));++ await refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });++ expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(201);+ expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toContain(+ 'outside-window',+ );+ });++ it('周期快照未满 200 条时视为完整 active 集合并清理缺席行', async () => {+ const d = did();+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [+ session('fresh'),+ session('stale-archived'),+ ]);+ applyRemoteSessionActivity(d, {+ sessionId: 'stale-archived',+ phase: 'running',+ compactDetail: 'still running',+ });+ invoke.mockResolvedValueOnce([session('fresh')]);++ await refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ });++ expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);+ expect(getRemoteSessionActivity('stale-archived')).toBeUndefined();+ expect(invoke).toHaveBeenCalledTimes(1);+ });++ it('周期满窗口用既有 sessions:get 有界补查并清理已归档的窗口外行', async () => {+ const d = did();+ const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('stale-archived')]);+ applyRemoteSessionActivity(d, {+ sessionId: 'stale-archived',+ phase: 'running',+ compactDetail: 'still running',+ });+ invoke+ .mockResolvedValueOnce(recent)+ .mockResolvedValueOnce(session('stale-archived', { status: 'archived' }));++ await refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ });++ expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(200);+ expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).not.toContain(+ 'stale-archived',+ );+ expect(getRemoteSessionActivity('stale-archived')).toBeUndefined();+ });++ it('周期满窗口补查 active 行时回填窗口外会话的权威元数据', async () => {+ const d = did();+ const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [+ session('outside-window', { title: 'old', pinnedAt: '2026-01-01T00:00:00.000Z' }),+ ]);+ invoke+ .mockResolvedValueOnce(recent)+ .mockResolvedValueOnce(+ session('outside-window', { status: 'active', title: 'new', pinnedAt: null }),+ );++ await refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ });++ expect(remoteProjectsStore.getDeviceSessions(d).find((s) => s.id === 'outside-window')).toEqual(+ expect.objectContaining({ title: 'new', pinnedAt: null }),+ );+ });++ it('周期满窗口每轮最多补查 8 个缺席缓存 id', async () => {+ const d = did();+ const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));+ const outside = Array.from({ length: 12 }, (_, index) => session(`outside-${index}`));+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', outside);+ invoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'local-db:sessions:list') return recent;+ return session(String(args[0]), { status: 'active' });+ });++ await refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ });++ const probes = invoke.mock.calls.filter(([, channel]) => channel === 'local-db:sessions:get');+ expect(probes).toHaveLength(8);+ expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(212);+ });++ it('周期满窗口的相邻补查批次按 8 条推进,不重复检查上一批', async () => {+ const d = did();+ const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));+ const outside = Array.from({ length: 20 }, (_, index) => session(`outside-${index}`));+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', outside);+ invoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'local-db:sessions:list') return recent;+ return session(String(args[0]), { status: 'active' });+ });++ await refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ });+ const firstProbeIds = invoke.mock.calls+ .filter(([, channel]) => channel === 'local-db:sessions:get')+ .map(([, , args]) => String(args[0]));++ invoke.mockClear();+ await refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ });+ const secondProbeIds = invoke.mock.calls+ .filter(([, channel]) => channel === 'local-db:sessions:get')+ .map(([, , args]) => String(args[0]));++ expect(firstProbeIds).toHaveLength(8);+ expect(secondProbeIds).toHaveLength(8);+ expect(firstProbeIds).toEqual(outside.slice(0, 8).map((item) => item.id));+ expect(secondProbeIds).toEqual(outside.slice(8, 16).map((item) => item.id));+ });++ it('前一批移除终态行后,下一批仍从原队列的紧邻候选继续', async () => {+ const d = did();+ const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));+ const outside = Array.from({ length: 20 }, (_, index) => session(`outside-${index}`));+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', outside);+ invoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'local-db:sessions:list') return recent;+ const sessionId = String(args[0]);+ return session(sessionId, {+ status: sessionId === 'outside-0' || sessionId === 'outside-1' ? 'archived' : 'active',+ });+ });++ await refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ });+ invoke.mockClear();++ await refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ });+ const secondProbeIds = invoke.mock.calls+ .filter(([, channel]) => channel === 'local-db:sessions:get')+ .map(([, , args]) => String(args[0]));++ expect(secondProbeIds).toEqual(outside.slice(8, 16).map((item) => item.id));+ });+it('同设备并发重拉合并为单飞执行,期间新触发只补跑一次', async () => {const d = did();invoke.mockResolvedValueOnce([session('old')]).mockResolvedValueOnce([session('fresh')]);@@ -155,17 +359,39 @@ describe('refreshRemoteDeviceSessions retry', () => {expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);});+ it('慢周期 merge 在途时忽略后续周期 tick,不 bump epoch 自取消', async () => {+ const d = did();+ const snapshot = deferred<Session[]>();+ invoke.mockReturnValueOnce(snapshot.promise);++ const first = refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ coalescingMode: 'weak',+ });+ const second = refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ coalescingMode: 'weak',+ });++ snapshot.resolve([session('slow-but-valid')]);+ await expect(Promise.all([first, second])).resolves.toEqual(['ok', 'ok']);+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual([+ 'slow-but-valid',+ ]);+ });+it('同设备补跑排队时立即作废当前 snapshot,避免旧结果短暂覆盖 push 状态', async () => {const d = did();const firstSnapshot = deferred<Session[]>();const secondSnapshot = deferred<Session[]>();const secondStarted = deferred<void>();- invoke- .mockReturnValueOnce(firstSnapshot.promise)- .mockImplementationOnce(() => {- secondStarted.resolve();- return secondSnapshot.promise;- });+ invoke.mockReturnValueOnce(firstSnapshot.promise).mockImplementationOnce(() => {+ secondStarted.resolve();+ return secondSnapshot.promise;+ });const first = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });const second = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });@@ -178,4 +404,50 @@ describe('refreshRemoteDeviceSessions retry', () => {await expect(Promise.all([first, second])).resolves.toEqual(['ok', 'ok']);expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);});++ it('事件型 refresh 排在弱周期 merge 后时保持强语义补跑', async () => {+ const d = did();+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('outside-window')]);+ const periodicSnapshot = deferred<Session[]>();+ const replacementSnapshot = deferred<Session[]>();+ const replacementStarted = deferred<void>();+ invoke.mockReturnValueOnce(periodicSnapshot.promise).mockImplementationOnce(() => {+ replacementStarted.resolve();+ return replacementSnapshot.promise;+ });++ const periodic = refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ coalescingMode: 'weak',+ });+ const bootstrap = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });++ periodicSnapshot.resolve([session('stale')]);+ await replacementStarted.promise;+ replacementSnapshot.resolve([session('fresh')]);++ await expect(Promise.all([periodic, bootstrap])).resolves.toEqual(['ok', 'ok']);+ expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);+ });++ it('事件型 refresh 在途时弱周期 tick 直接复用,不补跑也不取消当前请求', async () => {+ const d = did();+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('outside-window')]);+ const bootstrapSnapshot = deferred<Session[]>();+ invoke.mockReturnValueOnce(bootstrapSnapshot.promise);++ const bootstrap = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });+ const periodic = refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ coalescingMode: 'weak',+ });++ bootstrapSnapshot.resolve([session('fresh')]);++ await expect(Promise.all([bootstrap, periodic])).resolves.toEqual(['ok', 'ok']);+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);+ });});diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.tsindex edacc1e4f5..60c551d96e 100644--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts@@ -1,10 +1,9 @@/*** refreshRemoteDeviceSessions —— 立即(可 await)重拉某被控设备的会话列表(bootstrap / reconcile)。*- * 这是「读被控端真相」的一次性按需拉取,**不是**轮询补偿(控制端纯镜像下,稳态增量靠- * 被控端 sessions:patched/created push 驱动;本函数只用于「刚在被控端创建了一个会话、要马上- * navigate 过去」这类需要先把新 sessionId 注册进 store 才能避免 404 的 bootstrap-before-navigate- * 场景:listing tier 首拉、reconnect 重拉、fork / orca worker / 远程新建会话)。+ * 这是「读被控端真相」的一次性按需拉取。默认用于 listing tier 首拉、reconnect、+ * sessions:created reseed、fork / orca worker / 远程新建会话;周期 anti-entropy 也复用本函数,+ * 但使用 merge 模式,避免有界列表删除窗口外会话。** 用 per-device epoch 防乱序:两次重拉乱序 resolve 时,旧的那次结果被丢弃(只接受最新一次),* 避免旧 snapshot 覆盖新 snapshot(reconcile 规则)。@@ -18,13 +17,18 @@import type { Session } from '@/lib/ccAgent.types';import { createLogger } from '@/lib/logger';+import { extractIpcError } from '@/utils/ipcError';import { remoteProjectsStore } from './remoteProjectsStore';+import { removeRemoteSessionActivityEntry } from './remoteSessionActivityStore';const log = createLogger('device-link-refresh');/** 与 listing tier 的拉取上限一致(useDeviceLinkRemoteProjects 的 LIST_LIMIT)。 */const LIST_LIMIT = 200;+/** 满窗口时每轮最多补查多少个缺席缓存 id,避免退化成无界 N+1。 */+const MISSING_STATUS_PROBE_LIMIT = 8;+/** 默认重试次数(含首次):退避 250→500→1000→2000→3000ms,总窗口 ~6.75s,覆盖被控端冷启动迁移。 */const DEFAULT_MAX_ATTEMPTS = 6;@@ -43,7 +47,12 @@ const ACCESS_REVOKED_MARKER = 'DEVICE_LINK_ACCESS_REVOKED';* ⚠️ 超时码用 DEVICE_LINK_TIMEOUT:invoke 超时的原始 DeviceLinkError('INVOKE_TIMEOUT') 在 main IPC* 层被映射成 `[DEVICE_LINK_TIMEOUT]` 才到 renderer,这里匹配的是 renderer 实际看到的已映射码。*/-const TRANSIENT_MARKERS = ['DbClient not ready', 'NOT_CONNECTED', 'DEVICE_OFFLINE', 'DEVICE_LINK_TIMEOUT'] as const;+const TRANSIENT_MARKERS = [+ 'DbClient not ready',+ 'NOT_CONNECTED',+ 'DEVICE_OFFLINE',+ 'DEVICE_LINK_TIMEOUT',+] as const;/*** 该远程错误是否「瞬态、值得重试」。永久错误优先(命中即不重试);否则仅当命中已知瞬态标记@@ -66,6 +75,10 @@ export interface RefreshOptions {sleep?: (ms: number) => Promise<void>;/** 最大尝试次数(含首次),默认 DEFAULT_MAX_ATTEMPTS。 */maxAttempts?: number;+ /** sessions:list 始终有界,默认 merge;仅已知完整的调用方才可显式 replace。 */+ snapshotMode?: 'replace' | 'merge';+ /** 周期 tick 可弱合并到任意在途 refresh;事件型 refresh 默认强语义补跑。 */+ coalescingMode?: 'strong' | 'weak';}/**@@ -85,6 +98,39 @@ interface RefreshTask {const refreshTasks = new Map<string, RefreshTask>();+/**+ * 满窗口缺席行的轮询队列(per-device)。不能用 snapshot epoch 推导数组下标:前一轮+ * 确认终态并移除候选后,数组会收缩,重算下标会跳过紧邻项。队列在每轮开始时与当前+ * missing ids 对账,保留旧轮询顺序、移除已不缺席项,并把新缺席项追加到队尾。+ */+const missingStatusProbeQueues = new Map<string, string[]>();++function reconcileMissingStatusProbeQueue(+ deviceId: string,+ missingSessionIds: readonly string[],+): string[] {+ if (missingSessionIds.length === 0) {+ missingStatusProbeQueues.delete(deviceId);+ return [];+ }+ const missingIds = new Set(missingSessionIds);+ const previous = missingStatusProbeQueues.get(deviceId) ?? [];+ const queuedIds = new Set<string>();+ const queue: string[] = [];+ for (const sessionId of previous) {+ if (!missingIds.has(sessionId) || queuedIds.has(sessionId)) continue;+ queuedIds.add(sessionId);+ queue.push(sessionId);+ }+ for (const sessionId of missingSessionIds) {+ if (queuedIds.has(sessionId)) continue;+ queuedIds.add(sessionId);+ queue.push(sessionId);+ }+ missingStatusProbeQueues.set(deviceId, queue);+ return queue;+}+export async function refreshRemoteDeviceSessions(deviceId: string,name?: string,@@ -92,9 +138,23 @@ export async function refreshRemoteDeviceSessions(): Promise<RefreshResult> {const existing = refreshTasks.get(deviceId);if (existing) {+ const requestedSnapshotMode = opts.snapshotMode ?? 'merge';+ // periodic tick 是弱语义:已有任意 refresh 在途时直接复用,不能每个 interval tick+ // 都 bump epoch 让慢请求自取消。bootstrap/reseed 等事件型 refresh 仍走强语义补跑。+ if (opts.coalescingMode === 'weak') return existing.promise;+existing.rerun = true;existing.name = name ?? existing.name;- existing.opts = { ...existing.opts, ...opts };+ existing.opts = {+ ...existing.opts,+ ...opts,+ // 显式 replace 是更强的 snapshot 覆盖要求,不能被后续 merge 降级;默认的事件型+ // refresh 则保持安全的有界 merge,并通过上面的强 coalescing 语义确保补跑。+ snapshotMode:+ (existing.opts.snapshotMode ?? 'merge') === 'replace' || requestedSnapshotMode === 'replace'+ ? 'replace'+ : 'merge',+ };// 先让当前 in-flight snapshot 失效,否则它可能在排队的补跑开始前覆盖 push 带来的新状态。remoteProjectsStore.nextSnapshotEpoch(deviceId);return existing.promise;@@ -124,6 +184,66 @@ async function drainRefreshTask(deviceId: string, task: RefreshTask): Promise<Rereturn result;}+async function probeMissingSessionStatuses(+ deviceId: string,+ epoch: number,+ missingSessionIds: readonly string[],+): Promise<void> {+ const queue = reconcileMissingStatusProbeQueue(deviceId, missingSessionIds);+ if (queue.length === 0) return;+ const count = Math.min(MISSING_STATUS_PROBE_LIMIT, queue.length);+ const candidates = queue.slice(0, count);+ const results = await Promise.all(+ candidates.map(async (sessionId) => {+ try {+ const value = await window.electronAPI.deviceLink.invoke(+ deviceId,+ 'local-db:sessions:get',+ [sessionId],+ );+ return { sessionId, value };+ } catch (error) {+ return { sessionId, errorCode: extractIpcError(error)?.code };+ }+ }),+ );+ // 更强的 refresh / remove / disconnect 已使本轮失效时,不应用迟到的补查结果。+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return;+ const terminalIds = new Set<string>();+ for (const result of results) {+ if (result.errorCode === 'NOT_FOUND') {+ terminalIds.add(result.sessionId);+ remoteProjectsStore.applyPatch(deviceId, result.sessionId, { status: 'deleted' });+ removeRemoteSessionActivityEntry(result.sessionId);+ continue;+ }+ if (!result.value || typeof result.value !== 'object') continue;+ const session = result.value as Partial<Session>;+ if (session.id !== result.sessionId) continue;+ if (session.status === 'archived' || session.status === 'deleted') {+ terminalIds.add(result.sessionId);+ remoteProjectsStore.applyPatch(deviceId, result.sessionId, {+ status: session.status,+ updatedAt: session.updatedAt,+ });+ removeRemoteSessionActivityEntry(result.sessionId);+ continue;+ }+ // sessions:get 返回窗口外 active 行时同样是权威快照,回填 title / pinnedAt / model 等+ // 元数据;否则丢失 patched push 后会永久保留旧字段。+ remoteProjectsStore.applyPatch(deviceId, result.sessionId, { ...session });+ }+ const nextQueue = [+ ...queue.slice(count),+ ...candidates.filter((sessionId) => !terminalIds.has(sessionId)),+ ];+ if (nextQueue.length === 0) {+ missingStatusProbeQueues.delete(deviceId);+ } else {+ missingStatusProbeQueues.set(deviceId, nextQueue);+ }+}+async function runRefreshRemoteDeviceSessions(deviceId: string,name?: string,@@ -146,7 +266,28 @@ async function runRefreshRemoteDeviceSessions(// 乱序保护:本次拉取已不是最新一次 → 丢弃,别覆盖更新的结果。if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return 'gave-up';if (Array.isArray(list)) {- remoteProjectsStore.setDeviceSessions(deviceId, deviceName, list as Session[]);+ if ((opts.snapshotMode ?? 'merge') === 'merge') {+ const sessions = list as Session[];+ const incomingIds = new Set(sessions.map((session) => session.id));+ const missingSessionIds = remoteProjectsStore+ .getDeviceSessions(deviceId)+ .filter((session) => !incomingIds.has(session.id))+ .map((session) => session.id);+ // 未满 LIST_LIMIT 证明 active 集合完整,可安全 replace 并清掉缺席的归档/删除行。+ // 满窗口时先 merge,再用既有只读 sessions:get 有界轮询窗口外缓存 id 的终态。+ if (sessions.length < LIST_LIMIT) {+ missingStatusProbeQueues.delete(deviceId);+ remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions);+ for (const sessionId of missingSessionIds) {+ removeRemoteSessionActivityEntry(sessionId);+ }+ } else {+ remoteProjectsStore.mergeDeviceSessions(deviceId, deviceName, sessions);+ await probeMissingSessionStatuses(deviceId, epoch, missingSessionIds);+ }+ } else {+ remoteProjectsStore.setDeviceSessions(deviceId, deviceName, list as Session[]);+ }}return 'ok'; // 成功} catch (err) {diff --git a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.tsindex 66128f1514..a849cfe9d7 100644--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts@@ -9,7 +9,9 @@* DB 才是数据真相)。断链 / 设备下线时保留最近一次快照并标成 disconnected,* 让 All Sessions 稳定;明确撤销 / 关闭控制 / 删除才移除。**不做任何乐观预测 / 本地覆盖**——* 视图 = f(bootstrap snapshot + 被控端 push 流):- * · snapshot(`setDeviceSessions`):listing tier 订阅后拉一次全量 / reconnect 重拉。+ * · snapshot(`setDeviceSessions`):listing tier 订阅后拉一次有界列表 / reconnect 重拉。+ * · anti-entropy(`mergeDeviceSessions`):周期满窗口列表先更新命中行并保留窗口外会话,+ * 再由 refresh 层有界补查缺席 id 的终态;未满窗口则可直接安全替换。* · 增量(`applyPatch`):收到被控端 `local-db:sessions:patched` push 时就地幂等合并;* status=deleted/archived → 移出分片;落到未知 session → 丢弃(后续 snapshot 带最终态)。* · 新建(`requestRemoteReseed`):`sessions:created` push 无 row 数据 → 触发该设备重拉。@@ -124,7 +126,9 @@ function recompute(): void {sessionCount: shard.sessions.length,connected: shard.connectionStatus === 'connected',}))- .sort((a, b) => a.deviceName.localeCompare(b.deviceName) || a.deviceId.localeCompare(b.deviceId));+ .sort(+ (a, b) => a.deviceName.localeCompare(b.deviceName) || a.deviceId.localeCompare(b.deviceId),+ );if (!sameDeviceList(deviceListSnapshot, nextDevices)) deviceListSnapshot = nextDevices;}subs.forEach((fn) => fn());@@ -152,11 +156,7 @@ const actions = {* 逐字节不变时跳过(避免无谓重渲染);epoch 乱序保护在调用方(listing tier)用* nextSnapshotEpoch/isLatestSnapshotEpoch 完成,本函数无条件替换。*/- setDeviceSessions(- deviceId: string,- deviceName: string,- rawSessions: readonly Session[],- ): void {+ setDeviceSessions(deviceId: string, deviceName: string, rawSessions: readonly Session[]): void {const connectionStatus: DeviceLinkConnectionStatus = 'connected';const stamped = rawSessions.map((s) => stamp(s, deviceId, deviceName, connectionStatus));const existing = shards.get(deviceId);@@ -172,6 +172,24 @@ const actions = {recompute();},+ /**+ * 合并一份有界会话快照。周期 anti-entropy 只拿最近 LIST_LIMIT 条 + 旧置顶,响应缺席+ * 不能证明窗口外会话已归档/删除;因此命中行用权威值替换,未命中行先保留,再由 refresh+ * 层有界补查终态。首次无分片时等价于 setDeviceSessions。+ */+ mergeDeviceSessions(deviceId: string, deviceName: string, rawSessions: readonly Session[]): void {+ const existing = shards.get(deviceId);+ if (!existing) {+ actions.setDeviceSessions(deviceId, deviceName, rawSessions);+ return;+ }+ const incomingIds = new Set(rawSessions.map((session) => session.id));+ actions.setDeviceSessions(deviceId, deviceName, [+ ...rawSessions,+ ...existing.sessions.filter((session) => !incomingIds.has(session.id)),+ ]);+ },+/*** 应用一条被控端 `local-db:sessions:patched` 增量(push 驱动镜像核心)。幂等:* - status ∈ {deleted, archived} → 从分片移除该会话(active 视图不含)。@@ -194,7 +212,8 @@ const actions = {return;}const wasPinned = shard.sessions[idx]?.pinnedAt != null;- const unpinned = Object.prototype.hasOwnProperty.call(patch, 'pinnedAt') && patch.pinnedAt == null;+ const unpinned =+ Object.prototype.hasOwnProperty.call(patch, 'pinnedAt') && patch.pinnedAt == null;shard.sessions = shard.sessions.map((s) =>s.id === sessionId? {@@ -286,6 +305,11 @@ const actions = {return mergedSnapshot;},+ /** refresh anti-entropy 用:取某设备当前缓存分片,调用方只读。 */+ getDeviceSessions(deviceId: string): readonly Session[] {+ return shards.get(deviceId)?.sessions ?? EMPTY;+ },+/*** origin 判定:给定 sessionId 返回其所属被控设备 deviceId;本地会话返回 undefined。* 传输层 / SessionView / 消息分页据此决定走本机 IPC 还是 deviceLink 隧道。diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.tsindex 6dacc4deb5..e040ba881d 100644--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts@@ -15,7 +15,9 @@* 全量(reconcile 规则:先 subscribe 再 snapshot,中间窗口的增量由 push 兜)。* - 之后被控端的 `sessions:patched`(改名/置顶/删/归档/设置)经 push → makerChatStore 路由到* remoteProjectsStore.applyPatch;`sessions:created`(无 row 数据)→ 防抖重拉该设备。- * **不再 10s 轮询**(去掉轮询补偿;稳态全靠 push)。+ * - push 是低延迟主路径;另以低频有界 snapshot 做 anti-entropy,更新窗口内权威状态;+ * 满窗口时保留缺席行并有界轮询其终态,避免误删仍有效的窗口外会话,也让丢失的归档/删除+ * push 最终收敛。* - 设备瞬时不可达(下线 / relay connecting)→ 保留最近一次快照并标记 disconnected;* 明确不合格(关被控 / 被撤销 / 本机禁用控制)→ `unsubscribe` + removeDevice。* - WS 重连 → 对每个合格设备重新 subscribe + 重新 bootstrap(被控端可能重启过、订阅 registry 清空)。@@ -46,6 +48,30 @@ const log = createLogger('device-link-remote-projects');/** sessions:created reseed 防抖(被控端短时间多次创建会话 / orca 起多 worker 时合并重拉)。 */const RESEED_DEBOUNCE_MS = 300;+/** best-effort push 的窗口内 anti-entropy 周期。窗口外终态按有界轮询分批收敛。 */+const RECONCILE_INTERVAL_MS = 10_000;++type RemoteSessionsRefresh = (deviceId: string, name?: string) => Promise<unknown>;++/**+ * 启动 listing tier 的低频有界对账。setInterval 只负责触发;每设备的并发合并与乱序保护+ * 继续由 refreshRemoteDeviceSessions 负责。返回清理函数,避免窗口卸载后残留 timer。+ */+export function startRemoteSessionsReconciler(+ getEligibleDevices: () => Iterable<readonly [string, string]>,+ refresh: RemoteSessionsRefresh = refreshRemoteDeviceSessions,+ intervalMs = RECONCILE_INTERVAL_MS,+): () => void {+ const timer = setInterval(() => {+ for (const [deviceId, name] of getEligibleDevices()) {+ void refresh(deviceId, name).catch((err) => {+ log.debug(`periodic sessions reconcile failed for ${deviceId.slice(0, 8)}`, err);+ });+ }+ }, intervalMs);+ return () => clearInterval(timer);+}+type IneligibleRemoteProjectAction = 'disconnect' | 'remove' | 'ignore';export function resolveIneligibleRemoteProjectAction(input: {@@ -75,6 +101,10 @@ export function useDeviceLinkRemoteProjects(): void {}let disposed = false;+ /** relay 在线时才跑 anti-entropy;初始状态未知时保守暂停,避免离线失败重试。 */+ let linkOnline = false;+ /** push 一旦到达即权威:迟到的 getState 快照不得覆盖更新的 link status。 */+ let linkStatusPushSeen = false;/** 当前合格设备:deviceId → 友好名 */const eligible = new Map<string, string>();/** 本机主动关闭控制的目标设备(控制端本地偏好)。 */@@ -234,15 +264,30 @@ export function useDeviceLinkRemoteProjects(): void {deviceId,setTimeout(() => {reseedTimers.delete(deviceId);- if (!disposed && eligible.has(deviceId)) void refreshRemoteDeviceSessions(deviceId, name);+ if (!disposed && eligible.has(deviceId)) {+ void refreshRemoteDeviceSessions(deviceId, name, { snapshotMode: 'merge' });+ }}, RESEED_DEBOUNCE_MS),);});+ const stopPeriodicReconcile = startRemoteSessionsReconciler(+ () => (linkOnline ? eligible : []),+ async (deviceId, name) => {+ // sessions:list 是 200 条有界窗口;refresh 层会保留窗口外 active 行,并有界补查+ // 缺席缓存 id 的终态,不能直接把响应缺席解释成删除。+ const result = await refreshRemoteDeviceSessions(deviceId, name, {+ snapshotMode: 'merge',+ coalescingMode: 'weak',+ });+ if (result === 'revoked' && !disposed) handleRevoked(deviceId);+ },+ );void window.electronAPI.deviceLink.getState().then((state) => {if (disposed) return;+ if (!linkStatusPushSeen) linkOnline = state.linkStatus === 'online';disabledControlDeviceIds = new Set(state.disabledControlDeviceIds ?? []);reseed();})@@ -264,7 +309,8 @@ export function useDeviceLinkRemoteProjects(): void {// 被控端 active-catalog 变化:供应商目录与 capabilities.availableModels 必须同代刷新。// 两套缓存订阅会把完整结果原子推给已挂载选择器,刷新期间保留旧列表避免空白跳变。const offRemotePush = window.electronAPI.deviceLink.onRemotePush((push) => {- if (disposed || push.channel !== 'maker:provider:changed' || !eligible.has(push.deviceId)) return;+ if (disposed || push.channel !== 'maker:provider:changed' || !eligible.has(push.deviceId))+ return;evictDeviceProviders(push.deviceId);evictDeviceCapabilities(push.deviceId);void prefetchDeviceProviders(push.deviceId);@@ -274,6 +320,8 @@ export function useDeviceLinkRemoteProjects(): void {// WS 重连后:presence 重新对齐 + 对每个已合格设备重新 subscribe + 重新 bootstrap// (被控端可能重启过、订阅 registry 清空,这步重建订阅;reseed 补新设备)。const offStatus = window.electronAPI.deviceLink.onStatusChanged((p) => {+ linkStatusPushSeen = true;+ linkOnline = p.status === 'online';if (p.status !== 'online') {// relay 瞬时重连(connecting):保留远程会话镜像,只标记 disconnected,让 All Sessions// 不因网络抖动反复增删/重排。eligible 保留不动 → 重连 online 时下面的分支自动@@ -327,6 +375,7 @@ export function useDeviceLinkRemoteProjects(): void {return () => {disposed = true;setRemoteReseedImpl(null);+ stopPeriodicReconcile();for (const t of reseedTimers.values()) clearTimeout(t);reseedTimers.clear();bootstrapTasks.clear();