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(devices): keep device fingerprints out of visible names

Chris3547a6f7af28
diff --git a/apps/desktop/scripts/fixtures/teammates-section/ui-page.mjs b/apps/desktop/scripts/fixtures/teammates-section/ui-page.mjs
index 2623db6c43..f65a33a940 100644
--- a/apps/desktop/scripts/fixtures/teammates-section/ui-page.mjs
+++ b/apps/desktop/scripts/fixtures/teammates-section/ui-page.mjs
@@ -25,7 +25,7 @@ export default {
'src/renderer/features/bots/BotCreateMenu': 'export const BotCreateMenu=()=>null;',
'src/renderer/features/bots/BotDeleteDialog': 'export const BotDeleteDialog=()=>null;',
},
- cases: Object.fromEntries([
+ cases: { ...Object.fromEntries([
['default', '/bots/mate-6'],
['session', '/bots/mate-6/session/session-6'],
['history', '/bots/mate-6/history/session-6'],
@@ -47,7 +47,24 @@ export default {
data: { profiles: localProfiles, remoteBots, route },
}];
})),
+ 'device-names': {
+ about: 'Duplicate and missing computer names never expose device fingerprints in teammate rows',
+ data: { profiles: [], route: '/bots', remoteBots: [
+ { id: 'writer', name: 'Writer', deviceId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', deviceName: 'Mac Studio', online: true, preview: 'Ready', activityAt: 0 },
+ { id: 'researcher', name: 'Researcher', deviceId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', deviceName: 'Mac Studio', online: true, preview: 'Ready', activityAt: 0 },
+ { id: 'designer', name: 'Designer', deviceId: 'cccccccccccccccccccccccccccccccc', deviceName: '', online: false, preview: 'Ready', activityAt: 0 },
+ ] },
+ },
+ },
async check(page, ui) {
+ if (ui.case === 'device-names') {
+ const text = await page.locator('body').innerText();
+ assert.match(text, /Mac Studio \(1\)/);
+ assert.match(text, /Mac Studio \(2\)/);
+ assert.ok(text.includes(await ui.t('bots.cloud.unknownDevice')));
+ assert.doesNotMatch(text, /[abc]{32}/);
+ return;
+ }
const rows = page.getByText('Ready', { exact: true });
assert.equal(await rows.count(), 5);
assert.equal(await page.getByText('Translator', { exact: true }).count(), 0);
diff --git a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
index a6e61b8c26..b9f19eb431 100644
--- a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
+++ b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
@@ -371,13 +371,13 @@ describe('buildSwitcherDevices', () => {
]);
});
- it('被拒设备即使不在全量列表也列出(名字回退到 deviceId)', () => {
+ it('被拒设备即使不在全量列表也列出(名字回退到可读提示)', () => {
const result = buildSwitcherDevices({
fullList: [],
syncedDevices: [],
revoked: new Set(['gone-dev']),
});
- expect(result).toEqual([{ deviceId: 'gone-dev', name: 'gone-dev', status: 'rejected' }]);
+ expect(result).toEqual([{ deviceId: 'gone-dev', name: 'another computer', status: 'rejected' }]);
});
it('fullList 为 null(尚未加载)→ 仅由已同步 / 被拒撑起', () => {
diff --git a/apps/desktop/src/renderer/__tests__/myDevicesPanel.test.ts b/apps/desktop/src/renderer/__tests__/myDevicesPanel.test.ts
index 267059a1db..0ecd729324 100644
--- a/apps/desktop/src/renderer/__tests__/myDevicesPanel.test.ts
+++ b/apps/desktop/src/renderer/__tests__/myDevicesPanel.test.ts
@@ -4,7 +4,8 @@ import { act, cleanup, fireEvent, render, screen, within } from '@testing-librar
import { createElement } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-vi.mock('react-i18next', () => ({
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...await importOriginal<typeof import('react-i18next')>(),
useTranslation: () => ({ t: (key: string) => key }),
}));
@@ -46,7 +47,7 @@ function device(deviceId: string, name: string, isSelf = false): DeviceLinkDevic
describe('MyDevicesPanel device identity', () => {
afterEach(cleanup);
- it('shows the reported versions and complete identities of same-name devices', () => {
+ it('shows versions and compact names without exposing device fingerprints', () => {
const s = settings();
s.devices = [
{ ...device('self', 'Mac Studio', true), appVersion: '0.1.76' },
@@ -58,7 +59,8 @@ describe('MyDevicesPanel device identity', () => {
for (const d of s.devices) {
const row = document.querySelector(`[data-device-id="${d.deviceId}"]`);
- expect(row?.textContent).toContain(d.deviceId);
+ expect(row?.textContent).not.toContain(d.deviceId);
+ if (!d.isSelf && d.name === 'Mac Studio') expect(row?.textContent).toMatch(/Mac Studio \(\d\)/);
if (d.appVersion) expect(row?.textContent).toContain(`Cindy ${d.appVersion}`);
else {
expect(row?.textContent).not.toContain('Cindy null');
diff --git a/apps/desktop/src/renderer/__tests__/remoteProjectIdentity.test.ts b/apps/desktop/src/renderer/__tests__/remoteProjectIdentity.test.ts
index 2a39840f0e..7fa89061d6 100644
--- a/apps/desktop/src/renderer/__tests__/remoteProjectIdentity.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteProjectIdentity.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
- collectAmbiguousDeviceNames,
+ collectProjectDevices,
projectDisplayLabelWithMachine,
resolveRemoteProjectMachineIdentity,
} from '@/features/cc-agent/lib/remoteProjectIdentity';
@@ -67,7 +67,7 @@ describe('resolveRemoteProjectMachineIdentity', () => {
});
// 2026-08-12 用户裁决:设备 ID 是机器指纹哈希,对用户没有可读意义,默认不显示;
- // 只有两台设备撞名、光看名字分不出来时才附上消歧。
+ // 同名设备使用简短序号区分。
it('shows only the device-link friendly name when the name is unambiguous', () => {
const identity = resolveRemoteProjectMachineIdentity(
{
@@ -86,7 +86,7 @@ describe('resolveRemoteProjectMachineIdentity', () => {
});
});
- it('appends the device id only for names shared by more than one device', () => {
+ it('uses an ordinal for names shared by more than one device', () => {
const identity = resolveRemoteProjectMachineIdentity(
{
scope: 'remote',
@@ -95,17 +95,17 @@ describe('resolveRemoteProjectMachineIdentity', () => {
deviceLinkDeviceName: 'Office Mac',
},
[],
- { ambiguousDeviceNames: new Set(['office mac']) },
+ { devices: [{ deviceId: 'device-123', name: 'Office Mac' }, { deviceId: 'device-456', name: 'Office Mac' }] },
);
expect(identity).toEqual({
kind: 'device-link',
- label: 'Office Mac',
- detail: 'device-123',
- displayLabel: 'Office Mac · device-123',
+ label: 'Office Mac (1)',
+ detail: null,
+ displayLabel: 'Office Mac (1)',
});
});
- it('falls back to the device id as the label when no device name resolved', () => {
+ it('uses a readable fallback when no device name resolved', () => {
const identity = resolveRemoteProjectMachineIdentity(
{
scope: 'remote',
@@ -115,12 +115,12 @@ describe('resolveRemoteProjectMachineIdentity', () => {
},
[],
);
- // 名字拿不到时 label 已经是 ID 本身,detail 不再重复一遍。
+ // 无名称也不暴露机器指纹。
expect(identity).toEqual({
kind: 'device-link',
- label: 'device-123',
+ label: 'another computer',
detail: null,
- displayLabel: 'device-123',
+ displayLabel: 'another computer',
});
});
@@ -139,45 +139,14 @@ describe('resolveRemoteProjectMachineIdentity', () => {
});
});
-describe('collectAmbiguousDeviceNames', () => {
- const project = (deviceLinkDeviceId: string | null, deviceLinkDeviceName: string | null) => ({
- deviceLinkDeviceId,
- deviceLinkDeviceName,
- });
-
- it('flags a name only when it maps to more than one device id', () => {
- const ambiguous = collectAmbiguousDeviceNames([
- project('device-a', 'Dash Macbook Pro'),
- project('device-b', 'Dash Macbook Pro'),
- project('device-c', 'Office Mac'),
- ]);
- expect(ambiguous.has('dash macbook pro')).toBe(true);
- expect(ambiguous.has('office mac')).toBe(false);
- });
-
- it('does not flag several projects that live on the same device', () => {
- const ambiguous = collectAmbiguousDeviceNames([
- project('device-a', 'Dash Macbook Pro'),
- project('device-a', 'Dash Macbook Pro'),
- ]);
- expect(ambiguous.size).toBe(0);
- });
-
- it('compares names case-insensitively and ignores surrounding whitespace', () => {
- const ambiguous = collectAmbiguousDeviceNames([
- project('device-a', ' Dash Macbook Pro'),
- project('device-b', 'dash macbook pro '),
- ]);
- expect([...ambiguous]).toEqual(['dash macbook pro']);
- });
-
- it('skips entries without a device id or without a resolved name', () => {
- const ambiguous = collectAmbiguousDeviceNames([
- project(null, 'Dash Macbook Pro'),
- project('device-b', null),
- project('device-c', ' '),
- ]);
- expect(ambiguous.size).toBe(0);
+describe('collectProjectDevices', () => {
+ it('deduplicates project hosts without losing unnamed devices used for display fallback', () => {
+ expect(collectProjectDevices([
+ { deviceLinkDeviceId: 'b', deviceLinkDeviceName: 'Mac' },
+ { deviceLinkDeviceId: 'a', deviceLinkDeviceName: null },
+ { deviceLinkDeviceId: 'b', deviceLinkDeviceName: 'Mac' },
+ { deviceLinkDeviceId: null, deviceLinkDeviceName: null },
+ ])).toEqual([{ deviceId: 'a', name: null }, { deviceId: 'b', name: 'Mac' }]);
});
});
diff --git a/apps/desktop/src/renderer/__tests__/useProjectGroups.test.tsx b/apps/desktop/src/renderer/__tests__/useProjectGroups.test.tsx
index 690eb4c102..4f98bafc71 100644
--- a/apps/desktop/src/renderer/__tests__/useProjectGroups.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/useProjectGroups.test.tsx
@@ -63,7 +63,7 @@ it('updates collision labels when another device starts or stops sharing the nam
});
expect(result.current.projects[0].remoteMachineIdentity?.detail).toBeNull();
rerender({ rows: [rows[0], { ...rows[1], deviceLinkDeviceName: 'Mac' }] });
- expect(result.current.projects[0].remoteMachineIdentity?.detail).toBe('one');
+ expect(result.current.projects[0].remoteMachineIdentity?.displayLabel).toBe('Mac (1)');
rerender({ rows });
expect(result.current.projects[0].remoteMachineIdentity?.detail).toBeNull();
});
diff --git a/apps/desktop/src/renderer/__tests__/useProjectGroupsReuse.test.tsx b/apps/desktop/src/renderer/__tests__/useProjectGroupsReuse.test.tsx
index 4ae28cde0b..7d451ea99f 100644
--- a/apps/desktop/src/renderer/__tests__/useProjectGroupsReuse.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/useProjectGroupsReuse.test.tsx
@@ -96,7 +96,7 @@ describe('project grouping hook references', () => {
const { result, rerender } = renderHook(({ rows }) => useProjectGroups(rows), {
initialProps: { rows },
});
- expect(result.current.projects.every((p) => p.remoteMachineIdentity?.detail)).toBe(true);
+ expect(result.current.projects.map((p) => p.remoteMachineIdentity?.displayLabel).sort()).toEqual(['Same machine (1)', 'Same machine (2)']);
const next = rows.slice();
next[1] = { ...next[1], deviceLinkDeviceName: 'Renamed machine' };
rerender({ rows: next });
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 088bb0398f..7e6710eef6 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import {
useCallback,
useEffect,
@@ -7640,7 +7641,7 @@ export function ChatInput({
? t('newChat.chatInput.agentRelocation.titleOther', { device: target.name })
: deviceLinkDeviceId
? t('newChat.chatInput.agentRelocation.titleOther', {
- device: deviceLinkDeviceName || deviceLinkDeviceId,
+ device: deviceDisplayName(deviceLinkDeviceId, deviceLinkDeviceName),
})
: t('newChat.chatInput.agentRelocation.titleLocal'),
description: t('newChat.chatInput.agentRelocation.description'),
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index 916f5a6983..9d6b499538 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { ProviderShareQuotaViewingContext, useProviderShareQuotaViewing } from '@/features/provider-share/useProviderShareWeeklyQuota';
import { SpeedIcon } from './SpeedIcon';
import { ErrorNotice } from '@/components/ui/error-notice';
@@ -1763,7 +1764,7 @@ function ModelSelectorContentView({
const groupSize = groupMembers ? providerGroupDeviceCount(groupMembers) : readProviderShareGroupSize(provider);
const values = {
provider: provider ? providerDisplayName(provider, t) : providerId,
- device: device?.name || targetDeviceId,
+ device: deviceDisplayName(targetDeviceId, device?.name),
};
return groupSize != null
? t('newChat.modelSelector.unified.railRemoteProviderGroup', {
@@ -1809,7 +1810,7 @@ function ModelSelectorContentView({
);
return {
kind: 'running',
- deviceName: homeDeviceId ? remoteAgent?.homeDeviceName || homeDeviceId : null,
+ deviceName: homeDeviceId ? deviceDisplayName(homeDeviceId, remoteAgent?.homeDeviceName) : null,
usage: provider ? { provider, scope: { deviceId: homeDeviceId ?? null } } : null,
};
}
@@ -3407,7 +3408,7 @@ function ModelSelectorContentView({
const rowEffortValue = rowEffort === '' ? undefined : rowEffort;
const agentDevice = {
deviceId: targetDeviceId,
- name: remoteAgentDevices?.find((device) => device.deviceId === targetDeviceId)?.name || targetDeviceId,
+ name: deviceDisplayName(targetDeviceId, undefined, remoteAgentDevices ?? []),
};
const dismissIfApplied = (applied: boolean) => {
if (applied) {
diff --git a/apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx b/apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx
index 35ebfaa22d..910a88711e 100644
--- a/apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
@@ -8,7 +9,7 @@ import { toast } from '@/lib/toast';
export function PluginSetupRemoteDesktopButton({ deviceId }: { deviceId: string }) {
const { t } = useTranslation();
const devices = useDeviceLinkDeviceList();
- const name = devices?.find((device) => device.deviceId === deviceId)?.name || deviceId;
+ const name = deviceDisplayName(deviceId, undefined, devices ?? []);
const [opening, setOpening] = useState(false);
const mounted = useRef(true);
useEffect(
diff --git a/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx b/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx
index f847462883..0899a794ed 100644
--- a/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx
+++ b/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { Button } from '@/components/ui/button';
/**
* MyDevicesPanel —— 「远程控制」页统一的「我的设备」面板。
@@ -352,7 +353,7 @@ export function MyDevicesPanel({
</div>
) : (
<span className="truncate text-13 font-medium text-[var(--text-primary)]">
- {self?.name || t('settings.devices.thisDevice')}
+ {self?.name?.trim() && self.name.trim() !== self.deviceId ? self.name.trim() : t('settings.devices.thisDevice')}
</span>
)}
<span className="text-11 text-[var(--text-tertiary)]">
@@ -362,11 +363,6 @@ export function MyDevicesPanel({
})
: `${t('settings.devices.thisDevice')} · ${t(`settings.devices.linkStatus.${s.linkStatus}`)}`}
</span>
- {self ? (
- <span className="break-all text-11 text-[var(--text-tertiary)]">
- {self.deviceId}
- </span>
- ) : null}
{activeConnectionIssue ? (
<span className="text-11 text-[var(--error-fg)]">
{t(`settings.devices.connectionIssue.${activeConnectionIssue.kind}`)}
@@ -480,15 +476,12 @@ export function MyDevicesPanel({
</div>
) : (
<span className="truncate text-13 font-medium text-[var(--text-primary)]">
- {d.name}
+ {deviceDisplayName(d.deviceId, d.name, s.devices ?? [])}
</span>
)}
<span className="break-words text-11 text-[var(--text-tertiary)]">
{deviceSubtitle(d, t, { isControlling })}
</span>
- <span className="break-all text-11 text-[var(--text-tertiary)]">
- {d.deviceId}
- </span>
</div>
{editingId !== d.deviceId && (
<div className="flex shrink-0 items-center gap-1">
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botRosterDisplay.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botRosterDisplay.test.ts
index 798974876e..6f87b18a99 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botRosterDisplay.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botRosterDisplay.test.ts
@@ -43,11 +43,11 @@ function bot(
}
describe('Hermes-style Bot roster display', () => {
- it('distinguishes missing and duplicate host names by their actual device IDs', () => {
+ it('distinguishes missing and duplicate host names without exposing device IDs', () => {
const device = { deviceId: 'mac-1', name: ' Studio ' };
expect(botDeviceLabel(device, [device, device])).toBe('Studio');
- expect(botDeviceLabel(device, [device, { deviceId: 'mac-2', name: 'studio' }])).toBe('Studio (mac-1)');
- expect(botDeviceLabel({ deviceId: 'mac-2', name: ' ' }, [])).toBe('mac-2');
+ expect(botDeviceLabel(device, [device, { deviceId: 'mac-2', name: 'studio' }])).toBe('Studio (1)');
+ expect(botDeviceLabel({ deviceId: 'mac-2', name: ' ' }, [])).toBe('another computer');
});
it('sorts pinned Bots first and keeps recency ordering inside both groups', () => {
const rows = sortBotRoster([
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/cindyDeviceRoster.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/cindyDeviceRoster.test.ts
index 5a4c427608..d1cdd223a3 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/cindyDeviceRoster.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/cindyDeviceRoster.test.ts
@@ -87,7 +87,7 @@ describe('Cindy device roster', () => {
{},
'Local',
);
- expect(option.label).toBe('host/name');
+ expect(option.label).toBe('another computer');
expect(option.route).toBe('/bots/remote/host%2Fname/cindy-default');
});
});
diff --git a/apps/desktop/src/renderer/features/bots/botRosterDisplay.ts b/apps/desktop/src/renderer/features/bots/botRosterDisplay.ts
index cc23b86a06..810bd9bb31 100644
--- a/apps/desktop/src/renderer/features/bots/botRosterDisplay.ts
+++ b/apps/desktop/src/renderer/features/bots/botRosterDisplay.ts
@@ -1,18 +1,13 @@
import { withoutBotHiddenLanes } from './botGroupLane';
import type { BotProfile } from './botStore';
+import { deviceDisplayName } from '@/lib/deviceName';
/** Keep unnamed and identically named hosts distinguishable without changing routing IDs. */
export function botDeviceLabel(
device: { deviceId: string; name: string },
devices: readonly { deviceId: string; name: string }[],
): string {
- const name = device.name.trim();
- if (!name) return device.deviceId;
- const duplicate = devices.some(
- (other) => other.deviceId !== device.deviceId
- && other.name.trim().toLocaleLowerCase() === name.toLocaleLowerCase(),
- );
- return duplicate ? `${name} (${device.deviceId})` : name;
+ return deviceDisplayName(device.deviceId, device.name, devices);
}
function finiteTimestamp(value: unknown): number {
diff --git a/apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts b/apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts
index 398329d89b..ac52c15ccd 100644
--- a/apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts
+++ b/apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import type { BotProfile } from './botStore';
import { isRemoteBotUnread, type RemoteBot } from './remoteBotRoster';
@@ -35,14 +36,7 @@ export function cindyDeviceOptions(
): CindyDeviceOption[] {
const self = devices.find((device) => device.isSelf);
const remoteCindys = remoteBots.filter(isCindyDeviceBot);
- const peersByName = new Map<string, string[]>();
- for (const bot of remoteCindys) {
- const name = bot.deviceName.trim().toLocaleLowerCase();
- const peers = peersByName.get(name) ?? [];
- if (!peers.includes(bot.deviceId)) peers.push(bot.deviceId);
- peersByName.set(name, peers);
- }
- for (const peers of peersByName.values()) peers.sort();
+ const peers = remoteCindys.map((bot) => ({ deviceId: bot.deviceId, name: bot.deviceName }));
const local = bots
.filter(
(bot) =>
@@ -63,12 +57,11 @@ export function cindyDeviceOptions(
}));
const remote = remoteCindys
.map((bot) => {
- const name = bot.deviceName.trim() || bot.deviceId;
- const peers = peersByName.get(bot.deviceName.trim().toLocaleLowerCase())!;
+ const name = deviceDisplayName(bot.deviceId, bot.deviceName, peers);
return {
key: cindyDeviceKey(bot),
bot,
- label: peers.length > 1 ? `${name} (${peers.indexOf(bot.deviceId) + 1})` : name,
+ label: name,
deviceName: name,
online: bot.online,
unread: isRemoteBotUnread(bot),
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 35af6dceb5..e52d4b28aa 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { CompanionVoicePanel } from '../bots/voice/CompanionVoicePanel';
import { visibleVoiceCallMessages } from '../bots/voice/VoiceCallTranscript';
import { voiceTaskFailure } from '../bots/voice/VoiceReplyTracker';
@@ -6136,7 +6137,7 @@ function CCAgentSessionContent({
: botChatIdentity
? t(botChatIdentity.deviceId ? 'bots.devicePicker.remotePlaceholder' : botComposerPlaceholderKey(botChatIdentity.name), {
name: botChatIdentity.name,
- device: botChatIdentity.deviceName || botChatIdentity.deviceId,
+ device: deviceDisplayName(botChatIdentity.deviceId ?? '', botChatIdentity.deviceName),
})
: t('ccAgent.layout.chatPlaceholder')
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 1c57743283..e071bc87db 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { useRemoteDraftDefaults, useRemoteDraftSelection, useRemoteDraftPush } from './useRemoteDraftDefaults';
import { isModelEnabled, useModelVisibilityVersion } from '@/state/modelVisibilityPrefs';
/**
@@ -1193,7 +1194,7 @@ export function NewMakerDraftRoute() {
effectiveDeviceLinkDeviceId
? {
deviceId: effectiveDeviceLinkDeviceId,
- deviceName: effectiveDeviceLinkDeviceName ?? effectiveDeviceLinkDeviceId,
+ deviceName: deviceDisplayName(effectiveDeviceLinkDeviceId ?? '', effectiveDeviceLinkDeviceName),
status:
deviceLinkProjectsStatus === 'error'
? 'error'
@@ -3752,7 +3753,7 @@ export function NewMakerDraftRoute() {
// 运行目录(隧道侧 path guard 对「缺 workingDir」本来就是放行的,不放宽任何边界)。
if (isDeviceLinkDraft && effectiveDeviceLinkDeviceId) {
const deviceId = effectiveDeviceLinkDeviceId;
- const deviceName = effectiveDeviceLinkDeviceName ?? deviceId;
+ const deviceName = deviceDisplayName(deviceId, effectiveDeviceLinkDeviceName);
const invokeRemote = async (channel: string, args: unknown[]) => {
if (!isCurrentDataOwner()) {
throw new RemotePrecreatedWorktreeOwnerChangedError();
@@ -4929,7 +4930,7 @@ export function NewMakerDraftRoute() {
throw new Error(t('ccAgent.draft.createSessionFailed'));
}
const deviceId = effectiveDeviceLinkDeviceId;
- const deviceName = effectiveDeviceLinkDeviceName ?? deviceId;
+ const deviceName = deviceDisplayName(deviceId, effectiveDeviceLinkDeviceName);
const ownerAtGoal = dataOwnerAtGoal.dataOwnerId;
const invokeRemote = async (channel: string, args: unknown[]) => {
if (!isCurrentDataOwner()) {
@@ -6027,14 +6028,14 @@ export function NewMakerDraftRoute() {
{effectiveWorkingDir
? t('ccAgent.draft.remoteProjectBanner', {
device:
- effectiveDeviceLinkDeviceName ?? effectiveDeviceLinkDeviceId ?? '',
+ deviceDisplayName(effectiveDeviceLinkDeviceId ?? '', effectiveDeviceLinkDeviceName),
project:
effectiveWorkingDir.split(/[\\/]/).filter(Boolean).pop() ??
effectiveWorkingDir,
})
: t('ccAgent.draft.remoteDialogueBanner', {
device:
- effectiveDeviceLinkDeviceName ?? effectiveDeviceLinkDeviceId ?? '',
+ deviceDisplayName(effectiveDeviceLinkDeviceId ?? '', effectiveDeviceLinkDeviceName),
})}
</span>
</div>
@@ -6055,7 +6056,7 @@ export function NewMakerDraftRoute() {
isDeviceLinkDraft
? 'ccAgent.draft.agentDeviceElsewhereBanner'
: 'ccAgent.draft.agentDeviceBanner',
- { device: draft.agentDeviceName ?? effectiveAgentDeviceId ?? '' },
+ { device: deviceDisplayName(effectiveAgentDeviceId ?? '', draft.agentDeviceName) },
)}
</span>
</div>
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
index 57c425bc8c..aee9d4eedc 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { SessionTaskMenu } from './sidebar/SessionTaskMenu';
import { TaskMigrationStatus } from './TaskMigrationStatus';
/**
@@ -102,7 +103,7 @@ function AgentDeviceIndicator({
// 分享来的供应商(`share:<id>`)不在同账号设备列表里,名字取自已收到的分享。
const { nameFor: providerShareDeviceName } = useProviderShareAgentDevices();
const device = devices?.find((item) => item.deviceId === deviceId);
- const name = device?.name || providerShareDeviceName(deviceId) || deviceId;
+ const name = deviceDisplayName(deviceId, device?.name || providerShareDeviceName(deviceId));
const offline = device ? !device.online : false;
const vendor = agentKindToVendor(agentKind);
return (
@@ -620,7 +621,7 @@ export function SessionContentHeader({
{!isEditing && remoteIconKind && (
<Tip
text={
- session.deviceLinkDeviceName ?? session.deviceLinkDeviceId ?? session.remoteHostId ?? ''
+ session.deviceLinkDeviceId ? deviceDisplayName(session.deviceLinkDeviceId, session.deviceLinkDeviceName) : session.remoteHostId ?? ''
}
>
<RemoteProjectIcon
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts
index 4bec528c64..dca4c82976 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts
@@ -21,7 +21,7 @@ import {
type ProjectNode,
} from '../lib/projectGrouping';
import {
- collectAmbiguousDeviceNames,
+ collectProjectDevices,
resolveRemoteProjectMachineIdentity,
} from '../lib/remoteProjectIdentity';
@@ -71,11 +71,11 @@ export function useProjectGroups(
botOwnerBySessionId,
provisionalDraftTaskId,
]);
- const ambiguousDeviceNames = useMemo(
- () => collectAmbiguousDeviceNames(groups.projects),
+ const projectDevices = useMemo(
+ () => collectProjectDevices(groups.projects),
[groups.projects],
);
- const ambiguityKey = JSON.stringify([...ambiguousDeviceNames].sort());
+ const ambiguityKey = JSON.stringify(projectDevices);
// Weak keys keep only live grouping nodes. Registry/collision changes must
// re-enrich even unchanged nodes so remote labels never retain stale names.
const enrichedProjects = useMemo(
@@ -92,12 +92,12 @@ export function useProjectGroups(
const enriched = {
...project,
remoteMachineIdentity: resolveRemoteProjectMachineIdentity(project, sshHosts, {
- ambiguousDeviceNames,
+ devices: projectDevices,
}),
};
enrichedProjects.set(project, enriched);
return enriched;
}),
};
- }, [groups, equivalentResult, enrichedProjects, sshHosts, ambiguousDeviceNames]);
+ }, [groups, equivalentResult, enrichedProjects, sshHosts, projectDevices]);
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/remoteProjectIdentity.ts b/apps/desktop/src/renderer/features/cc-agent/lib/remoteProjectIdentity.ts
index 3809638381..ffa9581c6f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/remoteProjectIdentity.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/remoteProjectIdentity.ts
@@ -1,9 +1,12 @@
+import { deviceDisplayName } from '@/lib/deviceName';
+import type { DeviceNameSource } from '@cindy/maker-shared/device-list';
+
/** 远程项目在 UI 中显示的机器身份,统一供项目树、搜索与筛选使用。 */
export interface RemoteProjectMachineIdentity {
kind: 'ssh' | 'device-link';
- /** 主要身份:SSH alias、设备名,或无法解析时的持久化 id。 */
+ /** 主要身份:SSH alias、设备名,或本地化的未命名提示。 */
label: string;
- /** 补充身份:user@hostname[:port] 或设备 id。 */
+ /** 补充身份:user@hostname[:port] ;设备互联不附加原始 ID。 */
detail: string | null;
/** 适合 tooltip / 紧凑元信息行的完整单行文案。 */
displayLabel: string;
@@ -21,46 +24,21 @@ function joinIdentity(label: string, detail: string | null): string {
return detail ? `${label} · ${detail}` : label;
}
-/** 设备名归一(比对同名用):去空白 + 小写。 */
-function deviceNameKey(name: string): string {
- return name.trim().toLowerCase();
-}
-
export interface ResolveRemoteProjectIdentityOptions {
- /**
- * 「同名但不同设备」的设备名集合(deviceNameKey 归一后)。
- * device-link 的设备 ID 是机器指纹哈希,对用户没有可读意义,默认**不显示**
- * (2026-08-12 用户裁决);只有两台设备撞名、光看名字分不出来时才附在名字后面消歧。
- */
- ambiguousDeviceNames?: ReadonlySet<string>;
+ devices?: readonly DeviceNameSource[];
}
-/**
- * 从一批远程项目里找出需要显示设备 ID 消歧的设备名——同一个名字对应了两个以上
- * 不同 deviceId 时才算撞名。只统计真的有项目会渲染的设备:没有项目的同名设备不会
- * 在列表里出现,不构成用户看得见的歧义。
- */
-export function collectAmbiguousDeviceNames(
- projects: readonly Pick<
- RemoteProjectIdentitySource,
- 'deviceLinkDeviceId' | 'deviceLinkDeviceName'
- >[],
-): ReadonlySet<string> {
- const idsByName = new Map<string, Set<string>>();
+/** Visible project hosts, deduplicated by identity for compact name disambiguation. */
+export function collectProjectDevices(
+ projects: readonly Pick<RemoteProjectIdentitySource, 'deviceLinkDeviceId' | 'deviceLinkDeviceName'>[],
+): DeviceNameSource[] {
+ const devices = new Map<string, DeviceNameSource>();
for (const project of projects) {
- const deviceId = project.deviceLinkDeviceId;
- const name = project.deviceLinkDeviceName?.trim();
- if (!deviceId || !name) continue;
- const key = deviceNameKey(name);
- const ids = idsByName.get(key);
- if (ids) ids.add(deviceId);
- else idsByName.set(key, new Set([deviceId]));
- }
- const ambiguous = new Set<string>();
- for (const [key, ids] of idsByName) {
- if (ids.size > 1) ambiguous.add(key);
+ if (project.deviceLinkDeviceId) devices.set(project.deviceLinkDeviceId, {
+ deviceId: project.deviceLinkDeviceId, name: project.deviceLinkDeviceName,
+ });
}
- return ambiguous;
+ return [...devices.values()].sort((a, b) => a.deviceId.localeCompare(b.deviceId));
}
/** 把项目持久化身份与当前 SSH registry 合并成稳定、可读的展示模型。 */
@@ -72,14 +50,8 @@ export function resolveRemoteProjectMachineIdentity(
if (project.scope !== 'remote') return null;
if (project.deviceLinkDeviceId) {
- const resolvedName = project.deviceLinkDeviceName?.trim();
- const name = resolvedName || project.deviceLinkDeviceId;
- // 设备 ID 只在撞名时才露出来消歧(见 ResolveRemoteProjectIdentityOptions);
- // 名字都拿不到时 label 已经退化成 ID 本身,不再重复附一遍。
- const detail =
- resolvedName && options?.ambiguousDeviceNames?.has(deviceNameKey(resolvedName))
- ? project.deviceLinkDeviceId
- : null;
+ const name = deviceDisplayName(project.deviceLinkDeviceId, project.deviceLinkDeviceName, options?.devices);
+ const detail = null;
return {
kind: 'device-link',
label: name,
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx
index 4942a44a6a..a0183c84fe 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { MountedMenuContent } from '../MountedMenuContent';
/**
* ProjectNode — 单个 Project 节点(Header + 受控折叠的子 sessions)
@@ -480,7 +481,7 @@ const ProjectHeader = memo(function ProjectHeader({
<span className="min-w-0 max-w-full shrink truncate">{project.displayName}</span>
)}
{!isEditingName && isDeviceLink ? (
- <Tip text={remoteIdentity?.displayLabel ?? project.deviceLinkDeviceId ?? ''}>
+ <Tip text={remoteIdentity?.displayLabel ?? deviceDisplayName(project.deviceLinkDeviceId ?? '', project.deviceLinkDeviceName)}>
<RemoteProjectIcon
kind="device-link"
connectionStatus={project.deviceLinkConnectionStatus}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
index a9a1aa0452..30fc3e2f3c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { isCindyMakeFamilySource } from '../../../../../shared/cindyMakeMerge';
/**
* ProjectsSection — Sidebar 中部的 Projects 段
@@ -1215,7 +1216,7 @@ export function ProjectsSection({
? remoteDeviceIndex?.get(section.deviceId)
: undefined;
const name = section.deviceId
- ? (device?.name ?? cachedDeviceNames.get(section.deviceId) ?? section.deviceId)
+ ? (deviceDisplayName(section.deviceId, device?.name ?? cachedDeviceNames.get(section.deviceId)))
: t('ccAgent.sidebar.deviceGroup.local');
const online = section.deviceId ? (device?.online ?? false) : true;
const sectionCollapsed = collapsedDevices.has(key);
diff --git a/apps/desktop/src/renderer/features/device-link/switcherDevices.ts b/apps/desktop/src/renderer/features/device-link/switcherDevices.ts
index c649f6bb2d..ac3604b117 100644
--- a/apps/desktop/src/renderer/features/device-link/switcherDevices.ts
+++ b/apps/desktop/src/renderer/features/device-link/switcherDevices.ts
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
/**
* switcherDevices —— 机器切换栏设备列表 + 三态分类(纯函数,可单测)。
* ---------------------------------------------------------------------------
@@ -72,6 +73,7 @@ export function buildSwitcherDevices({
for (const id of selfIds) candidates.delete(id);
for (const id of mobileIds) candidates.delete(id);
+ const nameSources = [...candidates].map((deviceId) => ({ deviceId, name: nameById.get(deviceId) }));
const devices: SwitcherDevice[] = [];
for (const deviceId of candidates) {
// Shared tasks belong to task navigation, never the device selector.
@@ -83,7 +85,7 @@ export function buildSwitcherDevices({
} else if (cachedDevice && cachedDevice.connected !== false) {
status = 'connected';
}
- devices.push({ deviceId, name: nameById.get(deviceId) || deviceId, status });
+ devices.push({ deviceId, name: deviceDisplayName(deviceId, nameById.get(deviceId), nameSources), status });
}
// 统一按稳定身份(名字 → deviceId)排,不含状态/在线/时间 → 状态抖动不改变顺序
diff --git a/apps/desktop/src/renderer/features/input-handoff/InputHandoffCard.tsx b/apps/desktop/src/renderer/features/input-handoff/InputHandoffCard.tsx
index cebe63fe10..0bde6dd768 100644
--- a/apps/desktop/src/renderer/features/input-handoff/InputHandoffCard.tsx
+++ b/apps/desktop/src/renderer/features/input-handoff/InputHandoffCard.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
/**
* InputHandoffCard (代输入)
* ---------------------------------------------------------------------------
@@ -450,7 +451,7 @@ function LiveViewLink({ deviceId, requestId }: { deviceId: string; requestId: st
},
[],
);
- const name = devices?.find((device) => device.deviceId === deviceId)?.name || deviceId;
+ const name = deviceDisplayName(deviceId, undefined, devices ?? []);
return (
<QuietLink
disabled={opening}
diff --git a/apps/desktop/src/renderer/features/learn/LearnStatusCard.tsx b/apps/desktop/src/renderer/features/learn/LearnStatusCard.tsx
index 874f2aa561..57bd2fbc08 100644
--- a/apps/desktop/src/renderer/features/learn/LearnStatusCard.tsx
+++ b/apps/desktop/src/renderer/features/learn/LearnStatusCard.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { Button } from '@/components/ui/button';
/**
* LearnStatusCard —— /learn 蒸馏 run 的聊天流状态卡(systemCardType='learn')。
@@ -77,7 +78,7 @@ export function LearnStatusCard({ data, contextSessionId }: LearnStatusCardProps
if (cardDeviceId && distillSessionOrigin === undefined) {
void refreshRemoteDeviceSessions(
cardDeviceId,
- remoteProjectsStore.getDeviceName(cardDeviceId) ?? cardDeviceId,
+ deviceDisplayName(cardDeviceId, remoteProjectsStore.getDeviceName(cardDeviceId)),
);
return;
}
diff --git a/apps/desktop/src/renderer/features/provider-share/ProviderShareManagePage.tsx b/apps/desktop/src/renderer/features/provider-share/ProviderShareManagePage.tsx
index b32b9190e1..6ec3c66fc0 100644
--- a/apps/desktop/src/renderer/features/provider-share/ProviderShareManagePage.tsx
+++ b/apps/desktop/src/renderer/features/provider-share/ProviderShareManagePage.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { ProviderShareVisibilitySection } from './ProviderShareVisibilitySection';
import { SubscriptionFastSetting } from './SubscriptionFastSetting';
import { RemoteModelAccessSection, RemoteModelAccessDialog } from './RemoteModelAccessSection';
@@ -375,7 +376,7 @@ export function ProviderShareManagePage({
{deviceId && (
<p className="mt-2 text-12 leading-[1.5] text-[var(--settings-section-desc)]">
- {t('providerGroup.management.note', { device: selfDeviceName ?? deviceId })}
+ {t('providerGroup.management.note', { device: deviceDisplayName(deviceId ?? '', selfDeviceName) })}
</p>
)}
diff --git a/apps/desktop/src/renderer/features/remote-desktop/TaskRemoteDesktopButton.tsx b/apps/desktop/src/renderer/features/remote-desktop/TaskRemoteDesktopButton.tsx
index e1bfcdbbc6..1e1d19c13a 100644
--- a/apps/desktop/src/renderer/features/remote-desktop/TaskRemoteDesktopButton.tsx
+++ b/apps/desktop/src/renderer/features/remote-desktop/TaskRemoteDesktopButton.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { useEffect, useRef, useState } from 'react';
import { LoaderCircle, Monitor, MonitorOff } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -28,7 +29,7 @@ export function TaskRemoteDesktopButton({
}) {
const { t } = useTranslation();
const devices = useDeviceLinkDeviceList();
- const name = devices?.find((device) => device.deviceId === deviceId)?.name || deviceId;
+ const name = deviceDisplayName(deviceId, undefined, devices ?? []);
const availability = useRemoteDesktopAvailability(deviceId);
const [opening, setOpening] = useState(false);
const mounted = useRef(true);
diff --git a/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx b/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx
index 1dddecc1f6..edd145beec 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
import { Button } from '@/components/ui/button';
import { useModelPickerAgents } from '@/hooks/useAvailableAgents';
import * as React from 'react';
@@ -1154,7 +1155,7 @@ export function ModelEffortChip({
: undefined;
}, [agentDeviceId, remoteLocation, routeDevices.devices]);
const agentDeviceName = agentDeviceId
- ? (routeDevices.devices?.find((device) => device.deviceId === agentDeviceId)?.name || agentDeviceId)
+ ? (deviceDisplayName(agentDeviceId, undefined, routeDevices.devices ?? []))
: null;
const xdConnected = providers.some((p) => p.id === 'xd' && p.connected);
const availableModels = caps.capabilities?.availableModels;
diff --git a/apps/desktop/src/renderer/hooks/useVendorAuthGate.ts b/apps/desktop/src/renderer/hooks/useVendorAuthGate.ts
index d8c900f4f4..e97396612a 100644
--- a/apps/desktop/src/renderer/hooks/useVendorAuthGate.ts
+++ b/apps/desktop/src/renderer/hooks/useVendorAuthGate.ts
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/lib/deviceName';
/**
* useVendorAuthGate —— vendor 未就绪时弹通用 confirmDialog,确认后跳 settings。
*
@@ -329,7 +330,7 @@ export function useVendorAuthGate(): UseVendorAuthGateReturn {
// 直接说清哪台设备缺什么、去那台设备的哪个设置页处理:
// codex 二进制缺失 → 组件未就绪;来源未就绪 → 该 agent 暂无已连接的模型来源
// (去「设置 → 模型供应商」;codex / cc 文案对称)。
- const device = remoteProjectsStore.getDeviceName(deviceId) ?? deviceId;
+ const device = deviceDisplayName(deviceId, remoteProjectsStore.getDeviceName(deviceId));
let title: string;
let description: string;
if (remoteReadiness === 'binary-missing') {
diff --git a/apps/desktop/src/renderer/lib/deviceName.ts b/apps/desktop/src/renderer/lib/deviceName.ts
new file mode 100644
index 0000000000..968453533b
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/deviceName.ts
@@ -0,0 +1,6 @@
+import { deviceDisplayName as displayName, type DeviceNameSource } from '@cindy/maker-shared/device-list';
+import i18n from '@/i18n';
+
+export function deviceDisplayName(deviceId: string, name?: string | null, devices: readonly DeviceNameSource[] = []): string {
+ return displayName(deviceId, name, i18n.t('bots.cloud.unknownDevice'), devices);
+}
diff --git a/apps/mobile/app/companions/cloud/[actorId].tsx b/apps/mobile/app/companions/cloud/[actorId].tsx
index 013c3442e6..4c58522272 100644
--- a/apps/mobile/app/companions/cloud/[actorId].tsx
+++ b/apps/mobile/app/companions/cloud/[actorId].tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { useLocalSearchParams } from 'expo-router';
import { useAuth } from '@/auth/AuthContext';
import { CloudCompanionScreen } from '@/session/CloudCompanionScreen';
@@ -18,5 +19,5 @@ export default function CloudCompanionRoute() {
const actorId = firstParam(params.actorId);
const deviceId = firstParam(params.deviceId);
return <CloudCompanionScreen key={`${accountGeneration}:${actorId}`} actorId={actorId} botId={firstParam(params.botId)}
- deviceId={deviceId} deviceName={firstParam(params.deviceName) || deviceId} title={firstParam(params.title)} />;
+ deviceId={deviceId} deviceName={deviceDisplayName(deviceId, firstParam(params.deviceName))} title={firstParam(params.title)} />;
}
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index 5776e4c3f6..1f32dbf15e 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';
import { withNewSessionCreationRemoval } from '@/session/newSessionCreation';
import { useHeaderHeight } from 'expo-router/react-navigation';
@@ -172,7 +173,7 @@ function DeviceDetailScreenContent() {
search?: string;
}>();
const deviceId = readRouteString(params.deviceId) ?? '';
- const deviceName = readRouteString(params.name) ?? readRouteString(params.deviceName) ?? deviceId;
+ const deviceName = deviceDisplayName(deviceId, readRouteString(params.name) ?? readRouteString(params.deviceName));
// 从首页「查看全部 N 条对话」进来时带 workingDir + 项目名 → 仅显示该项目的会话(项目作用域)。
const projectWorkingDir = readRouteString(params.workingDir);
const routeProjectName = readRouteString(params.projectName);
diff --git a/apps/mobile/app/files/[sessionId].tsx b/apps/mobile/app/files/[sessionId].tsx
index a5618855d6..9fc802ed22 100644
--- a/apps/mobile/app/files/[sessionId].tsx
+++ b/apps/mobile/app/files/[sessionId].tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { FileTypeIcon, pickFileIcon } from '@/components/FileTypeIcon';
import { FileTypeTile } from '@/components/FileTypeTile';
import { SystemNavigationBack, useSystemNavigationBack } from '@/platform/chrome/SystemNavigationBack';
@@ -147,7 +148,7 @@ function RemoteFileBrowserContent() {
const sessionId = String(params.sessionId ?? '');
const routeDeviceId = readRouteString(params.deviceId);
const deviceId = routeDeviceId ?? remoteSessionStore.getSessionDeviceId(sessionId) ?? '';
- const deviceName = readRouteString(params.deviceName) ?? deviceId;
+ const deviceName = deviceDisplayName(deviceId, readRouteString(params.deviceName));
const relPath = readRouteString(params.relPath) ?? '';
const router = useRouter();
const guardedPush = useGuardedPush();
diff --git a/apps/mobile/app/resources/[collectionId]/[resourceId].tsx b/apps/mobile/app/resources/[collectionId]/[resourceId].tsx
index 556bf0ad7e..b6ab6e433e 100644
--- a/apps/mobile/app/resources/[collectionId]/[resourceId].tsx
+++ b/apps/mobile/app/resources/[collectionId]/[resourceId].tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { randomUUID } from 'expo-crypto';
import { useAuth } from '@/auth/AuthContext';
import { Redirect, useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
@@ -54,7 +55,7 @@ function RemoteResourceResolverScreenContent() {
const resourceId = firstParam(params.resourceId);
const resourceKind = firstParam(params.resourceKind);
const deviceId = firstParam(params.deviceId);
- const deviceName = firstParam(params.deviceName) || deviceId;
+ const deviceName = deviceDisplayName(deviceId, firstParam(params.deviceName));
const title = firstParam(params.title) || t('devices.resources.titleFallback');
const host = useMemo<RemoteResourceHostTarget>(
() => ({ deviceId, deviceName }),
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 1d6fad4e16..26f0e2d2b0 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { SessionQuickSendProvider } from '@/session/SessionQuickSendContext';
import { incomingShareSlotOrder } from '@/session/mobileLocalAttachmentUpload';
import { useIncomingShareComposer } from '@/session/useIncomingShareComposer';
@@ -1068,7 +1069,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
// 覆盖切回后新发起的预览);代际每次 session 变化都递增,能正确作废这类请求,也能让同一 session 内
// 新发起的请求作废旧请求。
const rewindRequestSeqRef = useRef(0);
- const deviceName = readRouteParam(params.deviceName) ?? deviceId;
+ const deviceName = deviceDisplayName(deviceId, readRouteParam(params.deviceName));
useFocusEffect(useCallback(() => {
rememberRecentTask({ pathname: '/sessions/[sessionId]', params: { deviceId, deviceName, sessionId } });
}, [deviceId, deviceName, sessionId]));
@@ -3024,7 +3025,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
})();
const remoteAgentDeviceName = useCallback(
(agentDeviceId: string) =>
- remoteAgentCatalogs.find((item) => item.deviceId === agentDeviceId)?.name ?? agentDeviceId,
+ deviceDisplayName(agentDeviceId, undefined, remoteAgentCatalogs),
[remoteAgentCatalogs],
);
const adaptiveWindow = useAdaptiveWindow();
@@ -3166,7 +3167,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
discardSessionComposerAttachmentStateRef.current();
switchDrawerSessionInPlace(navigation, {
deviceId: targetDeviceId,
- deviceName: targetSession.deviceLinkDeviceName ?? targetDeviceId,
+ deviceName: deviceDisplayName(targetDeviceId, targetSession.deviceLinkDeviceName),
sessionId: targetSession.id,
...(focusClientId ? { focusClientId } : {}),
});
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index f8010e5748..47d167d88d 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import {
reconcileNewSessionCatalogDraft,
reconcileNewSessionSubmitDraft,
@@ -514,7 +515,7 @@ function NewRemoteSessionContent({ creatingRef }: { creatingRef: { current: bool
creationError?: string;
}>();
const routeDeviceId = String(params.deviceId ?? '');
- const routeDeviceName = String(params.deviceName ?? routeDeviceId);
+ const routeDeviceName = deviceDisplayName(routeDeviceId, typeof params.deviceName === 'string' ? params.deviceName : undefined);
const initialWorkingDir = readRouteString(params.workingDir);
const visualFocusComposer = MOBILE_VISUAL_MOCK_ENABLED && readRouteString(params.visualFocusComposer) === '1';
// The home action lands in the compact pill; only a user's tap opens the card and keyboard.
@@ -550,7 +551,7 @@ function NewRemoteSessionContent({ creatingRef }: { creatingRef: { current: bool
const deviceLinkStatusRef = useRef(deviceLinkStatus);
deviceLinkStatusRef.current = deviceLinkStatus;
const routeDeviceFallback = useMemo<NewSessionDeviceOption | null>(
- () => routeDeviceId ? { deviceId: routeDeviceId, name: routeDeviceName || routeDeviceId } : null,
+ () => routeDeviceId ? { deviceId: routeDeviceId, name: deviceDisplayName(routeDeviceId, routeDeviceName) } : null,
[routeDeviceId, routeDeviceName],
);
const deviceOptions = useMemo(
@@ -580,7 +581,7 @@ function NewRemoteSessionContent({ creatingRef }: { creatingRef: { current: bool
() => deviceOptions.find((option) => option.deviceId === selectedDeviceId) ?? routeDeviceFallback,
[deviceOptions, routeDeviceFallback, selectedDeviceId],
);
- const selectedDeviceLabel = selectedDeviceOption?.name || selectedDeviceName || selectedDeviceId || t('session.new.selectDevice');
+ const selectedDeviceLabel = selectedDeviceId ? deviceDisplayName(selectedDeviceId, selectedDeviceOption?.name || selectedDeviceName) : t('session.new.selectDevice');
const maker = useMobileMakerTransport(selectedDeviceId);
const sessions = useRemoteSessions();
const projectAliases = useRemoteProjectAliases([selectedDeviceId]);
@@ -1817,11 +1818,11 @@ function NewRemoteSessionContent({ creatingRef }: { creatingRef: { current: bool
const previousDeviceId = selectedDeviceIdRef.current;
selectedDeviceIdRef.current = option.deviceId;
setSelectedDeviceId(option.deviceId);
- setSelectedDeviceName(option.name || option.deviceId);
+ setSelectedDeviceName(deviceDisplayName(option.deviceId, option.name));
void saveNewSessionPreferences({
device: {
deviceId: option.deviceId,
- name: option.name || option.deviceId,
+ name: deviceDisplayName(option.deviceId, option.name),
},
});
setDevicePickerOpen(false);
@@ -3986,7 +3987,7 @@ function NewRemoteSessionContent({ creatingRef }: { creatingRef: { current: bool
workspaceKind: effectiveDraft.workspaceKind,
device: {
deviceId: selectedDeviceId,
- name: selectedDeviceName || selectedDeviceId,
+ name: deviceDisplayName(selectedDeviceId, selectedDeviceName),
},
});
const creatingWorktree = worktreeIntent.applicable
@@ -4558,7 +4559,7 @@ function NewRemoteSessionContent({ creatingRef }: { creatingRef: { current: bool
workspaceKind: draft.workspaceKind,
device: {
deviceId: selectedDeviceId,
- name: selectedDeviceName || selectedDeviceId,
+ name: deviceDisplayName(selectedDeviceId, selectedDeviceName),
},
});
// 提交点联合终检(同 create(),代际安全版独立 review P1-1/P1-2):唯一数据源 =
@@ -5126,7 +5127,7 @@ function NewRemoteSessionContent({ creatingRef }: { creatingRef: { current: bool
const selected = option.deviceId === selectedDeviceId;
return (
<Pressable
- accessibilityLabel={t('session.new.selectDeviceNamed', { name: option.name || option.deviceId })}
+ accessibilityLabel={t('session.new.selectDeviceNamed', { name: deviceDisplayName(option.deviceId, option.name) })}
accessibilityRole="button"
key={option.deviceId}
onPress={() => selectDevice(option)}
@@ -5139,7 +5140,7 @@ function NewRemoteSessionContent({ creatingRef }: { creatingRef: { current: bool
strokeWidth={iconStroke.thin}
/>
<Text style={styles.deviceOptionText} numberOfLines={1}>
- {option.name || option.deviceId}
+ {deviceDisplayName(option.deviceId, option.name)}
</Text>
{selected ? (
<Check color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.medium} />
diff --git a/apps/mobile/src/__tests__/cloudCompanion.test.ts b/apps/mobile/src/__tests__/cloudCompanion.test.ts
index f754b4c443..d8b072e1fe 100644
--- a/apps/mobile/src/__tests__/cloudCompanion.test.ts
+++ b/apps/mobile/src/__tests__/cloudCompanion.test.ts
@@ -36,7 +36,7 @@ describe('cloud companion rows', () => {
expect(rows.find(item => item.item.ref.id === 'dash')?.host.deviceName).toBe('Studio');
// A new phone that never saw the main computer still gets an entry for the cloud conversation.
const mia = rows.find(item => item.item.ref.id === 'mia')!;
- expect(mia.host).toEqual({ deviceId: 'mac-c', deviceName: 'mac-c' });
+ expect(mia.host).toEqual({ deviceId: 'mac-c', deviceName: 'another computer' });
expect(mia.item.display).toMatchObject({ title: 'mia', avatar: { kind: 'emoji', value: '🦊' } });
expect(cloudActorForRow(actors, mia)?.id).toBe(id(5));
expect(cloudCompanionRows(items, []).map(item => item.key)).toEqual(items.map(item => item.key));
diff --git a/apps/mobile/src/__tests__/homeProjectMachineIdentity.test.ts b/apps/mobile/src/__tests__/homeProjectMachineIdentity.test.ts
index 3d1003b905..c1662400a2 100644
--- a/apps/mobile/src/__tests__/homeProjectMachineIdentity.test.ts
+++ b/apps/mobile/src/__tests__/homeProjectMachineIdentity.test.ts
@@ -1,3 +1,4 @@
+import i18n from '@/i18n';
import { describe, expect, it } from 'vitest';
import type { MobileHomeDeviceFilterItem, MobileHomeProjectGroup } from '@/session/mobileHome';
import { buildHomeProjectMachineIdentities } from '@/session/homeProjectMachineIdentity';
@@ -41,8 +42,8 @@ describe('project machine identity parity with Desktop', () => {
projects: [project('a', 'one', 'MacBook'), project('b', 'two', 'macbook')],
deviceFilters, selectedDeviceId: null,
}, connected);
- expect(result.get('a')?.displayLabel).toBe('MacBook · one');
- expect(result.get('b')?.displayLabel).toBe('macbook · two');
+ expect(result.get('a')?.displayLabel).toBe('MacBook (1)');
+ expect(result.get('b')?.displayLabel).toBe('macbook (2)');
const onlyOneVisible = buildHomeProjectMachineIdentities({
projects: [project('a', 'one', 'MacBook')], deviceFilters, selectedDeviceId: null,
}, connected);
@@ -104,13 +105,13 @@ describe('project machine identity parity with Desktop', () => {
expect([...buildHomeProjectMachineIdentities(home, evidence).values()].map(row => row.disconnected)).toEqual([false, false]);
});
- it('uses the current device name, falls back to ID for empty names, and skips unowned folders', () => {
+ it('uses the current device name, uses a readable fallback for empty names, and skips unowned folders', () => {
const result = buildHomeProjectMachineIdentities({
projects: [project('a', 'mac', 'Old name'), project('b', 'win', ''), project('c', null, '')],
deviceFilters: [device('mac', 'Renamed Mac'), device('win', ' ')], selectedDeviceId: null,
}, connected);
expect(result.get('a')?.displayLabel).toBe('Renamed Mac');
- expect(result.get('b')?.displayLabel).toBe('win');
+ expect(result.get('b')?.displayLabel).toBe(i18n.t('devices.cloudCompanion.unknownDevice'));
expect(result.has('c')).toBe(false);
});
});
diff --git a/apps/mobile/src/__tests__/mobileVoiceDictionaryView.test.ts b/apps/mobile/src/__tests__/mobileVoiceDictionaryView.test.ts
index e15e6430ec..9f9346cbf2 100644
--- a/apps/mobile/src/__tests__/mobileVoiceDictionaryView.test.ts
+++ b/apps/mobile/src/__tests__/mobileVoiceDictionaryView.test.ts
@@ -71,11 +71,11 @@ describe('collectMobileVoiceDictionaryHosts', () => {
]);
});
- it('设备没有名字时回退到 deviceId 前缀,不显示空标题', () => {
+ it('设备没有名字时显示可读提示,不显示 ID', () => {
const [host] = collectMobileVoiceDictionaryHosts([
device({ deviceId: 'abcdef1234567890', name: ' ' }),
]);
- expect(host.name).toBe('abcdef12');
+ expect(host.name).toBe('another computer');
});
it('平台判定只认桌面三件套', () => {
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index e81631a580..feb412e2b1 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -1678,7 +1678,7 @@ describe('new session model', () => {
expect(parseNewSessionDeviceOptions(encoded)).toEqual([
{ deviceId: 'pc', name: 'PC' },
- { deviceId: 'mac', name: 'mac' },
+ { deviceId: 'mac', name: '另一台电脑' },
]);
});
@@ -1687,7 +1687,7 @@ describe('new session model', () => {
{ deviceId: 'pc', name: 'PC' },
]);
expect(parseNewSessionDeviceOptions('not-json', { deviceId: 'pc', name: '' })).toEqual([
- { deviceId: 'pc', name: 'pc' },
+ { deviceId: 'pc', name: '另一台电脑' },
]);
expect(parseNewSessionDeviceOptions('')).toEqual([]);
});
diff --git a/apps/mobile/src/__tests__/remoteAgentCatalogs.test.ts b/apps/mobile/src/__tests__/remoteAgentCatalogs.test.ts
index 502928be70..291dea5077 100644
--- a/apps/mobile/src/__tests__/remoteAgentCatalogs.test.ts
+++ b/apps/mobile/src/__tests__/remoteAgentCatalogs.test.ts
@@ -50,7 +50,7 @@ describe('remote Agent catalogs', () => {
keepDeviceIds: [],
revokedDeviceIds: new Set(['revoked']),
})).toEqual([
- { deviceId: 'unnamed', name: 'unnamed', canOpen: true },
+ { deviceId: 'unnamed', name: 'another computer', canOpen: true },
{ deviceId: 'office', name: 'Office PC', canOpen: true },
{ deviceId: 'studio', name: 'Studio Mac', canOpen: true },
]);
diff --git a/apps/mobile/src/chat/cloudCompanion.ts b/apps/mobile/src/chat/cloudCompanion.ts
index e1524255dc..5cf067b9bd 100644
--- a/apps/mobile/src/chat/cloudCompanion.ts
+++ b/apps/mobile/src/chat/cloudCompanion.ts
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
/**
* 云端伙伴(docs/product-rules/cloud-companions.md §3.1)在手机上的纯逻辑:哪一行能在主力电脑离线时
* 打开云端对话、同一伙伴只在主力电脑名下列一行(没见过的主力电脑补一行离线入口)、换电脑后的等待与超时。
@@ -51,7 +52,7 @@ export function cloudCompanionRows(items: readonly HostedRemoteCollectionItem[],
const deviceId = actor.homeDeviceId!;
if (listed.some(row => row.item.ref.kind === 'bot' && row.item.ref.id === actor.externalId && row.host.deviceId === deviceId)) return [];
const ref = { collectionId: TEAMMATES, kind: 'bot', id: actor.externalId };
- return [{ key: JSON.stringify([deviceId, ref.collectionId, ref.kind, ref.id]), host: { deviceId, deviceName: deviceNames.get(deviceId) ?? deviceId },
+ return [{ key: JSON.stringify([deviceId, ref.collectionId, ref.kind, ref.id]), host: { deviceId, deviceName: deviceDisplayName(deviceId, deviceNames.get(deviceId)) },
item: { ref, display: { title: actor.name, avatar: cloudAvatar(actor) }, links: [], revision: CLOUD_ROW_REVISION } }];
});
return [...listed, ...added];
diff --git a/apps/mobile/src/device-link/DeviceManagementList.ios.tsx b/apps/mobile/src/device-link/DeviceManagementList.ios.tsx
index e9c7177da8..772829d226 100644
--- a/apps/mobile/src/device-link/DeviceManagementList.ios.tsx
+++ b/apps/mobile/src/device-link/DeviceManagementList.ios.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from './deviceName';
import { useMemo, useState } from 'react';
import { Host, ListItem } from '@expo/ui';
import { Button, Circle, HStack, List, Section, SwipeActions, Text } from '@expo/ui/swift-ui';
@@ -86,7 +87,7 @@ export function DeviceManagementList({
foregroundStyle({ type: 'hierarchical', style: 'primary' }),
]}
>
- {device.name}
+ {deviceDisplayName(device.deviceId, device.name)}
</Text>
</ListItem>
<SwipeActions.Actions edge="leading" allowsFullSwipe={false}>
diff --git a/apps/mobile/src/device-link/DeviceManagementList.tsx b/apps/mobile/src/device-link/DeviceManagementList.tsx
index 11ec6747b0..d679b0e27c 100644
--- a/apps/mobile/src/device-link/DeviceManagementList.tsx
+++ b/apps/mobile/src/device-link/DeviceManagementList.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from './deviceName';
import { useCallback, useMemo, useRef, useState } from 'react';
import { Pressable, RefreshControl, ScrollView, StyleSheet, View } from 'react-native';
import { useTranslation } from 'react-i18next';
@@ -146,7 +147,7 @@ function DeviceRow({
onSwipeableWillOpen={() => onWillOpen(ref.current)}
>
<Pressable
- accessibilityLabel={t('devices.management.openDevice', { name: row.device.name })}
+ accessibilityLabel={t('devices.management.openDevice', { name: deviceDisplayName(row.device.deviceId, row.device.name) })}
accessibilityRole="button"
onPress={() => onOpen(row.device)}
testID={`deviceManagement.open.${row.device.deviceId}`}
@@ -158,7 +159,7 @@ function DeviceRow({
color={colors.textSecondary}
/>
<View style={styles.labels}>
- <Text numberOfLines={1} style={styles.name}>{row.device.name}</Text>
+ <Text numberOfLines={1} style={styles.name}>{deviceDisplayName(row.device.deviceId, row.device.name)}</Text>
<View style={styles.status}>
{/* 状态点:可控用品牌 teal,其余(离线 / 未开远控 / 已撤销)用 muted(borderStrong)。 */}
<StatusDot tone={row.canOpen ? 'ready' : 'muted'} />
diff --git a/apps/mobile/src/device-link/deviceName.ts b/apps/mobile/src/device-link/deviceName.ts
index 3ea256b3c8..4538a96bb5 100644
--- a/apps/mobile/src/device-link/deviceName.ts
+++ b/apps/mobile/src/device-link/deviceName.ts
@@ -1 +1,8 @@
+import { deviceDisplayName as displayName, type DeviceNameSource } from '@cindy/maker-shared/device-list';
+import i18n from '@/i18n';
+
export const MAX_DEVICE_NAME_LENGTH = 64;
+
+export function deviceDisplayName(deviceId: string, name?: string | null, devices: readonly DeviceNameSource[] = []): string {
+ return displayName(deviceId, name, i18n.t('devices.cloudCompanion.unknownDevice'), devices);
+}
diff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.ts
index 482de10b7f..7127a33397 100644
--- a/apps/mobile/src/device-link/remoteResources.ts
+++ b/apps/mobile/src/device-link/remoteResources.ts
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import {
REMOTE_RESOURCE_GET_CHANNEL,
REMOTE_RESOURCE_INVOKE_CHANNEL,
@@ -88,7 +89,7 @@ export function remoteResourceDiscoveryTargets(
const known = new Set(previous.flatMap((collection) => collection.targets.map((host) => host.deviceId)));
return devices
.filter((device) => device.canOpen || (device.state === 'offline' && known.has(device.deviceId)))
- .map((device) => ({ deviceId: device.deviceId, deviceName: device.name,
+ .map((device) => ({ deviceId: device.deviceId, deviceName: deviceDisplayName(device.deviceId, device.name, devices),
...(!device.canOpen ? { offline: true } : {}),
}));
}
@@ -538,7 +539,7 @@ export function parseRemoteResourceTargets(value: unknown): RemoteResourceHostTa
) {
return [];
}
- return [{ deviceId, deviceName: deviceName || deviceId }];
+ return [{ deviceId, deviceName: deviceDisplayName(deviceId, deviceName) }];
});
} catch {
return [];
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
index 9ba87bd96c..f4fe210463 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { foldDesktopLayout, foldDesktopRegion } from "./foldDesktopLayout";
import { useAdaptiveWindow } from "@/platform/AdaptiveWindowContext";
import { controlRegion } from "@/platform/windowGeometry";
@@ -218,7 +219,7 @@ export default function RemoteDesktopScreen() {
handoff?: string;
}>();
const deviceId = typeof rawId === "string" ? rawId : "";
- const deviceName = typeof rawName === "string" ? rawName : deviceId;
+ const deviceName = deviceDisplayName(deviceId, typeof rawName === "string" ? rawName : undefined);
const handoff =
typeof rawHandoff === "string" && rawHandoff ? rawHandoff : undefined;
const router = useRouter();
diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsx
index b7d6d892c3..ff903f1efd 100644
--- a/apps/mobile/src/session/BotGroupChatScreen.tsx
+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import Reanimated from 'react-native-reanimated';
import { useSmoothMessageFollow } from './useSmoothMessageFollow';
import { AnimatedContentHeight } from './AnimatedContentHeight';
@@ -132,7 +133,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
const styles = useThemedStyles(makeStyles);
const router = useRouter();
const { user, accountGeneration } = useAuth();
- const host = useMemo<RemoteResourceHostTarget>(() => ({ deviceId, deviceName: deviceName || deviceId }), [deviceId, deviceName]);
+ const host = useMemo<RemoteResourceHostTarget>(() => ({ deviceId, deviceName: deviceDisplayName(deviceId, deviceName) }), [deviceId, deviceName]);
const chat = useBotGroupChat(host, groupId, threadRootId);
const identity = useBotGroupIdentities(deviceId);
const resolveMedia = useBotGroupRemoteMedia(deviceId);
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
index 2fee2f0fca..a491d0b62d 100644
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { MountOnFirstOpen } from './MountOnFirstOpen';
import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
import { TaskTagDots } from '@/session/TaskTags';
@@ -2381,7 +2382,7 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = false
pathname: '/sessions/[sessionId]',
params: {
deviceId,
- deviceName: session.deviceLinkDeviceName ?? deviceId,
+ deviceName: deviceDisplayName(deviceId, session.deviceLinkDeviceName),
sessionId: session.id,
...(focusClientId ? { focusClientId } : {}),
},
@@ -2397,7 +2398,7 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = false
const openNewSession = useCallback((project?: MobileHomeProjectGroup, suggestion?: RemoteTaskSuggestionId, explicitDeviceId?: string, origin?: ComposerMorphOrigin) => {
const { primaryDevice, newSessionDeviceOptions, selectedDeviceId } = newSessionTargetRef.current;
const deviceId = project?.deviceId ?? explicitDeviceId ?? primaryDevice?.deviceId;
- const deviceName = project?.deviceName ?? newSessionDeviceOptions.find((device) => device.deviceId === deviceId)?.name ?? primaryDevice?.label ?? deviceId ?? '';
+ const deviceName = deviceDisplayName(deviceId ?? '', project?.deviceName ?? newSessionDeviceOptions.find((device) => device.deviceId === deviceId)?.name ?? primaryDevice?.label);
if (!deviceId) {
setError(t('devices.list.error.noDevice'));
return;
@@ -2730,7 +2731,7 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = false
pathname: '/devices/[deviceId]',
params: {
deviceId,
- name: session.deviceLinkDeviceName ?? deviceId,
+ name: deviceDisplayName(deviceId, session.deviceLinkDeviceName),
automationGroupKey: group.baseKey,
automationName: group.title,
...(workingDir ? { automationWorkingDir: workingDir } : {}),
diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsx
index 7b64d864a2..30ac00b6de 100644
--- a/apps/mobile/src/session/InteractionPanel.tsx
+++ b/apps/mobile/src/session/InteractionPanel.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { PluginSetupNativeActions } from '@/plugins/PluginSetupNativeActions';
import { sha256 } from '@noble/hashes/sha256';
import { bytesToHex } from '@noble/hashes/utils';
@@ -1900,7 +1901,7 @@ function PluginSetupRemoteDesktopButton({ deviceId, busy }: { deviceId: string;
const devices = useRemoteDeviceIdentity();
const styles = useInteractionStyles();
const { t } = useTranslation();
- const deviceName = devices.find(device => device.deviceId === deviceId)?.name || deviceId;
+ const deviceName = deviceDisplayName(deviceId, undefined, devices);
const label = t('interaction.pluginSetup.remoteDesktop');
return <InteractionTouchButton accessibilityLabel={label} disabled={busy}
style={styles.primaryButton} testID="interaction.pluginSetup.remoteDesktop"
diff --git a/apps/mobile/src/session/NewTaskSelectionSheet.android.tsx b/apps/mobile/src/session/NewTaskSelectionSheet.android.tsx
index 48b086bac9..c21df4b873 100644
--- a/apps/mobile/src/session/NewTaskSelectionSheet.android.tsx
+++ b/apps/mobile/src/session/NewTaskSelectionSheet.android.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { ErrorNotice } from '@/components/ErrorNotice';
import { useEffect, useMemo, useRef, useState } from "react";
import { ActivityIndicator, View, useWindowDimensions } from "react-native";
@@ -91,7 +92,7 @@ export function NewTaskSelectionSheet(p: NewTaskSelectionSheetProps) {
p.devices.map((device) => (
<NewTaskSelectionRow
key={device.deviceId}
- title={device.name || device.deviceId}
+ title={deviceDisplayName(device.deviceId, device.name)}
leading={icon(Laptop)}
selected={device.deviceId === p.selectedDeviceId}
disabled={p.busy}
diff --git a/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx b/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx
index 66179b1345..dc2687312d 100644
--- a/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx
+++ b/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { NativeErrorNotice } from '@/components/NativeErrorNotice.ios';
import { Button, Image, Picker, ProgressView, Text, Toggle } from '@expo/ui/swift-ui';
import { disabled, font, foregroundStyle, frame, pickerStyle, tag, tint } from '@expo/ui/swift-ui/modifiers';
@@ -42,7 +43,7 @@ export function NewTaskSelectionSheet(p: NewTaskSelectionSheetProps) {
>
{p.page === 'device' ? <Section>
{p.devices.map(device => <ComposerNativeRow key={device.deviceId}
- title={device.name || device.deviceId} leading={icon('laptopcomputer')}
+ title={deviceDisplayName(device.deviceId, device.name)} leading={icon('laptopcomputer')}
selected={device.deviceId === p.selectedDeviceId} disabled={p.busy}
onPress={() => p.onDevice(device.deviceId)} testID="newSession.deviceOption" />)}
</Section> : p.page === 'workspace' ? <>
diff --git a/apps/mobile/src/session/SessionTaskLayout.tsx b/apps/mobile/src/session/SessionTaskLayout.tsx
index 1cb88a2ddd..8bae72f210 100644
--- a/apps/mobile/src/session/SessionTaskLayout.tsx
+++ b/apps/mobile/src/session/SessionTaskLayout.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { useCallback, useEffect, useRef, type ReactNode, type RefObject } from 'react';
import { Alert, Platform, StyleSheet, View } from 'react-native';
import { useLocalSearchParams, useNavigation } from 'expo-router';
@@ -32,7 +33,7 @@ export function SessionTaskLayout({ children }: {
const legacyHistory = readRouteParam(params.resourceHistorySessionId) === sessionId && !!sessionId;
useEffect(() => {
if (legacyHistory && deviceId) switchDrawerSessionInPlace(navigation, {
- sessionId, deviceId, deviceName: readRouteParam(params.deviceName) ?? deviceId,
+ sessionId, deviceId, deviceName: deviceDisplayName(deviceId, readRouteParam(params.deviceName)),
focusClientId: readRouteParam(params.focusClientId) ?? undefined,
});
}, [legacyHistory, deviceId, sessionId, navigation, params.deviceName, params.focusClientId]);
@@ -55,7 +56,7 @@ export function SessionTaskLayout({ children }: {
beforeSessionSwitchRef.current?.();
switchDrawerSessionInPlace(navigation, {
deviceId: targetDeviceId,
- deviceName: target.deviceLinkDeviceName ?? targetDeviceId,
+ deviceName: deviceDisplayName(targetDeviceId, target.deviceLinkDeviceName),
sessionId: target.id,
...(focusClientId ? { focusClientId } : {}),
});
diff --git a/apps/mobile/src/session/TeammateList.tsx b/apps/mobile/src/session/TeammateList.tsx
index 5f700ddab5..34239d1104 100644
--- a/apps/mobile/src/session/TeammateList.tsx
+++ b/apps/mobile/src/session/TeammateList.tsx
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { readWorkingPhase } from '@cindy/maker-shared';
import { memo, useCallback, useLayoutEffect, useMemo, useRef, useSyncExternalStore } from 'react';
import { View } from 'react-native';
@@ -109,7 +110,7 @@ export function useTeammateRowRenderer({ items, isOnline, connectionState, quiet
const time = timestamp !== undefined && Number.isFinite(new Date(timestamp).getTime())
? formatRemoteSessionSidebarTime(new Date(timestamp).toISOString(), now) : '';
return <TeammateRow key={`bot:${row.key}`} rowKey={row.key} deviceId={row.host.deviceId} botId={row.item.ref.id}
- title={title} device={ambiguous ? row.host.deviceName : undefined}
+ title={title} device={ambiguous ? deviceDisplayName(row.host.deviceId, row.host.deviceName) : undefined}
rawPreview={!generating && display.preview ? resolveRemoteText(display.preview, i18n.language) : ''}
subtitle={display.subtitle ? resolveRemoteText(display.subtitle, i18n.language) : ''}
avatarKind={display.avatar?.kind} avatarValue={display.avatar?.value}
diff --git a/apps/mobile/src/session/homeProjectMachineIdentity.ts b/apps/mobile/src/session/homeProjectMachineIdentity.ts
index e956354084..43dcd10ecc 100644
--- a/apps/mobile/src/session/homeProjectMachineIdentity.ts
+++ b/apps/mobile/src/session/homeProjectMachineIdentity.ts
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import type { DeviceLinkContextValue } from '@/device-link/DeviceLinkContext';
import type { MobileHomePresentation } from './mobileHome';
@@ -20,21 +21,14 @@ export function buildHomeProjectMachineIdentities(
const filters = new Map(home.deviceFilters.map((device) => [device.deviceId, device]));
const deviceName = (project: MobileHomePresentation['projects'][number]) =>
(filters.get(project.deviceId)?.label ?? project.deviceName).trim();
- const idsByName = new Map<string, Set<string>>();
- for (const project of home.projects) {
- const name = deviceName(project).toLowerCase();
- if (!project.deviceId || !name) continue;
- const ids = idsByName.get(name) ?? new Set<string>();
- ids.add(project.deviceId);
- idsByName.set(name, ids);
- }
+ const devices = home.projects.flatMap((project) => project.deviceId
+ ? [{ deviceId: project.deviceId, name: deviceName(project) }] : []);
const identities = new Map<string, HomeProjectMachineIdentity>();
for (const project of home.projects) {
if (!project.deviceId) continue;
const name = deviceName(project);
- const ambiguous = name && (idsByName.get(name.toLowerCase())?.size ?? 0) > 1;
identities.set(project.key, {
- displayLabel: ambiguous ? `${name} · ${project.deviceId}` : name || project.deviceId,
+ displayLabel: deviceDisplayName(project.deviceId, name, devices),
// A remounted list paints cached projects before its device roster arrives.
// Missing/stale roster rows and failed list reads are not connection evidence.
disconnected: connection.status !== 'online'
diff --git a/apps/mobile/src/session/mobileHome.ts b/apps/mobile/src/session/mobileHome.ts
index a3bca2f520..8027090aa0 100644
--- a/apps/mobile/src/session/mobileHome.ts
+++ b/apps/mobile/src/session/mobileHome.ts
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import type { RemoteSession } from '@/session/types';
import { isSharedTaskPeer } from '@cindy/device-link';
import { i18n } from '@/i18n';
@@ -24,7 +25,7 @@ export function buildMobileHomePresentation(options: MobileHomeOptions): MobileH
const base = buildMobileHomePresentationShared({ ...options, selectedDeviceId, localizer: mobilePresentationLocalizer });
const deviceFilters = base.deviceFilters.filter((filter) => !filter.deviceId || !isSharedTaskPeer(filter.deviceId)).map((filter) => ({
...filter,
- label: filter.deviceId === null ? i18n.t('devices.presentation.home.allDevices') : filter.label,
+ label: filter.deviceId === null ? i18n.t('devices.presentation.home.allDevices') : deviceDisplayName(filter.deviceId, filter.label),
statusLabel: filter.waitingCount > 0
? i18n.t('devices.presentation.home.waitingCount', { count: filter.waitingCount })
: filter.deviceId === null
@@ -52,7 +53,7 @@ export function buildMobileHomePresentation(options: MobileHomeOptions): MobileH
: undefined);
const deviceName = sourceDeviceName == null
? i18n.t('devices.presentation.home.unknownComputer')
- : project.deviceName;
+ : deviceDisplayName(project.deviceId ?? '', project.deviceName);
const workingDir = project.workingDir;
return {
...project,
diff --git a/apps/mobile/src/session/mobileVoiceDictionaryView.ts b/apps/mobile/src/session/mobileVoiceDictionaryView.ts
index 83dd6b8300..2dcb7be18f 100644
--- a/apps/mobile/src/session/mobileVoiceDictionaryView.ts
+++ b/apps/mobile/src/session/mobileVoiceDictionaryView.ts
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
/**
* 手机端语音词典展示模型(纯函数,不碰 UI 与网络)。
*
@@ -32,7 +33,7 @@ export function collectMobileVoiceDictionaryHosts(
.filter((device) => !device.isSelf && isDesktopDevice(device.platform))
.map((device) => ({
deviceId: device.deviceId,
- name: device.name?.trim() || device.deviceId.slice(0, 8),
+ name: deviceDisplayName(device.deviceId, device.name),
online: Boolean(device.online),
}))
;
@@ -61,7 +62,7 @@ export function patchMobileVoiceDictionaryHosts(
// 无变化时返回原引用:presence 事件很密集(手机、其它电脑的上下线都会来),
// 每次都造新数组会让设置页无谓重渲染。
if (!snapshot?.deviceId || !isDesktopDevice(snapshot.platform)) return hosts;
- const name = snapshot.deviceName?.trim() || snapshot.deviceId.slice(0, 8);
+ const name = deviceDisplayName(snapshot.deviceId, snapshot.deviceName || hosts.find((host) => host.deviceId === snapshot.deviceId)?.name);
const index = hosts.findIndex((host) => host.deviceId === snapshot.deviceId);
if (index < 0) {
return sortHosts([...hosts, { deviceId: snapshot.deviceId, name, online: Boolean(snapshot.online) }]);
diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.ts
index 88d669052e..ab3482467a 100644
--- a/apps/mobile/src/session/newSession.ts
+++ b/apps/mobile/src/session/newSession.ts
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
import { getSessionListActivityAt } from '@cindy/maker-shared/session-activity';
import { modelNeedsReselection } from './modelReselection';
import { stripTrailingPathSeparators } from '@cindy/maker-shared/path-text';
@@ -1192,7 +1193,7 @@ function readNewSessionDeviceOptionsParam(value: unknown): NewSessionDeviceOptio
const record = item as Record<string, unknown>;
const deviceId = readString(record.deviceId)?.trim() ?? '';
if (!deviceId) return [];
- const name = readString(record.name)?.trim() || deviceId;
+ const name = deviceDisplayName(deviceId, readString(record.name));
return [{ deviceId, name }];
});
} catch {
@@ -1209,7 +1210,7 @@ function normalizeNewSessionDeviceOptions(
const deviceId = option.deviceId.trim();
if (!deviceId || seen.has(deviceId)) continue;
seen.add(deviceId);
- result.push({ deviceId, name: option.name.trim() || deviceId });
+ result.push({ deviceId, name: deviceDisplayName(deviceId, option.name) });
}
return result;
}
diff --git a/apps/mobile/src/session/remoteAgentCatalogs.ts b/apps/mobile/src/session/remoteAgentCatalogs.ts
index 63a3d45d9a..43aeac8574 100644
--- a/apps/mobile/src/session/remoteAgentCatalogs.ts
+++ b/apps/mobile/src/session/remoteAgentCatalogs.ts
@@ -1,3 +1,4 @@
+import { deviceDisplayName } from '@/device-link/deviceName';
/**
* 远程 Agent 的「其他电脑」模型目录(纯逻辑,与桌面模型面板同口径):
* 手机的模型选择器在被控电脑自己的供应商之后,列出同账号其他电脑上开了「允许被远程调用」的
@@ -53,7 +54,7 @@ export function selectRemoteAgentDevices(input: {
.filter((item) => item.canOpen || input.keepDeviceIds.includes(item.device.deviceId))
.map((item) => ({
deviceId: item.device.deviceId,
- name: item.device.name?.trim() || item.device.deviceId,
+ name: deviceDisplayName(item.device.deviceId, item.device.name, input.devices),
canOpen: item.canOpen,
}));
}
diff --git a/packages/maker-shared/src/__tests__/deviceList.test.ts b/packages/maker-shared/src/__tests__/deviceList.test.ts
index 75868ce7ef..f5a2173f3a 100644
--- a/packages/maker-shared/src/__tests__/deviceList.test.ts
+++ b/packages/maker-shared/src/__tests__/deviceList.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
buildDeviceListPresentation,
deviceAccessState,
+ deviceDisplayName,
isControllableDevice,
platformLabel,
toDeviceListItems,
@@ -197,3 +198,20 @@ describe('shared device list presentation model', () => {
expect(empty.emptyTitle).toBe('还没有可显示的电脑');
});
});
+
+// Regression: full device fingerprints crowded teammate/project labels, including cached ID-as-name values.
+describe('device display names', () => {
+ it('recovers missing or cached ID names from the roster, otherwise uses localized copy', () => {
+ const id = 'eb2ad08b24c63a9e818609e29057ca8d1a4';
+ expect(deviceDisplayName(id, id, '未命名设备', [{ deviceId: id, name: ' Mac Studio ' }])).toBe('Mac Studio');
+ expect(deviceDisplayName(id, ' ', '未命名设备')).toBe('未命名设备');
+ expect(deviceDisplayName(id, id, '未命名设备')).toBe('未命名设备');
+ });
+ it('uses deterministic ordinals for distinct duplicate hosts without changing routing identities', () => {
+ const devices = [{ deviceId: 'b', name: 'Studio' }, { deviceId: 'a', name: ' studio ' }];
+ expect(deviceDisplayName('b', 'Studio', 'Computer', devices)).toBe('Studio (2)');
+ expect(deviceDisplayName('b', 'Studio', 'Computer', [...devices].reverse())).toBe('Studio (2)');
+ expect(deviceDisplayName('b', 'Studio', 'Computer', [devices[0], devices[0]])).toBe('Studio');
+ expect(devices.map((device) => device.deviceId)).toEqual(['b', 'a']);
+ });
+});
diff --git a/packages/maker-shared/src/deviceList.ts b/packages/maker-shared/src/deviceList.ts
index a6387e528d..7fd688229a 100644
--- a/packages/maker-shared/src/deviceList.ts
+++ b/packages/maker-shared/src/deviceList.ts
@@ -6,6 +6,34 @@ import {
export type DeviceAccessState = 'ready' | 'busy' | 'offline' | 'remote_disabled' | 'access_revoked' | 'self';
+export interface DeviceNameSource {
+ deviceId: string;
+ name?: string | null;
+}
+
+/** Presentation only: routing IDs must never become a computer's visible name. */
+export function deviceDisplayName(
+ deviceId: string,
+ name: string | null | undefined,
+ unnamed: string,
+ devices: readonly DeviceNameSource[] = [],
+): string {
+ const readable = (id: string, value: string | null | undefined) => {
+ const trimmed = value?.trim();
+ return trimmed && trimmed !== id ? trimmed : '';
+ };
+ const resolvedName = readable(deviceId, name)
+ || readable(deviceId, devices.find((device) => device.deviceId === deviceId)?.name);
+ const label = resolvedName || unnamed;
+ const peers = new Set([deviceId]);
+ for (const device of devices) {
+ const otherLabel = readable(device.deviceId, device.name) || unnamed;
+ if (otherLabel.toLowerCase() === label.toLowerCase()) peers.add(device.deviceId);
+ }
+ // Sorting identities keeps the suffix stable when a roster is reordered.
+ return peers.size > 1 ? `${label} (${[...peers].sort().indexOf(deviceId) + 1})` : label;
+}
+
export interface DeviceListDeviceLike {
busy: boolean;
deviceId: string;