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(desktop): address controller name lifecycle review

Chris332eaecfe23e
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
index faf4b6e5d4..c95b54f810 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
@@ -449,6 +449,7 @@ import {
setRemoteInvokeBusyChangedListener,
setSessionsSubscribedListener,
setControllerDisplayName,
+ purgeRevokedController,
getActiveControllers,
getUpdateRelaunchControllers,
hasInFlightRemoteInvokes,
@@ -586,6 +587,51 @@ describe('被控端控制链路生命周期', () => {
});
});
+ it('没有历史 presence 时先显示自报名,设备目录补齐后立即切换到数据库展示名', () => {
+ remoteControlEnabled = true;
+ const { client, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+
+ feed(subFrame('ctrl-late-directory', SUB, ['session:s1'], 'Host.local'));
+ expect(getActiveControllers()).toEqual([
+ { deviceId: 'ctrl-late-directory', name: 'Host.local' },
+ ]);
+
+ setControllerDisplayName('ctrl-late-directory', '数据库展示名');
+ expect(getActiveControllers()).toEqual([
+ { deviceId: 'ctrl-late-directory', name: '数据库展示名' },
+ ]);
+ });
+
+ it.each([
+ ['显式断链', (feed: (env: Envelope) => unknown, deviceId: string) => feed({
+ v: 1,
+ kind: 'link-close',
+ src: deviceId,
+ payload: { reason: 'user' },
+ })],
+ ['presence 离线', (_feed: (env: Envelope) => unknown, deviceId: string) => {
+ handleControllerOffline(deviceId);
+ }],
+ ['撤销访问', (_feed: (env: Envelope) => unknown, deviceId: string) => {
+ purgeRevokedController(deviceId);
+ }],
+ ] as const)('%s 会清掉旧链路自报名,新链路缺名时回退设备 ID 短码', (_label, close) => {
+ remoteControlEnabled = true;
+ const { client, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+ const deviceId = '1234567890abcdef';
+
+ setControllerDisplayName(deviceId, '数据库展示名');
+ feed(subFrame(deviceId, SUB, ['session:s1'], 'Old-Host.local'));
+ setControllerDisplayName(deviceId, '');
+ expect(getActiveControllers()).toEqual([{ deviceId, name: 'Old-Host.local' }]);
+
+ close(feed, deviceId);
+ feed(subFrame(deviceId, SUB, ['session:s2']));
+ expect(getActiveControllers()).toEqual([{ deviceId, name: '12345678' }]);
+ });
+
it('link-open(开关关)→ 不 accept、不记录', () => {
remoteControlEnabled = false;
const { client, calls, feed } = makeFakeClient();
diff --git a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
index e2d6481e5c..1d4daf8fb6 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
@@ -50,6 +50,27 @@ describe('mobile voice credential sync desktop bootstrap path', () => {
expect(deviceLinkHost).toContain('replayActiveSubscriptions(`presence-online:${snap.deviceId.slice(0, 8)}`, snap.deviceId);');
});
+ it('每个 relay 连接代上线时从设备目录补齐已在线控制端展示名', () => {
+ const deviceLinkHost = readFileSync(resolve(mainRoot, 'device-link/index.ts'), 'utf8');
+
+ expect(deviceLinkHost).toContain("serverApiFetch<DeviceDirectoryResponse>('/api/device-link/devices'");
+ const onlineBranch = deviceLinkHost.indexOf("if (status === 'online') {");
+ const seedCachedNames = deviceLinkHost.indexOf(
+ 'seedControllerDisplayNamesFromLastKnown();',
+ onlineBranch,
+ );
+ const refreshDirectory = deviceLinkHost.indexOf(
+ 'void refreshControllerDisplayNamesFromDirectory(displayNameGeneration);',
+ onlineBranch,
+ );
+ expect(onlineBranch).toBeGreaterThanOrEqual(0);
+ expect(seedCachedNames).toBeGreaterThan(onlineBranch);
+ expect(refreshDirectory).toBeGreaterThan(seedCachedNames);
+ expect(deviceLinkHost).toContain(
+ 'generation !== controllerDisplayNameRefreshGeneration',
+ );
+ });
+
it('keeps device-link:voice:credential-sync matched but rejected (feature removed, readable error for old mobile)', () => {
const dispatch = readFileSync(resolve(mainRoot, 'device-link/dispatch.ts'), 'utf8');
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 15196182dd..4934f4d0dc 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -598,6 +598,10 @@ function resolveControllerName(deviceId: string, reportedName: unknown): string
?? reportedControllerNameByDevice.get(deviceId);
}
+function clearReportedControllerName(deviceId: string): void {
+ reportedControllerNameByDevice.delete(deviceId);
+}
+
/**
* presence 设备名变化(含设置页重命名)时更新展示真相;已有活跃订阅立即重发
* controlled-state,让横幅不用等下一次 subscribe / 重连才改名。
@@ -1488,6 +1492,7 @@ export function dropAllControllers(
// 本地授权/订阅清理不能依赖弱网下 link-close 真正写进 socket。
log.warn(`closeLink to ${shortId(dst)} failed during ${reason}: ${String(err)}`);
}
+ clearReportedControllerName(dst);
}
clearAllRemoteInvokeState();
subscriptions.clearAll();
@@ -1508,6 +1513,7 @@ export function dropAllControllers(
*/
export function handleControllerOffline(deviceId: string): void {
acceptedLinkControllers.delete(deviceId);
+ clearReportedControllerName(deviceId);
clearSessionActivityStage(deviceId);
clearMakerEventBatchStage(deviceId);
cancelLinkAcceptRetry(deviceId);
@@ -1523,6 +1529,7 @@ export function forgetControllerInvokeState(deviceId: string): void {
/** 显式撤销时清理短时离线队列与 remembered topic,避免恢复后重放撤权期间数据。 */
export function purgeRevokedController(deviceId: string): void {
+ clearReportedControllerName(deviceId);
offlinePushQueue.clear(deviceId);
clearSessionActivityStage(deviceId);
clearMakerEventBatchStage(deviceId);
@@ -1575,6 +1582,7 @@ async function handleFrame(client: DeviceLinkClient, env: Envelope): Promise<voi
clearMakerEventBatchStage(src);
cancelLinkAcceptRetry(src);
acceptedLinkControllers.delete(src);
+ clearReportedControllerName(src);
// Keep the protocol-capability marker, but discard all remembered routing.
// A modern controller must reconnect and explicitly subscribe; restoring the
// legacy wildcard here would silently re-enable broad delivery.
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 2b539c4fa7..609006318e 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -42,6 +42,7 @@ import { createLogger } from '../logger';
import { onQuit } from '../lifecycle';
import { tryGetDbClient } from '../localDb/client/current';
import { createOutboundHttpAgent } from '../maker-host/outbound-fetch';
+import { serverApiFetch } from '../serverApiClient';
import {
DeviceLinkOwnershipArbiter,
createDbClientOwnershipStore,
@@ -54,7 +55,9 @@ import {
shouldAbortTransportTimeoutReopen,
} from './transportTimeoutReopen';
import {
+ isPlaceholderDeviceName,
readDeviceLinkSettings,
+ readLastKnownDeviceNames,
rememberLastKnownDeviceName,
updateDeviceLinkSetting,
writeDeviceLinkSetting,
@@ -138,6 +141,51 @@ export function deviceLinkApiBase(): string {
return getClientEndpoint('deviceLinkApiBaseUrl');
}
+type DeviceDirectoryResponse = {
+ devices?: Array<{ deviceId?: unknown; name?: unknown }>;
+};
+let controllerDisplayNameRefreshGeneration = 0;
+
+function seedControllerDisplayNamesFromLastKnown(): void {
+ for (const [deviceId, name] of Object.entries(readLastKnownDeviceNames())) {
+ setControllerDisplayName(deviceId, name);
+ }
+}
+
+/**
+ * presence 是增量流,新建连接不会收到已在线设备的历史快照;每个 relay 连接代
+ * 上线时从现有设备目录补齐展示名,避免 link-open 抢先时长期停在主机名回退。
+ */
+async function refreshControllerDisplayNamesFromDirectory(generation: number): Promise<void> {
+ try {
+ const result = await serverApiFetch<DeviceDirectoryResponse>('/api/device-link/devices', {
+ baseUrl: deviceLinkApiBase,
+ timeoutMs: 10_000,
+ });
+ if (
+ generation !== controllerDisplayNameRefreshGeneration
+ || linkTornDown
+ || client?.getStatus() !== 'online'
+ ) {
+ return;
+ }
+ const cachedNames = readLastKnownDeviceNames();
+ for (const device of result.devices ?? []) {
+ if (typeof device.deviceId !== 'string' || !device.deviceId.trim()) continue;
+ const deviceId = device.deviceId.trim();
+ const serverName = typeof device.name === 'string' ? device.name.trim() : '';
+ const hasDisplayName = !!serverName && !isPlaceholderDeviceName(serverName);
+ const displayName = hasDisplayName ? serverName : cachedNames[deviceId];
+ if (!displayName) continue;
+ setControllerDisplayName(deviceId, displayName);
+ if (hasDisplayName) void rememberLastKnownDeviceName(deviceId, serverName);
+ }
+ } catch (err) {
+ // 目录补齐是展示层 best-effort;失败时保留控制帧自报名 / 短 ID 回退,不影响建链。
+ log.warn(`device directory display-name refresh failed (non-fatal): ${String(err)}`);
+ }
+}
+
let client: DeviceLinkClient | null = null;
/**
@@ -487,6 +535,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
client.onStatusChange((status) => {
if (status !== 'online') {
+ controllerDisplayNameRefreshGeneration += 1;
// 不清 openLinkInFlight:登记生命周期的唯一判据是 promise settle(每个
// 请求 settle 时自清理,closeRemoteLink 的显式删除有取消代次兜底)。建链
// 可能正 park 在上线等待里,状态抖动时提前删登记会让同设备的下一次调用
@@ -510,6 +559,11 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
broadcast(DEVICE_LINK_PUSH.STATUS_CHANGED, { status });
handleContactsDeviceLinkStatusChanged(status === 'online');
if (status === 'online') {
+ // 本地 last-known 先同步种入,覆盖 REST 返回前的 link-open 竞态;随后用
+ // 当前设备目录刷新,补齐本连接代没有历史 presence 的已在线设备。
+ seedControllerDisplayNamesFromLastKnown();
+ const displayNameGeneration = ++controllerDisplayNameRefreshGeneration;
+ void refreshControllerDisplayNamesFromDirectory(displayNameGeneration);
// 断线前攒的 maker:event 批最先出去:它在时间上早于离线积压与重连后的
// 一切新推送,晚发会让控制端在终态之后又收到旧文本(见 dispatch 注释)。
flushMakerEventBatchesOnReconnect();
@@ -933,6 +987,7 @@ export function getMobileNotifyGeneration(): number {
function teardownActiveLink(): void {
if (!client || linkTornDown) return;
linkTornDown = true;
+ controllerDisplayNameRefreshGeneration += 1;
mobileNotifyGeneration += 1;
if (relayAuthRecoveryRetryTimer !== null) {
clearTimeout(relayAuthRecoveryRetryTimer);