Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): serialize device name cache updates
Chris4d1a529f1849
diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.tsindex 199b3c6976..a4deedd3cb 100644--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts@@ -124,6 +124,7 @@ function makeDeps(overrides?: Partial<DeviceLinkIpcDeps>): DeviceLinkIpcDeps {broadcast: vi.fn(),readLastKnownDeviceNames: vi.fn(() => ({})),rememberLastKnownDeviceName: vi.fn(async () => false),+ forgetLastKnownDeviceName: vi.fn(async () => false),...overrides,};}@@ -349,6 +350,43 @@ describe('device-link IPC handlers', () => {});});+ it.each([+ ['Host.local', 'Host.local'],+ [null, '12345678'],+ ] as const)(+ 'listDevices:数据库空名清除 last-known,并回退 selfName/设备短 ID(%s)',+ async (selfName, expectedName) => {+ const forgetLastKnownDeviceName = vi.fn(async () => true);+ const rememberLastKnownDeviceName = vi.fn(async () => false);+ const deps = makeDeps({+ apiFetch: vi.fn().mockResolvedValue({+ devices: [+ {+ deviceId: '1234567890abcdef',+ name: '',+ selfName,+ platform: 'darwin',+ lastSeenAt: '2026-06-23T00:00:00.000Z',+ online: false,+ busy: false,+ remoteControlEnabled: false,+ controlEnabled: true,+ isSelf: false,+ },+ ],+ }),+ readLastKnownDeviceNames: vi.fn(() => ({ '1234567890abcdef': '旧缓存名' })),+ rememberLastKnownDeviceName,+ forgetLastKnownDeviceName,+ });++ const result = await handleListDevices(deps);+ expect(result.devices[0]?.name).toBe(expectedName);+ expect(forgetLastKnownDeviceName).toHaveBeenCalledWith('1234567890abcdef');+ expect(rememberLastKnownDeviceName).not.toHaveBeenCalled();+ },+ );+it('listDevices:按本机 disabledControlDeviceIds 合成 controlEnabled=false', async () => {const deps = makeDeps({getState: () => ({diff --git a/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.ts b/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.tsindex 0a3f95cc04..6766984f6d 100644--- a/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkSettingsStore.test.ts@@ -256,6 +256,20 @@ describe('writeDeviceLinkSetting', () => {expect(readDeviceLinkSettings().lastKnownDeviceNames).toEqual({});});+ it('空名删除尚未完成时,同名有效名称恢复会排在删除后重新写回', async () => {+ h.seed(SETTINGS_PATH, JSON.stringify({ lastKnownDeviceNames: { 'dev-1': 'MacBook' } }));+ const {+ forgetLastKnownDeviceName,+ readDeviceLinkSettings,+ rememberLastKnownDeviceName,+ } = await load();++ const forget = forgetLastKnownDeviceName('dev-1');+ const remember = rememberLastKnownDeviceName('dev-1', 'MacBook');+ await expect(Promise.all([forget, remember])).resolves.toEqual([true, true]);+ expect(readDeviceLinkSettings().lastKnownDeviceNames).toEqual({ 'dev-1': 'MacBook' });+ });+it('rememberLastKnownDeviceName 写缓存失败时不影响调用方', async () => {h.writeFileSync.mockImplementationOnce(() => {throw new Error('disk full');diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.tsindex deac3f4bfa..dcef5a00e3 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts@@ -98,7 +98,9 @@ vi.mock('../outboundSessionReferences', () => ({rewriteOutboundSessionReferences: vi.fn(async (_c, a) => a),}));vi.mock('../settings-store', () => ({+ forgetLastKnownDeviceName: vi.fn(),isPlaceholderDeviceName: () => false,+ normalizeCachedDeviceName: (name: string) => name.trim() || null,readDeviceLinkSettings: () => ({remoteControlEnabled: true,keepAwake: false,diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex e3c930e89c..373e33f128 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -50,7 +50,9 @@ import {stripOutboundSessionReferenceSideChannels,} from './outboundSessionReferences';import {+ forgetLastKnownDeviceName,isPlaceholderDeviceName,+ normalizeCachedDeviceName,readDeviceLinkSettings,readLastKnownDeviceNames,rememberLastKnownDeviceName,@@ -106,6 +108,7 @@ export interface DeviceLinkIpcDeps {broadcast(channel: string, payload: unknown): void;readLastKnownDeviceNames(): Record<string, string>;rememberLastKnownDeviceName(deviceId: string, name: string): Promise<boolean>;+ forgetLastKnownDeviceName(deviceId: string): Promise<boolean>;/*** 出方向附件改写:把消息里的本机附件上传 OSS、替换成引用串(仅 send/steer/enqueue 生效)。* 可选 —— 测试可不注入(跳过改写,行为同旧版纯透传)。@@ -150,6 +153,7 @@ export function defaultDeps(): DeviceLinkIpcDeps {broadcast,readLastKnownDeviceNames,rememberLastKnownDeviceName,+ forgetLastKnownDeviceName,rewriteOutboundMedia,rewriteOutboundSessionReferences,};@@ -306,7 +310,10 @@ function reconcileDeviceNames(result: { devices: DeviceLinkServerDeviceView[] },deps: Pick<DeviceLinkIpcDeps,- 'getState' | 'readLastKnownDeviceNames' | 'rememberLastKnownDeviceName'+ | 'getState'+ | 'readLastKnownDeviceNames'+ | 'rememberLastKnownDeviceName'+ | 'forgetLastKnownDeviceName'>,): { devices: DeviceLinkDeviceView[] } {const cachedNames = deps.readLastKnownDeviceNames();@@ -321,6 +328,12 @@ function reconcileDeviceNames(if (device.name !== trimmedName) {name = trimmedName;}+ } else if (!trimmedName) {+ void deps.forgetLastKnownDeviceName(device.deviceId); // 显式清空与后台目录刷新保持同义+ const selfName = typeof device.selfName === 'string'+ ? normalizeCachedDeviceName(device.selfName)+ : null;+ name = selfName ?? device.deviceId.slice(0, 8);} else if (cachedNames[device.deviceId]) {name = cachedNames[device.deviceId];}diff --git a/apps/desktop/src/main/device-link/settings-store.ts b/apps/desktop/src/main/device-link/settings-store.tsindex fc66eedd51..14ecd9e43b 100644--- a/apps/desktop/src/main/device-link/settings-store.ts+++ b/apps/desktop/src/main/device-link/settings-store.ts@@ -281,6 +281,25 @@ export function writeLastKnownDeviceNames(names: Record<string, string>): Promisreturn writeDeviceLinkSetting('lastKnownDeviceNames', { ...names });}+/** 同一设备的名称判重与写入必须同序,避免旧删除覆盖紧随其后的同名恢复。 */+const lastKnownDeviceNameMutationByDevice = new Map<string, Promise<unknown>>();++function enqueueLastKnownDeviceNameMutation<T>(+ deviceId: string,+ mutation: () => Promise<T>,+): Promise<T> {+ const previous = lastKnownDeviceNameMutationByDevice.get(deviceId) ?? Promise.resolve();+ const task = previous.catch(() => undefined).then(mutation);+ lastKnownDeviceNameMutationByDevice.set(deviceId, task);+ const cleanup = (): void => {+ if (lastKnownDeviceNameMutationByDevice.get(deviceId) === task) {+ lastKnownDeviceNameMutationByDevice.delete(deviceId);+ }+ };+ void task.then(cleanup, cleanup);+ return task;+}+export async function setDeviceControlEnabled(deviceId: string,enabled: boolean,@@ -304,43 +323,47 @@ export async function setDeviceControlEnabled(export async function rememberLastKnownDeviceName(deviceId: string, name: string): Promise<boolean> {const normalizedName = normalizeCachedDeviceName(name);if (!deviceId.trim() || !normalizedName) return false;- const settings = readDeviceLinkSettings();- if (settings.lastKnownDeviceNames[deviceId] === normalizedName) return false;- try {- // 锁内基于盘上最新 map 合并单条,避免用旧 map 整体覆盖并发写入的其它条目- await updateDeviceLinkSetting('lastKnownDeviceNames', (latest) =>- latest[deviceId] === normalizedName ? latest : { ...latest, [deviceId]: normalizedName },- );- } catch (err) {- log.warn('remember last-known device name failed, continuing without cache update', {- deviceId,- error: err instanceof Error ? err.message : String(err),- });- return false;- }- return true;+ return enqueueLastKnownDeviceNameMutation(deviceId, async () => {+ const settings = readDeviceLinkSettings();+ if (settings.lastKnownDeviceNames[deviceId] === normalizedName) return false;+ try {+ // 锁内基于盘上最新 map 合并单条,避免用旧 map 整体覆盖并发写入的其它条目+ await updateDeviceLinkSetting('lastKnownDeviceNames', (latest) =>+ latest[deviceId] === normalizedName ? latest : { ...latest, [deviceId]: normalizedName },+ );+ } catch (err) {+ log.warn('remember last-known device name failed, continuing without cache update', {+ deviceId,+ error: err instanceof Error ? err.message : String(err),+ });+ return false;+ }+ return true;+ });}export async function forgetLastKnownDeviceName(deviceId: string): Promise<boolean> {const normalizedDeviceId = deviceId.trim();if (!normalizedDeviceId) return false;- let removed = false;- try {- await updateDeviceLinkSetting('lastKnownDeviceNames', (latest) => {- if (!(normalizedDeviceId in latest)) return latest;- const next = { ...latest };- delete next[normalizedDeviceId];- removed = true;- return next;- });- } catch (err) {- log.warn('forget last-known device name failed, continuing with in-memory fallback', {- deviceId: normalizedDeviceId,- error: err instanceof Error ? err.message : String(err),- });- return false;- }- return removed;+ return enqueueLastKnownDeviceNameMutation(normalizedDeviceId, async () => {+ let removed = false;+ try {+ await updateDeviceLinkSetting('lastKnownDeviceNames', (latest) => {+ if (!(normalizedDeviceId in latest)) return latest;+ const next = { ...latest };+ delete next[normalizedDeviceId];+ removed = true;+ return next;+ });+ } catch (err) {+ log.warn('forget last-known device name failed, continuing with in-memory fallback', {+ deviceId: normalizedDeviceId,+ error: err instanceof Error ? err.message : String(err),+ });+ return false;+ }+ return removed;+ });}export function normalizeCachedDeviceName(name: string): string | null {