Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): 优先使用 macOS 电脑名称作为设备默认名 (#4578)
Dasha89fb6ad1f9d
diff --git a/apps/desktop/src/main/device-link/__tests__/deviceName.test.ts b/apps/desktop/src/main/device-link/__tests__/deviceName.test.tsnew file mode 100644index 0000000000..1d03c2b1f6--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/deviceName.test.ts@@ -0,0 +1,86 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import os from 'node:os';++const { query } = vi.hoisted(() => ({ query: vi.fn() }));+vi.mock('node:child_process', () => ({ execFile: query }));+vi.mock('node:util', () => ({ promisify: () => query }));+vi.mock('node:os', () => ({ default: { hostname: vi.fn() } }));++beforeEach(() => {+ vi.resetModules();+ vi.resetAllMocks();+ vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');+ vi.mocked(os.hostname).mockReturnValue('DashdeMacBook-Pro.local');+});+afterEach(() => vi.restoreAllMocks());++describe('deviceName', () => {+ it('shares the pending lookup and reuses its result across reads and initialization', async () => {+ let finish!: (result: { stdout: string }) => void;+ query.mockReturnValue(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const { deviceName, initializeDeviceName } = await import('../deviceName');+ const ready = initializeDeviceName();+ expect(initializeDeviceName()).toBe(ready);+ expect(deviceName()).toBe('DashdeMacBook-Pro');+ finish({ stdout: ' Dash的 MacBook Pro.local\n' });+ await ready;+ await initializeDeviceName();+ expect(deviceName()).toBe('Dash的 MacBook Pro.local');+ expect(deviceName()).toBe('Dash的 MacBook Pro.local');+ expect(query).toHaveBeenCalledTimes(1);+ expect(query).toHaveBeenCalledWith('/usr/sbin/scutil', ['--get', 'ComputerName'], {+ encoding: 'utf8',+ timeout: 500,+ maxBuffer: 16 * 1024,+ killSignal: 'SIGKILL',+ });+ });++ it.each(['throw', 'reject'])('caches fallback when the OS lookup fails via %s', async (mode) => {+ const error = Object.assign(new Error('scutil timed out'), { code: 'ETIMEDOUT' });+ if (mode === 'reject') query.mockRejectedValue(error);+ else+ query.mockImplementation(() => {+ throw error;+ });+ const { deviceName, initializeDeviceName } = await import('../deviceName');+ await initializeDeviceName();+ await initializeDeviceName();+ expect(deviceName()).toBe('DashdeMacBook-Pro');+ expect(query).toHaveBeenCalledTimes(1);+ });++ it('falls back when ComputerName is blank', async () => {+ query.mockResolvedValue({ stdout: ' \n' });+ const { deviceName, initializeDeviceName } = await import('../deviceName');+ await initializeDeviceName();+ expect(deviceName()).toBe('DashdeMacBook-Pro');+ });++ it.each(['win32', 'linux'] as const)('does not run scutil on %s', async (platform) => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue(platform);+ vi.mocked(os.hostname).mockReturnValue(' WORK-PC ');+ const { deviceName, initializeDeviceName } = await import('../deviceName');+ await initializeDeviceName();+ expect(deviceName()).toBe('WORK-PC');+ expect(query).not.toHaveBeenCalled();+ });++ it.each([+ [' Mac.LOCAL. ', 'Mac'],+ ['Mac.local.example', 'Mac.local.example'],+ ['Mac.example.com', 'Mac.example.com'],+ [' ', 'Unknown Device'],+ ['.local', 'Unknown Device'],+ ])('normalizes fallback hostname %j to %j', async (hostname, expected) => {+ query.mockResolvedValue({ stdout: '' });+ vi.mocked(os.hostname).mockReturnValue(hostname);+ const { deviceName, initializeDeviceName } = await import('../deviceName');+ await initializeDeviceName();+ expect(deviceName()).toBe(expected);+ });+});diff --git a/apps/desktop/src/main/device-link/deviceName.ts b/apps/desktop/src/main/device-link/deviceName.tsnew file mode 100644index 0000000000..f5cd578fb4--- /dev/null+++ b/apps/desktop/src/main/device-link/deviceName.ts@@ -0,0 +1,48 @@+import { execFile } from 'node:child_process';+import os from 'node:os';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+let resolvedName: string | undefined;+let initialization: Promise<void> | undefined;++/** One process-lifetime lookup. Restart Cindy to pick up a changed ComputerName. */+export function initializeDeviceName(): Promise<void> {+ initialization ??= readDeviceName().then((name) => {+ resolvedName = name;+ });+ return initialization;+}++/** Default name reported to the relay; user-assigned names are handled by the server. */+export function deviceName(): string {+ return resolvedName ?? hostnameFallback();+}++async function readDeviceName(): Promise<string> {+ if (process.platform === 'darwin') {+ try {+ const { stdout } = await execFileAsync('/usr/sbin/scutil', ['--get', 'ComputerName'], {+ encoding: 'utf8',+ timeout: 500,+ killSignal: 'SIGKILL',+ maxBuffer: 16 * 1024,+ });+ const name = stdout.trim();+ if (name) return name;+ } catch {+ // Missing/unavailable ComputerName is expected to fall back to hostname.+ }+ }++ return hostnameFallback();+}++function hostnameFallback(): string {+ const name = os+ .hostname()+ .trim()+ .replace(/\.local\.?$/i, '')+ .trim();+ return name || 'Unknown Device';+}diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex b4d03cb9b7..3df7f6360e 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -11,6 +11,7 @@*/import os from 'node:os';+import { deviceName, initializeDeviceName } from './deviceName';import { watchNetworkChanges } from './networkChanges';import path from 'node:path';import { app, BrowserWindow } from 'electron';@@ -589,12 +590,6 @@ function recoverFromRelayAuthFailure(): void {});}-/** Windows 历史主机名可能带尾部空白/全大写,统一 trim;空值兜底 'Unknown Device' */-function deviceName(): string {- const name = os.hostname().trim();- return name || 'Unknown Device';-}-function buildDeviceInfo(): DeviceInfo {const info: DeviceInfo = {};const cpuLabel = normalizeDeviceInfoText(os.cpus()[0]?.model);@@ -643,6 +638,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): vreturn;}+ const deviceNameReady = initializeDeviceName();remoteCredentialHost.currentToken = () => {const membership = authManager.getCurrentUserId(), token = authManager.getAccessToken();return membership && token ? { realm: authManager.getActiveAuthRealm(), membership, authDevice: authManager.getDeviceId(), token } : null;@@ -650,6 +646,8 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): vclient = new DeviceLinkClient({getWsUrl: wsUrl,getToken: async () => {+ // Prepare the name before the first hello without blocking Electron's main thread.+ await deviceNameReady;const token = authManager.getAccessToken();if (token) return token;// 无现值(冷启动竞态/过期被清):尝试 refresh 一次,失败则跳过本轮重连