Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): guard device list name freshness
Chrisaf4abd088d4d
diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.tsindex a4deedd3cb..36a3c2f4b1 100644--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts@@ -35,6 +35,11 @@ vi.mock('./index', () => ({remoteUnsubscribe: vi.fn(),disconnectAllControllers: vi.fn(),broadcast: vi.fn(),+ captureControllerDisplayNameRequestEpoch: () => 0,+ readControllerDisplayNameFreshnessSince: () => ({+ changedAfterRequest: false,+ authoritativeName: null,+ }),}));vi.mock('../device-link/index', () => ({getDeviceLinkStatus: () => 'online',@@ -46,6 +51,11 @@ vi.mock('../device-link/index', () => ({remoteUnsubscribe: vi.fn(),disconnectAllControllers: vi.fn(),broadcast: vi.fn(),+ captureControllerDisplayNameRequestEpoch: () => 0,+ readControllerDisplayNameFreshnessSince: () => ({+ changedAfterRequest: false,+ authoritativeName: null,+ }),}));vi.mock('../device-link/dispatch', () => ({getActiveControllers: () => [],@@ -92,8 +102,16 @@ import {} from '../device-link/ipc';import { DeviceLinkError } from '@cindy/device-link';import { ServerApiError } from '../serverApiClient';-import { __testing as settingsTesting } from '../device-link/settings-store';+import {+ __testing as settingsTesting,+ normalizeCachedDeviceName,+} from '../device-link/settings-store';import { __testing as refcountTesting } from '../device-link/subscriptionRefcount';+import {+ applyControllerDisplayNamePresence,+ createControllerDisplayNameFreshnessTracker,+ getControllerDisplayNameFreshnessSince,+} from '../device-link/controllerDisplayNameFreshness';function makeDeps(overrides?: Partial<DeviceLinkIpcDeps>): DeviceLinkIpcDeps {return {@@ -125,6 +143,11 @@ function makeDeps(overrides?: Partial<DeviceLinkIpcDeps>): DeviceLinkIpcDeps {readLastKnownDeviceNames: vi.fn(() => ({})),rememberLastKnownDeviceName: vi.fn(async () => false),forgetLastKnownDeviceName: vi.fn(async () => false),+ captureControllerDisplayNameRequestEpoch: vi.fn(() => 0),+ readControllerDisplayNameFreshnessSince: vi.fn(() => ({+ changedAfterRequest: false,+ authoritativeName: null,+ })),...overrides,};}@@ -350,6 +373,94 @@ describe('device-link IPC handlers', () => {});});+ it.each([+ ['unknown', 'Host.local', 'Host.local'],+ ['no', null, '12345678'],+ ] as const)(+ 'listDevices:目录占位名 %s 无缓存时回退 selfName/设备短 ID(%s)',+ async (name, selfName, expectedName) => {+ 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(() => ({})),+ });++ const result = await handleListDevices(deps);+ expect(result.devices[0]?.name).toBe(expectedName);+ expect(deps.rememberLastKnownDeviceName).not.toHaveBeenCalled();+ expect(deps.forgetLastKnownDeviceName).not.toHaveBeenCalled();+ },+ );++ it.each([+ ['旧目录名', '新数据库名', 'remember', '新数据库名'],+ ['', '新数据库名', 'forget', '新数据库名'],+ ['旧目录名', '', 'remember', 'Host.local'],+ ] as const)(+ 'listDevices:旧目录 %s 在 presence(%s) 后不得触发 %s,并返回当前名称',+ async (directoryName, presenceName, _mutation, expectedName) => {+ const freshness = createControllerDisplayNameFreshnessTracker();+ const rememberLastKnownDeviceName = vi.fn(async () => true);+ const forgetLastKnownDeviceName = vi.fn(async () => true);+ const apiFetch: DeviceLinkIpcDeps['apiFetch'] = async <T>() => {+ applyControllerDisplayNamePresence({+ deviceId: 'dev-1',+ name: presenceName,+ selfName: 'Host.local',+ freshness,+ normalizeName: (value) => normalizeCachedDeviceName(value),+ setDisplayName: vi.fn(),+ setFallbackDisplayName: vi.fn(),+ rememberName: vi.fn(),+ forgetName: vi.fn(),+ });+ return {+ devices: [+ {+ deviceId: 'dev-1',+ name: directoryName,+ 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(expectedName);+ expect(rememberLastKnownDeviceName).not.toHaveBeenCalled();+ expect(forgetLastKnownDeviceName).not.toHaveBeenCalled();+ },+ );+it.each([['Host.local', 'Host.local'],[null, '12345678'],diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.tsindex dcef5a00e3..f0a88943de 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts@@ -90,6 +90,11 @@ vi.mock('../index', () => ({restoreController: vi.fn(),broadcast: vi.fn(),deviceLinkApiBase: 'https://example.invalid',+ captureControllerDisplayNameRequestEpoch: () => 0,+ readControllerDisplayNameFreshnessSince: () => ({+ changedAfterRequest: false,+ authoritativeName: null,+ }),}));vi.mock('../dispatch', () => ({ getActiveControllers: () => [] }));vi.mock('../outboundMedia', () => ({ rewriteOutboundMedia: vi.fn(async (_c, a) => a) }));diff --git a/apps/desktop/src/main/device-link/controllerDisplayNameFreshness.ts b/apps/desktop/src/main/device-link/controllerDisplayNameFreshness.tsindex 6e9476d1e9..144de701f8 100644--- a/apps/desktop/src/main/device-link/controllerDisplayNameFreshness.ts+++ b/apps/desktop/src/main/device-link/controllerDisplayNameFreshness.ts@@ -9,6 +9,11 @@ export interface ControllerDisplayNameDirectoryDevice {name?: unknown;}+export interface ControllerDisplayNameFreshnessSince {+ changedAfterRequest: boolean;+ authoritativeName: string | null;+}+type ControllerDisplayNameCandidate ={ kind: 'valid'; name: string } | { kind: 'empty' } | { kind: 'placeholder' };@@ -43,6 +48,17 @@ export function seedControllerDisplayNamesFromCache(}}+export function getControllerDisplayNameFreshnessSince(+ tracker: ControllerDisplayNameFreshnessTracker,+ deviceId: string,+ requestEpoch: number,+): ControllerDisplayNameFreshnessSince {+ return {+ changedAfterRequest: (tracker.epochByDevice.get(deviceId) ?? 0) > requestEpoch,+ authoritativeName: tracker.authoritativeNameByDevice.get(deviceId) ?? null,+ };+}+function classifyControllerDisplayName(value: unknown,normalizeName: (name: string) => string | null,@@ -110,7 +126,12 @@ export function applyControllerDisplayNameDirectorySnapshot(options: {for (const device of options.devices) {if (typeof device.deviceId !== 'string' || !device.deviceId.trim()) continue;const deviceId = device.deviceId.trim();- if ((options.freshness.epochByDevice.get(deviceId) ?? 0) > options.requestEpoch) continue;+ if (+ getControllerDisplayNameFreshnessSince(options.freshness, deviceId, options.requestEpoch)+ .changedAfterRequest+ ) {+ continue;+ }const candidate = classifyControllerDisplayName(device.name, options.normalizeName);if (candidate.kind === 'valid') {diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex ba9ea79c01..67aef1d6bf 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -90,6 +90,7 @@ import {applyControllerDisplayNameDirectorySnapshot,applyControllerDisplayNamePresence,createControllerDisplayNameFreshnessTracker,+ getControllerDisplayNameFreshnessSince,resetControllerDisplayNameFreshness,seedControllerDisplayNamesFromCache,} from './controllerDisplayNameFreshness';@@ -156,6 +157,21 @@ type DeviceDirectoryResponse = {let controllerDisplayNameRefreshGeneration = 0;const controllerDisplayNameFreshness = createControllerDisplayNameFreshnessTracker();+export function captureControllerDisplayNameRequestEpoch(): number {+ return controllerDisplayNameFreshness.epoch;+}++export function readControllerDisplayNameFreshnessSince(+ deviceId: string,+ requestEpoch: number,+): { changedAfterRequest: boolean; authoritativeName: string | null } {+ return getControllerDisplayNameFreshnessSince(+ controllerDisplayNameFreshness,+ deviceId,+ requestEpoch,+ );+}+function seedControllerDisplayNamesFromLastKnown(): void {seedControllerDisplayNamesFromCache(readLastKnownDeviceNames(),diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex 373e33f128..d8b5413477 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -41,6 +41,8 @@ import {restoreController,broadcast,deviceLinkApiBase,+ captureControllerDisplayNameRequestEpoch,+ readControllerDisplayNameFreshnessSince,} from './index';import { getActiveControllers } from './dispatch';import { rewriteOutboundMedia } from './outboundMedia';@@ -109,6 +111,11 @@ export interface DeviceLinkIpcDeps {readLastKnownDeviceNames(): Record<string, string>;rememberLastKnownDeviceName(deviceId: string, name: string): Promise<boolean>;forgetLastKnownDeviceName(deviceId: string): Promise<boolean>;+ captureControllerDisplayNameRequestEpoch(): number;+ readControllerDisplayNameFreshnessSince(+ deviceId: string,+ requestEpoch: number,+ ): { changedAfterRequest: boolean; authoritativeName: string | null };/*** 出方向附件改写:把消息里的本机附件上传 OSS、替换成引用串(仅 send/steer/enqueue 生效)。* 可选 —— 测试可不注入(跳过改写,行为同旧版纯透传)。@@ -154,6 +161,8 @@ export function defaultDeps(): DeviceLinkIpcDeps {readLastKnownDeviceNames,rememberLastKnownDeviceName,forgetLastKnownDeviceName,+ captureControllerDisplayNameRequestEpoch,+ readControllerDisplayNameFreshnessSince,rewriteOutboundMedia,rewriteOutboundSessionReferences,};@@ -296,11 +305,12 @@ export async function handleSetDeviceControlEnabled(export async function handleListDevices(deps: DeviceLinkIpcDeps,): Promise<{ devices: DeviceLinkDeviceView[] }> {+ const requestEpoch = deps.captureControllerDisplayNameRequestEpoch();try {const result = await deps.apiFetch<{ devices: DeviceLinkServerDeviceView[] }>('/api/device-link/devices',);- return reconcileDeviceNames(result, deps);+ return reconcileDeviceNames(result, deps, requestEpoch);} catch (err) {rethrowServerError(err);}@@ -314,13 +324,28 @@ function reconcileDeviceNames(| 'readLastKnownDeviceNames'| 'rememberLastKnownDeviceName'| 'forgetLastKnownDeviceName'+ | 'readControllerDisplayNameFreshnessSince'>,+ requestEpoch: number,): { devices: DeviceLinkDeviceView[] } {const cachedNames = deps.readLastKnownDeviceNames();const disabledControlDeviceIds = new Set(deps.getState().disabledControlDeviceIds ?? []);const devices = result.devices.map<DeviceLinkDeviceView>((device) => {let name = device.name;+ const selfName = typeof device.selfName === 'string'+ ? normalizeCachedDeviceName(device.selfName)+ : null;+ const freshness = deps.readControllerDisplayNameFreshnessSince(+ device.deviceId,+ requestEpoch,+ );+ if (freshness.changedAfterRequest) {+ name = freshness.authoritativeName ?? selfName ?? device.deviceId.slice(0, 8);+ const controlEnabled = !disabledControlDeviceIds.has(device.deviceId);+ return { ...device, name, controlEnabled };+ }+const trimmedName = device.name.trim();const hasDisplayName = !!trimmedName && !isPlaceholderDeviceName(trimmedName);if (hasDisplayName) {@@ -330,12 +355,11 @@ function reconcileDeviceNames(}} 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];+ } else {+ name = selfName ?? device.deviceId.slice(0, 8);}const controlEnabled = !disabledControlDeviceIds.has(device.deviceId);