Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): preserve device names across reconnect
Chris3457fdb3a6f2
diff --git a/apps/desktop/src/main/__tests__/deviceLinkControllerDisplayNameFreshness.test.ts b/apps/desktop/src/main/__tests__/deviceLinkControllerDisplayNameFreshness.test.tsindex c2b5f89ce3..3c21a5ace3 100644--- a/apps/desktop/src/main/__tests__/deviceLinkControllerDisplayNameFreshness.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkControllerDisplayNameFreshness.test.ts@@ -4,6 +4,8 @@ import {applyControllerDisplayNameDirectorySnapshot,applyControllerDisplayNamePresence,createControllerDisplayNameFreshnessTracker,+ getControllerDisplayNameFreshnessSince,+ resetControllerDisplayNameFreshness,seedControllerDisplayNamesFromCache,} from '../device-link/controllerDisplayNameFreshness';@@ -13,6 +15,84 @@ const normalizeName = (name: string): string | null => {};describe('controller display-name directory freshness', () => {+ it('列表请求跨断线重连时 freshness 代次保持单调,旧响应不得回写', () => {+ const freshness = createControllerDisplayNameFreshnessTracker();+ const setDisplayName = vi.fn();+ const rememberName = vi.fn();+ const forgetName = vi.fn();++ applyControllerDisplayNamePresence({+ deviceId: 'dev-1',+ name: '断线前名称',+ selfName: 'Host.local',+ freshness,+ normalizeName,+ setDisplayName,+ setFallbackDisplayName: setDisplayName,+ rememberName,+ forgetName,+ });+ const requestEpoch = freshness.epoch;++ resetControllerDisplayNameFreshness(freshness);+ applyControllerDisplayNamePresence({+ deviceId: 'dev-1',+ name: '重连后名称',+ selfName: 'Host.local',+ freshness,+ normalizeName,+ setDisplayName,+ setFallbackDisplayName: setDisplayName,+ rememberName,+ forgetName,+ });+ rememberName.mockClear();+ forgetName.mockClear();++ expect(freshness.epoch).toBeGreaterThan(requestEpoch);+ expect(getControllerDisplayNameFreshnessSince(freshness, 'dev-1', requestEpoch)).toEqual({+ changedAfterRequest: true,+ authoritativeName: '重连后名称',+ });++ applyControllerDisplayNameDirectorySnapshot({+ devices: [{ deviceId: 'dev-1', name: '' }],+ cachedNames: { 'dev-1': '断线前名称' },+ freshness,+ requestEpoch,+ normalizeName,+ setDisplayName,+ rememberName,+ forgetName,+ });+ expect(rememberName).not.toHaveBeenCalled();+ expect(forgetName).not.toHaveBeenCalled();+ expect(freshness.authoritativeNameByDevice.get('dev-1')).toBe('重连后名称');+ });++ it('两个控制端共享同一被控端时,一个控制端重连只恢复自己的名称状态', () => {+ const controllerA = createControllerDisplayNameFreshnessTracker();+ const controllerB = createControllerDisplayNameFreshnessTracker();+ const setA = vi.fn();+ const setB = vi.fn();++ seedControllerDisplayNamesFromCache({ target: '旧名称' }, controllerA, setA);+ seedControllerDisplayNamesFromCache({ target: '旧名称' }, controllerB, setB);+ setA.mockClear();+ setB.mockClear();++ resetControllerDisplayNameFreshness(controllerA);+ seedControllerDisplayNamesFromCache({ target: '新名称' }, controllerA, setA);+ const replaySubscriptionsA = vi.fn(() =>+ controllerA.authoritativeNameByDevice.get('target'),+ );++ expect(replaySubscriptionsA()).toBe('新名称');+ expect(controllerB.authoritativeNameByDevice.get('target')).toBe('旧名称');+ expect(setA).toHaveBeenCalledWith('target', '新名称');+ expect(setB).not.toHaveBeenCalled();+ });+it('旧 REST 响应晚于新 presence 时不覆盖提示、不回写旧缓存,重连继续使用新名称', () => {const freshness = createControllerDisplayNameFreshnessTracker();const requestEpoch = freshness.epoch;diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.tsindex 36a3c2f4b1..e1d8c7f83a 100644--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts@@ -111,6 +111,7 @@ import {applyControllerDisplayNamePresence,createControllerDisplayNameFreshnessTracker,getControllerDisplayNameFreshnessSince,+ resetControllerDisplayNameFreshness,} from '../device-link/controllerDisplayNameFreshness';function makeDeps(overrides?: Partial<DeviceLinkIpcDeps>): DeviceLinkIpcDeps {@@ -406,6 +407,66 @@ describe('device-link IPC handlers', () => {},);+ it('listDevices:断线重连后的新 presence 阻止断线前旧列表响应删除名称', async () => {+ const freshness = createControllerDisplayNameFreshnessTracker();+ applyControllerDisplayNamePresence({+ deviceId: 'dev-1',+ name: '断线前名称',+ selfName: 'Host.local',+ freshness,+ normalizeName: normalizeCachedDeviceName,+ setDisplayName: vi.fn(),+ setFallbackDisplayName: vi.fn(),+ rememberName: vi.fn(),+ forgetName: vi.fn(),+ });+ const rememberLastKnownDeviceName = vi.fn(async () => true);+ const forgetLastKnownDeviceName = vi.fn(async () => true);+ const apiFetch: DeviceLinkIpcDeps['apiFetch'] = async <T>() => {+ resetControllerDisplayNameFreshness(freshness);+ applyControllerDisplayNamePresence({+ deviceId: 'dev-1',+ name: '重连后名称',+ selfName: 'Host.local',+ freshness,+ normalizeName: normalizeCachedDeviceName,+ setDisplayName: vi.fn(),+ setFallbackDisplayName: vi.fn(),+ rememberName: vi.fn(),+ forgetName: vi.fn(),+ });+ return {+ devices: [+ {+ deviceId: 'dev-1',+ name: '',+ selfName: 'Host.local',+ platform: 'darwin',+ lastSeenAt: '2026-06-23T00:00:00.000Z',+ online: true,+ busy: false,+ remoteControlEnabled: true,+ controlEnabled: true,+ isSelf: false,+ },+ ],+ } as T;+ };+ const deps = makeDeps({+ apiFetch,+ rememberLastKnownDeviceName,+ forgetLastKnownDeviceName,+ captureControllerDisplayNameRequestEpoch: () => freshness.epoch,+ readControllerDisplayNameFreshnessSince: (deviceId, requestEpoch) =>+ getControllerDisplayNameFreshnessSince(freshness, deviceId, requestEpoch),+ });++ const result = await handleListDevices(deps);+ expect(result.devices[0]?.name).toBe('重连后名称');+ expect(rememberLastKnownDeviceName).not.toHaveBeenCalled();+ expect(forgetLastKnownDeviceName).not.toHaveBeenCalled();+ });+it.each([['旧目录名', '新数据库名', 'remember', '新数据库名'],['', '新数据库名', 'forget', '新数据库名'],diff --git a/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.ts b/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.tsindex 6766984f6d..bad6337fc2 100644--- a/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.ts@@ -270,6 +270,23 @@ describe('writeDeviceLinkSetting', () => {expect(readDeviceLinkSettings().lastKnownDeviceNames).toEqual({ 'dev-1': 'MacBook' });});+ it('remember/forget 待落盘时,同步读取先合并最新内存意图供重连 seed 使用', async () => {+ h.seed(SETTINGS_PATH, JSON.stringify({ lastKnownDeviceNames: { 'dev-1': '旧名称' } }));+ const {+ forgetLastKnownDeviceName,+ readLastKnownDeviceNames,+ rememberLastKnownDeviceName,+ } = await load();++ const remember = rememberLastKnownDeviceName('dev-1', '新名称');+ expect(readLastKnownDeviceNames()).toEqual({ 'dev-1': '新名称' });+ await expect(remember).resolves.toBe(true);++ const forget = forgetLastKnownDeviceName('dev-1');+ expect(readLastKnownDeviceNames()).toEqual({});+ await expect(forget).resolves.toBe(true);+ });+it('rememberLastKnownDeviceName 写缓存失败时不影响调用方', async () => {h.writeFileSync.mockImplementationOnce(() => {throw new Error('disk full');diff --git a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.tsindex d288ce3200..12f67ea155 100644--- a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts@@ -63,9 +63,14 @@ describe('mobile voice credential sync desktop bootstrap path', () => {'void refreshControllerDisplayNamesFromDirectory(displayNameGeneration);',onlineBranch,);+ const replaySubscriptions = deviceLinkHost.indexOf(+ "replayActiveSubscriptions('ws-online');",+ onlineBranch,+ );expect(onlineBranch).toBeGreaterThanOrEqual(0);expect(seedCachedNames).toBeGreaterThan(onlineBranch);expect(refreshDirectory).toBeGreaterThan(seedCachedNames);+ expect(replaySubscriptions).toBeGreaterThan(refreshDirectory);expect(deviceLinkHost).toContain('generation !== controllerDisplayNameRefreshGeneration',);diff --git a/apps/desktop/src/main/device-link/controllerDisplayNameFreshness.ts b/apps/desktop/src/main/device-link/controllerDisplayNameFreshness.tsindex 144de701f8..fb338e997e 100644--- a/apps/desktop/src/main/device-link/controllerDisplayNameFreshness.ts+++ b/apps/desktop/src/main/device-link/controllerDisplayNameFreshness.ts@@ -1,5 +1,6 @@export interface ControllerDisplayNameFreshnessTracker {epoch: number;+ resetEpoch: number;epochByDevice: Map<string, number>;authoritativeNameByDevice: Map<string, string>;}@@ -18,7 +19,12 @@ type ControllerDisplayNameCandidate ={ kind: 'valid'; name: string } | { kind: 'empty' } | { kind: 'placeholder' };export function createControllerDisplayNameFreshnessTracker(): ControllerDisplayNameFreshnessTracker {- return { epoch: 0, epochByDevice: new Map(), authoritativeNameByDevice: new Map() };+ return {+ epoch: 0,+ resetEpoch: 0,+ epochByDevice: new Map(),+ authoritativeNameByDevice: new Map(),+ };}function markControllerDisplayNamePresenceFresh(@@ -32,7 +38,8 @@ function markControllerDisplayNamePresenceFresh(export function resetControllerDisplayNameFreshness(tracker: ControllerDisplayNameFreshnessTracker,): void {- tracker.epoch = 0;+ tracker.epoch += 1;+ tracker.resetEpoch = tracker.epoch;tracker.epochByDevice.clear();tracker.authoritativeNameByDevice.clear();}@@ -54,7 +61,9 @@ export function getControllerDisplayNameFreshnessSince(requestEpoch: number,): ControllerDisplayNameFreshnessSince {return {- changedAfterRequest: (tracker.epochByDevice.get(deviceId) ?? 0) > requestEpoch,+ changedAfterRequest:+ tracker.resetEpoch > requestEpoch+ || (tracker.epochByDevice.get(deviceId) ?? 0) > requestEpoch,authoritativeName: tracker.authoritativeNameByDevice.get(deviceId) ?? null,};}diff --git a/apps/desktop/src/main/device-link/settings-store.ts b/apps/desktop/src/main/device-link/settings-store.tsindex 14ecd9e43b..6b15e100a3 100644--- a/apps/desktop/src/main/device-link/settings-store.ts+++ b/apps/desktop/src/main/device-link/settings-store.ts@@ -274,7 +274,12 @@ export function writeDeviceLinkSetting<K extends keyof DeviceLinkSettings>(}export function readLastKnownDeviceNames(): Record<string, string> {- return { ...readDeviceLinkSettings().lastKnownDeviceNames };+ const names = { ...readDeviceLinkSettings().lastKnownDeviceNames };+ for (const [deviceId, pending] of pendingLastKnownDeviceNameByDevice) {+ if (pending.name === null) delete names[deviceId];+ else names[deviceId] = pending.name;+ }+ return names;}export function writeLastKnownDeviceNames(names: Record<string, string>): Promise<void> {@@ -283,11 +288,22 @@ export function writeLastKnownDeviceNames(names: Record<string, string>): Promis/** 同一设备的名称判重与写入必须同序,避免旧删除覆盖紧随其后的同名恢复。 */const lastKnownDeviceNameMutationByDevice = new Map<string, Promise<unknown>>();+/**+ * presence 已生效、但设置文件写入仍在队列/跨实例锁中等待时的同步覆盖层。+ * relay 重连 seed 必须先看到这里的最新意图,不能用旧磁盘快照覆盖当前提示。+ */+const pendingLastKnownDeviceNameByDevice = new Map<+ string,+ { name: string | null }+>();function enqueueLastKnownDeviceNameMutation<T>(deviceId: string,+ pendingName: string | null,mutation: () => Promise<T>,): Promise<T> {+ const pending = { name: pendingName };+ pendingLastKnownDeviceNameByDevice.set(deviceId, pending);const previous = lastKnownDeviceNameMutationByDevice.get(deviceId) ?? Promise.resolve();const task = previous.catch(() => undefined).then(mutation);lastKnownDeviceNameMutationByDevice.set(deviceId, task);@@ -295,6 +311,9 @@ function enqueueLastKnownDeviceNameMutation<T>(if (lastKnownDeviceNameMutationByDevice.get(deviceId) === task) {lastKnownDeviceNameMutationByDevice.delete(deviceId);}+ if (pendingLastKnownDeviceNameByDevice.get(deviceId) === pending) {+ pendingLastKnownDeviceNameByDevice.delete(deviceId);+ }};void task.then(cleanup, cleanup);return task;@@ -323,7 +342,7 @@ export async function setDeviceControlEnabled(export async function rememberLastKnownDeviceName(deviceId: string, name: string): Promise<boolean> {const normalizedName = normalizeCachedDeviceName(name);if (!deviceId.trim() || !normalizedName) return false;- return enqueueLastKnownDeviceNameMutation(deviceId, async () => {+ return enqueueLastKnownDeviceNameMutation(deviceId, normalizedName, async () => {const settings = readDeviceLinkSettings();if (settings.lastKnownDeviceNames[deviceId] === normalizedName) return false;try {@@ -345,7 +364,7 @@ export async function rememberLastKnownDeviceName(deviceId: string, name: stringexport async function forgetLastKnownDeviceName(deviceId: string): Promise<boolean> {const normalizedDeviceId = deviceId.trim();if (!normalizedDeviceId) return false;- return enqueueLastKnownDeviceNameMutation(normalizedDeviceId, async () => {+ return enqueueLastKnownDeviceNameMutation(normalizedDeviceId, null, async () => {let removed = false;try {await updateDeviceLinkSetting('lastKnownDeviceNames', (latest) => {