Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复远程已归档任务为空 (#2175)
DavidShenXDb048356271c1
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.tsindex 20ac74f846..90e3279358 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts@@ -1259,6 +1259,8 @@ describe('远程交互接线不变式', () => {expect(src).toContain('let linkOnline = false');expect(src).toContain("if (!linkStatusPushSeen) linkOnline = state.linkStatus === 'online'");expect(src).toContain('linkStatusPushSeen = true');+ // debounce 排队后 relay 可能已进入 connecting;执行时必须重查实时状态,不能离线重试。+ expect(src).toContain('if (!disposed && linkOnline && eligible.has(deviceId))');});it('F4: extraDirs 远程跳过 sessionService.update(getSessionDeviceId 守卫,避免阻断 setExtraDirs)', () => {diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.tsindex da76019ffd..48f62ade18 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import {createReconcileBackoff,+ nextArchivedSessionRetryDelay,nextSessionListTokenRetryDelay,resolveIneligibleRemoteProjectAction,startRemoteSessionsReconciler,@@ -67,6 +68,19 @@ describe('session-list owner token retry backoff', () => {});});+describe('archived session retry backoff', () => {+ it('从 2s 指数退避到 30s,并在成功或生命周期清理后可从首档重启', () => {+ const delays: number[] = [];+ let previous = 0;+ for (let i = 0; i < 7; i += 1) {+ previous = nextArchivedSessionRetryDelay(previous);+ delays.push(previous);+ }+ expect(delays).toEqual([2_000, 4_000, 8_000, 16_000, 30_000, 30_000, 30_000]);+ expect(nextArchivedSessionRetryDelay(0)).toBe(2_000);+ });+});+describe('startRemoteSessionsReconciler', () => {it('periodically refreshes every eligible device and stops cleanly', async () => {vi.useFakeTimers();diff --git a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.tsindex ccfa238a18..ad94a63670 100644--- a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts+++ b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts@@ -88,6 +88,16 @@ describe('Dialogue sidebar section', () => {);});+ it('loads archived sessions on demand for the selected connected remote devices', () => {+ expect(sidebarSource).toContain("if (filter.status === 'active') return;");+ expect(sidebarSource).toContain("requestRemoteSessionStatus(device.deviceId, 'archived')");+ expect(sidebarSource).toContain('if (!device.connected) continue;');+ expect(sidebarSource).toContain('selectedRemoteIds && !selectedRemoteIds.has(device.deviceId)');+ // 折叠 rail 与展开态必须共用同一状态过滤结果,不能在「已归档」下继续露出 active。+ expect(sidebarSource).toContain('statusFilteredSessionsWithRemote');+ expect(sidebarSource).toContain('matchesSidebarSessionStatus');+ });+it('shows remote directory/task loading and failures before connecting or authoritative empty states', () => {const failureIndex = sidebarSource.indexOf('remoteSessionBootstrapFailures.length > 0 && !hasVisibleSidebarContent',@@ -110,14 +120,20 @@ describe('Dialogue sidebar section', () => {expect(remoteProjectsHookSource).not.toContain("result === 'gave-up' && !remoteProjectsStore.hasDevice(deviceId)",);+ expect(remoteProjectsHookSource).toContain(+ 'remoteProjectsStore.markSessionStatusFailed(deviceId, status)',+ );+ expect(remoteProjectsHookSource).toContain('scheduleArchivedSessionRetry(deviceId)');+ expect(remoteProjectsHookSource).toContain("retryRemoteSessionStatus(deviceId, 'archived')");+ expect(sidebarSource).toContain('useRemoteArchivedFailedDeviceIds()');+ expect(sidebarSource).toContain('useRemoteArchivedLoadedDeviceIds()');+ expect(sidebarSource).toContain("if (filter.status === 'archived')");});it('keeps remote background loading from changing the sidebar layout', () => {// Existing local/cached rows must stay in place while remote bootstrap runs in the background.// A partial loading notice in the scroll flow makes every row jump when it mounts/unmounts.- expect(sidebarSource).toContain(- '远程任务 / 设备目录的 loading 只在上面的「无内容」分支显示',- );+ expect(sidebarSource).toContain('远程任务 / 设备目录的 loading 只在上面的「无内容」分支显示');expect(sidebarSource).not.toMatch(/remoteDeviceDirectoryStatus === 'loading'\s*&&\s*\n?\s*\(\s*<RemoteSidebarLoadNotice[\s\S]*?partial\s*\/\>\s*\)/,);diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.tsindex f31d73639d..c40e58019d 100644--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts@@ -309,6 +309,99 @@ describe('refreshRemoteDeviceSessions retry', () => {]);});+ it('按需读取 archived 桶并保留既有 active 桶', async () => {+ const d = did();+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('active-1')], 'active');+ invoke.mockResolvedValueOnce([session('archived-1', { status: 'archived' })]);++ await expect(+ refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep, status: 'archived' }),+ ).resolves.toBe('ok');++ expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [+ 1000,+ 'archived',+ { includePinned: true },+ ]);+ expect(remoteProjectsStore.getDeviceSessions(d, 'active').map((s) => s.id)).toEqual([+ 'active-1',+ ]);+ expect(remoteProjectsStore.getDeviceSessions(d, 'archived').map((s) => s.id)).toEqual([+ 'archived-1',+ ]);+ });++ it('archived 列表混入 active 会话时按协议损坏处理且不覆盖 active 桶', async () => {+ const d = did();+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('active-1')], 'active');+ invoke.mockResolvedValueOnce([session('wrong-active')]);++ await expect(+ refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep, status: 'archived' }),+ ).resolves.toBe('gave-up');++ expect(remoteProjectsStore.getDeviceSessions(d, 'active').map((s) => s.id)).toEqual([+ 'active-1',+ ]);+ expect(remoteProjectsStore.hasLoadedSessionStatus(d, 'archived')).toBe(false);+ });++ it('同设备 active 与 archived 请求使用独立单飞和 epoch', async () => {+ const d = did();+ const activeSnapshot = deferred<Session[]>();+ const archivedSnapshot = deferred<Session[]>();+ invoke.mockImplementation(async (_deviceId, _channel, args) => {+ return args[1] === 'archived' ? archivedSnapshot.promise : activeSnapshot.promise;+ });++ const activeRefresh = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });+ const archivedRefresh = refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ status: 'archived',+ });+ archivedSnapshot.resolve([session('archived-1', { status: 'archived' })]);+ activeSnapshot.resolve([session('active-1')]);++ await expect(Promise.all([activeRefresh, archivedRefresh])).resolves.toEqual(['ok', 'ok']);+ expect(invoke).toHaveBeenCalledTimes(2);+ expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual([+ 'active-1',+ 'archived-1',+ ]);+ });++ it('archived 使用 1000 条产品窗口,保留第 201 条之后的有效任务并清理陈旧缓存', async () => {+ const d = did();+ const archived = Array.from({ length: 250 }, (_, index) =>+ session(`archived-recent-${index}`, { status: 'archived' }),+ );+ remoteProjectsStore.setDeviceSessions(+ d,+ 'Mac B',+ [session('stale-outside-window', { status: 'archived' })],+ 'archived',+ );+ invoke.mockResolvedValueOnce(archived);++ await refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ snapshotMode: 'merge',+ status: 'archived',+ });++ const archivedIds = remoteProjectsStore.getDeviceSessions(d, 'archived').map((item) => item.id);+ expect(archivedIds).toHaveLength(250);+ expect(archivedIds).toContain('archived-recent-200');+ expect(archivedIds).toContain('archived-recent-249');+ expect(archivedIds).not.toContain('stale-outside-window');+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [+ 1000,+ 'archived',+ { includePinned: true },+ ]);+ });+it('周期有界快照更新命中行但保留 200 条窗口外的有效会话', async () => {const d = did();const recent = Array.from({ length: 200 }, (_, index) =>@@ -376,7 +469,7 @@ describe('refreshRemoteDeviceSessions retry', () => {expect(invoke).toHaveBeenCalledTimes(1);});- it('周期满窗口用既有 sessions:get 有界补查并清理已归档的窗口外行', async () => {+ 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')]);@@ -394,10 +487,13 @@ describe('refreshRemoteDeviceSessions retry', () => {snapshotMode: 'merge',});- expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(200);- expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).not.toContain(+ expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(201);+ expect(remoteProjectsStore.getDeviceSessions(d, 'active').map((s) => s.id)).not.toContain('stale-archived',);+ expect(remoteProjectsStore.getDeviceSessions(d, 'archived')).toEqual([+ expect.objectContaining({ id: 'stale-archived', status: 'archived' }),+ ]);expect(getRemoteSessionActivity('stale-archived')).toBeUndefined();});diff --git a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.tsindex ce2021e215..459c82a3ea 100644--- a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts@@ -179,6 +179,14 @@ function expectPut(deviceId: string, sessionId: string, rows: unknown[]): void {);expect(hit).toBe(true);}++function expectNoPut(deviceId: string, sessionId: string, rows: unknown[]): void {+ const hit = putMessages.mock.calls.some(+ ([d, s2, r]) =>+ d === deviceId && s2 === sessionId && JSON.stringify(r) === JSON.stringify(rows),+ );+ expect(hit).toBe(false);+}const getSessionList = vi.fn(async () => ({devices: [] as never[],ownerToken: cachedOwnerToken,@@ -793,6 +801,29 @@ describe('remoteProjectsStore.hydrateFromCache', () => {expect(sessions[0].deviceLinkConnectionStatus).toBe('connected');});+ it('缓存里的 archived 行可先显示,但重连后仍需按需权威校准', () => {+ remoteProjectsStore.hydrateFromCache([+ {+ deviceId: 'dev-cold',+ deviceName: 'Cold',+ sessions: [{ id: 'cached-archived', status: 'archived' }] as never,+ },+ ]);+ expect(remoteProjectsStore.hasLoadedSessionStatus('dev-cold', 'archived')).toBe(false);++ remoteProjectsStore.setDeviceSessions('dev-cold', 'Cold', [{ id: 'fresh-active' }] as never);++ expect(remoteProjectsStore.getDeviceSessions('dev-cold', 'archived')).toEqual([+ expect.objectContaining({+ id: 'cached-archived',+ status: 'archived',+ deviceLinkConnectionStatus: 'connected',+ }),+ ]);+ expect(remoteProjectsStore.hasLoadedSessionStatus('dev-cold', 'active')).toBe(true);+ expect(remoteProjectsStore.hasLoadedSessionStatus('dev-cold', 'archived')).toBe(false);+ });+it('空会话列表的设备不种入(不画出一台空壳设备)', () => {remoteProjectsStore.hydrateFromCache([{ deviceId: 'dev-empty', deviceName: 'Empty', sessions: [] },@@ -1286,22 +1317,22 @@ describe('列表读在账号切换后整份作废', () => {});});-describe('会话离场时清消息缓存', () => {+describe('会话删除时清消息缓存', () => {// review(codex P1):会话可能不在当前(有界)分片里、甚至这台设备还没有分片,但它完全可能// 有一份上次打开时留下的缓存文件 —— 早退就等于把"别的控制端刚删掉的会话"的正文留在盘上。- it('会话不在分片里(甚至没有分片)时,终态推送同样清缓存', () => {- // 没有分片:直接对一台未知设备发终态 patch+ it('会话不在分片里(甚至没有分片)时,deleted 推送同样清缓存', () => {+ // 没有分片:直接对一台未知设备发 deleted patchremoteProjectsStore.applyPatch('dev-unknown', 'sess-ghost', { status: 'deleted' });expectPut('dev-unknown', 'sess-ghost', []);// 有分片但会话不在窗口内remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: 's-in' }] as never);putMessages.mockClear();- remoteProjectsStore.applyPatch(DEVICE_ID, 's-outside-window', { status: 'archived' });+ remoteProjectsStore.applyPatch(DEVICE_ID, 's-outside-window', { status: 'deleted' });expectPut(DEVICE_ID, 's-outside-window', []);});- it('被控端把会话标 deleted / archived → 清掉该会话的缓存文件', () => {+ it('deleted 清缓存,archived 保留缓存供归档任务离线查看', () => {remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: 's-del' },{ id: 's-arch' },@@ -1311,7 +1342,7 @@ describe('会话离场时清消息缓存', () => {remoteProjectsStore.applyPatch(DEVICE_ID, 's-arch', { status: 'archived' });expectPut(DEVICE_ID, 's-del', []);- expectPut(DEVICE_ID, 's-arch', []);+ expectNoPut(DEVICE_ID, 's-arch', []);});});diff --git a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.tsindex 3679d35cac..76a9b1d613 100644--- a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts@@ -3,7 +3,7 @@** 覆盖 device-link 控制端内存层的核心不变量:* - setDeviceSessions:打 device-link origin 标记 + 合并扁平列表 + sessionId→deviceId 注册 + 引用稳定- * - applyPatch:就地幂等合并 / status=deleted|archived 移出分片 / 落到未知 session 丢弃+ * - active/archived 分桶快照互不覆盖,applyPatch 在状态桶间迁移 / deleted 移出分片* - epoch:旧 snapshot 不覆盖新 snapshot(乱序保护)* - markDeviceDisconnected:断线保留快照 + 在线索引清理;removeDevice / clear:明确移除时清理*/@@ -14,6 +14,8 @@ import {remoteProjectsStore,getSessionDeviceId,retryRemoteSessionBootstrap,+ retryRemoteSessionStatus,+ requestRemoteSessionStatus,setRemoteReseedImpl,setRemoteSessionBootstrapRetryImpl,} from '@/features/device-link/remoteProjectsStore';@@ -129,6 +131,86 @@ describe('remoteProjectsStore', () => {expect(getSessionDeviceId('s2')).toBe('dev-C');});+ it('active / archived 权威快照只替换自己的状态桶', () => {+ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('active-1')], 'active');+ remoteProjectsStore.setDeviceSessions(+ 'dev-B',+ 'B',+ [mk('archived-1', { status: 'archived' })],+ 'archived',+ );++ expect(remoteProjectsStore.hasLoadedSessionStatus('dev-B', 'active')).toBe(true);+ expect(remoteProjectsStore.hasLoadedSessionStatus('dev-B', 'archived')).toBe(true);+ expect([...remoteProjectsStore.getArchivedLoadedDeviceIds()]).toEqual(['dev-B']);+ expect(remoteProjectsStore.getDeviceSessions('dev-B', 'active').map((s) => s.id)).toEqual([+ 'active-1',+ ]);+ expect(remoteProjectsStore.getDeviceSessions('dev-B', 'archived').map((s) => s.id)).toEqual([+ 'archived-1',+ ]);++ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('active-2')], 'active');+ expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual([+ 'active-2',+ 'archived-1',+ ]);+ });++ it('归档桶按设备+状态去重,active 在途不拦请求且成功只清 archived loading', () => {+ const reseed = vi.fn();+ setRemoteReseedImpl(reseed);+ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('active-1')]);+ remoteProjectsStore.markBootstrapLoading('dev-B');++ requestRemoteSessionStatus('dev-B', 'archived');+ requestRemoteSessionStatus('dev-B', 'archived');+ expect(reseed).toHaveBeenCalledTimes(1);+ expect(reseed).toHaveBeenCalledWith('dev-B', 'archived');+ expect(remoteProjectsStore.isSessionStatusLoading('dev-B', 'active')).toBe(true);+ expect(remoteProjectsStore.isSessionStatusLoading('dev-B', 'archived')).toBe(true);+ expect([...remoteProjectsStore.getBootstrapLoadingDeviceIds()]).toEqual(['dev-B']);++ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [], 'archived');+ expect(remoteProjectsStore.isSessionStatusLoading('dev-B', 'active')).toBe(true);+ expect(remoteProjectsStore.isSessionStatusLoading('dev-B', 'archived')).toBe(false);+ expect([...remoteProjectsStore.getBootstrapLoadingDeviceIds()]).toEqual(['dev-B']);+ requestRemoteSessionStatus('dev-B', 'archived');+ expect(reseed).toHaveBeenCalledTimes(1);+ });++ it('归档桶失败后显示失败态,并允许下一次按需请求自动重试', () => {+ const reseed = vi.fn();+ setRemoteReseedImpl(reseed);+ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('active-1')]);++ requestRemoteSessionStatus('dev-B', 'archived');+ remoteProjectsStore.markSessionStatusFailed('dev-B', 'archived');++ expect(remoteProjectsStore.isSessionStatusLoading('dev-B', 'archived')).toBe(false);+ expect(remoteProjectsStore.getBootstrapFailedDeviceIds().size).toBe(0);+ expect([...remoteProjectsStore.getArchivedFailedDeviceIds()]).toEqual(['dev-B']);++ requestRemoteSessionStatus('dev-B', 'archived');++ expect(reseed).toHaveBeenCalledTimes(2);+ expect(remoteProjectsStore.isSessionStatusLoading('dev-B', 'archived')).toBe(true);+ expect(remoteProjectsStore.getArchivedFailedDeviceIds().size).toBe(0);+ });++ it('已加载过 archived 桶后,失败恢复仍会强制重新拉取', () => {+ const reseed = vi.fn();+ setRemoteReseedImpl(reseed);+ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [], 'archived');+ remoteProjectsStore.markSessionStatusFailed('dev-B', 'archived');++ retryRemoteSessionStatus('dev-B', 'archived');++ expect(reseed).toHaveBeenCalledWith('dev-B', 'archived');+ expect(remoteProjectsStore.isSessionStatusLoading('dev-B', 'archived')).toBe(true);+ expect(remoteProjectsStore.getArchivedFailedDeviceIds().size).toBe(0);+ });+it('snapshot reference is stable across no-op (useSyncExternalStore safety)', () => {remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1')]);const a = remoteProjectsStore.getMergedRemoteSessions();@@ -146,13 +228,17 @@ describe('remoteProjectsStore', () => {expect(getSessionDeviceId('s1')).toBe('dev-B'); // origin 标记不丢});- it('status=deleted / archived → 移出分片', () => {+ it('status=deleted 移出分片,archived 保留完整行供归档筛选展示', () => {remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1'), mk('s2')]);remoteProjectsStore.applyPatch('dev-B', 's1', { status: 'deleted' });expect(remoteProjectsStore.getMergedRemoteSessions().map((x) => x.id)).toEqual(['s2']);remoteProjectsStore.applyPatch('dev-B', 's2', { status: 'archived' });- expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(0);+ expect(remoteProjectsStore.getDeviceSessions('dev-B', 'active')).toHaveLength(0);+ expect(remoteProjectsStore.getDeviceSessions('dev-B', 'archived')).toEqual([+ expect.objectContaining({ id: 's2', status: 'archived' }),+ ]);expect(getSessionDeviceId('s1')).toBeUndefined();+ expect(getSessionDeviceId('s2')).toBe('dev-B');});it('unpin 后触发 reseed,让仅因 includePinned 补入的旧会话被后续 snapshot 剔除', () => {@@ -165,7 +251,7 @@ describe('remoteProjectsStore', () => {remoteProjectsStore.applyPatch('dev-B', 'old-pinned', { pinnedAt: null });expect(remoteProjectsStore.getMergedRemoteSessions()[0].pinnedAt).toBeNull();- expect(reseed).toHaveBeenCalledWith('dev-B');+ expect(reseed).toHaveBeenCalledWith('dev-B', 'active');expect(reseed).toHaveBeenCalledTimes(1);});@@ -245,20 +331,38 @@ describe('remoteProjectsStore', () => {it('markDeviceDisconnected keeps sessions visible but removes the device from the online index', () => {remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1'), mk('s2')]);+ remoteProjectsStore.setDeviceSessions(+ 'dev-B',+ 'B',+ [mk('archived-1', { status: 'archived' })],+ 'archived',+ );remoteProjectsStore.markDeviceDisconnected('dev-B');const merged = remoteProjectsStore.getMergedRemoteSessions();- expect(merged.map((s) => s.id)).toEqual(['s1', 's2']);+ expect(merged.map((s) => s.id)).toEqual(['s1', 's2', 'archived-1']);expect(merged.every((s) => s.deviceLinkConnectionStatus === 'disconnected')).toBe(true);+ // 旧 archived 行作缓存保留,但权威标记失效,重连后侧栏会重新校准断线期间变化。+ expect(remoteProjectsStore.getArchivedLoadedDeviceIds().size).toBe(0);// origin 保留:打开会话仍知道要走哪个 device-link 隧道,连接状态由 banner / invoke 错误处理。expect(getSessionDeviceId('s1')).toBe('dev-B');// 在线索引清掉:useRemoteSessionConnection 会显示 host-offline。expect(remoteProjectsStore.getDeviceIds()).toEqual([]);expect(remoteProjectsStore.getDeviceList()).toEqual([- { deviceId: 'dev-B', deviceName: 'B', sessionCount: 2, connected: false },+ { deviceId: 'dev-B', deviceName: 'B', sessionCount: 3, connected: false },]);});+ it('markAllDisconnected invalidates archived authority for every cached device', () => {+ remoteProjectsStore.setDeviceSessions('dev-A', 'A', [], 'archived');+ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [], 'archived');+ expect([...remoteProjectsStore.getArchivedLoadedDeviceIds()]).toEqual(['dev-A', 'dev-B']);++ remoteProjectsStore.markAllDisconnected();++ expect(remoteProjectsStore.getArchivedLoadedDeviceIds().size).toBe(0);+ });+it('setDeviceSessions reconnects a disconnected cached shard', () => {remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1')]);remoteProjectsStore.markDeviceDisconnected('dev-B');@@ -296,20 +400,33 @@ describe('remoteProjectsStore', () => {expect(remoteProjectsStore.getBootstrapFailedDeviceIds().size).toBe(0);});- it('disconnect, removeDevice and clear discard bootstrap activity even before a shard exists', () => {+ it('disconnect, removeDevice and clear discard active / archived activity before a shard exists', () => {remoteProjectsStore.markBootstrapLoading('dev-loading');+ remoteProjectsStore.markSessionStatusLoading('dev-loading', 'archived');remoteProjectsStore.markDeviceDisconnected('dev-loading');expect(remoteProjectsStore.getBootstrapLoadingDeviceIds().size).toBe(0);+ expect(remoteProjectsStore.getArchivedLoadingDeviceIds().size).toBe(0);remoteProjectsStore.markBootstrapFailed('dev-A');+ remoteProjectsStore.markSessionStatusFailed('dev-A', 'archived');remoteProjectsStore.removeDevice('dev-A');expect(remoteProjectsStore.getBootstrapFailedDeviceIds().size).toBe(0);+ expect(remoteProjectsStore.getArchivedFailedDeviceIds().size).toBe(0);++ remoteProjectsStore.setDeviceSessions('dev-loaded', 'Loaded', [], 'archived');+ remoteProjectsStore.removeDevice('dev-loaded');+ expect(remoteProjectsStore.getArchivedLoadedDeviceIds().size).toBe(0);remoteProjectsStore.markBootstrapLoading('dev-A');remoteProjectsStore.markBootstrapFailed('dev-B');+ remoteProjectsStore.markSessionStatusLoading('dev-C', 'archived');+ remoteProjectsStore.markSessionStatusFailed('dev-D', 'archived');remoteProjectsStore.clear();expect(remoteProjectsStore.getBootstrapLoadingDeviceIds().size).toBe(0);expect(remoteProjectsStore.getBootstrapFailedDeviceIds().size).toBe(0);+ expect(remoteProjectsStore.getArchivedLoadingDeviceIds().size).toBe(0);+ expect(remoteProjectsStore.getArchivedFailedDeviceIds().size).toBe(0);+ expect(remoteProjectsStore.getArchivedLoadedDeviceIds().size).toBe(0);});it('clears only a superseded bootstrap loading state', () => {diff --git a/apps/desktop/src/renderer/__tests__/sidebarSessionStatusFilter.test.ts b/apps/desktop/src/renderer/__tests__/sidebarSessionStatusFilter.test.tsnew file mode 100644index 0000000000..5d2b463983--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/sidebarSessionStatusFilter.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest';++import { matchesSidebarSessionStatus } from '@/features/cc-agent/lib/sidebarSessionStatusFilter';+import type { SessionStatus } from '@/lib/ccAgent.types';++function row(status: SessionStatus, remote = false) {+ return {+ status,+ ...(remote ? { deviceLinkDeviceId: 'device-a' } : {}),+ };+}++describe('matchesSidebarSessionStatus', () => {+ it('远程行始终按用户选择筛选,不受本地旧桶或失败请求影响', () => {+ expect(matchesSidebarSessionStatus(row('archived', true), 'archived', 'active')).toBe(true);+ expect(matchesSidebarSessionStatus(row('active', true), 'archived', 'active')).toBe(false);+ expect(matchesSidebarSessionStatus(row('active', true), 'all', 'archived')).toBe(true);+ expect(matchesSidebarSessionStatus(row('archived', true), 'all', 'active')).toBe(true);+ });++ it('本地行继续跟随实际已落地的桶,all 桶才按用户选择收窄', () => {+ expect(matchesSidebarSessionStatus(row('active'), 'archived', 'active')).toBe(true);+ expect(matchesSidebarSessionStatus(row('archived'), 'archived', 'active')).toBe(false);+ expect(matchesSidebarSessionStatus(row('active'), 'archived', 'all')).toBe(false);+ expect(matchesSidebarSessionStatus(row('archived'), 'archived', 'all')).toBe(true);+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex bdde18e639..be81999df3 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -136,6 +136,7 @@ import {selectProjectBulkArchiveCandidates,} from './lib/projectBulkArchiveAction';import { sessionActivityMs } from './lib/dateSessionGrouping';+import { matchesSidebarSessionStatus } from './lib/sidebarSessionStatusFilter';import { sortProjectsForSidebar, sortSessionsForSidebar } from './lib/sidebarProjectSorting';import { isOrcaWorkerSession, resolveSessionRoute } from '@/lib/orcaSessionIdentity';import {@@ -216,7 +217,14 @@ import {prefetchDeviceGitSafetySettings,} from '@/hooks/useGitSafetySettings';import { recentWorkdirsStore } from '@/lib/recentWorkdirsStore';-import { useRemoteProjectSessions } from '@/features/device-link/remoteProjectsStore';+import {+ requestRemoteSessionStatus,+ useRemoteArchivedFailedDeviceIds,+ useRemoteArchivedLoadedDeviceIds,+ useRemoteArchivedLoadingDeviceIds,+ useRemoteDevices,+ useRemoteProjectSessions,+} from '@/features/device-link/remoteProjectsStore';import {selectVisibleSessions,setSelectedMachineIdTransient,@@ -228,6 +236,8 @@ import {isRemoteSessionWriteBlocked,} from './lib/remoteSessionWriteGuard';import {+ selectRemoteSessionBootstrapFailures,+ selectRemoteSessionBootstrapLoadingDevices,useEffectiveSelectedMachineId,useRemoteSessionBootstrapFailures,useRemoteSessionBootstrapLoading,@@ -395,12 +405,7 @@ export function CCAgentSidebarUpper() {const projectAliases = useProjectAliases();const searchProjectGroups = useProjectGroups(searchProjectSessions, projectAliases.aliases);const visibleSearchProjects = useMemo(- () =>- visibleSidebarProjects(- searchProjectGroups.projects,- hiddenProjectKeys,- localPlatform,- ),+ () => visibleSidebarProjects(searchProjectGroups.projects, hiddenProjectKeys, localPlatform),[searchProjectGroups.projects, hiddenProjectKeys, localPlatform],);const visibleSearchSessionIds = useMemo(@@ -513,11 +518,7 @@ export function CCAgentSidebarUpper() {const switchableSessions = allSessionsForAttention.filter((s) => !isOrcaWorkerSession(s));return buildDocModeSwitchProjects(switchableSessions).filter((project) =>- !projectKeyComparisonSetHas(- hiddenProjectComparisonKeys,- project.projectKey,- localPlatform,- ),+ !projectKeyComparisonSetHas(hiddenProjectComparisonKeys, project.projectKey, localPlatform),);}, [allSessionsForAttention, hiddenProjectComparisonKeys, localPlatform]);const filesProjectKey = filesSession ? projectIdentityKeyForSession(filesSession) : null;@@ -543,19 +544,39 @@ export function CCAgentSidebarUpper() {// 机器切换栏选中某机器后按 selectedMachineId 整体过滤(本机 → 只本地;远程 → 只该机器),// rail 与展开态共用同一选择态,保证 rail 折叠后仍尊重选中机器。const remoteProjectSessions = useRemoteProjectSessions();+ const remoteDevices = useRemoteDevices();const selectedMachineId = useEffectiveSelectedMachineId();+ useEffect(() => {+ if (filter.status === 'active') return;+ const selectedRemoteIds =+ selectedMachineId === MACHINE_ALL+ ? null+ : new Set(selectedMachineId.filter((deviceId) => deviceId !== MACHINE_LOCAL));+ for (const device of remoteDevices) {+ if (!device.connected) continue;+ if (selectedRemoteIds && !selectedRemoteIds.has(device.deviceId)) continue;+ requestRemoteSessionStatus(device.deviceId, 'archived');+ }+ }, [filter.status, remoteDevices, selectedMachineId]);const sessionsWithRemote = useMemo(() => selectVisibleSessions(sessionsHook.sessions, remoteProjectSessions, selectedMachineId),[sessionsHook.sessions, remoteProjectSessions, selectedMachineId],);+ const statusFilteredSessionsWithRemote = useMemo(+ () =>+ sessionsWithRemote.filter((session) =>+ matchesSidebarSessionStatus(session, filter.status, sessionsHook.effectiveIncludeArchived),+ ),+ [filter.status, sessionsHook.effectiveIncludeArchived, sessionsWithRemote],+ );const visibleSessionsWithRemote = useMemo(() =>sidebarSessionsWithHiddenProjectsAsDialogues(- sessionsWithRemote,+ statusFilteredSessionsWithRemote,hiddenProjectKeys,localPlatform,),- [sessionsWithRemote, hiddenProjectKeys, localPlatform],+ [statusFilteredSessionsWithRemote, hiddenProjectKeys, localPlatform],);// rail 未读集与展开态(ExpandedView.sidebarNotifications)同口径:把"定时任务有未读运行"的@@ -1085,15 +1106,9 @@ function ExpandedView({return next;}, [effectiveRunningSessionIds, backgroundActivitySessionIds, orcaLeadWorkerMap]);- // 关键:用 effectiveIncludeArchived(snapshot 实际所属桶)而非 filter.status- // 决定是否做客户端过滤——- // · effectiveIncludeArchived === 'all' → 桶含所有 status,- // 按 user 选中的 filter.status 收窄- // · 其它(active/archived 单 status 桶) → 桶内本应全是同一 status,- // 按桶 status 收窄即可- // 这样 user 点 status chip 后, sidebar 列表跟着 snapshot 一起切,- // 不会出现「user filter 立刻变 → 旧桶按新 filter 过滤后全空 → 新桶到才回填」- // 的空白帧。filter.status 仍只用于 chip 高亮和 IPC 桶决策。+ // 本地会话用 effectiveIncludeArchived(snapshot 实际所属桶)避免切桶时先闪空;+ // device-link 远程镜像同时持有 active / archived 两桶,必须独立按 filter.status 筛选,+ // 否则本地 archived/all 请求慢或失败时会把已加载的远程归档行持续隐藏。//// 单 status 桶为何要按桶 status 显式过滤(而不是直接信任桶内全是同 status):// patchLocal 是跨桶 in-place mutation —— doc 模式归档(WorkdirBrowseRoute)@@ -1116,10 +1131,99 @@ function ExpandedView({const dialogueCreatePending = selectedDialogueDeviceResolution.status === 'pending';// 「所有」或含远程设备的作用域还要等 device-link 首次 sessions snapshot;// 否则本地 sessions 先完成时会把尚未知的远程空数组误报成真实空态。- const remoteSessionBootstrapLoading = useRemoteSessionBootstrapLoading(selectedMachineId);- const remoteSessionBootstrapLoadingDevices =+ const activeRemoteSessionBootstrapLoading = useRemoteSessionBootstrapLoading(selectedMachineId);+ const activeRemoteSessionBootstrapLoadingDevices =useRemoteSessionBootstrapLoadingDevices(selectedMachineId);- const remoteSessionBootstrapFailures = useRemoteSessionBootstrapFailures(selectedMachineId);+ const activeRemoteSessionBootstrapFailures = useRemoteSessionBootstrapFailures(selectedMachineId);+ const archivedLoadingDeviceIds = useRemoteArchivedLoadingDeviceIds();+ const archivedFailedDeviceIds = useRemoteArchivedFailedDeviceIds();+ const archivedLoadedDeviceIds = useRemoteArchivedLoadedDeviceIds();+ const archivedRemoteSessionLoadingDevices = useMemo(+ () =>+ selectRemoteSessionBootstrapLoadingDevices({+ selectedMachineId,+ devices: switcherDevices,+ bootstrapLoadingDeviceIds: archivedLoadingDeviceIds,+ }),+ [archivedLoadingDeviceIds, selectedMachineId, switcherDevices],+ );+ const archivedRemoteSessionFailures = useMemo(+ () =>+ selectRemoteSessionBootstrapFailures({+ selectedMachineId,+ devices: switcherDevices,+ bootstrapFailedDeviceIds: archivedFailedDeviceIds,+ }),+ [archivedFailedDeviceIds, selectedMachineId, switcherDevices],+ );+ const activeArchivedPrerequisiteLoadingDevices = useMemo(+ () =>+ activeRemoteSessionBootstrapLoadingDevices.filter(+ (device) => !archivedLoadedDeviceIds.has(device.deviceId),+ ),+ [activeRemoteSessionBootstrapLoadingDevices, archivedLoadedDeviceIds],+ );+ const activeArchivedPrerequisiteFailures = useMemo(+ () =>+ activeRemoteSessionBootstrapFailures.filter(+ (device) => !archivedLoadedDeviceIds.has(device.deviceId),+ ),+ [activeRemoteSessionBootstrapFailures, archivedLoadedDeviceIds],+ );+ const remoteSessionBootstrapLoadingDevices = useMemo(() => {+ if (filter.status === 'active') return activeRemoteSessionBootstrapLoadingDevices;+ if (filter.status === 'archived') {+ return [+ ...new Map(+ [...activeArchivedPrerequisiteLoadingDevices, ...archivedRemoteSessionLoadingDevices].map(+ (device) => [device.deviceId, device],+ ),+ ).values(),+ ];+ }+ return [+ ...new Map(+ [...activeRemoteSessionBootstrapLoadingDevices, ...archivedRemoteSessionLoadingDevices].map(+ (device) => [device.deviceId, device],+ ),+ ).values(),+ ];+ }, [+ activeArchivedPrerequisiteLoadingDevices,+ activeRemoteSessionBootstrapLoadingDevices,+ archivedRemoteSessionLoadingDevices,+ filter.status,+ ]);+ const remoteSessionBootstrapFailures = useMemo(() => {+ if (filter.status === 'active') return activeRemoteSessionBootstrapFailures;+ if (filter.status === 'archived') {+ return [+ ...new Map(+ [...activeArchivedPrerequisiteFailures, ...archivedRemoteSessionFailures].map(+ (device) => [device.deviceId, device],+ ),+ ).values(),+ ];+ }+ return [+ ...new Map(+ [...activeRemoteSessionBootstrapFailures, ...archivedRemoteSessionFailures].map(+ (device) => [device.deviceId, device],+ ),+ ).values(),+ ];+ }, [+ activeArchivedPrerequisiteFailures,+ activeRemoteSessionBootstrapFailures,+ archivedRemoteSessionFailures,+ filter.status,+ ]);+ const remoteSessionBootstrapLoading =+ filter.status === 'active'+ ? activeRemoteSessionBootstrapLoading+ : filter.status === 'archived'+ ? remoteSessionBootstrapLoadingDevices.length > 0+ : activeRemoteSessionBootstrapLoading || archivedRemoteSessionLoadingDevices.length > 0;const deviceListRequestState = useDeviceLinkDeviceListRequestState();const remoteDeviceDirectoryRelevant =selectedMachineId === MACHINE_ALL ||@@ -1151,12 +1255,7 @@ function ExpandedView({const passesOrcaAndStatus = useCallback((s: Session) => {if (isOrcaWorkerSession(s)) return false;- if (effectiveIncludeArchived === 'all') {- if (filter.status !== 'all' && s.status !== filter.status) return false;- } else if (s.status !== effectiveIncludeArchived) {- return false;- }- return true;+ return matchesSidebarSessionStatus(s, filter.status, effectiveIncludeArchived);},[filter.status, effectiveIncludeArchived],);@@ -1215,8 +1314,7 @@ function ExpandedView({// Visibility is a negative overlay only. Keep the raw universe above for// filter/manual-order GC, and expose a separate catalogue to sidebar UI.const visibleProjectUniverse = useMemo(- () =>- visibleSidebarProjects(projectUniverse.projects, hiddenProjectKeys, localPlatform),+ () => visibleSidebarProjects(projectUniverse.projects, hiddenProjectKeys, localPlatform),[projectUniverse.projects, hiddenProjectKeys, localPlatform],);@@ -1375,7 +1473,9 @@ function ExpandedView({const visiblePinnedProjects = useMemo(() => {const allowedProjects = filter.projectsAsSet;return allProjectGroups.projects.flatMap((project) => {- if (projectKeyComparisonSetHas(hiddenProjectComparisonKeys, project.projectKey, localPlatform)) {+ if (+ projectKeyComparisonSetHas(hiddenProjectComparisonKeys, project.projectKey, localPlatform)+ ) {return [];}if (!pinnedProjectKeys.has(project.projectKey)) return [];diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarSessionStatusFilter.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarSessionStatusFilter.tsnew file mode 100644index 0000000000..4b705c0c61--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarSessionStatusFilter.ts@@ -0,0 +1,20 @@+import type { Session } from '@/lib/ccAgent.types';+import type { ListStatusFilter } from '@/lib/sessionService';++import type { FilterStatus } from '../hooks/useSidebarFilter';++/**+ * 本地会话跟随 useCCSessions 实际已落地的桶,避免切桶期间先闪空;device-link 远程镜像+ * 同时持有 active / archived 两桶,必须始终按用户当前选择筛选,不能被本地请求状态拖住。+ */+export function matchesSidebarSessionStatus(+ session: Pick<Session, 'status' | 'deviceLinkDeviceId'>,+ selectedStatus: FilterStatus,+ effectiveLocalStatus: ListStatusFilter,+): boolean {+ const desiredStatus =+ session.deviceLinkDeviceId || effectiveLocalStatus === 'all'+ ? selectedStatus+ : effectiveLocalStatus;+ return desiredStatus === 'all' || session.status === desiredStatus;+}diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.tsindex f8d2759b21..9b67a4652a 100644--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts@@ -20,7 +20,7 @@ import { createLogger } from '@/lib/logger';import { extractIpcError } from '@/utils/ipcError';import { DEVICE_LINK_RECONCILIATION_PROBE_MARKER } from '@cindy/maker-shared/device-link-contract';import type { RemoteSessionListSessionLike } from '@cindy/maker-shared/session-list';-import { remoteProjectsStore } from './remoteProjectsStore';+import { remoteProjectsStore, type RemoteSessionStatus } from './remoteProjectsStore';import { removeRemoteSessionActivityEntry } from './remoteSessionActivityStore';import type { CachedDeviceSessionsSnapshot } from './mirrorCacheClient';@@ -46,6 +46,9 @@ export function collectSessionListSnapshot(): CachedDeviceSessionsSnapshot[] {/** 与 listing tier 的拉取上限一致(useDeviceLinkRemoteProjects 的 LIST_LIMIT)。 */const LIST_LIMIT = 200;+/** 与本地侧栏 / local-db:sessions:list 的现行产品上限一致。 */+const ARCHIVED_LIST_LIMIT = 1000;+/** 满窗口时每轮最多补查多少个缺席缓存 id,避免退化成无界 N+1。 */const MISSING_STATUS_PROBE_LIMIT = 8;@@ -119,7 +122,10 @@ function hasOptionalFiniteNumber(record: Record<string, unknown>, key: string):);}-function isRemoteSessionListSession(value: unknown): value is RemoteSessionListSessionLike {+function isRemoteSessionListSession(+ value: unknown,+ expectedStatus: RemoteSessionStatus,+): value is RemoteSessionListSessionLike {if (!value || typeof value !== 'object' || Array.isArray(value)) return false;const session = value as Record<string, unknown>;const count = session._count;@@ -129,7 +135,7 @@ function isRemoteSessionListSession(value: unknown): value is RemoteSessionListStypeof session.title === 'string' &&isNullableString(session.workingDir) &&typeof session.model === 'string' &&- session.status === 'active' &&+ session.status === expectedStatus &&typeof session.agentKind === 'string' &&typeof session.createdAt === 'string' &&typeof session.updatedAt === 'string' &&@@ -170,8 +176,11 @@ function isRemoteSessionListSession(value: unknown): value is RemoteSessionListS);}-function parseRemoteSessionList(value: unknown): Session[] {- if (!Array.isArray(value) || !value.every(isRemoteSessionListSession)) {+function parseRemoteSessionList(value: unknown, expectedStatus: RemoteSessionStatus): Session[] {+ if (+ !Array.isArray(value) ||+ !value.every((session) => isRemoteSessionListSession(session, expectedStatus))+ ) {throw new Error('Invalid remote sessions response');}// local-db:sessions:list 是跨版本的列表投影;旧端允许缺少新版 Session 的附加字段。@@ -193,6 +202,8 @@ export interface RefreshOptions {maxAttempts?: number;/** sessions:list 始终有界,默认 merge;仅已知完整的调用方才可显式 replace。 */snapshotMode?: 'replace' | 'merge';+ /** 要读取的远程状态桶;默认 active,archived 仅由侧栏筛选按需触发。 */+ status?: RemoteSessionStatus;/** 周期 tick 可弱合并到任意在途 refresh;事件型 refresh 默认强语义补跑。 */coalescingMode?: 'strong' | 'weak';}@@ -215,6 +226,10 @@ interface RefreshTask {const refreshTasks = new Map<string, RefreshTask>();+function refreshTaskKey(deviceId: string, status: RemoteSessionStatus): string {+ return `${deviceId}\u0000${status}`;+}+/*** 满窗口缺席行的轮询队列(per-device)。不能用 snapshot epoch 推导数组下标:前一轮* 确认终态并移除候选后,数组会收缩,重算下标会跳过紧邻项。队列在每轮开始时与当前@@ -253,7 +268,9 @@ export async function refreshRemoteDeviceSessions(name?: string,opts: RefreshOptions = {},): Promise<RefreshResult> {- const existing = refreshTasks.get(deviceId);+ const status = opts.status ?? 'active';+ const taskKey = refreshTaskKey(deviceId, status);+ const existing = refreshTasks.get(taskKey);if (existing) {const requestedSnapshotMode = opts.snapshotMode ?? 'merge';// periodic tick 是弱语义:已有任意 refresh 在途时直接复用,不能每个 interval tick@@ -273,7 +290,7 @@ export async function refreshRemoteDeviceSessions(: 'merge',};// 先让当前 in-flight snapshot 失效,否则它可能在排队的补跑开始前覆盖 push 带来的新状态。- remoteProjectsStore.nextSnapshotEpoch(deviceId);+ remoteProjectsStore.nextSnapshotEpoch(deviceId, status);return existing.promise;}@@ -284,9 +301,9 @@ export async function refreshRemoteDeviceSessions(opts,};task.promise = drainRefreshTask(deviceId, task).finally(() => {- if (refreshTasks.get(deviceId) === task) refreshTasks.delete(deviceId);+ if (refreshTasks.get(taskKey) === task) refreshTasks.delete(taskKey);});- refreshTasks.set(deviceId, task);+ refreshTasks.set(taskKey, task);return task.promise;}@@ -325,7 +342,7 @@ async function probeMissingSessionStatuses(}),);// 更强的 refresh / remove / disconnect 已使本轮失效时,不应用迟到的补查结果。- if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return;+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, 'active')) return;const terminalIds = new Set<string>();for (const result of results) {if (result.errorCode === 'NOT_FOUND') {@@ -368,46 +385,54 @@ async function runRefreshRemoteDeviceSessions(): Promise<RefreshResult> {const sleep = opts.sleep ?? realSleep;const maxAttempts = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;+ const status = opts.status ?? 'active';+ const listLimit = status === 'archived' ? ARCHIVED_LIST_LIMIT : LIST_LIMIT;const deviceName = name ?? remoteProjectsStore.getDeviceName(deviceId) ?? deviceId;- const epoch = remoteProjectsStore.nextSnapshotEpoch(deviceId);+ const epoch = remoteProjectsStore.nextSnapshotEpoch(deviceId, status);let timeoutAttempts = 0;for (let attempt = 0; attempt < maxAttempts; attempt++) {// 被一次更新的重拉取代(期间又发起了新的 refresh)→ 停手,交给那一次(也避免无谓重试)。- if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return 'superseded';+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) return 'superseded';try {const value = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:list', [- LIST_LIMIT,- 'active',+ listLimit,+ status,{ includePinned: true },]);// 乱序保护:本次拉取已不是最新一次 → 丢弃,别覆盖更新的结果。- if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return 'superseded';- const sessions = parseRemoteSessionList(value);+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) return 'superseded';+ const sessions = parseRemoteSessionList(value, status);if ((opts.snapshotMode ?? 'merge') === 'merge') {const incomingIds = new Set(sessions.map((session) => session.id));const missingSessionIds = remoteProjectsStore- .getDeviceSessions(deviceId)+ .getDeviceSessions(deviceId, status).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);+ // archived 使用与本地侧栏一致的 1000 条产品窗口,可直接替换并清掉断线期间的+ // 删除 / 取消归档陈旧行;active 仍保持 200 条轻量窗口,满窗时有界补查缺席缓存。+ if (status === 'archived' || sessions.length < LIST_LIMIT) {+ if (status === 'active') {+ missingStatusProbeQueues.delete(deviceId);+ for (const sessionId of missingSessionIds) {+ removeRemoteSessionActivityEntry(sessionId);+ }}+ remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions, status);} else {- remoteProjectsStore.mergeDeviceSessions(deviceId, deviceName, sessions);- await probeMissingSessionStatuses(deviceId, epoch, missingSessionIds);+ remoteProjectsStore.mergeDeviceSessions(deviceId, deviceName, sessions, status);+ if (status === 'active') {+ await probeMissingSessionStatuses(deviceId, epoch, missingSessionIds);+ }}} else {- remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions);+ remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions, status);}return 'ok'; // 成功} catch (err) {- if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return 'superseded';+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) {+ return 'superseded';+ }const message = err instanceof Error ? err.message : String(err);// 访问被撤销:语义性终态,不重试、也不静默 give-up —— 让调用方 handleRevoked(见 ACCESS_REVOKED_MARKER)。if (message.includes(ACCESS_REVOKED_MARKER)) {diff --git a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.tsindex 27787bf78f..84803e9c0c 100644--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts@@ -9,11 +9,12 @@* DB 才是数据真相)。断链 / 设备下线时保留最近一次快照并标成 disconnected,* 让 All Sessions 稳定;明确撤销 / 关闭控制 / 删除才移除。**不做任何乐观预测 / 本地覆盖**——* 视图 = f(bootstrap snapshot + 被控端 push 流):- * · snapshot(`setDeviceSessions`):listing tier 订阅后拉一次有界列表 / reconnect 重拉。+ * · snapshot(`setDeviceSessions`):active 常驻同步;archived 由侧栏筛选按需同步,+ * 两个状态桶只替换自身、互不覆盖。* · anti-entropy(`mergeDeviceSessions`):周期满窗口列表先更新命中行并保留窗口外会话,* 再由 refresh 层有界补查缺席 id 的终态;未满窗口则可直接安全替换。* · 增量(`applyPatch`):收到被控端 `local-db:sessions:patched` push 时就地幂等合并;- * status=deleted/archived → 移出分片;落到未知 session → 丢弃(后续 snapshot 带最终态)。+ * status=deleted → 移出分片;active/archived → 在状态桶间迁移。* · 新建(`requestRemoteReseed`):`sessions:created` push 无 row 数据 → 触发该设备重拉。* 唯一例外是**投影层**的标题预览(`setPendingTitlePreview`):它不写分片、只在权威* 标题仍是系统占位(默认名 / fork 占位 / 本端登记过的合成占位)时顶替显示,被控端@@ -24,8 +25,8 @@* - **冷启动首屏借冷缓存**(`hydrateFromCache`):列表快照落在 main 的 userData* (`main/device-link/mirrorCacheStore.ts`),冷启动时先画上次看到的行,免得侧边栏* 等一次 bootstrap 往返才出现远程项目。这不动摇「零权威状态」:种入的分片一律标- * **disconnected**(缓存不是 live 设备)、只在该设备还没有分片时种入,bootstrap 的- * `setDeviceSessions` 一到就整片替换;设备已不合格时由既有+ * **disconnected**(缓存不是 live 设备)、只在该设备还没有分片时种入;缓存不标记任何+ * 状态桶已权威加载,active bootstrap 与 archived 按需请求仍会分别校准。设备已不合格时由既有* `resolveIneligibleRemoteProjectAction`(它的 `hasCachedShard` 判据)收敛为* disconnect / remove。缓存永不参与写路径。*@@ -36,8 +37,11 @@import { useSyncExternalStore } from 'react';import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';import type { DeviceLinkConnectionStatus, Session } from '@/lib/ccAgent.types';+import type { ListStatusFilter } from '@/lib/sessionService';import { clearCachedMessages } from './mirrorCacheClient';+export type RemoteSessionStatus = Exclude<ListStatusFilter, 'all'>;+/** 单台被控设备的内存分片。 */interface DeviceShard {deviceId: string;@@ -45,6 +49,8 @@ interface DeviceShard {connectionStatus: DeviceLinkConnectionStatus;/** 已打 device-link origin 标记的远端会话(可直接进 groupSessions)。 */sessions: Session[];+ /** 已拿到过权威列表的状态桶;空数组同样需要被记住,避免每次渲染都重复拉取。 */+ loadedStatuses: Set<RemoteSessionStatus>;}const shards = new Map<string, DeviceShard>();@@ -54,6 +60,8 @@ const subs = new Set<() => void>();* 一边保留旧快照、一边明确告知用户「正在重新读取」。*/let bootstrapLoadingDeviceIds: ReadonlySet<string> = new Set();+/** 按需读取归档桶的设备;与 active bootstrap 分开,避免并发请求互相提前清 loading。 */+let archivedLoadingDeviceIds: ReadonlySet<string> = new Set();/*** 最新一轮 bootstrap 以永久错误或重试耗尽告终的设备。这不是「权威空列表」;* 即使还保留旧 shard,UI 也必须标明读取失败。下一轮 bootstrap 开始时转 loading,@@ -62,6 +70,8 @@ let bootstrapLoadingDeviceIds: ReadonlySet<string> = new Set();* 两个集合都用不可变 Set 快照,保证 useSyncExternalStore 在内容不变时引用稳定。*/let bootstrapFailedDeviceIds: ReadonlySet<string> = new Set();+/** 最新一次 archived 按需读取失败的设备;独立于 active bootstrap failure。 */+let archivedFailedDeviceIds: ReadonlySet<string> = new Set();/*** 设备改名通知订阅(deviceId → 新名)。设备名走 REST PATCH(Device.name,不进 sessions 表),* 服务端不广播 presence;listing tier 把设备名缓存在自己的 eligible 表,改名时同步通知接入器@@ -81,12 +91,23 @@ const renameSubs = new Set<(deviceId: string, name: string) => void>();*/const snapshotEpoch = new Map<string, number>();+function snapshotEpochKey(deviceId: string, status: RemoteSessionStatus): string {+ return `${deviceId}\u0000${status}`;+}++function invalidateDeviceSnapshotEpochs(deviceId: string): void {+ for (const status of ['active', 'archived'] as const) {+ const key = snapshotEpochKey(deviceId, status);+ snapshotEpoch.set(key, (snapshotEpoch.get(key) ?? 0) + 1);+ }+}+/*** 重拉实现注入点:listing tier(useDeviceLinkRemoteProjects)挂载时注册一个「(防抖)重拉该* 设备会话列表」的实现,卸载时清。`requestRemoteReseed` 供 push 消费侧(makerChatStore 的* sessions:created 路由、applyPatch 的 unarchive 兜底)调用,不直接依赖 hook。*/-let reseedImpl: ((deviceId: string) => void) | null = null;+let reseedImpl: ((deviceId: string, status: RemoteSessionStatus) => void) | null = null;/*** 首次 sessions bootstrap 的显式重试实现。与普通 reseed 分开:普通 reseed 只做一次* merge snapshot;用户点击「重新读取任务」必须重新 subscribe,并让失败设备重新进入@@ -130,6 +151,8 @@ export interface RemoteDeviceSummary {/** 设备列表快照(缓存引用,内容不变时不换引用 → 满足 useSyncExternalStore getSnapshot 引用稳定性)。 */let deviceListSnapshot: RemoteDeviceSummary[] = [];const EMPTY_DEVICES: RemoteDeviceSummary[] = [];+/** 已成功拿到 archived 权威列表的设备(空列表也算);供 UI 判断 active 前置状态是否仍相关。 */+let archivedLoadedDeviceIds: ReadonlySet<string> = new Set();/** 设备列表结构相等(顺序敏感):用于 deviceListSnapshot 引用稳定性判定。 */function sameDeviceList(a: RemoteDeviceSummary[], b: RemoteDeviceSummary[]): boolean {@@ -147,6 +170,20 @@ function sameDeviceList(a: RemoteDeviceSummary[], b: RemoteDeviceSummary[]): booreturn true;}+function recomputeArchivedLoadedDeviceIds(): void {+ const next = new Set<string>();+ for (const shard of shards.values()) {+ if (shard.loadedStatuses.has('archived')) next.add(shard.deviceId);+ }+ if (+ next.size === archivedLoadedDeviceIds.size &&+ [...next].every((deviceId) => archivedLoadedDeviceIds.has(deviceId))+ ) {+ return;+ }+ archivedLoadedDeviceIds = next;+}+/*** 被控端建会话时的默认标题;权威标题仍等于它 = 还没起过名。*@@ -290,9 +327,44 @@ function recompute(): void {);if (!sameDeviceList(deviceListSnapshot, nextDevices)) deviceListSnapshot = nextDevices;}+ recomputeArchivedLoadedDeviceIds();subs.forEach((fn) => fn());}+/** 更新某个状态桶的读取态但不通知;调用方与其它 mutation 合并成一次通知。 */+function setSessionStatusLoading(+ deviceId: string,+ status: RemoteSessionStatus,+ loading: boolean,+): boolean {+ const source = status === 'active' ? bootstrapLoadingDeviceIds : archivedLoadingDeviceIds;+ const had = source.has(deviceId);+ if (had === loading) return false;+ const next = new Set(source);+ if (loading) next.add(deviceId);+ else next.delete(deviceId);+ if (status === 'active') bootstrapLoadingDeviceIds = next;+ else archivedLoadingDeviceIds = next;+ return true;+}++/** 更新某个状态桶的失败态但不通知;调用方与其它 mutation 合并成一次通知。 */+function setSessionStatusFailed(+ deviceId: string,+ status: RemoteSessionStatus,+ failed: boolean,+): boolean {+ const source = status === 'active' ? bootstrapFailedDeviceIds : archivedFailedDeviceIds;+ const had = source.has(deviceId);+ if (had === failed) return false;+ const next = new Set(source);+ if (failed) next.add(deviceId);+ else next.delete(deviceId);+ if (status === 'active') bootstrapFailedDeviceIds = next;+ else archivedFailedDeviceIds = next;+ return true;+}+/** 更新 bootstrap 状态但不通知;调用方与其它 mutation 合并成一次通知。 */function setBootstrapState(deviceId: string, state: 'idle' | 'loading' | 'failed'): boolean {const wasLoading = bootstrapLoadingDeviceIds.has(deviceId);@@ -301,18 +373,8 @@ function setBootstrapState(deviceId: string, state: 'idle' | 'loading' | 'failedconst failed = state === 'failed';if (wasLoading === loading && wasFailed === failed) return false;- if (wasLoading !== loading) {- const next = new Set(bootstrapLoadingDeviceIds);- if (loading) next.add(deviceId);- else next.delete(deviceId);- bootstrapLoadingDeviceIds = next;- }- if (wasFailed !== failed) {- const next = new Set(bootstrapFailedDeviceIds);- if (failed) next.add(deviceId);- else next.delete(deviceId);- bootstrapFailedDeviceIds = next;- }+ if (wasLoading !== loading) setSessionStatusLoading(deviceId, 'active', loading);+ if (wasFailed !== failed) setSessionStatusFailed(deviceId, 'active', failed);return true;}@@ -338,33 +400,72 @@ const actions = {* 逐字节不变时跳过(避免无谓重渲染);epoch 乱序保护在调用方(listing tier)用* nextSnapshotEpoch/isLatestSnapshotEpoch 完成,本函数无条件替换。*/- setDeviceSessions(deviceId: string, deviceName: string, rawSessions: readonly Session[]): void {+ setDeviceSessions(+ deviceId: string,+ deviceName: string,+ rawSessions: readonly Session[],+ status: RemoteSessionStatus = 'active',+ ): void {const connectionStatus: DeviceLinkConnectionStatus = 'connected';- const stamped = rawSessions.map((s) => stamp(s, deviceId, deviceName, connectionStatus));+ // 状态桶本身是权威筛选条件:跨版本兼容行 / 测试夹具可能缺 status,统一按本次+ // 请求桶补齐;refresh 层已在到达这里之前拒绝混入其它状态的协议损坏响应。+ const stamped = rawSessions.map((session) =>+ stamp({ ...session, status }, deviceId, deviceName, connectionStatus),+ );const existing = shards.get(deviceId);- const bootstrapStateCleared = setBootstrapState(deviceId, 'idle');+ const loadingStateCleared =+ status === 'active'+ ? setBootstrapState(deviceId, 'idle')+ : setSessionStatusLoading(deviceId, 'archived', false);+ const failedStateCleared =+ status === 'active' ? false : setSessionStatusFailed(deviceId, 'archived', false);+ const statusWasLoaded = existing?.loadedStatuses.has(status) ?? false;+ const incomingIds = new Set(stamped.map((session) => session.id));+ const preserved =+ existing?.sessions+ .filter((session) => session.status !== status && !incomingIds.has(session.id))+ .map((session) =>+ session.deviceLinkDeviceName === deviceName &&+ session.deviceLinkConnectionStatus === connectionStatus+ ? session+ : stamp(session, deviceId, deviceName, connectionStatus),+ ) ?? [];+ const nextSessions =+ status === 'active' ? [...stamped, ...preserved] : [...preserved, ...stamped];if (existing &&existing.connectionStatus === connectionStatus &&- JSON.stringify(existing.sessions) === JSON.stringify(stamped)+ existing.deviceName === deviceName &&+ JSON.stringify(existing.sessions) === JSON.stringify(nextSessions)) {- // 内容不变但设备名可能变了(改名走 renameDevice,不经这里);保持引用不动。- if (bootstrapStateCleared) subs.forEach((fn) => fn());+ if (!statusWasLoaded) {+ existing.loadedStatuses.add(status);+ recomputeArchivedLoadedDeviceIds();+ }+ if (loadingStateCleared || failedStateCleared || !statusWasLoaded) {+ subs.forEach((fn) => fn());+ }return;}- // 权威快照会整片替换分片:此前在片里、这次没回来的会话(patch 丢失期间被归档 /- // 删除)就此离场,它们的叠加层必须在这里回收 —— 之后 removeDevice 只遍历片里- // 还在的会话,再也够不着它们,unarchive/reseed 同一个仍是系统占位的会话时旧- // 预览会复活(PR #510 review P1)。+ // 权威快照只替换同状态桶,保留另一状态桶。此前在该桶、这次没回来的会话+ // (patch 丢失期间删除 / 跨桶迁移)就此离场;只有最终不在任一桶时才回收叠加层。// mergeDeviceSessions(anti-entropy 半窗口)先把窗口外的会话并回 stamped 才// 调到这里,不会被误判成离场。if (existing) {- const kept = new Set(stamped.map((session) => session.id));+ const kept = new Set(nextSessions.map((session) => session.id));for (const session of existing.sessions) {if (!kept.has(session.id)) dropTitleOverlay(session.id);}}- shards.set(deviceId, { deviceId, deviceName, connectionStatus, sessions: stamped });+ const loadedStatuses = new Set(existing?.loadedStatuses ?? []);+ loadedStatuses.add(status);+ shards.set(deviceId, {+ deviceId,+ deviceName,+ connectionStatus,+ sessions: nextSessions,+ loadedStatuses,+ });recompute();},@@ -386,11 +487,19 @@ const actions = {if (!deviceId || shards.has(deviceId)) continue;if (device.sessions.length === 0) continue;const deviceName = device.deviceName?.trim() || deviceId;+ const cachedSessions: Session[] = device.sessions.map((session) => ({+ ...session,+ // 历史缓存 / 测试夹具若缺 status,按旧版镜像语义视为 active;否则 active+ // bootstrap 会把它误当成另一个状态桶永久保留下来。+ status: session.status === 'archived' ? 'archived' : 'active',+ }));shards.set(deviceId, {deviceId,deviceName,connectionStatus: 'disconnected',- sessions: device.sessions.map((s) => stamp(s, deviceId, deviceName, 'disconnected')),+ sessions: cachedSessions.map((s) => stamp(s, deviceId, deviceName, 'disconnected')),+ // 冷缓存只用于首屏,不是本轮权威结果;重连后 active / archived 仍要分别校准。+ loadedStatuses: new Set(),});changed = true;}@@ -411,19 +520,13 @@ const actions = {/** 清除已被更新请求抢占的 loading 状态;不把它误报成一次终态失败。 */clearBootstrapLoading(deviceId: string): void {- if (!bootstrapLoadingDeviceIds.has(deviceId)) return;- const next = new Set(bootstrapLoadingDeviceIds);- next.delete(deviceId);- bootstrapLoadingDeviceIds = next;+ if (!setSessionStatusLoading(deviceId, 'active', false)) return;subs.forEach((fn) => fn());},/** 只清失败标记的兼容入口;snapshot 成功会由 setDeviceSessions 清掉全部 bootstrap 状态。 */clearBootstrapFailure(deviceId: string): void {- if (!bootstrapFailedDeviceIds.has(deviceId)) return;- const next = new Set(bootstrapFailedDeviceIds);- next.delete(deviceId);- bootstrapFailedDeviceIds = next;+ if (!setSessionStatusFailed(deviceId, 'active', false)) return;subs.forEach((fn) => fn());},@@ -432,42 +535,57 @@ const actions = {* 不能证明窗口外会话已归档/删除;因此命中行用权威值替换,未命中行先保留,再由 refresh* 层有界补查终态。首次无分片时等价于 setDeviceSessions。*/- mergeDeviceSessions(deviceId: string, deviceName: string, rawSessions: readonly Session[]): void {+ mergeDeviceSessions(+ deviceId: string,+ deviceName: string,+ rawSessions: readonly Session[],+ status: RemoteSessionStatus = 'active',+ ): void {const existing = shards.get(deviceId);if (!existing) {- actions.setDeviceSessions(deviceId, deviceName, rawSessions);+ actions.setDeviceSessions(deviceId, deviceName, rawSessions, status);return;}const incomingIds = new Set(rawSessions.map((session) => session.id));- actions.setDeviceSessions(deviceId, deviceName, [- ...rawSessions,- ...existing.sessions.filter((session) => !incomingIds.has(session.id)),- ]);+ actions.setDeviceSessions(+ deviceId,+ deviceName,+ [+ ...rawSessions,+ ...existing.sessions.filter(+ (session) => session.status === status && !incomingIds.has(session.id),+ ),+ ],+ status,+ );},/*** 应用一条被控端 `local-db:sessions:patched` 增量(push 驱动镜像核心)。幂等:- * - status ∈ {deleted, archived} → 从分片移除该会话(active 视图不含)。+ * - status=deleted → 从分片移除;active/archived → 在两个已加载状态桶间迁移。* - 其它字段(title/pinnedAt/model/effort/...)→ 就地合并。- * - 落到未知 session:若 status=active(unarchive 应重新出现)→ 触发 reseed 拉回;否则丢弃- * (后续 snapshot 自带最终态;对不在 active 视图的会话的改动控制端不关心)。+ * - 落到未知 session:active 一律重拉;archived 仅在归档桶已加载时重拉,避免后台+ * 为用户尚未查看的历史记录额外取数。*/applyPatch(deviceId: string, sessionId: string, patch: Record<string, unknown>): void {- const terminal = patch.status === 'deleted' || patch.status === 'archived';- // 终态清缓存必须放在**所有早退之前**:这个会话可能不在当前(有界)分片里、甚至这台设备+ const deleted = patch.status === 'deleted';+ // 删除清缓存必须放在**所有早退之前**:这个会话可能不在当前(有界)分片里、甚至这台设备// 还没有分片,但它完全可能有一份上次打开时留下的消息缓存文件 —— 那时早退就等于把// 「别的控制端刚删掉的会话」的正文一直留在盘上,直到 LRU 逐出 / 设备移除 / 登出- // (review: codex P1)。缓存是纯优化,多清一次无害。- if (terminal) clearCachedMessages(deviceId, sessionId);+ // (review: codex P1)。归档仍可从 Archived / All 打开,必须保留缓存供离线查看。+ if (deleted) clearCachedMessages(deviceId, sessionId);const shard = shards.get(deviceId);if (!shard) return;const idx = shard.sessions.findIndex((s) => s.id === sessionId);if (idx === -1) {- if (patch.status === 'active') requestRemoteReseed(deviceId);+ if (patch.status === 'active') requestRemoteReseed(deviceId, 'active');+ if (patch.status === 'archived' && shard.loadedStatuses.has('archived')) {+ requestRemoteReseed(deviceId, 'archived');+ }return;}const status = patch.status;- if (status === 'deleted' || status === 'archived') {+ if (status === 'deleted') {// 叠加层随会话一起离场:留着的话 removeDevice 也回收不到(它只遍历分片里还在的// 会话),之后 unarchive / reseed 会把边界前的旧预览顶回一个仍是系统占位的// 会话上(PR #510 review)。@@ -477,6 +595,10 @@ const actions = {recompute();return;}+ if (status === 'archived') {+ // 归档后仍保留完整行,供已归档 / 全部筛选直接展示;标题即时预览不跨归档边界。+ dropTitleOverlay(sessionId);+ }const wasPinned = shard.sessions[idx]?.pinnedAt != null;const unpinned =Object.prototype.hasOwnProperty.call(patch, 'pinnedAt') && patch.pinnedAt == null;@@ -492,7 +614,7 @@ const actions = {: s,);recompute();- if (wasPinned && unpinned) requestRemoteReseed(deviceId);+ if (wasPinned && unpinned) requestRemoteReseed(deviceId, 'active');},/**@@ -518,11 +640,24 @@ const actions = {* connecting 等瞬态断线,避免 All Sessions 因网络抖动反复增删远程会话。*/markDeviceDisconnected(deviceId: string): void {- snapshotEpoch.set(deviceId, (snapshotEpoch.get(deviceId) ?? 0) + 1);+ invalidateDeviceSnapshotEpochs(deviceId);const bootstrapStateCleared = setBootstrapState(deviceId, 'idle');+ const archivedLoadingCleared = setSessionStatusLoading(deviceId, 'archived', false);+ const archivedFailureCleared = setSessionStatusFailed(deviceId, 'archived', false);const shard = shards.get(deviceId);+ // 旧 archived 行可继续作断线缓存,但断线期间的 push 不会补播;重连后必须重新拉取,+ // 不能让「曾加载过」永久挡住按需校准。+ const archivedLoadedCleared = shard?.loadedStatuses.delete('archived') ?? false;if (!shard || shard.connectionStatus === 'disconnected') {- if (bootstrapStateCleared) subs.forEach((fn) => fn());+ if (archivedLoadedCleared) recomputeArchivedLoadedDeviceIds();+ if (+ bootstrapStateCleared ||+ archivedLoadingCleared ||+ archivedFailureCleared ||+ archivedLoadedCleared+ ) {+ subs.forEach((fn) => fn());+ }return;}shard.connectionStatus = 'disconnected';@@ -537,12 +672,22 @@ const actions = {markAllDisconnected(): void {for (const [k, v] of snapshotEpoch) snapshotEpoch.set(k, v + 1);const bootstrapStateChanged =- bootstrapLoadingDeviceIds.size > 0 || bootstrapFailedDeviceIds.size > 0;+ bootstrapLoadingDeviceIds.size > 0 ||+ archivedLoadingDeviceIds.size > 0 ||+ bootstrapFailedDeviceIds.size > 0 ||+ archivedFailedDeviceIds.size > 0;if (bootstrapLoadingDeviceIds.size > 0) bootstrapLoadingDeviceIds = new Set();+ if (archivedLoadingDeviceIds.size > 0) archivedLoadingDeviceIds = new Set();if (bootstrapFailedDeviceIds.size > 0) bootstrapFailedDeviceIds = new Set();+ if (archivedFailedDeviceIds.size > 0) archivedFailedDeviceIds = new Set();let shardChanged = false;+ let archivedLoadedChanged = false;for (const shard of shards.values()) {- if (!snapshotEpoch.has(shard.deviceId)) snapshotEpoch.set(shard.deviceId, 1);+ for (const status of ['active', 'archived'] as const) {+ const key = snapshotEpochKey(shard.deviceId, status);+ if (!snapshotEpoch.has(key)) snapshotEpoch.set(key, 1);+ }+ if (shard.loadedStatuses.delete('archived')) archivedLoadedChanged = true;if (shard.connectionStatus === 'disconnected') continue;shardChanged = true;shard.connectionStatus = 'disconnected';@@ -552,7 +697,10 @@ const actions = {}));}if (shardChanged) recompute();- else if (bootstrapStateChanged) subs.forEach((fn) => fn());+ else {+ if (archivedLoadedChanged) recomputeArchivedLoadedDeviceIds();+ if (bootstrapStateChanged || archivedLoadedChanged) subs.forEach((fn) => fn());+ }},/** 移除某台设备的所有远端会话(访问撤销 / 关被控 / 本机禁用控制 / 删除)。 */@@ -560,7 +708,7 @@ const actions = {// **自增**该设备 epoch(不 delete,见 snapshotEpoch 注释的 ABA):在途 refreshRemoteDeviceSessions// 的 epoch 立即失效,且下次 bootstrap 拿到更高 epoch,不会与断连前在途的 epoch 撞值。即使尚未建// shard(首拉未完成就被移除)也要 bump,否则在途首拉 await 回来仍能通过 isLatestSnapshotEpoch 加回。- snapshotEpoch.set(deviceId, (snapshotEpoch.get(deviceId) ?? 0) + 1);+ invalidateDeviceSnapshotEpochs(deviceId);// 标题叠加层随分片一起丢弃:撤销授权 / 关闭控制后该设备的会话已不在视图里,// 留着会在下次重新接入时把边界前的旧预览顶回一个仍是系统占位的会话上。for (const session of shards.get(deviceId)?.sessions ?? []) {@@ -568,8 +716,12 @@ const actions = {}const shardDeleted = shards.delete(deviceId);const bootstrapStateCleared = setBootstrapState(deviceId, 'idle');+ const archivedLoadingCleared = setSessionStatusLoading(deviceId, 'archived', false);+ const archivedFailureCleared = setSessionStatusFailed(deviceId, 'archived', false);if (shardDeleted) recompute();- else if (bootstrapStateCleared) subs.forEach((fn) => fn());+ else if (bootstrapStateCleared || archivedLoadingCleared || archivedFailureCleared) {+ subs.forEach((fn) => fn());+ }},/** 清空所有远端项目(登出 / device-link stopped / 卸载)。 */@@ -583,9 +735,14 @@ const actions = {landedSystemTitles.clear();synthesizedPreviewSessions.clear();const bootstrapStateChanged =- bootstrapLoadingDeviceIds.size > 0 || bootstrapFailedDeviceIds.size > 0;+ bootstrapLoadingDeviceIds.size > 0 ||+ archivedLoadingDeviceIds.size > 0 ||+ bootstrapFailedDeviceIds.size > 0 ||+ archivedFailedDeviceIds.size > 0;if (bootstrapLoadingDeviceIds.size > 0) bootstrapLoadingDeviceIds = new Set();+ if (archivedLoadingDeviceIds.size > 0) archivedLoadingDeviceIds = new Set();if (bootstrapFailedDeviceIds.size > 0) bootstrapFailedDeviceIds = new Set();+ if (archivedFailedDeviceIds.size > 0) archivedFailedDeviceIds = new Set();if (shards.size === 0) {if (bootstrapStateChanged) subs.forEach((fn) => fn());return;@@ -652,8 +809,43 @@ const actions = {},/** refresh anti-entropy 用:取某设备当前缓存分片,调用方只读。 */- getDeviceSessions(deviceId: string): readonly Session[] {- return shards.get(deviceId)?.sessions ?? EMPTY;+ getDeviceSessions(deviceId: string, status?: RemoteSessionStatus): readonly Session[] {+ const sessions = shards.get(deviceId)?.sessions ?? EMPTY;+ return status ? sessions.filter((session) => session.status === status) : sessions;+ },++ /** 该设备的指定状态桶是否已成功拿到过权威列表(权威空数组也算)。 */+ hasLoadedSessionStatus(deviceId: string, status: RemoteSessionStatus): boolean {+ return shards.get(deviceId)?.loadedStatuses.has(status) ?? false;+ },++ /** 按需状态桶开始读取;重复调用保持幂等。 */+ markSessionStatusLoading(deviceId: string, status: RemoteSessionStatus): void {+ const loadingChanged = setSessionStatusLoading(deviceId, status, true);+ const failureCleared = setSessionStatusFailed(deviceId, status, false);+ if (!loadingChanged && !failureCleared) return;+ subs.forEach((fn) => fn());+ },++ /** 指定状态桶当前是否在读取;供按 device+status 单飞判断。 */+ isSessionStatusLoading(deviceId: string, status: RemoteSessionStatus): boolean {+ return (status === 'active' ? bootstrapLoadingDeviceIds : archivedLoadingDeviceIds).has(+ deviceId,+ );+ },++ /** 按需状态桶读取失败 / 被抢占时清 loading,不影响另一个状态桶的请求。 */+ clearSessionStatusLoading(deviceId: string, status: RemoteSessionStatus): void {+ if (!setSessionStatusLoading(deviceId, status, false)) return;+ subs.forEach((fn) => fn());+ },++ /** 指定状态桶读取终态失败:清 loading 并保留可见失败态。 */+ markSessionStatusFailed(deviceId: string, status: RemoteSessionStatus): void {+ const loadingCleared = setSessionStatusLoading(deviceId, status, false);+ const failureChanged = setSessionStatusFailed(deviceId, status, true);+ if (!loadingCleared && !failureChanged) return;+ subs.forEach((fn) => fn());},/**@@ -719,16 +911,36 @@ const actions = {return bootstrapFailedDeviceIds;},+ /** 正在按需读取 archived 桶的设备;不得污染 active bootstrap 的全局就绪信号。 */+ getArchivedLoadingDeviceIds(): ReadonlySet<string> {+ return archivedLoadingDeviceIds;+ },++ /** archived 桶最新一次读取失败的设备;只由 archived/all 侧栏筛选消费。 */+ getArchivedFailedDeviceIds(): ReadonlySet<string> {+ return archivedFailedDeviceIds;+ },++ /** 已成功加载 archived 权威列表的设备;用于隔离尚未完成的 active 前置 bootstrap。 */+ getArchivedLoadedDeviceIds(): ReadonlySet<string> {+ return archivedLoadedDeviceIds;+ },+/** snapshot 乱序保护:发起一次全量拉取前取新 epoch。 */- nextSnapshotEpoch(deviceId: string): number {- const n = (snapshotEpoch.get(deviceId) ?? 0) + 1;- snapshotEpoch.set(deviceId, n);+ nextSnapshotEpoch(deviceId: string, status: RemoteSessionStatus = 'active'): number {+ const key = snapshotEpochKey(deviceId, status);+ const n = (snapshotEpoch.get(key) ?? 0) + 1;+ snapshotEpoch.set(key, n);return n;},/** snapshot 乱序保护:await 回来后判断本次拉取是否仍是最新一次(否则丢弃结果)。 */- isLatestSnapshotEpoch(deviceId: string, epoch: number): boolean {- return snapshotEpoch.get(deviceId) === epoch;+ isLatestSnapshotEpoch(+ deviceId: string,+ epoch: number,+ status: RemoteSessionStatus = 'active',+ ): boolean {+ return snapshotEpoch.get(snapshotEpochKey(deviceId, status)) === epoch;},};@@ -748,7 +960,9 @@ function subscribeRename(fn: (deviceId: string, name: string) => void): () => vo}/** listing tier 挂载时注册「重拉某设备」的实现;卸载时传 null 清。 */-export function setRemoteReseedImpl(fn: ((deviceId: string) => void) | null): void {+export function setRemoteReseedImpl(+ fn: ((deviceId: string, status: RemoteSessionStatus) => void) | null,+): void {reseedImpl = fn;}@@ -763,8 +977,28 @@ export function setRemoteSessionBootstrapRetryImpl(fn: ((deviceId: string) => vo* - applyPatch 收到未知 session 的 status=active(unarchive)→ 重拉补回。* 实现(含防抖)由 listing tier 注入;未挂载时 no-op。*/-export function requestRemoteReseed(deviceId: string): void {- reseedImpl?.(deviceId);+export function requestRemoteReseed(+ deviceId: string,+ status: RemoteSessionStatus = 'active',+): void {+ reseedImpl?.(deviceId, status);+}++/**+ * 侧栏状态筛选按需确保远程状态桶已加载。active 由 listing tier 常驻同步;archived+ * 仅在用户查看「已归档 / 全部」时调用。请求在途或桶已权威落地时 no-op。+ */+export function requestRemoteSessionStatus(deviceId: string, status: RemoteSessionStatus): void {+ if (actions.hasLoadedSessionStatus(deviceId, status)) return;+ retryRemoteSessionStatus(deviceId, status);+}++/** 失败恢复入口:忽略“曾成功加载”标记,强制按 device+status 重新拉取。 */+export function retryRemoteSessionStatus(deviceId: string, status: RemoteSessionStatus): void {+ if (actions.isSessionStatusLoading(deviceId, status)) return;+ if (!reseedImpl) return;+ actions.markSessionStatusLoading(deviceId, status);+ reseedImpl(deviceId, status);}/** 用户可见错误态的重试入口:重新订阅并拉取该设备的首次任务快照。 */@@ -787,6 +1021,21 @@ export function useRemoteBootstrapFailedDeviceIds(): ReadonlySet<string> {return useSyncExternalStore(subscribe, actions.getBootstrapFailedDeviceIds);}+/** 归档状态按需读取中的设备;与 active bootstrap loading 严格隔离。 */+export function useRemoteArchivedLoadingDeviceIds(): ReadonlySet<string> {+ return useSyncExternalStore(subscribe, actions.getArchivedLoadingDeviceIds);+}++/** 归档状态按需读取失败的设备;与 active bootstrap failure 严格隔离。 */+export function useRemoteArchivedFailedDeviceIds(): ReadonlySet<string> {+ return useSyncExternalStore(subscribe, actions.getArchivedFailedDeviceIds);+}++/** 已成功拿到 archived 权威列表的设备(权威空数组也算)。 */+export function useRemoteArchivedLoadedDeviceIds(): ReadonlySet<string> {+ return useSyncExternalStore(subscribe, actions.getArchivedLoadedDeviceIds);+}+/** 组件内订阅:当前正在重新读取任务快照的设备集合。 */export function useRemoteBootstrapLoadingDeviceIds(): ReadonlySet<string> {return useSyncExternalStore(subscribe, actions.getBootstrapLoadingDeviceIds);diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.tsindex c05102bc1d..3558b40c23 100644--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts@@ -36,9 +36,12 @@ import { useAuth } from '@/contexts/AuthContext';import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { createLogger } from '@/lib/logger';import {+ requestRemoteSessionStatus,remoteProjectsStore,+ retryRemoteSessionStatus,setRemoteReseedImpl,setRemoteSessionBootstrapRetryImpl,+ type RemoteSessionStatus,} from './remoteProjectsStore';import {clearRemoteSessionActivity,@@ -68,6 +71,9 @@ const log = createLogger('device-link-remote-projects');/** session-list owner 令牌补读退避:不断恢复,但长期故障时不每 2 秒打一次 IPC。 */const SESSION_LIST_TOKEN_RETRY_BASE_MS = 2_000;const SESSION_LIST_TOKEN_RETRY_MAX_MS = 30_000;+/** archived 按需读取失败后自动恢复;独立于 active 的周期 anti-entropy。 */+const ARCHIVED_SESSION_RETRY_BASE_MS = 2_000;+const ARCHIVED_SESSION_RETRY_MAX_MS = 30_000;/** 返回下一次列表令牌补读的等待时间;账号边界 effect 重建时从 0 重新开始。 */export function nextSessionListTokenRetryDelay(previousMs: number): number {@@ -77,6 +83,14 @@ export function nextSessionListTokenRetryDelay(previousMs: number): number {return Math.min(previousMs * 2, SESSION_LIST_TOKEN_RETRY_MAX_MS);}+/** 返回 archived 按需读取失败后的下一档退避;持续恢复但封顶 30 秒。 */+export function nextArchivedSessionRetryDelay(previousMs: number): number {+ if (!Number.isFinite(previousMs) || previousMs < ARCHIVED_SESSION_RETRY_BASE_MS) {+ return ARCHIVED_SESSION_RETRY_BASE_MS;+ }+ return Math.min(previousMs * 2, ARCHIVED_SESSION_RETRY_MAX_MS);+}+/*** 启动 session-list owner 令牌补读循环。返回清理函数;账号边界 effect 每次重建都会创建新的* retryDelayMs,因此新账号从 2 秒重新开始,旧账号的 timer 由 cleanup 取消。@@ -282,8 +296,11 @@ export function useDeviceLinkRemoteProjects(): void {const eligible = new Map<string, string>();/** 本机主动关闭控制的目标设备(控制端本地偏好)。 */let disabledControlDeviceIds = new Set<string>();- /** sessions:created reseed 的 per-device 防抖 timer */+ /** sessions:created / archived 按需加载的 per-device+status 防抖 timer */const reseedTimers = new Map<string, ReturnType<typeof setTimeout>>();+ /** archived 读取终态失败后的 per-device 自动重试。 */+ const archivedRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();+ const archivedRetryDelayMs = new Map<string, number>();const bootstrapTasks = new Map<string,{ promise: Promise<void>; rerun: boolean; name: string }@@ -293,12 +310,40 @@ export function useDeviceLinkRemoteProjects(): void {const isAccessRevoked = (err: unknown): boolean =>extractIpcError(err)?.code === 'DEVICE_LINK_ACCESS_REVOKED';+ const clearArchivedSessionRetry = (deviceId: string): void => {+ const timer = archivedRetryTimers.get(deviceId);+ if (timer) clearTimeout(timer);+ archivedRetryTimers.delete(deviceId);+ archivedRetryDelayMs.delete(deviceId);+ };++ const clearAllArchivedSessionRetries = (): void => {+ for (const timer of archivedRetryTimers.values()) clearTimeout(timer);+ archivedRetryTimers.clear();+ archivedRetryDelayMs.clear();+ };++ const scheduleArchivedSessionRetry = (deviceId: string): void => {+ if (disposed || !eligible.has(deviceId) || archivedRetryTimers.has(deviceId)) return;+ const delay = nextArchivedSessionRetryDelay(archivedRetryDelayMs.get(deviceId) ?? 0);+ archivedRetryDelayMs.set(deviceId, delay);+ archivedRetryTimers.set(+ deviceId,+ setTimeout(() => {+ archivedRetryTimers.delete(deviceId);+ if (disposed || !eligible.has(deviceId) || !linkOnline) return;+ retryRemoteSessionStatus(deviceId, 'archived');+ }, delay),+ );+ };+/*** 被某被控端撤销访问权限:移出合格集 + 记入 revokedDevicesStore(设置页显示「已撤销」)+* 移除其项目/对话 + 驱逐远端快照缓存。该设备 presence 仍在线/允许被控,故下次 presence 会再* subscribeAndBootstrap 重试 —— 被控端恢复后即自动接回。*/const handleRevoked = (deviceId: string): void => {+ clearArchivedSessionRetry(deviceId);eligible.delete(deviceId);revokedDevicesStore.markRevoked(deviceId);remoteProjectsStore.removeDevice(deviceId);@@ -409,6 +454,7 @@ export function useDeviceLinkRemoteProjects(): void {disabledControl: disabledControlDeviceIds.has(d.deviceId),});if (action === 'ignore') return;+ clearArchivedSessionRetry(d.deviceId);if (wasEligible) {window.electronAPI.deviceLink.unsubscribe(d.deviceId, ['sessions']).catch(() => {});}@@ -456,6 +502,7 @@ export function useDeviceLinkRemoteProjects(): void {for (const deviceId of remoteProjectsStore.getAllDeviceIds()) {if (authoritative.has(deviceId) || eligible.has(deviceId)) continue;log.debug(`removing cached shard absent from listDevices: ${deviceId.slice(0, 8)}`);+ clearArchivedSessionRetry(deviceId);remoteProjectsStore.removeDevice(deviceId);removeRemoteSessionActivityForDevice(deviceId);// 权威列表里没有它 = 明确离场,和撤销 / 关被控同一档:登记进 hydration 黑名单,@@ -495,18 +542,43 @@ export function useDeviceLinkRemoteProjects(): void {void subscribeAndBootstrap(deviceId, name);});- // sessions:created push(无 row 数据)/ applyPatch 的 unarchive 兜底 → 防抖重拉该设备(reconcile)。- setRemoteReseedImpl((deviceId) => {+ // sessions:created / applyPatch 状态迁移 / 侧栏归档筛选 → 按设备+状态防抖重拉。+ setRemoteReseedImpl((deviceId, status: RemoteSessionStatus) => {const name = eligible.get(deviceId);- if (!name) return;- const prev = reseedTimers.get(deviceId);+ if (!name || disposed) {+ if (status === 'archived') {+ clearArchivedSessionRetry(deviceId);+ remoteProjectsStore.clearSessionStatusLoading(deviceId, status);+ }+ return;+ }+ const timerKey = `${deviceId}\u0000${status}`;+ const prev = reseedTimers.get(timerKey);if (prev) clearTimeout(prev);reseedTimers.set(- deviceId,+ timerKey,setTimeout(() => {- reseedTimers.delete(deviceId);- if (!disposed && eligible.has(deviceId)) {- void refreshRemoteDeviceSessions(deviceId, name, { snapshotMode: 'merge' });+ reseedTimers.delete(timerKey);+ if (!disposed && linkOnline && eligible.has(deviceId)) {+ void refreshRemoteDeviceSessions(deviceId, name, {+ snapshotMode: 'merge',+ status,+ }).then((result) => {+ if (result === 'revoked' && !disposed) {+ handleRevoked(deviceId);+ } else if (result === 'gave-up' && status === 'archived') {+ remoteProjectsStore.markSessionStatusFailed(deviceId, status);+ scheduleArchivedSessionRetry(deviceId);+ } else if (result === 'superseded' && status === 'archived') {+ clearArchivedSessionRetry(deviceId);+ remoteProjectsStore.clearSessionStatusLoading(deviceId, status);+ } else if (result === 'ok' && status === 'archived') {+ clearArchivedSessionRetry(deviceId);+ }+ });+ } else if (status === 'archived') {+ clearArchivedSessionRetry(deviceId);+ remoteProjectsStore.clearSessionStatusLoading(deviceId, status);}}, RESEED_DEBOUNCE_MS),);@@ -590,6 +662,7 @@ export function useDeviceLinkRemoteProjects(): void {linkStatusPushSeen = true;linkOnline = p.status === 'online';if (p.status !== 'online') {+ clearAllArchivedSessionRetries();// relay 瞬时重连(connecting):保留远程会话镜像,只标记 disconnected,让 All Sessions// 不因网络抖动反复增删/重排。eligible 保留不动 → 重连 online 时下面的分支自动// 重 subscribe+bootstrap。stopped(登出 / 停服)才清空。@@ -624,6 +697,7 @@ export function useDeviceLinkRemoteProjects(): void {if (disposed) return;disabledControlDeviceIds = new Set(p.disabledControlDeviceIds ?? []);if (!p.enabled) {+ clearArchivedSessionRetry(p.deviceId);const wasEligible = eligible.delete(p.deviceId);if (wasEligible) {window.electronAPI.deviceLink.unsubscribe(p.deviceId, ['sessions']).catch(() => {});@@ -668,6 +742,7 @@ export function useDeviceLinkRemoteProjects(): void {stopPeriodicReconcile();for (const t of reseedTimers.values()) clearTimeout(t);reseedTimers.clear();+ clearAllArchivedSessionRetries();bootstrapTasks.clear();offPresence();offRemotePush();