Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 完善词典听错词编辑与同步 (#3278)
Dash81f367d5ae9e
diff --git a/apps/desktop/src/main/__tests__/deviceLinkControllerPresenceDirectory.test.ts b/apps/desktop/src/main/__tests__/deviceLinkControllerPresenceDirectory.test.tsnew file mode 100644index 0000000000..e5281535f4--- /dev/null+++ b/apps/desktop/src/main/__tests__/deviceLinkControllerPresenceDirectory.test.ts@@ -0,0 +1,335 @@+import { describe, expect, it, vi } from 'vitest';++import {+ applyControllerPresenceDirectorySnapshot,+ createControllerPresenceFreshnessTracker,+ markControllerPresenceFresh,+ resetControllerPresenceFreshness,+} from '../device-link/controllerPresenceDirectory';++function createHarness() {+ const freshness = createControllerPresenceFreshnessTracker();+ const onlineByDevice = new Map<string, boolean>();+ const platformByDevice = new Map<string, string>();+ const nameByDevice = new Map<string, string>();+ const exchanged = vi.fn();++ return {+ freshness,+ onlineByDevice,+ platformByDevice,+ nameByDevice,+ exchanged,+ markPresence(deviceId: string, online: boolean, platform: string) {+ markControllerPresenceFresh(freshness, deviceId);+ onlineByDevice.set(deviceId, online);+ platformByDevice.set(deviceId, platform);+ },+ apply(+ devices: Parameters<typeof applyControllerPresenceDirectorySnapshot>[0]['devices'],+ requestEpoch = freshness.epoch,+ ) {+ applyControllerPresenceDirectorySnapshot({+ devices,+ requestEpoch,+ selfDeviceId: 'self-device',+ freshness,+ getOnline: (deviceId) => onlineByDevice.get(deviceId),+ setOnline: (deviceId, online) => onlineByDevice.set(deviceId, online),+ forgetOnline: (deviceId) => onlineByDevice.delete(deviceId),+ setPlatform: (deviceId, platform) => {+ if (platform) platformByDevice.set(deviceId, platform);+ else platformByDevice.delete(deviceId);+ },+ setName: (deviceId, name) => nameByDevice.set(deviceId, name),+ shouldNotifyPeerOnline: ({ online, platform }) =>+ online &&+ platform !== null &&+ ['darwin', 'win32', 'linux', 'ios', 'android'].includes(platform),+ onPeerBecameOnline: exchanged,+ });+ },+ };+}++describe('controller presence directory snapshot', () => {+ it('冷启动时从目录初始化已在线桌面并触发一次词典握手', () => {+ const h = createHarness();++ h.apply([+ {+ deviceId: 'peer-desktop',+ name: 'Database Name',+ selfName: 'MacBook Pro',+ online: true,+ platform: 'darwin',+ isSelf: false,+ },+ ]);++ expect(h.onlineByDevice.get('peer-desktop')).toBe(true);+ expect(h.platformByDevice.get('peer-desktop')).toBe('darwin');+ expect(h.nameByDevice.get('peer-desktop')).toBe('MacBook Pro');+ expect(h.exchanged).toHaveBeenCalledWith('peer-desktop', 'darwin');+ });++ it('排除本机和离线设备,桌面与手机重复目录都不重复制造上线边沿', () => {+ const h = createHarness();+ const devices = [+ { deviceId: 'self-device', online: true, platform: 'darwin', isSelf: true },+ { deviceId: 'peer-phone', online: true, platform: 'ios', isSelf: false },+ { deviceId: 'peer-offline', online: false, platform: 'win32', isSelf: false },+ { deviceId: 'peer-desktop', online: true, platform: 'linux', isSelf: false },+ ];++ h.apply(devices);+ h.apply(devices);++ expect(h.exchanged).toHaveBeenCalledTimes(2);+ expect(h.exchanged).toHaveBeenCalledWith('peer-phone', 'ios');+ expect(h.exchanged).toHaveBeenCalledWith('peer-desktop', 'linux');+ expect(h.onlineByDevice.get('peer-phone')).toBe(true);+ expect(h.onlineByDevice.get('peer-offline')).toBe(false);+ expect(h.onlineByDevice.has('self-device')).toBe(false);+ });++ it('请求期间到达的实时 presence 优先,不被在途旧目录覆盖', () => {+ const h = createHarness();+ const requestEpoch = h.freshness.epoch;++ markControllerPresenceFresh(h.freshness, 'peer-desktop');+ h.onlineByDevice.set('peer-desktop', false);+ h.platformByDevice.set('peer-desktop', 'win32');+ h.nameByDevice.set('peer-desktop', 'Live Name');+ h.apply(+ [+ {+ deviceId: 'peer-desktop',+ name: 'Stale Name',+ online: true,+ platform: 'darwin',+ isSelf: false,+ },+ ],+ requestEpoch,+ );++ expect(h.onlineByDevice.get('peer-desktop')).toBe(false);+ expect(h.platformByDevice.get('peer-desktop')).toBe('win32');+ expect(h.nameByDevice.get('peer-desktop')).toBe('Live Name');+ expect(h.exchanged).not.toHaveBeenCalled();+ });++ it('首次看到的在线目录项缺平台时保持未知,让后续真实 presence 仍能触发上线', () => {+ const h = createHarness();++ h.apply([+ {+ deviceId: 'peer-desktop',+ online: true,+ platform: null,+ isSelf: false,+ },+ ]);++ expect(h.onlineByDevice.has('peer-desktop')).toBe(false);+ expect(h.platformByDevice.has('peer-desktop')).toBe(false);+ expect(h.exchanged).not.toHaveBeenCalled();+ });++ it('在线目录项的平台不受支持时保持未知,后续规范平台仍能形成上线边沿', () => {+ const h = createHarness();++ h.apply([+ {+ deviceId: 'peer-desktop',+ online: true,+ platform: 'legacy-desktop',+ isSelf: false,+ },+ ]);++ expect(h.onlineByDevice.has('peer-desktop')).toBe(false);+ expect(h.platformByDevice.has('peer-desktop')).toBe(false);+ expect(h.exchanged).not.toHaveBeenCalled();++ h.apply([+ {+ deviceId: 'peer-desktop',+ online: true,+ platform: 'darwin',+ isSelf: false,+ },+ ]);++ expect(h.onlineByDevice.get('peer-desktop')).toBe(true);+ expect(h.platformByDevice.get('peer-desktop')).toBe('darwin');+ expect(h.exchanged).toHaveBeenCalledWith('peer-desktop', 'darwin');+ });++ it.each([null, 'legacy-desktop'])(+ '后续在线目录项平台为 %s 时保留可信状态,明确离线后再清除',+ (incompletePlatform) => {+ const h = createHarness();++ h.apply([+ {+ deviceId: 'peer-desktop',+ online: true,+ platform: 'darwin',+ isSelf: false,+ },+ ]);+ h.apply([+ {+ deviceId: 'peer-desktop',+ online: true,+ platform: incompletePlatform,+ isSelf: false,+ },+ ]);++ expect(h.onlineByDevice.get('peer-desktop')).toBe(true);+ expect(h.platformByDevice.get('peer-desktop')).toBe('darwin');+ expect(h.exchanged).toHaveBeenCalledTimes(1);++ h.apply([+ {+ deviceId: 'peer-desktop',+ online: false,+ platform: incompletePlatform,+ isSelf: false,+ },+ ]);++ expect(h.onlineByDevice.get('peer-desktop')).toBe(false);+ expect(h.platformByDevice.has('peer-desktop')).toBe(false);+ expect(h.exchanged).toHaveBeenCalledTimes(1);+ },+ );++ it('在线目录项缺平台时不清除实时 presence 已确认的在线状态与平台', () => {+ const h = createHarness();+ h.markPresence('peer-desktop', true, 'darwin');++ h.apply([+ {+ deviceId: 'peer-desktop',+ online: true,+ platform: null,+ isSelf: false,+ },+ ]);++ expect(h.onlineByDevice.get('peer-desktop')).toBe(true);+ expect(h.platformByDevice.get('peer-desktop')).toBe('darwin');+ expect(h.exchanged).not.toHaveBeenCalled();+ });++ it('目录离线快照不把实时 presence 已确认的在线设备降级', () => {+ const h = createHarness();+ h.markPresence('peer-desktop', true, 'darwin');++ h.apply([+ {+ deviceId: 'peer-desktop',+ selfName: 'Directory Name',+ online: false,+ platform: 'win32',+ isSelf: false,+ },+ ]);++ expect(h.onlineByDevice.get('peer-desktop')).toBe(true);+ expect(h.platformByDevice.get('peer-desktop')).toBe('darwin');+ expect(h.nameByDevice.get('peer-desktop')).toBe('Directory Name');+ expect(h.exchanged).not.toHaveBeenCalled();+ });++ it('目录在线快照不把实时 presence 已确认的离线设备升级', () => {+ const h = createHarness();+ h.markPresence('peer-desktop', false, 'win32');++ h.apply([+ {+ deviceId: 'peer-desktop',+ online: true,+ platform: 'darwin',+ isSelf: false,+ },+ ]);++ expect(h.onlineByDevice.get('peer-desktop')).toBe(false);+ expect(h.platformByDevice.get('peer-desktop')).toBe('win32');+ expect(h.exchanged).not.toHaveBeenCalled();+ });++ it('实时 presence 到达前,后续目录快照持续更新状态并只在上线边沿握手', () => {+ const h = createHarness();++ h.apply([+ {+ deviceId: 'peer-desktop',+ online: false,+ platform: 'win32',+ isSelf: false,+ },+ ]);+ h.apply([+ {+ deviceId: 'peer-desktop',+ online: true,+ platform: 'darwin',+ isSelf: false,+ },+ ]);+ h.apply([+ {+ deviceId: 'peer-desktop',+ online: true,+ platform: 'darwin',+ isSelf: false,+ },+ ]);++ expect(h.onlineByDevice.get('peer-desktop')).toBe(true);+ expect(h.platformByDevice.get('peer-desktop')).toBe('darwin');+ expect(h.exchanged).toHaveBeenCalledTimes(1);+ expect(h.exchanged).toHaveBeenCalledWith('peer-desktop', 'darwin');++ h.apply([+ {+ deviceId: 'peer-desktop',+ online: false,+ platform: 'win32',+ isSelf: false,+ },+ ]);++ expect(h.onlineByDevice.get('peer-desktop')).toBe(false);+ expect(h.platformByDevice.get('peer-desktop')).toBe('win32');+ expect(h.exchanged).toHaveBeenCalledTimes(1);+ });++ it('连接代重置后允许新目录重新初始化同一设备', () => {+ const h = createHarness();+ const oldRequestEpoch = h.freshness.epoch;+ markControllerPresenceFresh(h.freshness, 'peer-desktop');+ resetControllerPresenceFreshness(h.freshness);++ h.apply(+ [+ {+ deviceId: 'peer-desktop',+ online: true,+ platform: 'darwin',+ isSelf: false,+ },+ ],+ oldRequestEpoch + 2,+ );++ expect(h.onlineByDevice.get('peer-desktop')).toBe(true);+ expect(h.exchanged).toHaveBeenCalledWith('peer-desktop', 'darwin');+ });+});diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.tsindex c2a752efc0..9c75204af3 100644--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts@@ -35,7 +35,9 @@ vi.mock('./index', () => ({remoteUnsubscribe: vi.fn(),disconnectAllControllers: vi.fn(),broadcast: vi.fn(),+ applyControllerPresenceListSnapshot: vi.fn(),captureControllerDisplayNameRequestEpoch: () => 0,+ captureControllerPresenceRequestEpoch: () => 0,readControllerDisplayNameFreshnessSince: () => ({changedAfterRequest: false,authoritativeName: null,@@ -51,7 +53,9 @@ vi.mock('../device-link/index', () => ({remoteUnsubscribe: vi.fn(),disconnectAllControllers: vi.fn(),broadcast: vi.fn(),+ applyControllerPresenceListSnapshot: vi.fn(),captureControllerDisplayNameRequestEpoch: () => 0,+ captureControllerPresenceRequestEpoch: () => 0,readControllerDisplayNameFreshnessSince: () => ({changedAfterRequest: false,authoritativeName: null,@@ -145,8 +149,10 @@ function makeDeps(overrides?: Partial<DeviceLinkIpcDeps>): DeviceLinkIpcDeps {rememberLastKnownDeviceName: vi.fn(async () => false),forgetLastKnownDeviceName: vi.fn(async () => false),applyControllerDisplayNameListSnapshot: vi.fn(),+ applyControllerPresenceListSnapshot: vi.fn(),beginControllerDisplayNameDirectoryRefresh: vi.fn(() => 1),captureControllerDisplayNameRequestEpoch: vi.fn(() => 0),+ captureControllerPresenceRequestEpoch: vi.fn(() => 0),isLatestControllerDisplayNameDirectoryRefresh: vi.fn(() => true),waitForNewerControllerDisplayNameDirectoryRefresh: vi.fn(async () => {}),readControllerDisplayNameFreshnessSince: vi.fn(() => ({@@ -302,6 +308,7 @@ describe('device-link IPC handlers', () => {'listDevices:被后台目录淘汰的旧响应(%s)等待后返回当前权威名(%s)',async (name, authoritativeName, expectedName) => {const applyControllerDisplayNameListSnapshot = vi.fn();+ const applyControllerPresenceListSnapshot = vi.fn();const rememberLastKnownDeviceName = vi.fn(async () => true);const forgetLastKnownDeviceName = vi.fn(async () => true);const waitForNewerControllerDisplayNameDirectoryRefresh = vi.fn(async () => {});@@ -323,6 +330,7 @@ describe('device-link IPC handlers', () => {],}),applyControllerDisplayNameListSnapshot,+ applyControllerPresenceListSnapshot,rememberLastKnownDeviceName,forgetLastKnownDeviceName,beginControllerDisplayNameDirectoryRefresh: vi.fn(() => 1),@@ -340,6 +348,7 @@ describe('device-link IPC handlers', () => {expect(waitForNewerControllerDisplayNameDirectoryRefresh).toHaveBeenCalledWith(1);expect(applyControllerDisplayNameListSnapshot).not.toHaveBeenCalled();+ expect(applyControllerPresenceListSnapshot).not.toHaveBeenCalled();expect(rememberLastKnownDeviceName).not.toHaveBeenCalled();expect(forgetLastKnownDeviceName).not.toHaveBeenCalled();},@@ -356,11 +365,13 @@ describe('device-link IPC handlers', () => {const rememberLastKnownDeviceName = vi.fn(async () => true);const forgetLastKnownDeviceName = vi.fn(async () => true);const applyControllerDisplayNameListSnapshot = vi.fn();+ const applyControllerPresenceListSnapshot = vi.fn();const deps = makeDeps({apiFetch,rememberLastKnownDeviceName,forgetLastKnownDeviceName,applyControllerDisplayNameListSnapshot,+ applyControllerPresenceListSnapshot,});const device = (name: string) => ({deviceId: 'dev-1',@@ -394,6 +405,11 @@ describe('device-link IPC handlers', () => {[expect.objectContaining({ deviceId: 'dev-1', name: '新数据库名' })],0,);+ expect(applyControllerPresenceListSnapshot).toHaveBeenCalledTimes(1);+ expect(applyControllerPresenceListSnapshot).toHaveBeenCalledWith(+ [expect.objectContaining({ deviceId: 'dev-1', online: true, platform: 'darwin' })],+ 0,+ );},);diff --git a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.tsindex a1eee6198e..612188ae01 100644--- a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts@@ -50,7 +50,7 @@ describe('mobile voice credential sync desktop bootstrap path', () => {expect(deviceLinkHost).toContain('replayActiveSubscriptions(`presence-online:${snap.deviceId.slice(0, 8)}`, snap.deviceId);');});- it('每个 relay 连接代上线时从设备目录补齐已在线控制端展示名', () => {+ it('每个 relay 连接代上线时从设备目录补齐展示名与已在线桌面', () => {const deviceLinkHost = readFileSync(resolve(mainRoot, 'device-link/index.ts'), 'utf8');expect(deviceLinkHost).toContain("serverApiFetch<DeviceDirectoryResponse>('/api/device-link/devices'");@@ -84,7 +84,10 @@ describe('mobile voice credential sync desktop bootstrap path', () => {'latestControllerDisplayNameDirectoryRefresh = {',);expect(deviceLinkHost).toContain(- 'const requestEpoch = controllerDisplayNameFreshness.epoch;',+ 'const displayNameRequestEpoch = controllerDisplayNameFreshness.epoch;',+ );+ expect(deviceLinkHost).toContain(+ 'const presenceRequestEpoch = controllerPresenceFreshness.epoch;',);expect(deviceLinkHost).toContain('applyControllerDisplayNamePresence({',@@ -93,6 +96,13 @@ describe('mobile voice credential sync desktop bootstrap path', () => {"Object.prototype.hasOwnProperty.call(snap, 'selfName')",);expect(deviceLinkHost).toContain('applyControllerDisplayNameDirectorySnapshot({');+ expect(deviceLinkHost).toContain('applyControllerPresenceListSnapshot(result.devices ?? [], presenceRequestEpoch);');+ expect(deviceLinkHost).toContain(+ 'markControllerPresenceFresh(controllerPresenceFreshness, snap.deviceId);',+ );+ expect(deviceLinkHost).toContain(+ 'if (isMobilePlatform(platform)) handleMobilePeerOnline(deviceId);',+ );});it('presence 展示名统一走协调器,无有效权威名时保留 dispatch 回退链', () => {diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.tsindex 439fb39cca..e0166e6f51 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts@@ -91,8 +91,10 @@ vi.mock('../index', () => ({broadcast: vi.fn(),deviceLinkApiBase: 'https://example.invalid',applyControllerDisplayNameListSnapshot: vi.fn(),+ applyControllerPresenceListSnapshot: vi.fn(),beginControllerDisplayNameDirectoryRefresh: vi.fn(() => 1),captureControllerDisplayNameRequestEpoch: () => 0,+ captureControllerPresenceRequestEpoch: () => 0,isLatestControllerDisplayNameDirectoryRefresh: vi.fn(() => true),waitForNewerControllerDisplayNameDirectoryRefresh: vi.fn(async () => {}),readControllerDisplayNameFreshnessSince: () => ({diff --git a/apps/desktop/src/main/device-link/controllerPlatform.ts b/apps/desktop/src/main/device-link/controllerPlatform.tsindex 129e4c628a..e9e991bef8 100644--- a/apps/desktop/src/main/device-link/controllerPlatform.ts+++ b/apps/desktop/src/main/device-link/controllerPlatform.ts@@ -16,13 +16,16 @@* 无依赖叶子模块,两边都能安全引用,且平台事实只有一份。*/-/**- * 手机平台取值(手机侧 `Platform.OS` 的全集)。- * 对应的桌面侧判据是 voice-input/dictionarySyncDriver 的 `DESKTOP_PLATFORMS`- * (`darwin` / `win32` / `linux`);两张表互不重叠,新增平台时同步。- */+/** 桌面平台取值(Node.js `process.platform` 中客户端支持的全集)。 */+const DESKTOP_PLATFORMS = new Set(['darwin', 'win32', 'linux']);+/** 手机平台取值(手机侧 `Platform.OS` 的全集)。 */const MOBILE_PLATFORMS = new Set(['ios', 'android']);+/** 是否桌面平台。未知值保持 fail-closed,不参与桌面词典同步。 */+export function isDesktopPlatform(platform: string | undefined | null): boolean {+ return typeof platform === 'string' && DESKTOP_PLATFORMS.has(platform);+}+/*** 是否手机平台。*@@ -35,11 +38,17 @@ export function isMobilePlatform(platform: string | undefined | null): boolean {return typeof platform === 'string' && MOBILE_PLATFORMS.has(platform);}+/** 是否当前客户端认识的平台;目录只用这些值初始化在线设备。 */+export function isSupportedControllerPlatform(platform: string | undefined | null): boolean {+ return isDesktopPlatform(platform) || isMobilePlatform(platform);+}+const platformByDevice = new Map<string, string>();-/** presence 变更时登记(唯一写入点在 device-link/index.ts 的 onPresenceChanged)。 */-export function setControllerPlatform(deviceId: string, platform: string): void {- platformByDevice.set(deviceId, platform);+/** presence / 冷启动目录快照变更时登记;未知值删除旧连接代残留,保持 fail-closed。 */+export function setControllerPlatform(deviceId: string, platform: string | null): void {+ if (platform) platformByDevice.set(deviceId, platform);+ else platformByDevice.delete(deviceId);}/** 未登记(presence 未到 / 已清空)返回 undefined —— 调用方按未知处理,不要猜。 */diff --git a/apps/desktop/src/main/device-link/controllerPresenceDirectory.ts b/apps/desktop/src/main/device-link/controllerPresenceDirectory.tsnew file mode 100644index 0000000000..98a1fc897a--- /dev/null+++ b/apps/desktop/src/main/device-link/controllerPresenceDirectory.ts@@ -0,0 +1,125 @@+import { isSupportedControllerPlatform } from './controllerPlatform.js';++export interface ControllerPresenceFreshnessTracker {+ epoch: number;+ epochByDevice: Map<string, number>;+}++export interface ControllerPresenceDirectoryDevice {+ deviceId?: unknown;+ name?: unknown;+ selfName?: unknown;+ online?: unknown;+ platform?: unknown;+ isSelf?: unknown;+}++export function createControllerPresenceFreshnessTracker(): ControllerPresenceFreshnessTracker {+ return {+ epoch: 0,+ epochByDevice: new Map(),+ };+}++/** 任何实时 presence 都比它发起前的 REST 目录请求更新。 */+export function markControllerPresenceFresh(+ tracker: ControllerPresenceFreshnessTracker,+ deviceId: string,+): void {+ tracker.epoch += 1;+ tracker.epochByDevice.set(deviceId, tracker.epoch);+}++/** relay 连接代切换后,旧连接上的 presence 不能压住新目录快照。 */+export function resetControllerPresenceFreshness(+ tracker: ControllerPresenceFreshnessTracker,+): void {+ tracker.epoch += 1;+ tracker.epochByDevice.clear();+}++function presenceChangedAfterRequest(+ tracker: ControllerPresenceFreshnessTracker,+ deviceId: string,+ requestEpoch: number,+): boolean {+ return (tracker.epochByDevice.get(deviceId) ?? 0) > requestEpoch;+}++function hasRealtimePresence(+ tracker: ControllerPresenceFreshnessTracker,+ deviceId: string,+): boolean {+ return tracker.epochByDevice.has(deviceId);+}++function normalizeDirectoryName(device: ControllerPresenceDirectoryDevice): string | null {+ for (const value of [device.selfName, device.name]) {+ if (typeof value !== 'string') continue;+ const normalized = value.trim();+ if (normalized) return normalized;+ }+ return null;+}++/**+ * presence 是增量流,新连接不会收到已经在线设备的历史状态。实时 presence 到达前,+ * 设备目录持续维护当前快照;一旦当前连接代见过该设备的实时 presence,目录无论返回+ * 在线还是离线都不再覆盖状态与平台,避免滞后的 REST 快照双向误翻转。设备名仍可由+ * 目录独立更新。+ *+ * 首次看到的在线设备若缺少客户端支持的平台值,保持为「在线状态未知」,让后续真实+ * presence 仍会形成上线边沿;后续不完整目录则保留已经建立的可信在线状态,直到目录+ * 明确报告离线,避免旧版目录记录中断词典同步。+ */+export function applyControllerPresenceDirectorySnapshot(options: {+ devices: readonly ControllerPresenceDirectoryDevice[];+ requestEpoch: number;+ selfDeviceId: string | null;+ freshness: ControllerPresenceFreshnessTracker;+ getOnline: (deviceId: string) => boolean | undefined;+ setOnline: (deviceId: string, online: boolean) => void;+ forgetOnline: (deviceId: string) => void;+ setPlatform: (deviceId: string, platform: string | null) => void;+ setName: (deviceId: string, name: string) => void;+ shouldNotifyPeerOnline: (device: {+ deviceId: string;+ online: boolean;+ platform: string | null;+ }) => boolean;+ onPeerBecameOnline: (deviceId: string, platform: string | null) => void;+}): void {+ for (const device of options.devices) {+ if (typeof device.deviceId !== 'string' || !device.deviceId.trim()) continue;+ const deviceId = device.deviceId.trim();+ if (device.isSelf === true || deviceId === options.selfDeviceId) continue;+ if (presenceChangedAfterRequest(options.freshness, deviceId, options.requestEpoch)) continue;+ if (typeof device.online !== 'boolean') continue;++ const reportedPlatform =+ typeof device.platform === 'string' && device.platform.trim() ? device.platform.trim() : null;+ const platform = isSupportedControllerPlatform(reportedPlatform) ? reportedPlatform : null;+ const name = normalizeDirectoryName(device);+ if (name) options.setName(deviceId, name);++ if (hasRealtimePresence(options.freshness, deviceId)) continue;++ const wasOnline = options.getOnline(deviceId);+ if (device.online && platform === null) {+ if (wasOnline !== true) {+ options.setPlatform(deviceId, null);+ options.forgetOnline(deviceId);+ }+ continue;+ }++ options.setPlatform(deviceId, platform);+ options.setOnline(deviceId, device.online);+ if (+ wasOnline !== true &&+ options.shouldNotifyPeerOnline({ deviceId, online: device.online, platform })+ ) {+ options.onPeerBecameOnline(deviceId, platform);+ }+ }+}diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex d06e2b47ed..eedfa7713b 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -26,6 +26,7 @@ import {type DeviceLinkConnectionIssue,type DeviceLinkStatus,type DeviceInfo,+ type DeviceView,type HelloPayload,type PresenceSnapshot,type InvokeResultPayload,@@ -99,6 +100,13 @@ import {seedControllerDisplayNamesFromCache,type ControllerDisplayNameDirectoryDevice,} from './controllerDisplayNameFreshness';+import {+ applyControllerPresenceDirectorySnapshot,+ createControllerPresenceFreshnessTracker,+ markControllerPresenceFresh,+ resetControllerPresenceFreshness,+ type ControllerPresenceDirectoryDevice,+} from './controllerPresenceDirectory';import { setBusyProbe, helloBusy, pollBusyChange, resetBusyDedupe } from './busyReporter';import {DL_VOICE_DICTIONARY_SYNC_CHANNEL,@@ -159,15 +167,11 @@ export function deviceLinkApiBase(): string {}type DeviceDirectoryResponse = {- devices?: Array<{- deviceId?: unknown;- name?: unknown;- online?: unknown;- platform?: unknown;- }>;+ devices?: DeviceView[];};let controllerDisplayNameRefreshGeneration = 0;const controllerDisplayNameFreshness = createControllerDisplayNameFreshnessTracker();+const controllerPresenceFreshness = createControllerPresenceFreshnessTracker();let latestControllerDisplayNameDirectoryRefresh: {sequence: number;promise: Promise<void>;@@ -177,6 +181,10 @@ export function captureControllerDisplayNameRequestEpoch(): number {return controllerDisplayNameFreshness.epoch;}+export function captureControllerPresenceRequestEpoch(): number {+ return controllerPresenceFreshness.epoch;+}+export function beginControllerDisplayNameDirectoryRefresh(): number {return beginControllerDisplayNameDirectoryRequest(controllerDisplayNameFreshness);}@@ -232,6 +240,41 @@ export function applyControllerDisplayNameListSnapshot(});}+/**+ * Renderer 主动刷新设备列表时也会拿到同一份权威目录。复用这份快照补齐当前+ * relay 连接代的 peer 视图,避免自动刷新失败后必须等下一次重连才同步词典。+ */+export function applyControllerPresenceListSnapshot(+ devices: readonly ControllerPresenceDirectoryDevice[],+ requestEpoch: number,+): void {+ if (linkTornDown || client?.getStatus() !== 'online') return;+ applyControllerPresenceDirectorySnapshot({+ devices,+ requestEpoch,+ selfDeviceId: client.getSelfDeviceId(),+ freshness: controllerPresenceFreshness,+ getOnline: (deviceId) => presenceOnlineByDevice.get(deviceId),+ setOnline: (deviceId, online) => presenceOnlineByDevice.set(deviceId, online),+ forgetOnline: (deviceId) => presenceOnlineByDevice.delete(deviceId),+ setPlatform: setControllerPlatform,+ setName: (deviceId, name) => presenceNameByDevice.set(deviceId, name),+ shouldNotifyPeerOnline: ({ deviceId, online, platform }) =>+ online &&+ !isDeviceRevoked(deviceId) &&+ (isMobilePlatform(platform) ||+ shouldExchangeDictionaryWith({+ online,+ platform,+ revoked: false,+ })),+ onPeerBecameOnline: (deviceId, platform) => {+ if (isMobilePlatform(platform)) handleMobilePeerOnline(deviceId);+ else handleDesktopPeerOnline(deviceId);+ },+ });+}+function seedControllerDisplayNamesFromLastKnown(): void {seedControllerDisplayNamesFromCache(readLastKnownDeviceNames(),@@ -242,12 +285,14 @@ function seedControllerDisplayNamesFromLastKnown(): void {/*** presence 是增量流,新建连接不会收到已在线设备的历史快照;每个 relay 连接代- * 上线时从现有设备目录补齐展示名,避免 link-open 抢先时长期停在主机名回退。+ * 上线时从现有设备目录补齐展示名与 peer 状态,让已在线桌面立即交换词典、+ * 已在线手机立即收到只读投影。*/async function runControllerDisplayNamesFromDirectory(generation: number,directoryRequestSequence: number,- requestEpoch: number,+ displayNameRequestEpoch: number,+ presenceRequestEpoch: number,): Promise<void> {try {const result = await serverApiFetch<DeviceDirectoryResponse>('/api/device-link/devices', {@@ -267,7 +312,7 @@ async function runControllerDisplayNamesFromDirectory(devices: result.devices ?? [],cachedNames,freshness: controllerDisplayNameFreshness,- requestEpoch,+ requestEpoch: displayNameRequestEpoch,normalizeName: normalizeCachedDeviceName,setDisplayName: setControllerDisplayName,rememberName: (deviceId, name) => {@@ -277,38 +322,22 @@ async function runControllerDisplayNamesFromDirectory(void forgetLastKnownDeviceName(deviceId);},});- // presence 是增量:桌面刚连上 relay 时,已在线手机不会再发一帧上线。- // 目录补齐展示名的同时,给这些手机补一次只读词典投影。- for (const device of result.devices ?? []) {- const deviceId = typeof device.deviceId === 'string' ? device.deviceId : '';- const platform = typeof device.platform === 'string' ? device.platform : '';- if (- !deviceId- || device.online !== true- || !isMobilePlatform(platform)- || isDeviceRevoked(deviceId)- ) {- continue;- }- // 目录发现也要写回后续广播读的那份在线集合,否则只补发一次,- // 词典变更 / 开关切换时 listOnlineMobileDevices 仍是空的。- presenceOnlineByDevice.set(deviceId, true);- setControllerPlatform(deviceId, platform);- handleMobilePeerOnline(deviceId);- }+ applyControllerPresenceListSnapshot(result.devices ?? [], presenceRequestEpoch);} catch (err) {- // 目录补齐是展示层 best-effort;失败时保留控制帧自报名 / 短 ID 回退,不影响建链。- log.warn(`device directory display-name refresh failed (non-fatal): ${String(err)}`);+ // 目录补齐是 best-effort;失败时展示名仍有回退,peer 状态仍可由后续 presence 补上。+ log.warn(`device directory peer refresh failed (non-fatal): ${String(err)}`);}}function refreshControllerDisplayNamesFromDirectory(generation: number): Promise<void> {const directoryRequestSequence = beginControllerDisplayNameDirectoryRefresh();- const requestEpoch = controllerDisplayNameFreshness.epoch;+ const displayNameRequestEpoch = controllerDisplayNameFreshness.epoch;+ const presenceRequestEpoch = controllerPresenceFreshness.epoch;const promise = runControllerDisplayNamesFromDirectory(generation,directoryRequestSequence,- requestEpoch,+ displayNameRequestEpoch,+ presenceRequestEpoch,);latestControllerDisplayNameDirectoryRefresh = {sequence: directoryRequestSequence,@@ -698,6 +727,9 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): vpresenceOnlineByDevice.clear();presenceAvailableByDevice.clear();resetControllerDisplayNameFreshness(controllerDisplayNameFreshness);+ resetControllerPresenceFreshness(controllerPresenceFreshness);+ clearControllerPlatforms();+ presenceNameByDevice.clear();}broadcast(DEVICE_LINK_PUSH.STATUS_CHANGED, { status });handleContactsDeviceLinkStatusChanged(status === 'online');@@ -741,6 +773,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): vtransportTimeoutReopen.trigger(deviceId);});client.onPresenceChanged((snap: PresenceSnapshot) => {+ markControllerPresenceFresh(controllerPresenceFreshness, snap.deviceId);const wasAvailable = presenceAvailableByDevice.get(snap.deviceId);const available = snap.online && snap.remoteControlEnabled;const wasOnline = presenceOnlineByDevice.get(snap.deviceId);@@ -1186,6 +1219,7 @@ function teardownActiveLink(): void {// client 为 null 时 sendPush 也是 no-op。presenceOnlineByDevice.clear();resetControllerDisplayNameFreshness(controllerDisplayNameFreshness);+ resetControllerPresenceFreshness(controllerPresenceFreshness);clearControllerPlatforms();clearControllerDisplayNames();presenceNameByDevice.clear();diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex 3baff648df..63a44bbcee 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -42,8 +42,10 @@ import {broadcast,deviceLinkApiBase,applyControllerDisplayNameListSnapshot,+ applyControllerPresenceListSnapshot,beginControllerDisplayNameDirectoryRefresh,captureControllerDisplayNameRequestEpoch,+ captureControllerPresenceRequestEpoch,isLatestControllerDisplayNameDirectoryRefresh,readControllerDisplayNameFreshnessSince,waitForNewerControllerDisplayNameDirectoryRefresh,@@ -119,10 +121,15 @@ export interface DeviceLinkIpcDeps {devices: readonly DeviceLinkServerDeviceView[],requestEpoch: number,): void;+ applyControllerPresenceListSnapshot(+ devices: readonly DeviceLinkServerDeviceView[],+ requestEpoch: number,+ ): void;beginControllerDisplayNameDirectoryRefresh(): number;isLatestControllerDisplayNameDirectoryRefresh(sequence: number): boolean;waitForNewerControllerDisplayNameDirectoryRefresh(sequence: number): Promise<void>;captureControllerDisplayNameRequestEpoch(): number;+ captureControllerPresenceRequestEpoch(): number;readControllerDisplayNameFreshnessSince(deviceId: string,requestEpoch: number,@@ -173,8 +180,10 @@ export function defaultDeps(): DeviceLinkIpcDeps {rememberLastKnownDeviceName,forgetLastKnownDeviceName,applyControllerDisplayNameListSnapshot,+ applyControllerPresenceListSnapshot,beginControllerDisplayNameDirectoryRefresh,captureControllerDisplayNameRequestEpoch,+ captureControllerPresenceRequestEpoch,isLatestControllerDisplayNameDirectoryRefresh,readControllerDisplayNameFreshnessSince,waitForNewerControllerDisplayNameDirectoryRefresh,@@ -333,6 +342,7 @@ export function handleListDevices(const sequence = ++deviceListRequestSequence;const directoryRequestSequence = deps.beginControllerDisplayNameDirectoryRefresh();const requestEpoch = deps.captureControllerDisplayNameRequestEpoch();+ const presenceRequestEpoch = deps.captureControllerPresenceRequestEpoch();let request!: Promise<DeviceListResult>;request = deps.apiFetch<{ devices: DeviceLinkServerDeviceView[] }>('/api/device-link/devices',@@ -345,6 +355,7 @@ export function handleListDevices();if (isLatestDirectorySnapshot) {deps.applyControllerDisplayNameListSnapshot(result.devices, requestEpoch);+ deps.applyControllerPresenceListSnapshot(result.devices, presenceRequestEpoch);} else {await deps.waitForNewerControllerDisplayNameDirectoryRefresh(directoryRequestSequence);latest = latestDeviceListRequest;diff --git a/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts b/apps/desktop/src/main/voice-input/VoiceInputDataStore.tsindex b913a7b467..46a6b3020f 100644--- a/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts+++ b/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts@@ -3,11 +3,14 @@ import fs from 'node:fs';import path from 'node:path';import {+ DEFAULT_MATERIALIZE_LIMITS,addManualEntry,deleteTerms,dictionaryTermKey,+ materializeDictionary,recordLearningEvent,renameTerm,+ replaceTermAliases,termKeyFromMaterializedId,type DictationDictionaryLearningAction,type MaterializedDictionary,@@ -169,6 +172,57 @@ export class VoiceInputDataStore {);}+ editDictionaryEntry(entryId: string, nextText: string, aliases: string[]): VoiceInputSettings {+ const state = voiceDictionarySyncStore.getState();+ const termKey = termKeyFromMaterializedId(state, entryId);+ if (!termKey) return cloneSettings(this.load().settings);+ const targetKey = dictionaryTermKey(nextText);+ const visibleEntry = materializeDictionary(state).entries.find((entry) => entry.id === entryId);+ const allEntry = materializeDictionary(state, {+ ...DEFAULT_MATERIALIZE_LIMITS,+ maxAliases: Number.MAX_SAFE_INTEGER,+ }).entries.find((entry) => entry.id === entryId);+ const editableAliasKeys = new Set(+ visibleEntry?.aliases.map((alias) => dictionaryTermKey(alias.text)) ?? [],+ );+ const submittedAliasKeys = new Set(aliases.map((alias) => dictionaryTermKey(alias)));+ const visibleAliasesUnchanged =+ submittedAliasKeys.size === editableAliasKeys.size &&+ [...submittedAliasKeys].every((aliasKey) => editableAliasKeys.has(aliasKey));+ // UI 按产品上限只展示前 8 个别名。更低权重的别名仍属于同步正本,原样保存时+ // 不能把用户根本没看见的第 9 个及之后条目当作删除;但用户增删或替换了+ // 任一可见项时,提交集合就是完整显式意图,否则新别名可能立刻被隐藏高频项挤出。+ const hiddenAliases = visibleAliasesUnchanged+ ? allEntry?.aliases+ .filter((alias) => !editableAliasKeys.has(dictionaryTermKey(alias.text)))+ .map((alias) => alias.text) ?? []+ : [];+ const nextAliases = [...aliases, ...hiddenAliases].filter(+ (alias) => dictionaryTermKey(alias) !== targetKey,+ );+ return this.applyDictionaryMutation((current, clock) => {+ const nowMs = Date.now();+ // 先在原词条上替换别名,再搬到新主键。若新主键已存在,它原有的独立证据与别名+ // 会由 renameTerm 正常合并,不会被这次编辑整份覆盖掉。+ const aliasesEdited = replaceTermAliases(current, clock, {+ termKey,+ primaryText: nextText,+ aliases: nextAliases,+ nowMs,+ });+ const renamed = renameTerm(aliasesEdited.state, aliasesEdited.clock, {+ termKey,+ nextText,+ nowMs,+ });+ return {+ state: renamed.state,+ clock: renamed.clock,+ changed: aliasesEdited.changed || renamed.changed,+ };+ });+ }+recordDictionaryLearningActions(actions: DictationDictionaryLearningAction[]): {settings: VoiceInputSettings;newAutomaticEntries: Array<Pick<VoiceInputDictionaryEntry, 'id' | 'text'>>;@@ -769,6 +823,33 @@ export function registerVoiceInputDataStoreIpc(): void {},);+ ipcMain.handle(+ 'voice-input:dictionary:edit-entry',+ (+ event,+ payload: { entryId?: unknown; text?: unknown; aliases?: unknown },+ ): VoiceInputSettings => {+ try {+ assertTrustedAppRendererEvent(event);+ const entryId = typeof payload?.entryId === 'string' ? payload.entryId : '';+ const text =+ typeof payload?.text === 'string'+ ? payload.text.slice(0, MAX_VOICE_INPUT_DICTIONARY_ENTRY_CHARS)+ : '';+ const aliases = Array.isArray(payload?.aliases)+ ? payload.aliases+ .filter((item): item is string => typeof item === 'string')+ .map((item) => item.slice(0, MAX_VOICE_INPUT_DICTIONARY_ENTRY_CHARS))+ .slice(0, MAX_VOICE_INPUT_DICTIONARY_ALIASES)+ : [];+ if (!entryId) return voiceInputDataStore.getSettings();+ return voiceInputDataStore.editDictionaryEntry(entryId, text, aliases);+ } catch (error) {+ throwVoiceInputDataStoreIpcError(error);+ }+ },+ );+ipcMain.handle('voice-input:dictionary-learning:record-actions', (event, actions: unknown) => {try {// 这个 handler 直接往词典正本里写。没有守卫的话,任意子帧(webview、插件面板)diff --git a/apps/desktop/src/main/voice-input/__tests__/dictionarySyncStore.test.ts b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncStore.test.tsindex 165758dd63..48362adca6 100644--- a/apps/desktop/src/main/voice-input/__tests__/dictionarySyncStore.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncStore.test.ts@@ -44,9 +44,15 @@ const { voiceDictionarySyncStore } = await import('../VoiceDictionarySyncStore.jconst { sanitizeDictionaryLearningActions, voiceInputDataStore } = await import('../VoiceInputDataStore.js');-const { addManualEntry, createEmptySyncState, createHlcClock, deleteTerms, recordLearningEvent } = await import(- '@cindy/voice-input-core'-);+const {+ DEFAULT_MATERIALIZE_LIMITS,+ addManualEntry,+ createEmptySyncState,+ createHlcClock,+ deleteTerms,+ materializeDictionary,+ recordLearningEvent,+} = await import('@cindy/voice-input-core');const DATA_FILE = 'voice-input-data.v1.json';const SYNC_FILE = 'voice-dictionary-sync.v1.json';@@ -120,7 +126,7 @@ describe('词典同步落盘 —— 首次迁移', () => {});describe('词典同步落盘 —— 写入路径', () => {- it('手动添加、改写、删除都落到同步状态并回投影到词典文件', () => {+ it('手动添加、改写主词与误识别写法、删除都落到同步状态并回投影到词典文件', () => {writeDictionaryFile({ dictionaryEntries: [] });voiceInputDataStore.getSettings();@@ -131,10 +137,86 @@ describe('词典同步落盘 —— 写入路径', () => {voiceInputDataStore.renameDictionaryEntry(entryId, 'LiteLLM');expect(readDictionaryFile().dictionaryEntries.map((entry) => entry.text)).toEqual(['LiteLLM']);+ voiceInputDataStore.editDictionaryEntry(entryId, 'LiteLLM', ['light llm', '莱特 LLM']);+ expect(+ voiceInputDataStore.getSettings().dictionaryEntries[0].aliases.map((alias) => alias.text),+ ).toEqual(['light llm', '莱特 LLM']);+voiceInputDataStore.deleteDictionaryEntries([entryId]);expect(readDictionaryFile().dictionaryEntries).toEqual([]);});+ it('编辑可见别名时保留物化上限之外的历史别名', () => {+ writeDictionaryFile({ dictionaryEntries: [] });+ voiceInputDataStore.getSettings();+ const aliases = Array.from({ length: 10 }, (_, index) => `alias-${index}`);+ voiceDictionarySyncStore.mutate((state, clock) =>+ recordLearningEvent(state, clock, {+ text: 'Vibe Coding',+ aliases,+ stage: 'entry',+ nowMs: 1_000,+ }),+ );+ const entry = voiceDictionarySyncStore.materialize().entries[0];+ expect(entry.aliases).toHaveLength(8);++ voiceInputDataStore.editDictionaryEntry(+ entry.id,+ entry.text,+ entry.aliases.map((alias) => alias.text),+ );++ const allAliases = materializeDictionary(voiceDictionarySyncStore.getState(), {+ ...DEFAULT_MATERIALIZE_LIMITS,+ maxAliases: Number.MAX_SAFE_INTEGER,+ }).entries[0].aliases;+ expect(allAliases.map((alias) => alias.text).sort()).toEqual(aliases.sort());++ voiceInputDataStore.editDictionaryEntry(entry.id, entry.text, []);+ expect(+ materializeDictionary(voiceDictionarySyncStore.getState(), {+ ...DEFAULT_MATERIALIZE_LIMITS,+ maxAliases: Number.MAX_SAFE_INTEGER,+ }).entries[0].aliases,+ ).toEqual([]);+ });++ it('替换可见别名时以提交集合为准,不让隐藏高频别名挤掉新值', () => {+ writeDictionaryFile({ dictionaryEntries: [] });+ voiceInputDataStore.getSettings();+ const aliases = Array.from({ length: 10 }, (_, index) => `alias-${index}`);+ for (const [index, alias] of aliases.entries()) {+ for (let count = 0; count < aliases.length - index; count += 1) {+ voiceDictionarySyncStore.mutate((state, clock) =>+ recordLearningEvent(state, clock, {+ text: 'Vibe Coding',+ aliases: [alias],+ stage: 'entry',+ nowMs: 1_000 + index,+ }),+ );+ }+ }+ const entry = voiceDictionarySyncStore.materialize().entries[0];+ expect(entry.aliases).toHaveLength(8);++ const submittedAliases = [+ ...entry.aliases.slice(1).map((alias) => alias.text),+ 'brand new alias',+ ];+ voiceInputDataStore.editDictionaryEntry(entry.id, entry.text, submittedAliases);++ const visibleAliases = voiceDictionarySyncStore.materialize().entries[0].aliases;+ expect(visibleAliases.map((alias) => alias.text)).toContain('brand new alias');+ expect(visibleAliases.map((alias) => alias.text)).not.toContain(entry.aliases[0].text);+ const allAliases = materializeDictionary(voiceDictionarySyncStore.getState(), {+ ...DEFAULT_MATERIALIZE_LIMITS,+ maxAliases: Number.MAX_SAFE_INTEGER,+ }).entries[0].aliases;+ expect(allAliases.map((alias) => alias.text).sort()).toEqual(submittedAliases.sort());+ });+it('通用 settings 更新不能整份覆盖词典(会绕过同步状态)', () => {writeDictionaryFile({ dictionaryEntries: [] });voiceInputDataStore.addManualDictionaryEntry('Cindy');@@ -816,6 +898,18 @@ describe('词典同步落盘 —— 第十轮收口', () => {expect(body).toContain('sanitizeDictionaryEntryIds');});+ it('编辑误识别写法的 IPC 校验 sender,并限制条数与单条长度', () => {+ const source = fs.readFileSync(+ path.join(__dirname, '..', 'VoiceInputDataStore.ts'),+ 'utf-8',+ );+ const handler = source.slice(source.indexOf("'voice-input:dictionary:edit-entry'"));+ const body = handler.slice(0, handler.indexOf('});'));+ expect(body).toContain('assertTrustedAppRendererEvent');+ expect(body).toContain('MAX_VOICE_INPUT_DICTIONARY_ENTRY_CHARS');+ expect(body).toContain('MAX_VOICE_INPUT_DICTIONARY_ALIASES');+ });+it('用户显式打开同步会被记成 override,即使它和当前默认值相同', () => {writeDictionaryFile({ dictionaryEntries: [] });voiceInputDataStore.updateSettings({ dictionarySyncEnabled: false });diff --git a/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts b/apps/desktop/src/main/voice-input/dictionarySyncDriver.tsindex d5b5cc93da..fdb5c743d2 100644--- a/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts+++ b/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts@@ -19,10 +19,13 @@ import { MAX_FRAME_BYTES } from '@cindy/device-link';import type { MobileVoiceDictionarySnapshotResult } from '@cindy/maker-shared/device-link-contract';import { buildStateVersionVector, type VoiceDictionarySyncState } from '@cindy/voice-input-core';+import { isDesktopPlatform } from '../device-link/controllerPlatform.js';import { createLogger } from '../logger.js';import { voiceDictionarySyncStore } from './VoiceDictionarySyncStore.js';import { voiceInputDataStore } from './VoiceInputDataStore.js';+export { isDesktopPlatform };+const log = createLogger('voice-input:dictionary-sync-driver');/** push 帧 channel。payload 形状见 {@link DictionarySyncFramePayload}。 */@@ -32,8 +35,6 @@ export const DL_VOICE_DICTIONARY_SYNC_CHANNEL = 'device-link:voice:dictionary:syconst BROADCAST_DEBOUNCE_MS = 8_000;/** 兜底心跳:即便没有任何本地变更,也定期交换一次,收敛因丢帧错过的状态。 */const BROADCAST_INTERVAL_MS = 30 * 60 * 1000;-/** 桌面平台白名单:手机(ios/android)不参与 push 同步。 */-const DESKTOP_PLATFORMS = new Set(['darwin', 'win32', 'linux']);/*** 单帧状态的字节上限,留出信封与编码余量。*@@ -76,10 +77,6 @@ let intervalTimer: NodeJS.Timeout | null = null;/** 同进程内快照发出序号:取墙上时间与上一发+1 的较大值,时钟回拨也不会倒序。 */let lastEmittedAt = 0;-export function isDesktopPlatform(platform: string | undefined | null): boolean {- return typeof platform === 'string' && DESKTOP_PLATFORMS.has(platform);-}-/*** 是否与某台设备交换词典。*@@ -200,7 +197,11 @@ export function handleIncomingDictionaryState(src: string, payload: unknown): vo* (而不是报错),手机侧照常降级到无词典,不打断语音输入。*/export function readDictionaryProjectionForMobile(): {- entries: Array<{ text: string; frequency: number; aliases: Array<{ text: string; count: number }> }>;+ entries: Array<{+ text: string;+ frequency: number;+ aliases: Array<{ text: string; count: number }>;+ }>;stateVector?: Record<string, string>;} {// 版本向量对合并单调(逐节点取 max),所以「逐节点 ≥」等价于「已经见过对方的@@ -264,8 +265,8 @@ function buildMobileSnapshot(): MobileVoiceDictionarySnapshotResult | null {// 与桌面 CRDT 同一条上限:超限帧会被 relay 拒绝。这里不另造分片协议,// 手机保留上次缓存,词典缩小后下一次上线/变更再推。log.error(- `mobile dictionary snapshot is too large to push (${bytes} bytes > ${MAX_STATE_FRAME_BYTES}); `- + 'phones will keep their last cache until the dictionary shrinks',+ `mobile dictionary snapshot is too large to push (${bytes} bytes > ${MAX_STATE_FRAME_BYTES}); ` ++ 'phones will keep their last cache until the dictionary shrinks',);return null;}@@ -310,8 +311,8 @@ function buildFrame(options?: { requestReply?: boolean }): DictionarySyncFramePa// 超限:发出去只会被 relay 拒绝并抛错,且此后每次广播都一样。宁可这一轮不发,// 也要让日志把原因说清楚 —— 否则表现是「同步无声无息地不工作了」。log.error(- `dictionary state frame is too large to sync (${bytes} bytes > ${MAX_STATE_FRAME_BYTES}); `- + 'peers will not receive updates until the dictionary shrinks',+ `dictionary state frame is too large to sync (${bytes} bytes > ${MAX_STATE_FRAME_BYTES}); ` ++ 'peers will not receive updates until the dictionary shrinks',);return null;}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex e6029d6e7f..810785e228 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1495,6 +1495,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('voice-input:dictionary:import-entries', texts),renameDictionaryEntry: (entryId: string, text: string): Promise<unknown> =>ipcRenderer.invoke('voice-input:dictionary:rename-entry', { entryId, text }),+ editDictionaryEntry: (entryId: string, text: string, aliases: string[]): Promise<unknown> =>+ ipcRenderer.invoke('voice-input:dictionary:edit-entry', { entryId, text, aliases }),recordDictionaryLearningActions: (actions: unknown[]): Promise<unknown> =>ipcRenderer.invoke('voice-input:dictionary-learning:record-actions', actions),getHistory: (limit?: number): unknown => {diff --git a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsxindex 4ef8873817..e125ffd668 100644--- a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx+++ b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx@@ -44,6 +44,11 @@ import {} from '@/voice-input/appShortcutConflict';import { findComposerVoiceInputConflict } from '@/voice-input/composerVoiceInputConflict';import { shouldShowInputMonitoringBadge } from '@/voice-input/inputMonitoringBadge';+import {+ formatVoiceInputDictionaryAliasDraft,+ parseVoiceInputDictionaryAliasDraft,+ voiceInputDictionaryEntryMatches,+} from '@/voice-input/dictionaryEditor';import {createVoiceInputModifierShortcut,createVoiceInputShortcutFromEvent,@@ -161,17 +166,6 @@ function formatUsd(costUsd: number): string {return `$${costUsd.toFixed(2)}`;}-function dictionaryEntryMatches(- entry: VoiceInputDictionaryEntry,- filter: DictionaryFilter,- query: string,-): boolean {- if (filter !== 'all' && entry.source !== filter) return false;- const normalizedQuery = query.trim().toLocaleLowerCase();- if (!normalizedQuery) return true;- return entry.text.toLocaleLowerCase().includes(normalizedQuery);-}-function dictionarySourceIcon(source: VoiceInputDictionaryEntrySource): ReactNode {if (source === 'automatic') return <Sparkles size={14} />;return <Keyboard size={14} />;@@ -1069,7 +1063,7 @@ export function VoiceInputSection() {setDictionarySyncEnabled,addDictionaryEntry: addDictionarySettingEntry,importDictionaryEntries: importDictionarySettingEntries,- renameDictionaryEntry: renameDictionarySettingEntry,+ editDictionaryEntry: editDictionarySettingEntry,deleteDictionaryEntry: deleteDictionarySettingEntry,setShortcut,} = useVoiceInputSettings();@@ -1091,6 +1085,7 @@ export function VoiceInputSection() {const [newDictionaryEntryText, setNewDictionaryEntryText] = useState('');const [editingDictionaryEntryId, setEditingDictionaryEntryId] = useState<string | null>(null);const [editingDictionaryEntryText, setEditingDictionaryEntryText] = useState('');+ const [editingDictionaryEntryAliases, setEditingDictionaryEntryAliases] = useState('');const [permissions, setPermissions] = useState<VoiceInputSystemPermissions>(() =>normalizeVoiceInputSystemPermissions(window.electronAPI.voiceInput.getSystemPermissionsCached()));@@ -1797,7 +1792,7 @@ export function VoiceInputSection() {() =>settings.dictionaryEntries.filter((entry) =>- dictionaryEntryMatches(entry, dictionaryFilter, dictionarySearch),+ voiceInputDictionaryEntryMatches(entry, dictionaryFilter, dictionarySearch),).sort((a, b) => {if (a.source !== b.source) return a.source === 'manual' ? -1 : 1;@@ -1908,11 +1903,13 @@ export function VoiceInputSection() {const startEditingDictionaryEntry = useCallback((entry: VoiceInputDictionaryEntry) => {setEditingDictionaryEntryId(entry.id);setEditingDictionaryEntryText(entry.text);+ setEditingDictionaryEntryAliases(formatVoiceInputDictionaryAliasDraft(entry.aliases));}, []);const cancelEditingDictionaryEntry = useCallback(() => {setEditingDictionaryEntryId(null);setEditingDictionaryEntryText('');+ setEditingDictionaryEntryAliases('');}, []);const saveEditingDictionaryEntry = useCallback(() => {@@ -1925,15 +1922,17 @@ export function VoiceInputSection() {});return;}- void renameDictionarySettingEntry(editingDictionaryEntryId, text).then((ok) => {+ const aliases = parseVoiceInputDictionaryAliasDraft(editingDictionaryEntryAliases, text);+ void editDictionarySettingEntry(editingDictionaryEntryId, text, aliases).then((ok) => {if (ok) cancelEditingDictionaryEntry();});}, [cancelEditingDictionaryEntry,deleteDictionarySettingEntry,+ editDictionarySettingEntry,+ editingDictionaryEntryAliases,editingDictionaryEntryId,editingDictionaryEntryText,- renameDictionarySettingEntry,]);const deleteDictionaryEntry = useCallback(@@ -2454,92 +2453,192 @@ export function VoiceInputSection() {'group min-w-0 rounded-[12px] border border-[var(--settings-input-border)]','bg-[var(--settings-input-bg)] px-3 py-2.5 transition-colors','hover:bg-[var(--settings-menu-bg-hover)]',+ editing && 'md:col-span-2',)}>{editing ? (- <div className="flex min-w-0 items-center gap-1.5">- <input- ref={editingDictionaryEntryInputRef}- value={editingDictionaryEntryText}- onChange={(event) => setEditingDictionaryEntryText(event.currentTarget.value)}- onKeyDown={(event) => {- if (event.key === 'Enter' && !event.nativeEvent.isComposing) {- event.preventDefault();- saveEditingDictionaryEntry();+ <div className="flex min-w-0 flex-col gap-2.5">+ <label className="flex min-w-0 flex-col gap-1">+ <span className="text-11 font-medium text-[var(--settings-section-sublabel)]">+ {t('settings.voiceInput.refinement.dictionary.termLabel')}+ </span>+ <input+ ref={editingDictionaryEntryInputRef}+ value={editingDictionaryEntryText}+ onChange={(event) =>+ setEditingDictionaryEntryText(event.currentTarget.value)}- if (event.key === 'Escape') {- cancelEditingDictionaryEntry();+ onKeyDown={(event) => {+ if (+ event.key === 'Enter' &&+ !event.nativeEvent.isComposing+ ) {+ event.preventDefault();+ saveEditingDictionaryEntry();+ }+ if (event.key === 'Escape') cancelEditingDictionaryEntry();+ }}+ aria-label={t(+ 'settings.voiceInput.refinement.dictionary.editAriaLabel',+ )}+ className={cn(+ 'h-9 min-w-0 rounded-full px-3 text-13',+ 'border border-[var(--settings-input-border)] bg-[var(--settings-theme-card-bg)]',+ 'text-[var(--settings-input-text)] outline-none transition-colors',+ 'focus-visible:border-[var(--settings-input-border-focus)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',+ )}+ />+ </label>++ <label className="flex min-w-0 flex-col gap-1">+ <span className="text-11 font-medium text-[var(--settings-section-sublabel)]">+ {t(+ 'settings.voiceInput.refinement.dictionary.aliasesEditLabel',+ )}+ </span>+ <textarea+ value={editingDictionaryEntryAliases}+ onChange={(event) =>+ setEditingDictionaryEntryAliases(event.currentTarget.value)}- }}- aria-label={t('settings.voiceInput.refinement.dictionary.editAriaLabel')}- className="h-8 min-w-0 flex-1 bg-transparent text-13 text-[var(--settings-input-text)] outline-none"- />- <Tip text={t('settings.voiceInput.refinement.dictionary.save')} side="top">- <button- type="button"- onClick={saveEditingDictionaryEntry}- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-[var(--settings-section-title)] text-[var(--settings-theme-card-bg)] transition-opacity hover:opacity-85"- aria-label={t('settings.voiceInput.refinement.dictionary.save')}- >- <Check size={14} />- </button>- </Tip>- <Tip text={t('settings.voiceInput.refinement.dictionary.cancel')} side="top">- <button- type="button"- onClick={cancelEditingDictionaryEntry}+ onKeyDown={(event) => {+ if (+ (event.metaKey || event.ctrlKey) &&+ event.key === 'Enter' &&+ !event.nativeEvent.isComposing+ ) {+ event.preventDefault();+ saveEditingDictionaryEntry();+ }+ if (event.key === 'Escape') cancelEditingDictionaryEntry();+ }}+ aria-label={t(+ 'settings.voiceInput.refinement.dictionary.aliasesEditAriaLabel',+ )}+ placeholder={t(+ 'settings.voiceInput.refinement.dictionary.aliasesPlaceholder',+ )}+ rows={3}className={cn(- 'flex h-7 w-7 shrink-0 items-center justify-center rounded-full transition-colors',- 'border border-[var(--settings-btn-secondary-border)]',- 'bg-[var(--settings-btn-secondary-bg)] text-[var(--settings-btn-secondary-text)]',- 'hover:bg-[var(--settings-btn-secondary-hover-bg)]',+ 'min-h-[76px] w-full resize-y rounded-lg px-3 py-2 text-12 leading-[1.45]',+ 'border border-[var(--settings-input-border)] bg-[var(--settings-theme-card-bg)]',+ 'text-[var(--settings-input-text)] outline-none transition-colors',+ 'placeholder:text-[var(--text-placeholder)]',+ 'focus-visible:border-[var(--settings-input-border-focus)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',)}- aria-label={t('settings.voiceInput.refinement.dictionary.cancel')}+ />+ <span className="text-11 leading-[1.35] text-[var(--settings-section-sublabel)] opacity-70">+ {t('settings.voiceInput.refinement.dictionary.aliasesEditHint')}+ </span>+ </label>++ <div className="flex items-center justify-end gap-1.5">+ <Tip+ text={t('settings.voiceInput.refinement.dictionary.cancel')}+ side="top">- <X size={14} />- </button>- </Tip>+ <button+ type="button"+ onClick={cancelEditingDictionaryEntry}+ className={cn(+ 'flex h-7 w-7 shrink-0 items-center justify-center rounded-full transition-colors',+ 'border border-[var(--settings-btn-secondary-border)]',+ 'bg-[var(--settings-btn-secondary-bg)] text-[var(--settings-btn-secondary-text)]',+ 'hover:bg-[var(--settings-btn-secondary-hover-bg)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',+ )}+ aria-label={t(+ 'settings.voiceInput.refinement.dictionary.cancel',+ )}+ >+ <X size={14} />+ </button>+ </Tip>+ <Tip+ text={t('settings.voiceInput.refinement.dictionary.save')}+ side="top"+ >+ <button+ type="button"+ onClick={saveEditingDictionaryEntry}+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-[var(--settings-section-title)] text-[var(--settings-theme-card-bg)] transition-opacity hover:opacity-85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"+ aria-label={t(+ 'settings.voiceInput.refinement.dictionary.save',+ )}+ >+ <Check size={14} />+ </button>+ </Tip>+ </div></div>) : (- <div className="flex min-w-0 items-center gap-2">+ <div className="flex min-w-0 items-start gap-2"><spanrole="img"className={cn(- 'flex h-4 w-4 shrink-0 items-center justify-center rounded-full',+ 'mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full',entry.source === 'automatic'? 'text-[var(--settings-section-title)] opacity-70': 'text-[var(--settings-section-sublabel)] opacity-45',)}- aria-label={t(`settings.voiceInput.refinement.dictionary.sources.${entry.source}`)}- title={t(`settings.voiceInput.refinement.dictionary.sources.${entry.source}`)}+ aria-label={t(+ `settings.voiceInput.refinement.dictionary.sources.${entry.source}`,+ )}+ title={t(+ `settings.voiceInput.refinement.dictionary.sources.${entry.source}`,+ )}>{dictionarySourceIcon(entry.source)}</span>- <span className="min-w-0 flex-1 truncate text-13 font-medium text-[var(--settings-section-title)]">- {entry.text}- </span>+ <div className="min-w-0 flex-1">+ <p className="truncate text-13 font-medium text-[var(--settings-section-title)]">+ {entry.text}+ </p>+ {entry.aliases.length > 0 ? (+ <p className="mt-0.5 line-clamp-2 text-11 leading-[1.35] text-[var(--settings-section-sublabel)] opacity-75">+ {t('settings.voiceInput.refinement.dictionary.aliases', {+ aliases: entry.aliases+ .map((alias) => alias.text)+ .join(+ t(+ 'settings.voiceInput.refinement.dictionary.aliasSeparator',+ ),+ ),+ })}+ </p>+ ) : null}+ </div><divclassName={cn('flex shrink-0 items-center gap-1 opacity-0 transition-opacity','group-hover:opacity-100 group-focus-within:opacity-100',)}>- <Tip text={t('settings.voiceInput.refinement.dictionary.edit')} side="top">+ <Tip+ text={t('settings.voiceInput.refinement.dictionary.edit')}+ side="top"+ ><buttontype="button"onClick={() => startEditingDictionaryEntry(entry)}- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--settings-section-sublabel)] transition-colors hover:bg-[var(--settings-btn-secondary-hover-bg)] hover:text-[var(--settings-section-title)]"- aria-label={t('settings.voiceInput.refinement.dictionary.edit')}+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--settings-section-sublabel)] transition-colors hover:bg-[var(--settings-btn-secondary-hover-bg)] hover:text-[var(--settings-section-title)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"+ aria-label={t(+ 'settings.voiceInput.refinement.dictionary.edit',+ )}><Pencil size={13} /></button></Tip>- <Tip text={t('settings.voiceInput.refinement.dictionary.delete')} side="top">+ <Tip+ text={t('settings.voiceInput.refinement.dictionary.delete')}+ side="top"+ ><buttontype="button"onClick={() => deleteDictionaryEntry(entry.id)}- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--settings-section-sublabel)] transition-colors hover:bg-[var(--settings-btn-secondary-hover-bg)] hover:text-[var(--settings-section-title)]"- aria-label={t('settings.voiceInput.refinement.dictionary.delete')}+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--settings-section-sublabel)] transition-colors hover:bg-[var(--settings-btn-secondary-hover-bg)] hover:text-[var(--settings-section-title)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"+ aria-label={t(+ 'settings.voiceInput.refinement.dictionary.delete',+ )}><Trash2 size={13} /></button>diff --git a/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts b/apps/desktop/src/renderer/hooks/useVoiceInputSettings.tsindex 6baf9f64e7..e9bd228e17 100644--- a/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts+++ b/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts@@ -202,6 +202,7 @@ export function useVoiceInputSettings(): {addDictionaryEntry: (text: string) => Promise<boolean>;importDictionaryEntries: (texts: string[]) => Promise<boolean>;renameDictionaryEntry: (entryId: string, text: string) => Promise<boolean>;+ editDictionaryEntry: (entryId: string, text: string, aliases: string[]) => Promise<boolean>;deleteDictionaryEntry: (entryId: string) => Promise<boolean>;recordDictionaryLearningActions: (actions: DictationDictionaryLearningAction[]) => void;setShortcut: (shortcut: VoiceInputShortcut | null) => Promise<VoiceInputShortcutUpdateResult>;@@ -309,6 +310,14 @@ export function useVoiceInputSettings(): {[runDictionaryMutation],);+ const editDictionaryEntry = useCallback(+ (entryId: string, text: string, aliases: string[]) =>+ runDictionaryMutation(() =>+ window.electronAPI.voiceInput.editDictionaryEntry(entryId, text, aliases),+ ),+ [runDictionaryMutation],+ );+const deleteDictionaryEntry = useCallback((entryId: string) =>runDictionaryMutation(() => window.electronAPI.voiceInput.deleteDictionaryEntries([entryId])),@@ -368,6 +377,7 @@ export function useVoiceInputSettings(): {addDictionaryEntry,importDictionaryEntries,renameDictionaryEntry,+ editDictionaryEntry,deleteDictionaryEntry,recordDictionaryLearningActions,setShortcut,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex a60f6be851..83d83a71d8 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1048,6 +1048,13 @@"cancel": "Cancel","edit": "Edit","delete": "Delete",+ "termLabel": "Term",+ "aliasSeparator": ", ",+ "aliases": "Often misheard as: {{aliases}}",+ "aliasesEditLabel": "Often misheard as",+ "aliasesEditAriaLabel": "Edit common misrecognitions",+ "aliasesPlaceholder": "One misrecognition per line",+ "aliasesEditHint": "Use one per line. Clear the field to remove them all.","searchAriaLabel": "Search dictionary","closeSearch": "Close search","searchPlaceholder": "Search dictionary",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 2acf34613e..5d562064d8 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1048,6 +1048,13 @@"cancel": "キャンセル","edit": "編集","delete": "削除",+ "termLabel": "辞書の語",+ "aliasSeparator": "、",+ "aliases": "よくある誤認識:{{aliases}}",+ "aliasesEditLabel": "よくある誤認識",+ "aliasesEditAriaLabel": "よくある誤認識を編集",+ "aliasesPlaceholder": "誤認識を 1 行に 1 件入力",+ "aliasesEditHint": "1 行に 1 件入力します。すべて削除するには空欄にします。","searchAriaLabel": "辞書を検索","closeSearch": "検索を閉じる","searchPlaceholder": "辞書を検索",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 950cea6f73..a4ebab153c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1048,6 +1048,13 @@"cancel": "취소","edit": "편집","delete": "삭제",+ "termLabel": "사전 단어",+ "aliasSeparator": ", ",+ "aliases": "자주 잘못 인식됨: {{aliases}}",+ "aliasesEditLabel": "자주 잘못 인식되는 표현",+ "aliasesEditAriaLabel": "자주 잘못 인식되는 표현 편집",+ "aliasesPlaceholder": "한 줄에 하나씩 입력",+ "aliasesEditHint": "한 줄에 하나씩 입력하세요. 모두 삭제하려면 비워 두세요.","searchAriaLabel": "사전 검색","closeSearch": "검색 접기","searchPlaceholder": "사전 검색",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex d74045b361..001ffcf42c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1048,6 +1048,13 @@"cancel": "取消","edit": "编辑","delete": "删除",+ "termLabel": "词条",+ "aliasSeparator": "、",+ "aliases": "常被听成:{{aliases}}",+ "aliasesEditLabel": "常被听成",+ "aliasesEditAriaLabel": "编辑常见误识别写法",+ "aliasesPlaceholder": "每行一个误识别写法",+ "aliasesEditHint": "每行一个;清空即可删除全部误识别写法。","searchAriaLabel": "搜索词典","closeSearch": "收起搜索","searchPlaceholder": "搜索词典",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 9643569d26..9015462404 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1048,6 +1048,13 @@"cancel": "取消","edit": "編輯","delete": "刪除",+ "termLabel": "詞條",+ "aliasSeparator": "、",+ "aliases": "常被聽成:{{aliases}}",+ "aliasesEditLabel": "常被聽成",+ "aliasesEditAriaLabel": "編輯常見誤識別寫法",+ "aliasesPlaceholder": "每行一個誤識別寫法",+ "aliasesEditHint": "每行一個;清空即可刪除全部誤識別寫法。","searchAriaLabel": "搜尋詞典","closeSearch": "收起搜尋","searchPlaceholder": "搜尋詞典",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 313d842fc3..ac5c969cbf 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1758,6 +1758,11 @@ interface ElectronAPI {addDictionaryEntry: (text: string) => Promise<VoiceInputSettingsData>;importDictionaryEntries: (texts: string[]) => Promise<VoiceInputSettingsData>;renameDictionaryEntry: (entryId: string, text: string) => Promise<VoiceInputSettingsData>;+ editDictionaryEntry: (+ entryId: string,+ text: string,+ aliases: string[],+ ) => Promise<VoiceInputSettingsData>;recordDictionaryLearningActions: (actions: VoiceInputDictionaryLearningAction[]) => Promise<{settings: VoiceInputSettingsData;newAutomaticEntries: Array<{ id: string; text: string }>;diff --git a/apps/desktop/src/renderer/voice-input/__tests__/dictionaryEditor.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/dictionaryEditor.test.tsnew file mode 100644index 0000000000..07efb51eda--- /dev/null+++ b/apps/desktop/src/renderer/voice-input/__tests__/dictionaryEditor.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import type { VoiceInputDictionaryEntry } from '../../../shared/voiceInputData';+import {+ formatVoiceInputDictionaryAliasDraft,+ parseVoiceInputDictionaryAliasDraft,+ voiceInputDictionaryEntryMatches,+} from '../dictionaryEditor';++const ENTRY: VoiceInputDictionaryEntry = {+ id: 'dict:vibe-coding',+ text: 'Vibe Coding',+ source: 'automatic',+ frequency: 4,+ aliases: [+ { text: 'web coding', count: 3, lastSeenAt: 3 },+ { text: 'vibe coating', count: 1, lastSeenAt: 4 },+ ],+ createdAt: 1,+ updatedAt: 4,+};++describe('voice dictionary editor', () => {+ it('formats aliases one per line for direct editing', () => {+ expect(formatVoiceInputDictionaryAliasDraft(ENTRY.aliases)).toBe('web coding\nvibe coating');+ });++ it('removes duplicate lines and excludes the term itself', () => {+ expect(+ parseVoiceInputDictionaryAliasDraft(+ ' web coding\nVibe Coding\nWEB CODING\n vibe coating ',+ 'Vibe Coding',+ ),+ ).toEqual(['web coding', 'vibe coating']);+ });++ it('round-trips aliases containing commas and semicolons', () => {+ const aliases: VoiceInputDictionaryEntry['aliases'] = [+ { text: 'Smith, Jr.', count: 2, lastSeenAt: 3 },+ { text: 'ACME; Inc.', count: 1, lastSeenAt: 4 },+ ];+ expect(+ parseVoiceInputDictionaryAliasDraft(formatVoiceInputDictionaryAliasDraft(aliases), 'X'),+ ).toEqual(['Smith, Jr.', 'ACME; Inc.']);+ });++ it('searches both the term and its misrecognition aliases', () => {+ expect(voiceInputDictionaryEntryMatches(ENTRY, 'all', 'coating')).toBe(true);+ expect(voiceInputDictionaryEntryMatches(ENTRY, 'manual', 'coating')).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/voice-input/dictionaryEditor.ts b/apps/desktop/src/renderer/voice-input/dictionaryEditor.tsnew file mode 100644index 0000000000..45020a4153--- /dev/null+++ b/apps/desktop/src/renderer/voice-input/dictionaryEditor.ts@@ -0,0 +1,46 @@+import { dictionaryTermKey } from '@cindy/voice-input-core';++import {+ MAX_VOICE_INPUT_DICTIONARY_ALIASES,+ normalizeVoiceInputDictionaryEntryText,+ type VoiceInputDictionaryEntry,+ type VoiceInputDictionaryEntrySource,+} from '../../shared/voiceInputData';++export type VoiceInputDictionaryFilter = 'all' | VoiceInputDictionaryEntrySource;++/** 编辑框一行一个误识别写法,便于直接增删和调整。 */+export function formatVoiceInputDictionaryAliasDraft(+ aliases: VoiceInputDictionaryEntry['aliases'],+): string {+ return aliases.map((alias) => alias.text).join('\n');+}++/** 按行读取,归一化、去重并排除与主词条相同的写法。逗号和分号可以是别名正文。 */+export function parseVoiceInputDictionaryAliasDraft(draft: string, termText: string): string[] {+ const termKey = dictionaryTermKey(termText);+ const seen = new Set<string>();+ const aliases: string[] = [];+ for (const part of draft.replace(/\r\n?/g, '\n').split(/\n+/)) {+ const text = normalizeVoiceInputDictionaryEntryText(part);+ const key = dictionaryTermKey(text);+ if (!key || key === termKey || seen.has(key)) continue;+ seen.add(key);+ aliases.push(text);+ if (aliases.length >= MAX_VOICE_INPUT_DICTIONARY_ALIASES) break;+ }+ return aliases;+}++export function voiceInputDictionaryEntryMatches(+ entry: VoiceInputDictionaryEntry,+ filter: VoiceInputDictionaryFilter,+ query: string,+): boolean {+ if (filter !== 'all' && entry.source !== filter) return false;+ const normalizedQuery = query.trim().toLocaleLowerCase();+ if (!normalizedQuery) return true;+ return [entry.text, ...entry.aliases.map((alias) => alias.text)].some((text) =>+ text.toLocaleLowerCase().includes(normalizedQuery),+ );+}diff --git a/packages/voice-input-core/src/__tests__/dictionarySyncAliasEdit.test.ts b/packages/voice-input-core/src/__tests__/dictionarySyncAliasEdit.test.tsnew file mode 100644index 0000000000..46e73412ac--- /dev/null+++ b/packages/voice-input-core/src/__tests__/dictionarySyncAliasEdit.test.ts@@ -0,0 +1,625 @@+/**+ * 用户编辑误识别写法时的同步语义。+ *+ * 别名删除不能只改本机投影:离线设备回来会把旧 alias map 合并回来。这里锁住+ * 计数下界删除语义的核心不变量:删除不复活、并发学习不丢失、改名不重复计数。+ */++import { describe, expect, it } from "vitest";++import {+ DEFAULT_TOMBSTONE_TTL_MS,+ createEmptySyncState,+ createHlcClock,+ dictionaryTermKey,+ gcTombstones,+ isValidSyncState,+ listLiveIncarnations,+ materializeDictionary,+ mergeSyncStates,+ recordLearningEvent,+ renameTerm,+ replaceTermAliases,+} from "../dictionary-sync";+import {+ isAliasRemovalMarkerKey,+ parseAliasRemovalMarker,+} from "../dictionary-sync/alias-removal";++function learnedBase() {+ let state = createEmptySyncState();+ let clock = createHlcClock("node-a", 1_000);+ for (let round = 0; round < 4; round += 1) {+ const learned = recordLearningEvent(state, clock, {+ text: "Vibe Coding",+ aliases: round < 3 ? ["web coding"] : ["vibe coating"],+ stage: "entry",+ nowMs: 1_000 + round,+ });+ state = learned.state;+ clock = learned.clock;+ }+ return { state, clock };+}++describe("词典别名编辑", () => {+ it("完整替换别名集合,保留频次并把用户编辑认作手动词条", () => {+ const base = learnedBase();+ const edited = replaceTermAliases(base.state, base.clock, {+ termKey: "Vibe Coding",+ aliases: ["web coding", "Vibe Coder"],+ nowMs: 2_000,+ });++ const entry = materializeDictionary(edited.state).entries[0];+ expect(entry.frequency).toBe(4);+ expect(entry.source).toBe("manual");+ expect(entry.aliases.map((alias) => alias.text).sort()).toEqual([+ "Vibe Coder",+ "web coding",+ ]);+ expect(+ entry.aliases.find((alias) => alias.text === "web coding")?.count,+ ).toBe(3);+ expect(+ entry.aliases.find((alias) => alias.text === "Vibe Coder")?.count,+ ).toBe(1);+ expect(isValidSyncState(edited.state)).toBe(true);+ });++ it("离线设备带回旧状态时,被删别名不会复活", () => {+ const base = learnedBase();+ const edited = replaceTermAliases(base.state, base.clock, {+ termKey: "Vibe Coding",+ aliases: ["web coding"],+ nowMs: 2_000,+ });++ const merged = mergeSyncStates(edited.state, base.state);+ expect(+ materializeDictionary(merged).entries[0].aliases.map(+ (alias) => alias.text,+ ),+ ).toEqual(["web coding"]);+ });++ it("两台设备基于同一状态并发编辑时采用 add-wins,且词条频次不翻倍", () => {+ const base = learnedBase();+ const a = replaceTermAliases(base.state, createHlcClock("node-a", 3_000), {+ termKey: "Vibe Coding",+ aliases: ["web coding", "Vibe Coder"],+ nowMs: 3_000,+ });+ const b = replaceTermAliases(base.state, createHlcClock("node-b", 4_000), {+ termKey: "Vibe Coding",+ aliases: ["web coding", "vibe code in"],+ nowMs: 4_000,+ });++ const entry = materializeDictionary(mergeSyncStates(a.state, b.state))+ .entries[0];+ expect(entry.frequency).toBe(4);+ expect(entry.aliases.map((alias) => alias.text).sort()).toEqual([+ "Vibe Coder",+ "vibe code in",+ "web coding",+ ]);+ });++ it("删除别名不会吞掉离线设备并发产生的新学习证据", () => {+ const base = learnedBase();+ const edited = replaceTermAliases(base.state, base.clock, {+ termKey: "Vibe Coding",+ aliases: [],+ nowMs: 3_000,+ });+ const learned = recordLearningEvent(+ base.state,+ createHlcClock("node-b", 4_000),+ {+ text: "Vibe Coding",+ aliases: ["fresh alias"],+ stage: "entry",+ nowMs: 4_000,+ },+ );++ const entry = materializeDictionary(+ mergeSyncStates(edited.state, learned.state),+ ).entries[0];+ expect(entry.frequency).toBe(5);+ expect(entry.aliases.map((alias) => [alias.text, alias.count])).toEqual([+ ["fresh alias", 1],+ ]);+ });++ it("别名编辑与同目标改名并发时复用同一化身,不重复计算频次", () => {+ const base = learnedBase();+ const aliasesEdited = replaceTermAliases(base.state, base.clock, {+ termKey: "Vibe Coding",+ primaryText: "VibeCoder",+ aliases: ["web coding"],+ nowMs: 3_000,+ });+ const editedAndRenamed = renameTerm(+ aliasesEdited.state,+ aliasesEdited.clock,+ {+ termKey: "Vibe Coding",+ nextText: "VibeCoder",+ nowMs: 3_000,+ },+ );+ const directlyRenamed = renameTerm(+ base.state,+ createHlcClock("node-b", 4_000),+ {+ termKey: "Vibe Coding",+ nextText: "VibeCoder",+ nowMs: 4_000,+ },+ );++ const entry = materializeDictionary(+ mergeSyncStates(editedAndRenamed.state, directlyRenamed.state),+ ).entries[0];+ expect(entry.frequency).toBe(4);+ expect(entry.aliases.map((alias) => alias.text)).toEqual(["web coding"]);+ });++ it("别名删除与另一台设备改名并发时,删除意图跟随搬移后的化身", () => {+ const base = learnedBase();+ const aliasesEdited = replaceTermAliases(+ base.state,+ createHlcClock("node-a", 3_000),+ {+ termKey: "Vibe Coding",+ aliases: ["vibe coating"],+ nowMs: 3_000,+ },+ );+ const renamed = renameTerm(base.state, createHlcClock("node-b", 4_000), {+ termKey: "Vibe Coding",+ nextText: "VibeCoder",+ nowMs: 4_000,+ });++ const forward = mergeSyncStates(aliasesEdited.state, renamed.state);+ const backward = mergeSyncStates(renamed.state, aliasesEdited.state);+ expect(backward).toEqual(forward);+ expect(mergeSyncStates(forward, forward)).toEqual(forward);+ expect(materializeDictionary(forward).entries[0].text).toBe("VibeCoder");+ expect(+ materializeDictionary(forward).entries[0].aliases.map(+ (alias) => alias.text,+ ),+ ).toEqual(["vibe coating"]);++ const collected = gcTombstones(forward, { nowMs: 10_000, ttlMs: 0 });+ expect(+ materializeDictionary(collected).entries[0].aliases.map(+ (alias) => alias.text,+ ),+ ).toEqual(["vibe coating"]);+ });++ it("并发别名编辑可穿过连续改名链,并保持 merge 结合律", () => {+ const base = learnedBase();+ const aliasesEdited = replaceTermAliases(+ base.state,+ createHlcClock("node-a", 3_000),+ {+ termKey: "Vibe Coding",+ aliases: ["vibe coating"],+ nowMs: 3_000,+ },+ );+ const firstRename = renameTerm(+ base.state,+ createHlcClock("node-b", 4_000),+ {+ termKey: "Vibe Coding",+ nextText: "VibeCoder",+ nowMs: 4_000,+ },+ );+ const secondRename = renameTerm(firstRename.state, firstRename.clock, {+ termKey: "VibeCoder",+ nextText: "VC",+ nowMs: 5_000,+ });+ const concurrentlyLearned = recordLearningEvent(+ base.state,+ createHlcClock("node-c", 6_000),+ {+ text: "Vibe Coding",+ aliases: ["fresh alias"],+ stage: "entry",+ nowMs: 6_000,+ },+ );++ const left = mergeSyncStates(+ mergeSyncStates(aliasesEdited.state, secondRename.state),+ concurrentlyLearned.state,+ );+ const right = mergeSyncStates(+ aliasesEdited.state,+ mergeSyncStates(secondRename.state, concurrentlyLearned.state),+ );+ expect(left).toEqual(right);+ const entry = materializeDictionary(left).entries[0];+ expect(entry.text).toBe("VC");+ expect(entry.aliases.map((alias) => alias.text).sort()).toEqual([+ "fresh alias",+ "vibe coating",+ ]);+ });++ it("不同目标的并发改名与旧键学习不破坏 merge 结合律", () => {+ const base = learnedBase();+ const renamedGamma = renameTerm(+ base.state,+ createHlcClock("node-a", 3_000),+ {+ termKey: "Vibe Coding",+ nextText: "Gamma",+ nowMs: 3_000,+ },+ );+ const learned = recordLearningEvent(+ base.state,+ createHlcClock("node-b", 4_000),+ {+ text: "Vibe Coding",+ aliases: ["fresh alias"],+ stage: "entry",+ nowMs: 4_000,+ },+ );+ const renamedBeta = renameTerm(+ base.state,+ createHlcClock("node-c", 5_000),+ {+ termKey: "Vibe Coding",+ nextText: "Beta",+ nowMs: 5_000,+ },+ );++ const left = mergeSyncStates(+ mergeSyncStates(renamedGamma.state, learned.state),+ renamedBeta.state,+ );+ const right = mergeSyncStates(+ renamedGamma.state,+ mergeSyncStates(learned.state, renamedBeta.state),+ );+ expect(left).toEqual(right);+ expect(materializeDictionary(left)).toEqual(materializeDictionary(right));+ });++ it("连续修改别名不会凭空增加词条频次", () => {+ const base = learnedBase();+ const first = replaceTermAliases(base.state, base.clock, {+ termKey: "Vibe Coding",+ aliases: ["web coding"],+ nowMs: 2_000,+ });+ const second = replaceTermAliases(first.state, first.clock, {+ termKey: "Vibe Coding",+ aliases: ["Vibe Coder"],+ nowMs: 3_000,+ });++ const entry = materializeDictionary(second.state).entries[0];+ expect(entry.frequency).toBe(4);+ expect(entry.aliases.map((alias) => alias.text)).toEqual(["Vibe Coder"]);+ });++ it("删除下界跟随化身改名,旧版式的透明搬移不会让别名复活", () => {+ const base = learnedBase();+ const edited = replaceTermAliases(base.state, base.clock, {+ termKey: "Vibe Coding",+ aliases: ["web coding"],+ nowMs: 2_000,+ });+ const renamed = renameTerm(edited.state, edited.clock, {+ termKey: "Vibe Coding",+ nextText: "VibeCoder",+ nowMs: 3_000,+ });++ const record = renamed.state.records[dictionaryTermKey("VibeCoder")];+ const live = listLiveIncarnations(record);+ expect(+ live+ .flatMap((incarnation) => Object.keys(incarnation.aliases))+ .filter(isAliasRemovalMarkerKey),+ ).toHaveLength(1);+ expect(+ materializeDictionary(renamed.state).entries[0].aliases.map(+ (alias) => alias.text,+ ),+ ).toEqual(["web coding"]);+ });++ it("同一别名反复删加只更新固定删除槽,不按编辑次数增长", () => {+ let state = createEmptySyncState();+ let clock = createHlcClock("node-a", 1_000);+ const learned = recordLearningEvent(state, clock, {+ text: "内部代号",+ aliases: ["inside code"],+ stage: "entry",+ nowMs: 1_000,+ });+ state = learned.state;+ clock = learned.clock;++ for (let round = 0; round < 100; round += 1) {+ const removed = replaceTermAliases(state, clock, {+ termKey: "内部代号",+ aliases: [],+ nowMs: 2_000 + round * 2,+ });+ const restored = replaceTermAliases(removed.state, removed.clock, {+ termKey: "内部代号",+ aliases: ["inside code"],+ nowMs: 2_001 + round * 2,+ });+ state = restored.state;+ clock = restored.clock;+ }+ const removed = replaceTermAliases(state, clock, {+ termKey: "内部代号",+ aliases: [],+ nowMs: 3_000,+ });++ const record = removed.state.records[dictionaryTermKey("内部代号")];+ const aliases = listLiveIncarnations(record)[0].aliases;+ expect(Object.keys(aliases).filter(isAliasRemovalMarkerKey)).toHaveLength(+ 1,+ );+ expect(Object.keys(aliases)).toHaveLength(2);+ expect(materializeDictionary(removed.state).entries[0].aliases).toEqual([]);+ });++ it("未到期的别名删除下界保持不动,到期后与原别名成组回收", () => {+ const base = learnedBase();+ const removed = replaceTermAliases(base.state, base.clock, {+ termKey: "Vibe Coding",+ aliases: [],+ nowMs: 2_000,+ });++ expect(+ gcTombstones(removed.state, {+ nowMs: 3_000,+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,+ }),+ ).toBe(removed.state);++ const before = materializeDictionary(removed.state);+ const collected = gcTombstones(removed.state, {+ nowMs: 2_000 + DEFAULT_TOMBSTONE_TTL_MS + 1,+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,+ });+ expect(materializeDictionary(collected)).toEqual(before);+ const record = collected.records[dictionaryTermKey("Vibe Coding")];+ expect(Object.keys(listLiveIncarnations(record)[0].aliases)).toEqual([]);+ });++ it("过期前重新添加的别名不被回收,再次删除会刷新回收期限", () => {+ const base = learnedBase();+ const removed = replaceTermAliases(base.state, base.clock, {+ termKey: "Vibe Coding",+ aliases: [],+ nowMs: 2_000,+ });+ const restored = replaceTermAliases(removed.state, removed.clock, {+ termKey: "Vibe Coding",+ aliases: ["web coding"],+ nowMs: 3_000,+ });+ const collectedAfterFirstTtl = gcTombstones(restored.state, {+ nowMs: 2_000 + DEFAULT_TOMBSTONE_TTL_MS + 1,+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,+ });+ expect(+ materializeDictionary(collectedAfterFirstTtl).entries[0].aliases.map(+ (alias) => alias.text,+ ),+ ).toEqual(["web coding"]);++ const removedAgain = replaceTermAliases(restored.state, restored.clock, {+ termKey: "Vibe Coding",+ aliases: [],+ nowMs: 4_000,+ });+ const keptByRefreshedDeadline = gcTombstones(removedAgain.state, {+ nowMs: 2_000 + DEFAULT_TOMBSTONE_TTL_MS + 1,+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,+ });+ const keptRecord = keptByRefreshedDeadline.records[dictionaryTermKey("Vibe Coding")];+ const keptAliases = listLiveIncarnations(keptRecord)[0].aliases;+ expect(keptAliases["web coding"]).toBeDefined();+ expect(Object.keys(keptAliases).filter(isAliasRemovalMarkerKey)).toHaveLength(1);+ expect(materializeDictionary(keptByRefreshedDeadline).entries[0].aliases).toEqual([]);++ const collected = gcTombstones(removedAgain.state, {+ nowMs: 4_000 + DEFAULT_TOMBSTONE_TTL_MS + 1,+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,+ });+ const record = collected.records[dictionaryTermKey("Vibe Coding")];+ expect(Object.keys(listLiveIncarnations(record)[0].aliases)).toEqual([]);+ });++ it("同一别名的多节点删除下界到期后一起回收", () => {+ const base = learnedBase();+ const learnedOnB = recordLearningEvent(+ base.state,+ createHlcClock("node-b", 3_000),+ {+ text: "Vibe Coding",+ aliases: ["web coding"],+ stage: "entry",+ nowMs: 3_000,+ },+ );+ const removed = replaceTermAliases(learnedOnB.state, learnedOnB.clock, {+ termKey: "Vibe Coding",+ aliases: [],+ nowMs: 4_000,+ });+ const recordBefore = removed.state.records[dictionaryTermKey("Vibe Coding")];+ const aliasesBefore = listLiveIncarnations(recordBefore)[0].aliases;+ const webCodingMarkers = Object.entries(aliasesBefore).filter(+ ([aliasKey, alias]) =>+ parseAliasRemovalMarker(aliasKey, alias)?.aliasKey === "web coding",+ );+ expect(webCodingMarkers).toHaveLength(2);++ const collected = gcTombstones(removed.state, {+ nowMs: 4_000 + DEFAULT_TOMBSTONE_TTL_MS + 1,+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,+ });+ const recordAfter = collected.records[dictionaryTermKey("Vibe Coding")];+ expect(Object.keys(listLiveIncarnations(recordAfter)[0].aliases)).toEqual([]);+ });++ it("TTL 回收后同节点重加别名,旧副本的删除下界不会吞掉新值", () => {+ const base = learnedBase();+ const removed = replaceTermAliases(base.state, base.clock, {+ termKey: "Vibe Coding",+ aliases: [],+ nowMs: 2_000,+ });+ const collected = gcTombstones(removed.state, {+ nowMs: 2_000 + DEFAULT_TOMBSTONE_TTL_MS + 1,+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,+ });+ const restoredAt = 2_000 + DEFAULT_TOMBSTONE_TTL_MS + 2;+ const restored = replaceTermAliases(collected, removed.clock, {+ termKey: "Vibe Coding",+ aliases: ["web coding"],+ nowMs: restoredAt,+ });++ const mergedWithOldRemoval = mergeSyncStates(restored.state, removed.state);+ expect(+ materializeDictionary(mergedWithOldRemoval).entries[0].aliases.map(+ (alias) => [alias.text, alias.count],+ ),+ ).toEqual([["web coding", 1]]);++ const removedAgain = replaceTermAliases(+ mergedWithOldRemoval,+ restored.clock,+ {+ termKey: "Vibe Coding",+ aliases: [],+ nowMs: restoredAt + 1,+ },+ );+ expect(materializeDictionary(removedAgain.state).entries[0].aliases).toEqual([]);+ const beforeRefreshedTtl = gcTombstones(removedAgain.state, {+ nowMs: restoredAt + 2,+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,+ });+ const keptRecord = beforeRefreshedTtl.records[dictionaryTermKey("Vibe Coding")];+ const keptAliases = listLiveIncarnations(keptRecord)[0].aliases;+ expect(keptAliases["web coding"]).toBeDefined();+ expect(Object.keys(keptAliases).filter(isAliasRemovalMarkerKey)).toHaveLength(1);+ expect(materializeDictionary(beforeRefreshedTtl).entries[0].aliases).toEqual([]);++ const collectedAgain = gcTombstones(removedAgain.state, {+ nowMs: restoredAt + 1 + DEFAULT_TOMBSTONE_TTL_MS + 1,+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,+ });+ const record = collectedAgain.records[dictionaryTermKey("Vibe Coding")];+ expect(Object.keys(listLiveIncarnations(record)[0].aliases)).toEqual([]);+ });++ it("连续替换为不同别名时,过期回收后状态只保留当前别名", () => {+ const base = learnedBase();+ let state = base.state;+ let clock = base.clock;+ for (let round = 0; round < 100; round += 1) {+ const edited = replaceTermAliases(state, clock, {+ termKey: "Vibe Coding",+ aliases: [`alias-${round}`],+ nowMs: 2_000 + round,+ });+ state = edited.state;+ clock = edited.clock;+ }++ const recordBefore = state.records[dictionaryTermKey("Vibe Coding")];+ expect(Object.keys(listLiveIncarnations(recordBefore)[0].aliases).length).toBeGreaterThan(100);++ const collected = gcTombstones(state, {+ nowMs: 2_099 + DEFAULT_TOMBSTONE_TTL_MS + 1,+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,+ });+ const recordAfter = collected.records[dictionaryTermKey("Vibe Coding")];+ expect(Object.keys(listLiveIncarnations(recordAfter)[0].aliases)).toEqual(["alias-99"]);+ expect(materializeDictionary(collected).entries[0].aliases.map((alias) => alias.text)).toEqual([+ "alias-99",+ ]);+ });++ it("删除标记可承载点号、Unicode 别名和特殊节点身份", () => {+ const base = recordLearningEvent(+ createEmptySyncState(),+ createHlcClock("设备-😀", 1_000),+ {+ text: "产品代号",+ aliases: ["ACME.研发😀"],+ stage: "entry",+ nowMs: 1_000,+ },+ );+ const edited = replaceTermAliases(base.state, base.clock, {+ termKey: "产品代号",+ aliases: [],+ nowMs: 2_000,+ });++ expect(isValidSyncState(edited.state)).toBe(true);+ expect(+ materializeDictionary(mergeSyncStates(edited.state, base.state))+ .entries[0].aliases,+ ).toEqual([]);+ });++ it("改名到既有词条时保留目标别名,也允许把旧主词保存为别名", () => {+ const base = learnedBase();+ const target = recordLearningEvent(base.state, base.clock, {+ text: "VibeCoder",+ aliases: ["vibe coder old"],+ stage: "entry",+ nowMs: 2_000,+ });+ const aliasesEdited = replaceTermAliases(target.state, target.clock, {+ termKey: "Vibe Coding",+ primaryText: "VibeCoder",+ aliases: ["Vibe Coding", "vibe coder new"],+ nowMs: 3_000,+ });+ const renamed = renameTerm(aliasesEdited.state, aliasesEdited.clock, {+ termKey: "Vibe Coding",+ nextText: "VibeCoder",+ nowMs: 3_000,+ });++ const entry = materializeDictionary(renamed.state).entries[0];+ expect(entry.text).toBe("VibeCoder");+ expect(entry.frequency).toBe(5);+ expect(entry.aliases.map((alias) => alias.text).sort()).toEqual([+ "Vibe Coding",+ "vibe coder new",+ "vibe coder old",+ ]);+ });+});diff --git a/packages/voice-input-core/src/dictionary-sync/alias-removal.ts b/packages/voice-input-core/src/dictionary-sync/alias-removal.tsnew file mode 100644index 0000000000..a595b06f23--- /dev/null+++ b/packages/voice-input-core/src/dictionary-sync/alias-removal.ts@@ -0,0 +1,185 @@+/**+ * 别名删除下界。+ *+ * 别名计数是按节点分桶的 GCounter,不能直接删 key:离线副本会把旧值合并回来。+ * 删除时在**同一个化身的 aliases map** 里写一条零计数的隐藏别名,key 固定标识+ * “原别名 + 计数节点”,`lastSeenAt` 借作已观察计数下界。这样有三点好处:+ *+ * 1. 旧客户端会原样合并、改名搬运这条隐藏别名,但因为计数为 0 不会展示它;+ * 2. 同一别名反复删加只更新固定 key,状态不会按编辑次数增长;+ * 3. `lastSeenAt` 在旧版合并里本来就取 max,因此并发删除也会保留更高下界。+ *+ * 旧客户端不知道如何扣除下界,所以升级前仍可能显示已删除的历史别名;但它不会+ * 丢掉或破坏删除意图,新客户端再次接收状态后会正确物化。+ */++import { compareHlc, hlcWallMs, type HlcTimestamp } from "./hlc";+import {+ createDictionaryMap,+ type GCounter,+ type SyncAliasState,+} from "./types";++const ALIAS_REMOVAL_KEY_PREFIX = "\u0000cindy-alias-removal-v1:";++export interface AliasRemovalMarker {+ aliasKey: string;+ counterNodeId: string;+ removedCount: number;+}++export interface AliasRemovalState {+ floor: GCounter;+ latestStamp: HlcTimestamp;+}++export type AliasRemovalIndex = Map<string, AliasRemovalState>;++export function isAliasRemovalMarkerKey(aliasKey: string): boolean {+ return aliasKey.startsWith(ALIAS_REMOVAL_KEY_PREFIX);+}++export function createAliasRemovalMarker(+ stamp: HlcTimestamp,+ marker: AliasRemovalMarker,+): { key: string; state: SyncAliasState } {+ const payload = encodeURIComponent(+ JSON.stringify([1, marker.aliasKey, marker.counterNodeId]),+ );+ return {+ key: `${ALIAS_REMOVAL_KEY_PREFIX}${payload}`,+ state: {+ text: "",+ textStamp: stamp,+ counters: createDictionaryMap<number>(),+ // 隐藏 marker 不参与展示;这里借用旧版 merge 已有的 max 寄存器保存删除下界。+ lastSeenAt: marker.removedCount,+ },+ };+}++export function parseAliasRemovalMarker(+ aliasKey: string,+ alias: SyncAliasState,+): AliasRemovalMarker | null {+ if (!isAliasRemovalMarkerKey(aliasKey)) return null;+ try {+ const raw = JSON.parse(+ decodeURIComponent(aliasKey.slice(ALIAS_REMOVAL_KEY_PREFIX.length)),+ );+ if (!Array.isArray(raw) || raw.length !== 3 || raw[0] !== 1) return null;+ const [, removedAliasKey, counterNodeId] = raw;+ if (+ typeof removedAliasKey !== "string" ||+ removedAliasKey.length === 0 ||+ isAliasRemovalMarkerKey(removedAliasKey)+ ) {+ return null;+ }+ if (typeof counterNodeId !== "string" || counterNodeId.length === 0)+ return null;+ if (!Number.isSafeInteger(alias.lastSeenAt) || alias.lastSeenAt <= 0)+ return null;+ if (Object.values(alias.counters).some((count) => count > 0)) return null;+ return {+ aliasKey: removedAliasKey,+ counterNodeId,+ removedCount: alias.lastSeenAt,+ };+ } catch {+ return null;+ }+}++export function indexAliasRemovalMarkers(+ aliases: Readonly<Record<string, SyncAliasState>>,+): AliasRemovalIndex {+ const index: AliasRemovalIndex = new Map();+ for (const [aliasKey, alias] of Object.entries(aliases)) {+ const marker = parseAliasRemovalMarker(aliasKey, alias);+ if (!marker) continue;+ let removal = index.get(marker.aliasKey);+ if (!removal) {+ removal = {+ floor: createDictionaryMap<number>(),+ latestStamp: alias.textStamp,+ };+ index.set(marker.aliasKey, removal);+ }+ removal.floor[marker.counterNodeId] = Math.max(+ removal.floor[marker.counterNodeId] ?? 0,+ marker.removedCount,+ );+ if (compareHlc(alias.textStamp, removal.latestStamp) > 0) {+ removal.latestStamp = alias.textStamp;+ }+ }+ return index;+}++export function readAliasVisibleCount(+ counters: GCounter,+ removalFloor?: GCounter,+): number {+ let total = 0;+ for (const [nodeId, value] of Object.entries(counters)) {+ if (!Number.isFinite(value) || value <= 0) continue;+ total += Math.max(0, Math.floor(value) - (removalFloor?.[nodeId] ?? 0));+ }+ return total;+}++/**+ * 读取一个别名的当前可见计数。+ *+ * GC 后同一节点重新添加别名时,旧副本可能带回更高的历史计数与删除下界,让+ * GCounter 差值重新变成 0。别名的 LWW 文本时间戳同时承担这一代“重新添加”的+ * 证据:它晚于最新删除 marker 时至少保留 1 次用户确认,避免旧下界吞掉新值。+ */+export function readAliasStateVisibleCount(+ alias: SyncAliasState,+ removal?: AliasRemovalState,+): number {+ const count = readAliasVisibleCount(alias.counters, removal?.floor);+ if (count > 0 || !removal) return count;+ return compareHlc(alias.textStamp, removal.latestStamp) > 0 ? 1 : 0;+}++/**+ * 成组回收已经不可见且删除时间超过 TTL 的别名与删除下界。+ *+ * 原别名和 marker 必须一起删除:只删其中一边,要么会让旧计数立刻复活,要么会+ * 留下永远没有展示意义的孤儿状态。超过 TTL 才回流的旧副本仍可能把别名带回来,+ * 这个兼容边界与词条化身墓碑回收一致。+ */+export function gcExpiredRemovedAliases(+ aliases: Readonly<Record<string, SyncAliasState>>,+ thresholdMs: number,+): Record<string, SyncAliasState> {+ const floors = indexAliasRemovalMarkers(aliases);+ const latestRemovalMs = new Map<string, number>();+ for (const [aliasKey, alias] of Object.entries(aliases)) {+ const marker = parseAliasRemovalMarker(aliasKey, alias);+ if (!marker) continue;+ latestRemovalMs.set(+ marker.aliasKey,+ Math.max(latestRemovalMs.get(marker.aliasKey) ?? 0, hlcWallMs(alias.textStamp)),+ );+ }++ const expiredAliasKeys = new Set<string>();+ for (const [aliasKey, removalMs] of latestRemovalMs) {+ const alias = aliases[aliasKey];+ if (alias && readAliasStateVisibleCount(alias, floors.get(aliasKey)) > 0) continue;+ if (removalMs < thresholdMs) expiredAliasKeys.add(aliasKey);+ }+ if (expiredAliasKeys.size === 0) return aliases as Record<string, SyncAliasState>;++ const collected = createDictionaryMap<SyncAliasState>();+ for (const [aliasKey, alias] of Object.entries(aliases)) {+ const marker = parseAliasRemovalMarker(aliasKey, alias);+ const removedAliasKey = marker?.aliasKey ?? aliasKey;+ if (!expiredAliasKeys.has(removedAliasKey)) collected[aliasKey] = alias;+ }+ return collected;+}diff --git a/packages/voice-input-core/src/dictionary-sync/materialize.ts b/packages/voice-input-core/src/dictionary-sync/materialize.tsindex 246521c210..31d17f7368 100644--- a/packages/voice-input-core/src/dictionary-sync/materialize.ts+++ b/packages/voice-input-core/src/dictionary-sync/materialize.ts@@ -11,6 +11,12 @@*/import { compareHlc } from './hlc';+import { createMovedAliasResolver, type ResolveMovedAliases } from './moved-aliases';+import {+ indexAliasRemovalMarkers,+ isAliasRemovalMarkerKey,+ readAliasStateVisibleCount,+} from './alias-removal';import {hasDictionaryKey,listLiveIncarnations,@@ -92,6 +98,7 @@ export function materializeDictionary(): MaterializedDictionary {const entries: Array<MaterializedEntry & { key: string }> = [];const candidates: Array<MaterializedCandidate & { key: string }> = [];+ const resolveMovedAliases = createMovedAliasResolver(state);for (const [key, record] of Object.entries(state.records)) {const live = listLiveIncarnations(record);@@ -107,7 +114,7 @@ export function materializeDictionary(const stage = live.some((item) => item.stage === 'entry') ? 'entry' : 'candidate';const total = Math.max(1, live.reduce((sum, item) => sum + readCounterTotal(item.counters), 0));const text = pickDisplayText(live);- const aliases = mergeLiveAliases(live, limits.maxAliases);+ const aliases = mergeLiveAliases(key, live, limits.maxAliases, resolveMovedAliases);const createdAt = live.reduce((min, item) => Math.min(min, item.createdAt), live[0].createdAt);const updatedAt = live.reduce((max, item) => Math.max(max, item.updatedAt), live[0].updatedAt);@@ -148,13 +155,19 @@ export function materializeDictionary(* (化身内部按节点分桶取 max 已经在合并阶段做完,这里不会重复计入同一事件。)*/function mergeLiveAliases(+ recordKey: string,live: ReadonlyArray<DictionaryIncarnation>,maxAliases: number,+ resolveMovedAliases: ResolveMovedAliases,): MaterializedAlias[] {const totals = new Map<string, { text: string; textStamp: string; count: number; lastSeenAt: number }>();for (const incarnation of live) {- for (const [aliasKey, alias] of Object.entries(incarnation.aliases)) {- const count = readCounterTotal(alias.counters);+ const aliases = resolveMovedAliases(recordKey, incarnation);+ const removalIndex = indexAliasRemovalMarkers(aliases);+ for (const [aliasKey, alias] of Object.entries(aliases)) {+ if (isAliasRemovalMarkerKey(aliasKey)) continue;+ const count = readAliasStateVisibleCount(alias, removalIndex.get(aliasKey));+ if (count === 0) continue;const existing = totals.get(aliasKey);if (!existing) {totals.set(aliasKey, {diff --git a/packages/voice-input-core/src/dictionary-sync/move-tag.ts b/packages/voice-input-core/src/dictionary-sync/move-tag.tsnew file mode 100644index 0000000000..9627a2339d--- /dev/null+++ b/packages/voice-input-core/src/dictionary-sync/move-tag.ts@@ -0,0 +1,26 @@+import { HLC_PREFIX_LENGTH, type HlcTimestamp } from "./hlc";++/**+ * 搬移化身时用的确定性 tag。+ *+ * 两台设备必须为同一次改名算出同一个新 tag,同时又不能复用会被原键墓碑覆盖的+ * 旧 tag。保留 HLC 前缀可避免把任一设备的时钟推向未来,定长哈希则避免反复改名+ * 让 tag 持续增长。+ */+export function deriveMoveTag(+ sourceTag: HlcTimestamp,+ targetKey: string,+): HlcTimestamp {+ const prefix = sourceTag.slice(0, HLC_PREFIX_LENGTH);+ return `${prefix}mv${fold36(`${sourceTag}\u0000${targetKey}`)}`;+}++/** FNV-1a 折叠成定长 base36。只用于派生搬移标记,不参与任何安全判断。 */+function fold36(input: string): string {+ let hash = 0x811c9dc5;+ for (let index = 0; index < input.length; index += 1) {+ hash ^= input.charCodeAt(index);+ hash = Math.imul(hash, 0x01000193) >>> 0;+ }+ return hash.toString(36).padStart(7, "0");+}diff --git a/packages/voice-input-core/src/dictionary-sync/moved-aliases.ts b/packages/voice-input-core/src/dictionary-sync/moved-aliases.tsnew file mode 100644index 0000000000..57503df245--- /dev/null+++ b/packages/voice-input-core/src/dictionary-sync/moved-aliases.ts@@ -0,0 +1,119 @@+import { compareHlc, HLC_PREFIX_LENGTH, type HlcTimestamp } from "./hlc";+import { deriveMoveTag } from "./move-tag";+import {+ createDictionaryMap,+ hasDictionaryKey,+ type DictionaryIncarnation,+ type GCounter,+ type SyncAliasState,+ type VoiceDictionarySyncState,+} from "./types";++export type ResolveMovedAliases = (+ recordKey: string,+ incarnation: DictionaryIncarnation,+) => Record<string, SyncAliasState>;++interface AliasAncestor {+ recordKey: string;+ tag: HlcTimestamp;+ incarnation: DictionaryIncarnation;+}++/**+ * 解析改名链上属于同一化身的别名状态。+ *+ * State v1 没有单独的 move-op,但「原 tag 的墓碑 + 目标键上的确定性派生 tag」足以+ * 还原搬移边。这里只合并别名这类随化身搬运的状态,不改写 CRDT 正本,因此底层+ * merge 仍保持纯逐字段 join,不会因左右结合顺序产生不同结果。+ */+export function createMovedAliasResolver(+ state: VoiceDictionarySyncState,+): ResolveMovedAliases {+ const ancestorsByPrefix = new Map<string, AliasAncestor[]>();+ for (const [recordKey, record] of Object.entries(state.records)) {+ for (const [tag, incarnation] of Object.entries(record.incarnations)) {+ if (!hasDictionaryKey(record.tombstones, tag)) continue;+ const prefix = tag.slice(0, HLC_PREFIX_LENGTH);+ const ancestors = ancestorsByPrefix.get(prefix) ?? [];+ ancestors.push({ recordKey, tag, incarnation });+ ancestorsByPrefix.set(prefix, ancestors);+ }+ }++ const memo = new Map<+ string,+ Map<HlcTimestamp, Record<string, SyncAliasState>>+ >();+ const visiting = new Set<DictionaryIncarnation>();++ const resolve: ResolveMovedAliases = (recordKey, incarnation) => {+ const cached = memo.get(recordKey)?.get(incarnation.tag);+ if (cached) return cached;+ // 派生 tag 理论上不会成环;异常状态或哈希碰撞下仍要 fail-safe,避免物化递归挂死。+ if (visiting.has(incarnation)) return incarnation.aliases;+ visiting.add(incarnation);++ let aliases = incarnation.aliases;+ const prefix = incarnation.tag.slice(0, HLC_PREFIX_LENGTH);+ for (const ancestor of ancestorsByPrefix.get(prefix) ?? []) {+ if (ancestor.incarnation === incarnation) continue;+ if (deriveMoveTag(ancestor.tag, recordKey) !== incarnation.tag) continue;+ aliases = mergeAliasMaps(+ aliases,+ resolve(ancestor.recordKey, ancestor.incarnation),+ );+ }++ visiting.delete(incarnation);+ let byTag = memo.get(recordKey);+ if (!byTag) {+ byTag = new Map();+ memo.set(recordKey, byTag);+ }+ byTag.set(incarnation.tag, aliases);+ return aliases;+ };++ return resolve;+}++function mergeAliasMaps(+ a: Readonly<Record<string, SyncAliasState>>,+ b: Readonly<Record<string, SyncAliasState>>,+): Record<string, SyncAliasState> {+ const merged = createDictionaryMap<SyncAliasState>();+ for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {+ const left = a[key];+ const right = b[key];+ if (!left || !right) {+ merged[key] = left ?? right;+ continue;+ }+ const textOrder = compareHlc(left.textStamp, right.textStamp);+ const textFromLeft =+ textOrder > 0 || (textOrder === 0 && left.text >= right.text);+ merged[key] = {+ text: textFromLeft ? left.text : right.text,+ textStamp: textFromLeft ? left.textStamp : right.textStamp,+ counters: mergeCounters(left.counters, right.counters),+ lastSeenAt: Math.max(left.lastSeenAt, right.lastSeenAt),+ };+ }+ return merged;+}++function mergeCounters(a: GCounter, b: GCounter): GCounter {+ const merged = createDictionaryMap<number>();+ for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {+ const value = Math.max(normalizeCount(a[key]), normalizeCount(b[key]));+ if (value > 0) merged[key] = value;+ }+ return merged;+}++function normalizeCount(value: number | undefined): number {+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)+ return 0;+ return Math.floor(value);+}diff --git a/packages/voice-input-core/src/dictionary-sync/mutate.ts b/packages/voice-input-core/src/dictionary-sync/mutate.tsindex 4c017a1fe4..426e55ac8c 100644--- a/packages/voice-input-core/src/dictionary-sync/mutate.ts+++ b/packages/voice-input-core/src/dictionary-sync/mutate.ts@@ -11,9 +11,19 @@* 恒等于真实事件数,与同步了多少次、以什么拓扑同步无关。*/-import { HLC_PREFIX_LENGTH, tickHlc, type HlcClock, type HlcTimestamp } from './hlc';+import { compareHlc, hlcWallMs, tickHlc, type HlcClock, type HlcTimestamp } from './hlc';import { MATERIALIZED_ID_PREFIX, materializeDictionary, pickDisplayText } from './materialize';+import { deriveMoveTag } from './move-tag';+import { createMovedAliasResolver } from './moved-aliases';import { dictionaryTermKey, normalizeDictionaryTermText } from './text';+import {+ createAliasRemovalMarker,+ gcExpiredRemovedAliases,+ indexAliasRemovalMarkers,+ isAliasRemovalMarkerKey,+ readAliasStateVisibleCount,+ readAliasVisibleCount,+} from './alias-removal';import {copyDictionaryMap,createDictionaryMap,@@ -105,12 +115,13 @@ export function recordLearningEvent(// 新建化身让状态无限膨胀。落在哪个化身上不影响总数:计数按节点分桶,不同设备// 各记各的桶,合并后求和仍是真实事件总数。const target = live[0];+ const targetAliases = createMovedAliasResolver(state)(key, target);return {state: putRecord(state, key, {...record!,incarnations: {...copyDictionaryMap(record!.incarnations),- [target.tag]: bumpIncarnation(target, {+ [target.tag]: bumpIncarnation({ ...target, aliases: targetAliases }, {nodeId: clock.nodeId,stage: input.stage,aliasTexts,@@ -391,32 +402,6 @@ export interface RenameTermInput {* - 改成了另一个词(主键变了):等价于「删掉旧词 + 添加新词」。此时**不写抑制**——* 用户是在改名,不是拒绝这个词,否则新写法若日后被自动学习到会被自己的抑制挡住。*/-/**- * 搬移化身时用的确定性 tag。- *- * 要同时满足三件事:两台设备算出同一个值(否则合并后两个化身并存、频次翻倍)、- * 与原 tag 不同(否则被原键刚打下的墓碑盖住)、以及仍是规范 HLC(定长前缀 + 无点- * nodeId,校验与定序都依赖它)。- *- * 做法是保留原 tag 的墙钟与计数器段(所以它在时间序上仍落在原处,不会把任何设备的- * 时钟推向未来),只把 nodeId 段换成一个由「原 tag + 目标键」折叠出来的定长标记 ——- * 定长是必须的,否则反复改名会让 tag 越来越长。- */-function deriveMoveTag(sourceTag: HlcTimestamp, targetKey: string): HlcTimestamp {- const prefix = sourceTag.slice(0, HLC_PREFIX_LENGTH);- return `${prefix}mv${fold36(`${sourceTag}\u0000${targetKey}`)}`;-}--/** FNV-1a 折叠成定长 base36。只用于派生搬移标记,不参与任何安全判断。 */-function fold36(input: string): string {- let hash = 0x811c9dc5;- for (let index = 0; index < input.length; index += 1) {- hash ^= input.charCodeAt(index);- hash = Math.imul(hash, 0x01000193) >>> 0;- }- return hash.toString(36).padStart(7, '0');-}-export function renameTerm(state: VoiceDictionarySyncState,clock: HlcClock,@@ -428,7 +413,13 @@ export function renameTerm(if (!fromKey || !toKey) return { state, clock, changed: false };const record = state.records[fromKey];- const live = record ? listLiveIncarnations(record) : [];+ const resolveMovedAliases = createMovedAliasResolver(state);+ const live = record+ ? listLiveIncarnations(record).map((incarnation) => ({+ ...incarnation,+ aliases: resolveMovedAliases(fromKey, incarnation),+ }))+ : [];if (live.length === 0) return { state, clock, changed: false };if (fromKey !== toKey) {@@ -503,6 +494,154 @@ export function renameTerm(};}+export interface ReplaceTermAliasesInput {+ /** 要编辑的词条主键。 */+ termKey: string;+ /** 保存后的主词;改名时用它排除“别名与主词相同”,默认仍取 termKey。 */+ primaryText?: string;+ /** 保存后的完整别名集合;缺少的旧别名视为删除。 */+ aliases: ReadonlyArray<string>;+ nowMs: number;+}++/**+ * 替换一条词的完整别名集合。+ *+ * 保留别名原有的观察计数,只给真正新增或重新添加的别名记一次用户确认。删除记录+ * “当时已观察到的各节点计数下界”,物化只展示下界之后的新证据:旧副本回流不会复活,+ * 与删除并发发生的新学习也不会被吞掉。词条化身本身不替换,所以频次与并发改名都不会+ * 因这次别名编辑重复计数。+ */+export function replaceTermAliases(+ state: VoiceDictionarySyncState,+ clock: HlcClock,+ input: ReplaceTermAliasesInput,+): MutationResult {+ const key = dictionaryTermKey(input.termKey);+ const record = key ? state.records[key] : undefined;+ const resolveMovedAliases = createMovedAliasResolver(state);+ const live = record+ ? listLiveIncarnations(record).map((incarnation) => ({+ ...incarnation,+ aliases: resolveMovedAliases(key, incarnation),+ }))+ : [];+ if (!key || !record || live.length === 0) return { state, clock, changed: false };++ const primaryKey = dictionaryTermKey(input.primaryText ?? input.termKey);+ const aliasTexts = normalizeAliasTexts(input.aliases, primaryKey);+ const desired = new Map(aliasTexts.map((text) => [dictionaryTermKey(text), text]));+ const current = new Map<string, { text: string; stamp: HlcTimestamp }>();+ for (const incarnation of live) {+ const removalIndex = indexAliasRemovalMarkers(incarnation.aliases);+ for (const [aliasKey, alias] of Object.entries(incarnation.aliases)) {+ if (isAliasRemovalMarkerKey(aliasKey)) continue;+ const removal = removalIndex.get(aliasKey);+ if (readAliasStateVisibleCount(alias, removal) === 0) continue;+ const existing = current.get(aliasKey);+ if (!existing || compareHlc(alias.textStamp, existing.stamp) > 0) {+ current.set(aliasKey, { text: alias.text, stamp: alias.textStamp });+ }+ }+ }+ const unchanged =+ current.size === desired.size &&+ [...desired].every(([aliasKey, text]) => current.get(aliasKey)?.text === text) &&+ live.every((incarnation) => incarnation.source === 'manual' && incarnation.stage === 'entry');+ if (unchanged) return { state, clock, changed: false };++ const ticked = tickHlc(clock, input.nowMs);+ const primaryTag = [...live].sort((a, b) => a.tag.localeCompare(b.tag))[0].tag;+ const incarnations = copyDictionaryMap(record.incarnations);++ for (const incarnation of live) {+ const aliases = copyDictionaryMap(incarnation.aliases);+ const floors = indexAliasRemovalMarkers(incarnation.aliases);++ for (const [aliasKey, existing] of Object.entries(incarnation.aliases)) {+ if (isAliasRemovalMarkerKey(aliasKey)) continue;+ const desiredText = desired.get(aliasKey);+ if (desiredText !== undefined) {+ if (existing.text !== desiredText) {+ aliases[aliasKey] = {+ ...existing,+ text: desiredText,+ textStamp: ticked.stamp,+ };+ }+ continue;+ }++ const removal = floors?.get(aliasKey);+ const visibleCount = readAliasStateVisibleCount(existing, removal);+ if (visibleCount === 0) continue;+ const counterVisibleCount = readAliasVisibleCount(existing.counters, removal?.floor);+ for (const [counterNodeId, rawCount] of Object.entries(existing.counters)) {+ const removedCount = Math.floor(rawCount);+ if (removedCount <= (removal?.floor[counterNodeId] ?? 0)) continue;+ const marker = createAliasRemovalMarker(ticked.stamp, {+ aliasKey,+ counterNodeId,+ removedCount,+ });+ aliases[marker.key] = marker.state;+ }+ // TTL 回收后重新添加、再合并旧副本时,原 GCounter 与旧下界可能再次持平;+ // 可见性此时来自较新的 alias.textStamp。删除要刷新一个既有下界的时间戳,+ // 否则旧 marker 仍早于别名,这次删除会被误判成一次重新添加。+ if (counterVisibleCount === 0) {+ const fallbackCounter = Object.entries(existing.counters)+ .filter(([, rawCount]) => Math.floor(rawCount) > 0)+ .sort(([nodeA], [nodeB]) => nodeA.localeCompare(nodeB))[0];+ if (fallbackCounter) {+ const [counterNodeId, rawCount] = fallbackCounter;+ const marker = createAliasRemovalMarker(ticked.stamp, {+ aliasKey,+ counterNodeId,+ removedCount: Math.floor(rawCount),+ });+ aliases[marker.key] = marker.state;+ }+ }+ }++ if (incarnation.tag === primaryTag) {+ for (const [aliasKey, text] of desired) {+ if (current.has(aliasKey)) continue;+ const existing = aliases[aliasKey];+ const removal = floors?.get(aliasKey);+ const counters = copyDictionaryMap(existing?.counters);+ counters[clock.nodeId] =+ Math.max(counters[clock.nodeId] ?? 0, removal?.floor[clock.nodeId] ?? 0) + 1;+ aliases[aliasKey] = {+ ...(existing ?? {+ counters,+ lastSeenAt: input.nowMs,+ }),+ text,+ textStamp: ticked.stamp,+ counters,+ lastSeenAt: Math.max(existing?.lastSeenAt ?? 0, input.nowMs),+ };+ }+ }++ incarnations[incarnation.tag] = {+ ...incarnation,+ source: 'manual',+ stage: 'entry',+ aliases,+ updatedAt: Math.max(incarnation.updatedAt, input.nowMs),+ };+ }++ return {+ state: putRecord(state, key, { ...record, incarnations }),+ clock: ticked.clock,+ changed: true,+ };+}+/*** 把词条 id 翻译回合并主键。UI 只持有 id,删除入口需要这一步。*@@ -530,7 +669,7 @@ export interface GcOptions {ttlMs: number;}-/** 墓碑默认保留 180 天。 */+/** 词条化身墓碑默认保留 180 天。 */export const DEFAULT_TOMBSTONE_TTL_MS = 180 * 24 * 60 * 60 * 1000;/**@@ -594,34 +733,56 @@ export function pruneWeakAutomaticCandidates(* 常见的自伤。** 已知边界:回收之后,一台离线时长超过 TTL 的设备重新上线,理论上能把它手里的- * 旧化身带回来。自动词条有抑制集合兜底(抑制不过期),所以真正能复活的只剩- * 「手动词条 + 设备离线超过 TTL」这一种组合。+ * 旧化身或已删除别名带回来。自动词条有抑制集合兜底(抑制不过期),所以词条层面+ * 真正能复活的只剩「手动词条 + 设备离线超过 TTL」这一种组合;别名与它采用+ * 相同的离线兼容窗口。*/export function gcTombstones(state: VoiceDictionarySyncState,options: GcOptions,): VoiceDictionarySyncState {const threshold = options.nowMs - options.ttlMs;- let changed = false;+ const hasExpiredState = Object.values(state.records).some(+ (record) =>+ Object.values(record.tombstones).some((stamp) => hlcWallMs(stamp) < threshold) ||+ Object.values(record.incarnations).some((incarnation) =>+ Object.entries(incarnation.aliases).some(+ ([aliasKey, alias]) =>+ isAliasRemovalMarkerKey(aliasKey) && hlcWallMs(alias.textStamp) < threshold,+ ),+ ),+ );+ if (!hasExpiredState) return state;++ // 并发别名编辑可能仍挂在即将回收的改名前化身上。先沿搬移链把别名状态压实到+ // 所有保留下来的后继化身,再删过期状态;否则 180 天后被删别名会在新词上复活。+ const resolveMovedAliases = createMovedAliasResolver(state);// 用户文本作键 —— 必须无原型,否则 GC 后给 `__proto__` 赋值会走原型 setter,// 那条合法词条会被静默丢掉,而且这个丢失还会被持久化并同步出去。const records: Record<string, DictionaryRecord> = createDictionaryMap<DictionaryRecord>();+ let changed = false;for (const [key, record] of Object.entries(state.records)) {const tombstones: Record<HlcTimestamp, HlcTimestamp> = createDictionaryMap<HlcTimestamp>();const expired = new Set<HlcTimestamp>();for (const [tag, stamp] of Object.entries(record.tombstones)) {- if (readTombstoneWallMs(stamp) < threshold) expired.add(tag);+ if (hlcWallMs(stamp) < threshold) {+ expired.add(tag);+ changed = true;+ }else tombstones[tag] = stamp;}- if (expired.size === 0) {- records[key] = record;- continue;- }- changed = true;const incarnations: Record<HlcTimestamp, DictionaryIncarnation> = createDictionaryMap<DictionaryIncarnation>();for (const [tag, incarnation] of Object.entries(record.incarnations)) {- if (!expired.has(tag)) incarnations[tag] = incarnation;+ if (!expired.has(tag)) {+ const resolvedAliases = resolveMovedAliases(key, incarnation);+ const aliases = gcExpiredRemovedAliases(resolvedAliases, threshold);+ changed = changed || aliases !== resolvedAliases;+ incarnations[tag] = {+ ...incarnation,+ aliases,+ };+ }}if (Object.keys(incarnations).length > 0 || Object.keys(tombstones).length > 0) {records[key] = { incarnations, tombstones };@@ -631,11 +792,6 @@ export function gcTombstones(return changed ? { ...state, records } : state;}-function readTombstoneWallMs(stamp: HlcTimestamp): number {- const parsed = Number.parseInt(stamp.slice(0, 10), 36);- return Number.isFinite(parsed) ? parsed : 0;-}-function putRecord(state: VoiceDictionarySyncState,key: string,@@ -726,7 +882,7 @@ function normalizeAliasTexts(aliases: ReadonlyArray<string> | undefined, termKeyconst text = normalizeDictionaryTermText(raw);const key = dictionaryTermKey(text);// 别名等于词条本身没有意义(desktop 学习路径同样会把它过滤掉)。- if (!key || key === termKey || seen.has(key)) continue;+ if (!key || key === termKey || isAliasRemovalMarkerKey(key) || seen.has(key)) continue;seen.add(key);result.push(text);}