Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 修复设备会话加载终态 (#471)

Dashe17a6b220bfc
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkDeviceListLoading.test.tsx b/apps/desktop/src/renderer/__tests__/deviceLinkDeviceListLoading.test.tsx
index d510007437..e85aafba83 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkDeviceListLoading.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkDeviceListLoading.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
-import { renderHook, waitFor } from '@testing-library/react';
+import { act, renderHook, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
afterEach(() => {
@@ -8,21 +8,32 @@ afterEach(() => {
});
describe('useDeviceLinkDeviceList initial request', () => {
- it('marks a rejected initial device-list request as settled without fabricating an empty list', async () => {
- const listDevices = vi.fn().mockRejectedValue(new Error('relay unavailable'));
+ it('re-enters loading when online retries a rejected request with no device snapshot', async () => {
+ let resolveRetry: ((value: { devices: DeviceLinkDeviceView[] }) => void) | undefined;
+ const retry = new Promise<{ devices: DeviceLinkDeviceView[] }>((resolve) => {
+ resolveRetry = resolve;
+ });
+ let statusChanged:
+ ((payload: { status: 'stopped' | 'connecting' | 'online' }) => void) | undefined;
+ const listDevices = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('relay unavailable'))
+ .mockReturnValueOnce(retry);
vi.stubGlobal('electronAPI', {
deviceLink: {
listDevices,
onPresenceChanged: vi.fn(),
- onStatusChanged: vi.fn(),
+ onStatusChanged: vi.fn(
+ (callback: (payload: { status: 'stopped' | 'connecting' | 'online' }) => void) => {
+ statusChanged = callback;
+ },
+ ),
onControlTargetChanged: vi.fn(),
},
});
- const {
- useDeviceLinkDeviceList,
- useDeviceLinkDeviceListSettled,
- } = await import('@/features/device-link/useDeviceLinkDeviceList');
+ const { useDeviceLinkDeviceList, useDeviceLinkDeviceListSettled } =
+ await import('@/features/device-link/useDeviceLinkDeviceList');
const { result } = renderHook(() => ({
devices: useDeviceLinkDeviceList(),
settled: useDeviceLinkDeviceListSettled(),
@@ -32,5 +43,12 @@ describe('useDeviceLinkDeviceList initial request', () => {
await waitFor(() => expect(result.current.settled).toBe(true));
expect(result.current.devices).toBeNull();
expect(listDevices).toHaveBeenCalledTimes(1);
+
+ act(() => statusChanged?.({ status: 'online' }));
+ expect(listDevices).toHaveBeenCalledTimes(2);
+ expect(result.current).toEqual({ devices: null, settled: false });
+
+ await act(async () => resolveRetry?.({ devices: [] }));
+ await waitFor(() => expect(result.current).toEqual({ devices: [], settled: true }));
});
});
diff --git a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
index ee3121817f..52d48d4d7b 100644
--- a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
+++ b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
@@ -385,6 +385,7 @@ describe('normalizeSelectedMachineId 配合可选中集(连接中可保留,被
describe('shouldWaitForRemoteSessionBootstrap', () => {
const connecting = [{ deviceId: 'dev-a', name: 'Mac A', status: 'connecting' as const }];
+ const noBootstrapFailures = new Set<string>();
it('所有机器:设备清单或在线远端首快照未落地 → 保持加载态', () => {
expect(
@@ -393,6 +394,7 @@ describe('shouldWaitForRemoteSessionBootstrap', () => {
deviceListSettled: false,
devices: [],
syncedDevices: [],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(true);
expect(
@@ -401,6 +403,7 @@ describe('shouldWaitForRemoteSessionBootstrap', () => {
deviceListSettled: true,
devices: connecting,
syncedDevices: [],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(true);
});
@@ -414,6 +417,21 @@ describe('shouldWaitForRemoteSessionBootstrap', () => {
syncedDevices: [
{ deviceId: 'dev-a', deviceName: 'Mac A', sessionCount: 0, connected: false },
],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
+ }),
+ ).toBe(false);
+ });
+
+ it('明确选择已有权威 shard 的设备时,不等待独立的设备清单重试', () => {
+ expect(
+ shouldWaitForRemoteSessionBootstrap({
+ selectedMachineId: ['dev-a'],
+ deviceListSettled: false,
+ devices: connecting,
+ syncedDevices: [
+ { deviceId: 'dev-a', deviceName: 'Mac A', sessionCount: 0, connected: false },
+ ],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(false);
});
@@ -425,6 +443,7 @@ describe('shouldWaitForRemoteSessionBootstrap', () => {
deviceListSettled: true,
devices: [],
syncedDevices: [],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(false);
});
@@ -436,6 +455,7 @@ describe('shouldWaitForRemoteSessionBootstrap', () => {
deviceListSettled: false,
devices: [],
syncedDevices: [],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(false);
expect(
@@ -444,6 +464,7 @@ describe('shouldWaitForRemoteSessionBootstrap', () => {
deviceListSettled: true,
devices: connecting,
syncedDevices: [],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(false);
expect(
@@ -452,6 +473,7 @@ describe('shouldWaitForRemoteSessionBootstrap', () => {
deviceListSettled: true,
devices: connecting,
syncedDevices: [],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(true);
});
@@ -463,6 +485,7 @@ describe('shouldWaitForRemoteSessionBootstrap', () => {
deviceListSettled: true,
devices: [{ deviceId: 'dev-a', name: 'Mac A', status: 'rejected' }],
syncedDevices: [],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(false);
expect(
@@ -473,18 +496,47 @@ describe('shouldWaitForRemoteSessionBootstrap', () => {
syncedDevices: [
{ deviceId: 'dev-a', deviceName: 'Mac A', sessionCount: 2, connected: false },
],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(false);
});
+
+ it('bootstrap 终态失败的连接中设备不再无限 loading;其它未结算设备仍继续等待', () => {
+ const devices = [
+ { deviceId: 'dev-a', name: 'Mac A', status: 'connecting' as const },
+ { deviceId: 'dev-b', name: 'Mac B', status: 'connecting' as const },
+ ];
+ expect(
+ shouldWaitForRemoteSessionBootstrap({
+ selectedMachineId: ['dev-a'],
+ deviceListSettled: true,
+ devices,
+ syncedDevices: [],
+ bootstrapFailedDeviceIds: new Set(['dev-a']),
+ }),
+ ).toBe(false);
+ expect(
+ shouldWaitForRemoteSessionBootstrap({
+ selectedMachineId: MACHINE_ALL,
+ deviceListSettled: true,
+ devices,
+ syncedDevices: [],
+ bootstrapFailedDeviceIds: new Set(['dev-a']),
+ }),
+ ).toBe(true);
+ });
});
describe('shouldShowSelectedMachineConnectingPlaceholder', () => {
+ const noBootstrapFailures = new Set<string>();
+
it('在线可控但尚未同步会话 → 显示连接中占位', () => {
expect(
shouldShowSelectedMachineConnectingPlaceholder({
rawSelection: ['dev-a'],
devices: [{ deviceId: 'dev-a', name: 'Mac A', status: 'connecting' }],
syncedDevices: [],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(true);
});
@@ -497,6 +549,7 @@ describe('shouldShowSelectedMachineConnectingPlaceholder', () => {
syncedDevices: [
{ deviceId: 'dev-a', deviceName: 'Mac A', sessionCount: 2, connected: false },
],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(false);
});
@@ -509,10 +562,22 @@ describe('shouldShowSelectedMachineConnectingPlaceholder', () => {
syncedDevices: [
{ deviceId: 'dev-a', deviceName: 'Mac A', sessionCount: 0, connected: false },
],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(true);
});
+ it('选中设备的 bootstrap 已终态失败 → 停止连接中占位并进入真实空态', () => {
+ expect(
+ shouldShowSelectedMachineConnectingPlaceholder({
+ rawSelection: ['dev-a'],
+ devices: [{ deviceId: 'dev-a', name: 'Mac A', status: 'connecting' }],
+ syncedDevices: [],
+ bootstrapFailedDeviceIds: new Set(['dev-a']),
+ }),
+ ).toBe(false);
+ });
+
it('多选:全是连接中且无缓存 → 占位;混入本机或已连接设备 → 不占位', () => {
const devices = [
{ deviceId: 'dev-a', name: 'Mac A', status: 'connecting' as const },
@@ -523,6 +588,7 @@ describe('shouldShowSelectedMachineConnectingPlaceholder', () => {
rawSelection: ['dev-a'],
devices,
syncedDevices: [],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(true);
expect(
@@ -530,6 +596,7 @@ describe('shouldShowSelectedMachineConnectingPlaceholder', () => {
rawSelection: ['dev-a', 'dev-b'],
devices,
syncedDevices: [],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(false);
expect(
@@ -537,6 +604,7 @@ describe('shouldShowSelectedMachineConnectingPlaceholder', () => {
rawSelection: ['local', 'dev-a'],
devices,
syncedDevices: [],
+ bootstrapFailedDeviceIds: noBootstrapFailures,
}),
).toBe(false);
});
diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
index 30dfe2db27..4b263c0cd9 100644
--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
@@ -129,6 +129,19 @@ describe('refreshRemoteDeviceSessions retry', () => {
expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toContain('only');
});
+ it('断连使在途快照失效 → 返回 superseded,不冒充终态请求失败', async () => {
+ const d = did();
+ const snapshot = deferred<Session[]>();
+ invoke.mockReturnValueOnce(snapshot.promise);
+
+ const refresh = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });
+ remoteProjectsStore.markAllDisconnected();
+ snapshot.resolve([session('stale')]);
+
+ await expect(refresh).resolves.toBe('superseded');
+ expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(0);
+ });
+
it('首拉 active 列表时要求被控端补齐置顶,避免旧置顶被 200 条窗口截掉', async () => {
const d = did();
invoke.mockResolvedValueOnce([
diff --git a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts
index b1f1a39268..3ed0d1b063 100644
--- a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts
@@ -214,6 +214,31 @@ describe('remoteProjectsStore', () => {
]);
});
+ it('tracks terminal bootstrap failures with stable snapshots and clears them after a successful snapshot', () => {
+ const before = remoteProjectsStore.getBootstrapFailedDeviceIds();
+ remoteProjectsStore.markBootstrapFailed('dev-B');
+ const failed = remoteProjectsStore.getBootstrapFailedDeviceIds();
+ expect(failed).not.toBe(before);
+ expect([...failed]).toEqual(['dev-B']);
+
+ remoteProjectsStore.markBootstrapFailed('dev-B');
+ expect(remoteProjectsStore.getBootstrapFailedDeviceIds()).toBe(failed);
+
+ remoteProjectsStore.setDeviceSessions('dev-B', 'B', []);
+ expect(remoteProjectsStore.getBootstrapFailedDeviceIds().size).toBe(0);
+ });
+
+ it('removeDevice and clear discard bootstrap failure state even before a shard exists', () => {
+ remoteProjectsStore.markBootstrapFailed('dev-A');
+ remoteProjectsStore.removeDevice('dev-A');
+ expect(remoteProjectsStore.getBootstrapFailedDeviceIds().size).toBe(0);
+
+ remoteProjectsStore.markBootstrapFailed('dev-A');
+ remoteProjectsStore.markBootstrapFailed('dev-B');
+ remoteProjectsStore.clear();
+ expect(remoteProjectsStore.getBootstrapFailedDeviceIds().size).toBe(0);
+ });
+
it('clear resets everything', () => {
remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1'), mk('s2')]);
remoteProjectsStore.clear();
diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
index 60c551d96e..75d71237b3 100644
--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
@@ -83,11 +83,12 @@ export interface RefreshOptions {
/**
* 重拉结果:
- * - `ok`:成功落地最新快照(或本次被更新一次取代而让位,语义上无需调用方善后);
+ * - `ok`:成功落地最新快照;
* - `revoked`:被控端在 bootstrap 期间撤销了访问权限 → 调用方应 handleRevoked;
+ * - `superseded`:断连 / 清理等外部状态变化使本次快照失效 → 不是请求失败,等待后续重连;
* - `gave-up`:瞬态重试耗尽 / 永久非撤销错误 → 调用方照常收尾(push / reconnect 会兜底补上)。
*/
-export type RefreshResult = 'ok' | 'revoked' | 'gave-up';
+export type RefreshResult = 'ok' | 'revoked' | 'superseded' | 'gave-up';
interface RefreshTask {
promise: Promise<RefreshResult>;
@@ -256,7 +257,7 @@ async function runRefreshRemoteDeviceSessions(
for (let attempt = 0; attempt < maxAttempts; attempt++) {
// 被一次更新的重拉取代(期间又发起了新的 refresh)→ 停手,交给那一次(也避免无谓重试)。
- if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return 'gave-up';
+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return 'superseded';
try {
const list = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:list', [
LIST_LIMIT,
@@ -264,7 +265,7 @@ async function runRefreshRemoteDeviceSessions(
{ includePinned: true },
]);
// 乱序保护:本次拉取已不是最新一次 → 丢弃,别覆盖更新的结果。
- if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return 'gave-up';
+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return 'superseded';
if (Array.isArray(list)) {
if ((opts.snapshotMode ?? 'merge') === 'merge') {
const sessions = list as Session[];
@@ -291,7 +292,7 @@ async function runRefreshRemoteDeviceSessions(
}
return 'ok'; // 成功
} catch (err) {
- if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return 'gave-up';
+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) 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.ts
index a849cfe9d7..de793d19aa 100644
--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
@@ -37,6 +37,14 @@ interface DeviceShard {
const shards = new Map<string, DeviceShard>();
const subs = new Set<() => void>();
+/**
+ * 已完成一次 bootstrap、但以永久错误或重试耗尽告终且尚无权威 sessions shard 的设备。
+ * 这不是「权威空列表」:仅用于让侧边栏结束无限 loading;下一次 reconnect/bootstrap
+ * 开始时会清掉,成功 snapshot 也会清掉。
+ *
+ * 用不可变 Set 快照,保证 useSyncExternalStore 在内容不变时引用稳定。
+ */
+let bootstrapFailedDeviceIds: ReadonlySet<string> = new Set();
/**
* 设备改名通知订阅(deviceId → 新名)。设备名走 REST PATCH(Device.name,不进 sessions 表),
* 服务端不广播 presence;listing tier 把设备名缓存在自己的 eligible 表,改名时同步通知接入器
@@ -134,6 +142,17 @@ function recompute(): void {
subs.forEach((fn) => fn());
}
+/** 更新 bootstrap 失败快照但不通知;调用方与其它 mutation 合并成一次通知。 */
+function setBootstrapFailed(deviceId: string, failed: boolean): boolean {
+ const has = bootstrapFailedDeviceIds.has(deviceId);
+ if (has === failed) return false;
+ const next = new Set(bootstrapFailedDeviceIds);
+ if (failed) next.add(deviceId);
+ else next.delete(deviceId);
+ bootstrapFailedDeviceIds = next;
+ return true;
+}
+
/** 给一条远端会话打上 device-link origin 标记(供 groupSessions + 传输层识别)。 */
function stamp(
session: Session,
@@ -160,18 +179,32 @@ const actions = {
const connectionStatus: DeviceLinkConnectionStatus = 'connected';
const stamped = rawSessions.map((s) => stamp(s, deviceId, deviceName, connectionStatus));
const existing = shards.get(deviceId);
+ const failureCleared = setBootstrapFailed(deviceId, false);
if (
existing &&
existing.connectionStatus === connectionStatus &&
JSON.stringify(existing.sessions) === JSON.stringify(stamped)
) {
// 内容不变但设备名可能变了(改名走 renameDevice,不经这里);保持引用不动。
+ if (failureCleared) subs.forEach((fn) => fn());
return;
}
shards.set(deviceId, { deviceId, deviceName, connectionStatus, sessions: stamped });
recompute();
},
+ /** bootstrap 永久失败 / 重试耗尽且没有 sessions shard:记录终态,避免侧边栏无限 loading。 */
+ markBootstrapFailed(deviceId: string): void {
+ if (!setBootstrapFailed(deviceId, true)) return;
+ subs.forEach((fn) => fn());
+ },
+
+ /** 新一轮 bootstrap 开始或 snapshot 成功:重新进入等待 / 已同步状态。 */
+ clearBootstrapFailure(deviceId: string): void {
+ if (!setBootstrapFailed(deviceId, false)) return;
+ subs.forEach((fn) => fn());
+ },
+
/**
* 合并一份有界会话快照。周期 anti-entropy 只拿最近 LIST_LIMIT 条 + 旧置顶,响应缺席
* 不能证明窗口外会话已归档/删除;因此命中行用权威值替换,未命中行先保留,再由 refresh
@@ -286,8 +319,10 @@ const actions = {
// 的 epoch 立即失效,且下次 bootstrap 拿到更高 epoch,不会与断连前在途的 epoch 撞值。即使尚未建
// shard(首拉未完成就被移除)也要 bump,否则在途首拉 await 回来仍能通过 isLatestSnapshotEpoch 加回。
snapshotEpoch.set(deviceId, (snapshotEpoch.get(deviceId) ?? 0) + 1);
- if (!shards.delete(deviceId)) return;
- recompute();
+ const shardDeleted = shards.delete(deviceId);
+ const failureCleared = setBootstrapFailed(deviceId, false);
+ if (shardDeleted) recompute();
+ else if (failureCleared) subs.forEach((fn) => fn());
},
/** 清空所有远端项目(登出 / device-link stopped / 卸载)。 */
@@ -295,7 +330,12 @@ const actions = {
// 所有设备 epoch 无条件**自增**(不 clear-to-0,见 snapshotEpoch 注释的 ABA):清空时在途
// 首拉立即失效;下一轮 bootstrap 拿到更高 epoch,不会与清空前的 epoch 撞值把陈旧 snapshot 盖回。
for (const [k, v] of snapshotEpoch) snapshotEpoch.set(k, v + 1);
- if (shards.size === 0) return;
+ const failureChanged = bootstrapFailedDeviceIds.size > 0;
+ if (failureChanged) bootstrapFailedDeviceIds = new Set();
+ if (shards.size === 0) {
+ if (failureChanged) subs.forEach((fn) => fn());
+ return;
+ }
shards.clear();
recompute();
},
@@ -340,6 +380,11 @@ const actions = {
return deviceListSnapshot;
},
+ /** 机器切换栏 loading 判定用:已终态失败且尚无权威 sessions shard 的设备 id。 */
+ getBootstrapFailedDeviceIds(): ReadonlySet<string> {
+ return bootstrapFailedDeviceIds;
+ },
+
/** snapshot 乱序保护:发起一次全量拉取前取新 epoch。 */
nextSnapshotEpoch(deviceId: string): number {
const n = (snapshotEpoch.get(deviceId) ?? 0) + 1;
@@ -393,6 +438,11 @@ export function useRemoteDevices(): RemoteDeviceSummary[] {
return useSyncExternalStore(subscribe, actions.getDeviceList);
}
+/** 组件内订阅:bootstrap 已终态失败、下一次重试尚未开始的设备集合。 */
+export function useRemoteBootstrapFailedDeviceIds(): ReadonlySet<string> {
+ return useSyncExternalStore(subscribe, actions.getBootstrapFailedDeviceIds);
+}
+
/** 非组件上下文(presence 订阅器 / 传输层)读写入口。 */
export const remoteProjectsStore = { ...actions, subscribe, subscribeRename };
diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkDeviceList.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkDeviceList.ts
index aa110d81a5..1c11853032 100644
--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkDeviceList.ts
+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkDeviceList.ts
@@ -119,6 +119,13 @@ function ensureStarted(): void {
if (started) return;
started = true;
const refresh = (): void => {
+ // 上一轮在尚无设备快照时失败只代表「该次请求已结算」。online / push 触发了新的
+ // 有意义重试后要重新进入 loading,直到这次请求成功或失败;否则失败后重连期间会
+ // 把 devices=null + settled=true 误当成权威空列表。
+ if (devices === null && initialRequestSettled) {
+ initialRequestSettled = false;
+ subs.forEach((fn) => fn());
+ }
loadGeneration += 1; // 本次为最新一次拉取,作废所有更早的在途响应(见 loadGeneration 注释)。
const gen = loadGeneration;
window.electronAPI.deviceLink
diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
index e040ba881d..99f184629d 100644
--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
@@ -141,6 +141,8 @@ export function useDeviceLinkRemoteProjects(): void {
* 任一步返回 ACCESS_REVOKED → 标记已撤销并移除该设备;全程无撤销 → 清掉残留标记(恢复收尾)。
*/
const runSubscribeAndBootstrap = async (deviceId: string, name: string): Promise<void> => {
+ // 新一轮 bootstrap 是有意义的重试:恢复 loading,直到本轮落下 snapshot 或再次终态失败。
+ remoteProjectsStore.clearBootstrapFailure(deviceId);
try {
await window.electronAPI.deviceLink.subscribe(deviceId, ['sessions']);
} catch (err) {
@@ -152,13 +154,19 @@ export function useDeviceLinkRemoteProjects(): void {
// (而非静默 give-up)→ 这里 handleRevoked,而不是继续预取能力 / 清撤销标记无视拒绝。
const result = await refreshRemoteDeviceSessions(deviceId, name);
if (result === 'revoked') return void handleRevoked(deviceId);
- if (disposed) return;
+ if (disposed || !eligible.has(deviceId)) return;
+ if (result === 'gave-up' && !remoteProjectsStore.hasDevice(deviceId)) {
+ // 永久错误(如旧被控端 CHANNEL_NOT_ALLOWED)或瞬态重试耗尽:不是权威空列表,
+ // 但本轮 bootstrap 已有终态,不能让「所有」侧边栏永久停在 loading。
+ // superseded 表示断连 / 清理使请求失效,必须等重连,不能误记成终态失败。
+ remoteProjectsStore.markBootstrapFailed(deviceId);
+ }
// 预取被控端能力(model/effort/fast/permission/fork/rewind),使首次打开远程会话时
// 模型下拉等不为空、modelDefinitions 同步层已热。fire-and-forget,失败不阻断。
void prefetchDeviceCapabilities(deviceId);
void prefetchDeviceProviders(deviceId);
void prefetchDeviceGitSafetySettings(deviceId);
- // 未被撤销(ok 或瞬态 give-up):清掉可能残留的「已撤销」标记(被控端恢复 → 自动接回的收尾)。
+ // 未被撤销(ok 或普通失败):清掉可能残留的「已撤销」标记(被控端恢复 → 自动接回的收尾)。
revokedDevicesStore.clearRevoked(deviceId);
};
diff --git a/apps/desktop/src/renderer/features/device-link/useMachineSwitcher.ts b/apps/desktop/src/renderer/features/device-link/useMachineSwitcher.ts
index 993a708099..91e72dd69c 100644
--- a/apps/desktop/src/renderer/features/device-link/useMachineSwitcher.ts
+++ b/apps/desktop/src/renderer/features/device-link/useMachineSwitcher.ts
@@ -22,7 +22,11 @@
*/
import { useCallback, useMemo, useSyncExternalStore } from 'react';
-import { useRemoteDevices, type RemoteDeviceSummary } from './remoteProjectsStore';
+import {
+ useRemoteBootstrapFailedDeviceIds,
+ useRemoteDevices,
+ type RemoteDeviceSummary,
+} from './remoteProjectsStore';
import { revokedDevicesStore } from './revokedDevicesStore';
import {
useDeviceLinkDeviceList,
@@ -43,6 +47,7 @@ export interface SelectedMachineConnectingInput {
rawSelection: MachineSelection;
devices: readonly SwitcherDevice[];
syncedDevices: readonly RemoteDeviceSummary[];
+ bootstrapFailedDeviceIds: ReadonlySet<string>;
}
export interface RemoteSessionBootstrapLoadingInput {
@@ -50,6 +55,7 @@ export interface RemoteSessionBootstrapLoadingInput {
deviceListSettled: boolean;
devices: readonly SwitcherDevice[];
syncedDevices: readonly RemoteDeviceSummary[];
+ bootstrapFailedDeviceIds: ReadonlySet<string>;
}
/**
@@ -62,19 +68,30 @@ export function shouldWaitForRemoteSessionBootstrap({
deviceListSettled,
devices,
syncedDevices,
+ bootstrapFailedDeviceIds,
}: RemoteSessionBootstrapLoadingInput): boolean {
const selectedRemoteIds =
selectedMachineId === MACHINE_ALL
? null
: new Set(selectedMachineId.filter((id) => id !== MACHINE_LOCAL));
if (selectedRemoteIds?.size === 0) return false;
- if (!deviceListSettled) return true;
const syncedIds = new Set(syncedDevices.map((device) => device.deviceId));
+ // 明确选择的远端设备若都已有权威 shard(包括 0 会话),设备目录的独立重试不应
+ // 把已知作用域重新挡回 loading;「所有」仍必须等目录结算,才能知道完整远端集合。
+ if (
+ selectedRemoteIds !== null &&
+ [...selectedRemoteIds].every((deviceId) => syncedIds.has(deviceId))
+ ) {
+ return false;
+ }
+ if (!deviceListSettled) return true;
+
return devices.some(
(device) =>
device.status === 'connecting' &&
!syncedIds.has(device.deviceId) &&
+ !bootstrapFailedDeviceIds.has(device.deviceId) &&
(selectedRemoteIds === null || selectedRemoteIds.has(device.deviceId)),
);
}
@@ -89,12 +106,14 @@ export function shouldShowSelectedMachineConnectingPlaceholder({
rawSelection,
devices,
syncedDevices,
+ bootstrapFailedDeviceIds,
}: SelectedMachineConnectingInput): boolean {
const effective = normalizeSelectedMachineId(rawSelection, selectableDeviceIds(devices));
if (effective === MACHINE_ALL || effective.includes(MACHINE_LOCAL)) return false;
for (const deviceId of effective) {
const selectedDevice = devices.find((d) => d.deviceId === deviceId);
if (selectedDevice?.status !== 'connecting') return false;
+ if (bootstrapFailedDeviceIds.has(deviceId)) return false;
const cachedSessionCount =
syncedDevices.find((d) => d.deviceId === deviceId)?.sessionCount ?? 0;
if (cachedSessionCount > 0) return false;
@@ -141,10 +160,12 @@ export function useSelectedMachineConnecting(): boolean {
const raw = useSelectedMachineId();
const devices = useSwitcherDevices();
const synced = useRemoteDevices();
+ const bootstrapFailedDeviceIds = useRemoteBootstrapFailedDeviceIds();
return shouldShowSelectedMachineConnectingPlaceholder({
rawSelection: raw,
devices,
syncedDevices: synced,
+ bootstrapFailedDeviceIds,
});
}
@@ -159,6 +180,7 @@ export function useRemoteSessionBootstrapLoading(
const deviceListSettled = useDeviceLinkDeviceListSettled();
const devices = useSwitcherDevices();
const synced = useRemoteDevices();
+ const bootstrapFailedDeviceIds = useRemoteBootstrapFailedDeviceIds();
return useMemo(
() =>
shouldWaitForRemoteSessionBootstrap({
@@ -166,8 +188,9 @@ export function useRemoteSessionBootstrapLoading(
deviceListSettled,
devices,
syncedDevices: synced,
+ bootstrapFailedDeviceIds,
}),
- [selectedMachineId, deviceListSettled, devices, synced],
+ [selectedMachineId, deviceListSettled, devices, synced, bootstrapFailedDeviceIds],
);
}