Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(voice-input): 语音词典在同账号设备之间自动同步 (#682)

Dash2f5e4a607902
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 1d97bf54ac..ce732e9551 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -31,6 +31,7 @@ import {
DL_VOICE_TRANSCRIBE_CHANNEL,
DL_VOICE_CREDENTIAL_SYNC_CHANNEL,
DL_VOICE_DICTIONARY_LEARNING_CHANNEL,
+ DL_VOICE_DICTIONARY_GET_CHANNEL,
DeviceLinkError,
parseFsWatchTopic,
type Envelope,
@@ -53,6 +54,7 @@ import { runDeviceLinkInvokeContext } from './invoke-context';
import { fetchLocalMediaToOss } from './mediaFetch';
import { transcribeRemoteVoiceInput } from './voiceTranscribe';
import { adviseAndRecordVoiceInputDictionaryLearning } from '../voice-input/index.js';
+import { readDictionaryProjectionForMobile } from '../voice-input/dictionarySyncDriver.js';
import { setBroadcastTapListener } from './broadcast-tap';
import * as subscriptions from './subscriptions';
import { LEGACY_TOPIC, type ActiveController } from './subscriptions';
@@ -939,6 +941,19 @@ export async function runInvoke(
};
}
+ // device-link:voice:dictionary:get 是手机拉取本机词典的只读快照。手机在后台不维持
+ // WebSocket,拿不到桌面之间对等同步的 push 帧,所以改为需要时主动拉一份;它只读、
+ // 不参与合并,避免移动端维护一份会分叉的词典。
+ if (payload.channel === DL_VOICE_DICTIONARY_GET_CHANNEL) {
+ try {
+ return { ok: true, result: { ok: true, ...readDictionaryProjectionForMobile() } };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ log.warn(`voice:dictionary:get failed from ${shortId(src)}: ${message}`);
+ return { ok: false, error: { code: 'VOICE_DICTIONARY_GET_FAILED', message } };
+ }
+ }
+
// device-link:voice:dictionary-learning 是手机端 voice refine 后的术语学习 evidence 回写:
// 手机只负责检测用户编辑,真正 advisor + 词典写入仍在被控桌面执行,避免移动端词典分叉。
if (payload.channel === DL_VOICE_DICTIONARY_LEARNING_CHANNEL) {
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index e586e0afb7..daf5e0853e 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -53,6 +53,16 @@ import {
handleControllerOffline,
} from './dispatch';
import { setBusyProbe, helloBusy, pollBusyChange, resetBusyDedupe } from './busyReporter';
+import {
+ DL_VOICE_DICTIONARY_SYNC_CHANNEL,
+ broadcastDictionaryNow,
+ handleDesktopPeerOnline,
+ handleIncomingDictionaryState,
+ initVoiceDictionarySync,
+ notifyLocalDictionaryChanged,
+ shouldExchangeDictionaryWith,
+} from '../voice-input/dictionarySyncDriver';
+import { onVoiceInputDictionaryChanged } from '../voice-input/VoiceInputDataStore';
import { resetAll as resetSubscriptionRefs, snapshotSubscriptions } from './subscriptionRefcount';
import { getControllersForTopic } from './subscriptions';
import {
@@ -99,6 +109,21 @@ let appliedKeepAwake: boolean | null = null;
let pendingQuitOwnershipRelease: Promise<void> | null = null;
const openLinkInFlight = new Map<string, Promise<LinkAcceptPayload>>();
const presenceAvailableByDevice = new Map<string, boolean>();
+/**
+ * 词典同步的对端选择只看「在线 + 是桌面」,不看 remoteControlEnabled ——
+ * push 帧不属于 relay 的控制类帧,自己设备之间同步词典不该要求对方开放被控。
+ */
+const presenceOnlineByDevice = new Map<string, boolean>();
+const presencePlatformByDevice = new Map<string, string>();
+let unsubscribeDictionaryChanged: (() => void) | null = null;
+
+/**
+ * 用户撤销过访问权限的设备,同样不参与词典同步 —— 撤销的意图是「不再跟这台设备
+ * 交换数据」,不只是「不许它操作我」。
+ */
+function isDeviceRevoked(deviceId: string): boolean {
+ return readDeviceLinkSettings().revokedControllers.includes(deviceId);
+}
/**
* relay 连续报 auth-failed 时,两次主动 refresh 之间的最小间隔。
@@ -229,6 +254,10 @@ export function initDeviceLinkService(): void {
client.onStatusChange((status) => {
if (status !== 'online') openLinkInFlight.clear();
+ // 断线期间 relay 不会为对端补发 offline presence,重连后同一台电脑仍以
+ // online 到达,`wasOnline` 还是 true —— 上线握手不会触发,而断线这段时间的
+ // 改动谁也不会主动推。清空在线视图,让重连后的 presence 重新走一遍握手。
+ if (status !== 'online') presenceOnlineByDevice.clear();
broadcast(DEVICE_LINK_PUSH.STATUS_CHANGED, { status });
if (status === 'online') replayActiveSubscriptions('ws-online');
});
@@ -247,7 +276,10 @@ export function initDeviceLinkService(): void {
client.onPresenceChanged((snap: PresenceSnapshot) => {
const wasAvailable = presenceAvailableByDevice.get(snap.deviceId);
const available = snap.online && snap.remoteControlEnabled;
+ const wasOnline = presenceOnlineByDevice.get(snap.deviceId);
presenceAvailableByDevice.set(snap.deviceId, available);
+ presenceOnlineByDevice.set(snap.deviceId, snap.online);
+ presencePlatformByDevice.set(snap.deviceId, snap.platform);
void rememberLastKnownDeviceName(snap.deviceId, snap.deviceName); // best-effort 名称缓存,不阻塞 presence 处理
broadcast(DEVICE_LINK_PUSH.PRESENCE_CHANGED, snap);
// 被控端兜底:对等控制端下线 → 清掉它在本机的订阅 registry(防僵尸订阅持续 sendPush)。
@@ -255,6 +287,19 @@ export function initDeviceLinkService(): void {
if (available && wasAvailable === false) {
replayActiveSubscriptions(`presence-online:${snap.deviceId.slice(0, 8)}`, snap.deviceId);
}
+ // 词典同步不看「允许被控」开关(push 帧不是控制类帧,这是自己设备之间的数据
+ // 流动),但撤销过的设备必须排除 —— 判定统一走 shouldExchangeDictionaryWith,
+ // 三个入口共用一份条件。
+ if (
+ wasOnline !== true
+ && shouldExchangeDictionaryWith({
+ online: snap.online,
+ platform: snap.platform,
+ revoked: isDeviceRevoked(snap.deviceId),
+ })
+ ) {
+ handleDesktopPeerOnline(snap.deviceId);
+ }
});
// 被控端:接线入站隧道(link-open / invoke / link-close → 本机 handler dispatch)
@@ -283,6 +328,21 @@ export function initDeviceLinkService(): void {
}
if (env.kind !== 'push') return;
const p = env.payload as PushPayload;
+ // 词典同步帧在 main 侧消费,不转给 renderer —— 它不是远程视图事件,
+ // renderer 也不该看到别的设备的同步状态。
+ if (p?.channel === DL_VOICE_DICTIONARY_SYNC_CHANNEL) {
+ // 入站与出站走同一份准入判定:这条通道承载的是可写 CRDT 状态,只接受电脑
+ // 对端。手机在这套设计里是只读消费者(走 invoke 拉快照),不该能推状态过来
+ // 改桌面词典 —— 出站已经这么把关了,入站漏掉就等于白设。
+ if (shouldExchangeDictionaryWith({
+ online: true,
+ platform: presencePlatformByDevice.get(env.src),
+ revoked: isDeviceRevoked(env.src),
+ })) {
+ handleIncomingDictionaryState(env.src, p.payload);
+ }
+ return;
+ }
broadcast(DEVICE_LINK_PUSH.REMOTE_PUSH, {
deviceId: env.src,
channel: p.channel,
@@ -290,6 +350,26 @@ export function initDeviceLinkService(): void {
});
});
+ // 词典对等同步:传输能力注入驱动,驱动只管什么时候发、发给谁。
+ initVoiceDictionarySync({
+ sendState: (deviceId, payload) => {
+ client?.sendPush(deviceId, DL_VOICE_DICTIONARY_SYNC_CHANNEL, payload);
+ },
+ listOnlineDesktopDevices: () =>
+ [...presenceOnlineByDevice.entries()]
+ .filter(([deviceId, online]) => shouldExchangeDictionaryWith({
+ online,
+ platform: presencePlatformByDevice.get(deviceId),
+ revoked: isDeviceRevoked(deviceId),
+ }))
+ .map(([deviceId]) => deviceId),
+ });
+ if (unsubscribeDictionaryChanged) unsubscribeDictionaryChanged();
+ unsubscribeDictionaryChanged = onVoiceInputDictionaryChanged((options) => {
+ if (options?.immediate) broadcastDictionaryNow();
+ else notifyLocalDictionaryChanged();
+ });
+
// 同机多实例单持有者仲裁:共享 userData(同 deviceId)的多个实例中,只有认领
// 成功的持有者才连 relay,其余被动待命 —— 否则 relay 的 last-wins 顶号语义会
// 让双活实例无限互踢(4409 循环),手机端远程连接在实例间漂移。见 ./ownership.ts。
@@ -435,6 +515,12 @@ function teardownActiveLink(): void {
}
dropAllControllers(client, 'shutdown');
presenceAvailableByDevice.clear();
+ // 词典同步驱动是进程级的,**不随单次链路起停**:多实例仲裁的 demote → acquire
+ // 只会 client.start(),不会重跑 initDeviceLinkService,在这里 stop 掉它会让词典
+ // 同步在降级过一次之后永久失效。清空 presence 就够了 —— 没有对端就不会发送,
+ // client 为 null 时 sendPush 也是 no-op。
+ presenceOnlineByDevice.clear();
+ presencePlatformByDevice.clear();
resetSubscriptionRefs();
resetBusyDedupe(); // 重置 busy dedupe,避免重连后首个真实 busy 状态被旧值压掉
client.stop();
diff --git a/apps/desktop/src/main/voice-input/VoiceDictionarySyncStore.ts b/apps/desktop/src/main/voice-input/VoiceDictionarySyncStore.ts
new file mode 100644
index 0000000000..397bba6078
--- /dev/null
+++ b/apps/desktop/src/main/voice-input/VoiceDictionarySyncStore.ts
@@ -0,0 +1,599 @@
+/**
+ * 语音词典同步状态的落盘层(CRDT 正本)。
+ *
+ * ## 为什么是 sidecar 而不是塞进 voice-input-data.v1.json
+ *
+ * 旧版本客户端读写词典文件时会整份重写(`normalizeVoiceInputDataSnapshot` 只保留
+ * 它认识的字段),塞进去的同步状态会被静默丢掉 —— 一次降级就把所有设备的合并
+ * 历史抹平。放在旁边的独立文件里,旧版本不认识也不会碰它;升级回来后靠
+ * `reconcileFromLocalSnapshot` 认领降级期间的改动。
+ *
+ * 另一个好处是 UI 与 IPC 完全不用改形状:词典对外仍然是
+ * `VoiceInputSettings.dictionaryEntries` 那三件套,只是它们的真相变成了本状态的
+ * 物化结果。
+ *
+ * ## 计数只在 mutate 里增长
+ *
+ * 运行期的一切词典变更都必须经由本类的 `mutate`(内部调 voice-input-core 的原语)。
+ * 绝对不要靠「比对文件与状态的差异」来推断本地变更 —— 合并进来的远端计数会被当成
+ * 本地新增再记一遍,同步一轮翻一倍。文件比对只在启动时跑一次(reconcile),且只
+ * 认领存在性、不认领频次。
+ */
+
+import { app } from 'electron';
+import { randomUUID } from 'node:crypto';
+import { isDeepStrictEqual } from 'node:util';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ DEFAULT_TOMBSTONE_TTL_MS,
+ createDictionaryMap,
+ createEmptySyncState,
+ createHlcClock,
+ dictionaryTermKey,
+ findMaxHlc,
+ VOICE_DICTIONARY_SYNC_VERSION,
+ gcTombstones,
+ isValidSyncState,
+ materializeDictionary,
+ mergeSyncStates,
+ observeHlc,
+ pruneWeakAutomaticCandidates,
+ reconcileFromLocalSnapshot,
+ type HlcClock,
+ type LocalDictionarySnapshot,
+ type MaterializedDictionary,
+ type DictionaryIncarnation,
+ type DictionaryRecord,
+ type DictionarySuppression,
+ type MutationResult,
+ type SyncAliasState,
+ type VoiceDictionarySyncState,
+} from '@cindy/voice-input-core';
+
+import { createLogger } from '../logger.js';
+import { getActiveAppSession, ownerScopedUserDataPath } from '../appSessionState.js';
+
+const log = createLogger('voice-input:dictionary-sync');
+const DATA_FILE_NAME = 'voice-dictionary-sync.v1.json';
+
+interface StoredSyncData {
+ version: 1;
+ /**
+ * 本设备的同步身份。本地生成并长期保持不变 —— 不能用 relay 的 deviceId:
+ * 那个值在重新配对后可能变化,而计数器分桶一旦换 key 就会把同一台设备的历史
+ * 事件重复计入。
+ */
+ nodeId: string;
+ clock: { wallMs: number; counter: number };
+ state: VoiceDictionarySyncState;
+ /** 上次物化写进词典文件的主键集合;降级回收判断删除时用。 */
+ lastMaterializedKeys: string[];
+ /**
+ * sidecar 不存在但投影文件里已有词典 —— 说明同步状态丢了(手工删、磁盘损坏),
+ * 而不是首次安装。此时投影里的频次可能含有别的设备合并进来的计数,不能当作
+ * 本机证据重新播种,否则与那台设备再同步时同一份事件会被记两遍。
+ * 只是本次加载的判断结果,不落盘。
+ */
+ lostSidecarWithProjection?: boolean;
+ /**
+ * 盘上的 sidecar 是更高版本(更新的客户端写的),本进程读不懂。
+ *
+ * 此时整个 store 进入旁路:不读、不合并、更不写。降级回来的旧客户端如果照常
+ * 走流程,会把读不懂的状态当成空状态物化出一份空词典,再用 markMaterialized
+ * 把空的 v1 状态覆盖写回 —— 用户的词典和所有设备的合并历史一起没了。
+ * 这个标记不落盘,只是本次加载的判断结果。
+ */
+ incompatible?: boolean;
+}
+
+export class VoiceDictionarySyncStore {
+ private data: StoredSyncData | null = null;
+ private dataOwnerId: string | null = null;
+ /**
+ * sidecar 丢了、但投影里还有词典时,挂起的认领。
+ *
+ * 这种恢复不能立刻做:本机丢掉了全部身份历史,认领会为每个词造出全新化身,而
+ * 别的设备上「删掉某个词」的墓碑指向的是老化身 —— 盖不住新化身,那个词就在合并
+ * 后复活了。所以先挂起,等第一次与对端合并(墓碑到齐)之后再认领,并且认领时
+ * 不越过墓碑。用户在这之前动词典的话就地落地,不能让编辑等一个不知何时到来的对端。
+ */
+ private pendingRecovery: LocalDictionarySnapshot | null = null;
+
+ /** 告知本次加载:投影文件里已有词典(用于判断 sidecar 是丢了还是首次安装)。 */
+ noteProjectionHasDictionary(): void {
+ const current = this.load();
+ if (current.lostSidecarWithProjection !== undefined) return;
+ if (Object.keys(current.state.records).length > 0) {
+ this.data = { ...current, lostSidecarWithProjection: false };
+ return;
+ }
+ this.data = { ...current, lostSidecarWithProjection: true };
+ }
+
+ /** 盘上的同步状态是否来自更新的客户端。true 时调用方必须完全绕开同步。 */
+ isIncompatible(): boolean {
+ return this.load().incompatible === true;
+ }
+
+ getNodeId(): string {
+ return this.load().nodeId;
+ }
+
+ getState(): VoiceDictionarySyncState {
+ return this.load().state;
+ }
+
+ materialize(): MaterializedDictionary {
+ return materializeDictionary(this.load().state);
+ }
+
+ /**
+ * 执行一次本地变更。返回物化结果;状态没变时返回 null,调用方据此跳过写盘与广播。
+ */
+ mutate(
+ apply: (state: VoiceDictionarySyncState, clock: HlcClock) => MutationResult,
+ ): MaterializedDictionary | null {
+ const current = this.load();
+ // 读不懂盘上的 sidecar 时,本机没有可信的同步状态 —— 基于空状态算出来的物化
+ // 结果会把用户现有词典覆盖成空。这条路径必须硬失败,由调用方决定怎么办。
+ if (current.incompatible) throw new VoiceDictionarySyncUnavailableError();
+ // 挂起的恢复必须先落地:否则这次变更基于一份空状态物化,会把用户词典覆盖成空。
+ this.flushPendingRecovery('local-edit');
+ const base = this.load();
+ const result = apply(base.state, this.readClock(base));
+ if (!result.changed) return null;
+ return this.commit(result.state, result.clock);
+ }
+
+ /**
+ * 合并远端设备送来的状态。返回物化结果;没有引入任何新信息时返回 null。
+ *
+ * 入参是未经校验的隧道 payload,先过结构校验:形状不对或版本更高时会被归一化成
+ * 空状态,合并即无变化,坏帧不会污染本机词典。合并本身幂等,所以重复投递、乱序、
+ * 迟到的帧都可以无条件喂进来。
+ */
+ mergeRemote(remote: unknown): MaterializedDictionary | null {
+ const current = this.load();
+ if (current.incompatible) return null;
+ // 坏帧、版本更高的帧都会被归一化成空状态 —— 那不是「对端词典是空的」,而是
+ // 「这一帧没法用」。挂起的恢复等的是一份**真的**对端状态(墓碑随它一起到达),
+ // 拿坏帧当信号会在墓碑到齐之前就播种新化身,对端删掉的词随后复活。
+ const isUsableFrame = isValidSyncState(remote);
+ const remoteState = isUsableFrame ? (remote as VoiceDictionarySyncState) : createEmptySyncState();
+ const merged = mergeSyncStates(current.state, remoteState);
+ if (isSameState(merged, current.state)) {
+ // 合并没引入新信息,但「收到了一份合法的对端状态」本身就是挂起恢复在等的信号:
+ // 对端是新机器、或它的词典也是空的时,每次握手都会走到这里 —— 不在这里落地的话,
+ // 本机会一直只显示投影、对外发空状态,直到用户手动改一次词典才自愈。
+ return isUsableFrame ? this.flushPendingRecovery('merged') : null;
+ }
+ // 抬高本地时钟,保证本机之后产出的时间戳大于已经观察到的一切。
+ const maxRemote = findMaxHlc(remoteState);
+ const clock = maxRemote
+ ? observeHlc(this.readClock(current), maxRemote, Date.now())
+ : this.readClock(current);
+ const materialized = this.commit(merged, clock);
+ // 对端墓碑已经在本地了,挂起的恢复现在可以安全落地。
+ return this.flushPendingRecovery('merged') ?? materialized;
+ }
+
+ /**
+ * 启动时认领「同步状态之外」对词典文件的改动(只可能来自旧版本客户端)。
+ * 文件与上次物化一致时是空操作。
+ */
+ reconcile(
+ snapshot: LocalDictionarySnapshot,
+ options?: { syncEnabled?: boolean },
+ ): MaterializedDictionary | null {
+ const current = this.load();
+ // sidecar 丢了但投影还在时(手工删、磁盘坏),这里会拿一份新 nodeId 把投影里
+ // 的频次当作**本机**证据重新播种 —— 而那些数字里含有别的设备合并进来的部分。
+ // 一旦与那台设备再同步,同一份事件就在两个节点桶里各记一遍,频次凭空翻倍。
+ // 这种情形只认领存在性,不认领计数。
+ // 同步关着就只有本机会写这份词典,认领没有复活风险,不必等对端。
+ if (current.lostSidecarWithProjection && options?.syncEnabled !== false) {
+ // 挂起,等对端墓碑到齐。期间 settings 保留投影文件的内容,用户照常看到词典。
+ this.pendingRecovery = snapshot;
+ log.info('deferred dictionary recovery until peer state is merged', {
+ entries: snapshot.entries.length,
+ });
+ return null;
+ }
+ return this.reconcileNow(snapshot, { recovery: current.lostSidecarWithProjection === true });
+ }
+
+ /**
+ * 落地挂起的恢复认领。合并过对端状态之后调用最安全(墓碑已到齐);本地变更前也
+ * 必须调用 —— 否则 mutate 会基于空状态物化,把词典覆盖成空。
+ */
+ flushPendingRecovery(reason: 'merged' | 'local-edit'): MaterializedDictionary | null {
+ // 必须先 load():账号边界的检查在那里面,挂起的快照可能属于上一个账号。
+ this.load();
+ const snapshot = this.pendingRecovery;
+ if (!snapshot) return null;
+ log.info('applying deferred dictionary recovery', { reason, entries: snapshot.entries.length });
+ let materialized: MaterializedDictionary | null;
+ try {
+ materialized = this.reconcileNow(snapshot, { recovery: true });
+ } catch (error) {
+ // 认领没落地就不能把快照丢掉:调用方回滚后重试时,这份词典是唯一的来源 ——
+ // 丢了的话重试只会物化出新编辑的那一条,把整份恢复中的词典覆盖掉。
+ throw error;
+ }
+ this.pendingRecovery = null;
+ return materialized;
+ }
+
+ hasPendingRecovery(): boolean {
+ this.load();
+ return this.pendingRecovery !== null;
+ }
+
+ private reconcileNow(
+ snapshot: LocalDictionarySnapshot,
+ options: { recovery: boolean },
+ ): MaterializedDictionary | null {
+ const current = this.load();
+ const result = reconcileFromLocalSnapshot(current.state, this.readClock(current), {
+ // 恢复模式只认领存在性:投影里的频次含有从别的设备合并进来的部分,当成本机
+ // 新证据重新播种,再与那台设备同步时同一批事件会在两个节点桶里各记一遍。
+ snapshot: options.recovery ? stripCountsFromSnapshot(snapshot) : snapshot,
+ lastMaterializedKeys: current.lastMaterializedKeys,
+ nowMs: Date.now(),
+ allowTombstonedRevival: !options.recovery,
+ });
+ if (!result.changed) return null;
+ log.info('reclaimed dictionary edits made by an older client', {
+ entries: snapshot.entries.length,
+ });
+ return this.commit(result.state, result.clock);
+ }
+
+ /**
+ * 把状态恢复到某次 mutate 之前。
+ *
+ * 词典写入是两段式的:先改同步状态(sidecar),再把物化结果写进词典文件。第二段
+ * 失败时(磁盘满、重命名被拦)状态会领先于用户看到的内容,而重试往往是 no-op ——
+ * sidecar 里已经有这次操作了,于是 UI 一直停在旧内容直到重启。调用方在第二段
+ * 失败时用这个回滚。
+ */
+ rollbackTo(snapshot: SyncRollbackPoint): void {
+ const current = this.load();
+ this.persist({
+ ...current,
+ state: snapshot.state,
+ clock: { wallMs: snapshot.clock.wallMs, counter: snapshot.clock.counter },
+ // key 基线也要一起退。它是下次降级回收判断「哪些词被删了」的唯一依据:留着
+ // 这次失败写下的新基线,回收就会拿它去对照回滚后的状态,把用户看到的那次
+ // 变更反向执行一遍。
+ lastMaterializedKeys: snapshot.lastMaterializedKeys,
+ });
+ }
+
+ /** 供调用方在 mutate 前留存回滚点。 */
+ snapshotForRollback(): SyncRollbackPoint {
+ const current = this.load();
+ return {
+ state: current.state,
+ clock: this.readClock(current),
+ lastMaterializedKeys: current.lastMaterializedKeys,
+ };
+ }
+
+ /** 记录本次物化写进词典文件的主键,供下次降级回收判断删除。 */
+ markMaterialized(materialized: MaterializedDictionary): void {
+ const current = this.load();
+ // 必须与 CRDT 主键同一套折叠规则(locale 无关),否则回收判断会认错词条。
+ const keys = materialized.entries.map((entry) => dictionaryTermKey(entry.text));
+ if (sameKeys(keys, current.lastMaterializedKeys)) return;
+ this.persist({ ...current, lastMaterializedKeys: keys });
+ }
+
+ /** 回收过期墓碑,并裁掉超出硬上限的自动候选。启动时跑一次即可,失败不影响功能。 */
+ collectGarbage(): void {
+ const current = this.load();
+ const nowMs = Date.now();
+ const collected = gcTombstones(current.state, { nowMs, ttlMs: DEFAULT_TOMBSTONE_TTL_MS });
+ // 自动候选没有上限的话,状态会随学习单调增长,直到整份状态超过 relay 单帧上限 ——
+ // 此后每一次同步广播都被静默丢弃,而被挤出展示的那些候选用户既看不见也删不掉。
+ const pruned = pruneWeakAutomaticCandidates(collected, this.readClock(current), { nowMs });
+ if (pruned.state === current.state) return;
+ if (pruned.changed) log.info('pruned weak automatic candidates over the authoritative cap');
+ this.persist({
+ ...current,
+ state: pruned.state,
+ clock: { wallMs: pruned.clock.wallMs, counter: pruned.clock.counter },
+ });
+ }
+
+ private commit(state: VoiceDictionarySyncState, clock: HlcClock): MaterializedDictionary {
+ const current = this.load();
+ this.persist({
+ ...current,
+ state,
+ clock: { wallMs: clock.wallMs, counter: clock.counter },
+ });
+ // 用 persist 之后的状态物化,而不是传进来的那份:persist 会把盘上另一个进程
+ // 刚写下的事件合并进来,拿合并前的状态物化会让投影少掉对方的词条。
+ return materializeDictionary(this.data?.state ?? state);
+ }
+
+ /**
+ * 写盘前把盘上的状态合并进来。
+ *
+ * 同一个 userData 可能被多个进程共用(dev 与正式版共用目录、被动实例)。每个进程
+ * 都把 sidecar 缓存在内存里各写各的,后写的那次会用自己那份过期快照整体覆盖掉
+ * 另一个进程刚记下的事件 —— 词条就这么没了。
+ *
+ * 这里不需要真正的跨进程锁:状态本身是 CRDT,写之前重读一次再合并即可,合并幂等
+ * 且可交换。剩下的窗口(读完到 rename 之间)只会丢掉极短时间内另一进程的写入,
+ * 而不是整份状态,并且下一次任意一侧的写入就会把它带回来。
+ *
+ * **已知精度损失**:共用 sidecar 的进程也共用同一个 nodeId,同一毫秒各自 +1 时
+ * 计数按节点取 max 会塌成一次。给每个进程分配独立 nodeId 能解决,但那样计数桶会
+ * 随启动次数无限增长 —— 频次只是排序权重,少记几次远好过让状态无界膨胀。
+ */
+ private mergeWithOnDiskState(next: StoredSyncData, filePath: string): StoredSyncData {
+ let onDisk: StoredSyncData;
+ try {
+ onDisk = normalizeStoredData(JSON.parse(fs.readFileSync(filePath, 'utf-8')) as unknown);
+ } catch {
+ // 文件不存在(首次写)或读不出来:没有可合并的东西,按原样写。
+ return next;
+ }
+ // 盘上的是更新客户端写的:一个字节都不能碰,让 persist 的调用方拿到失败。
+ if (onDisk.incompatible) return next;
+ const mergedState = mergeSyncStates(next.state, onDisk.state);
+ if (isSameState(mergedState, next.state)) return next;
+ log.info('merged concurrent dictionary state from disk before persisting');
+ const maxOnDisk = findMaxHlc(onDisk.state);
+ const clock = maxOnDisk
+ ? observeHlc(this.readClock(next), maxOnDisk, Date.now())
+ : this.readClock(next);
+ return {
+ ...next,
+ state: mergedState,
+ clock: { wallMs: clock.wallMs, counter: clock.counter },
+ };
+ }
+
+ private readClock(data: StoredSyncData): HlcClock {
+ return { wallMs: data.clock.wallMs, counter: data.clock.counter, nodeId: data.nodeId };
+ }
+
+ private load(): StoredSyncData {
+ const ownerId = getActiveAppSession().dataOwnerId;
+ if (this.data && this.dataOwnerId !== ownerId) {
+ this.data = null;
+ // 挂起的恢复属于**上一个**账号:留着的话,新账号的第一次编辑或合并会把上个
+ // 账号的词条写进它的 CRDT 和投影里。
+ this.pendingRecovery = null;
+ }
+ this.dataOwnerId = ownerId;
+ if (this.data) return this.data;
+
+ const filePath = getDataFilePath();
+ try {
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf-8')) as unknown;
+ this.data = normalizeStoredData(parsed);
+ return this.data;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ log.warn('dictionary sync state read failed, starting fresh', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ this.data = createInitialData();
+ return this.data;
+ }
+ }
+
+ private persist(next: StoredSyncData): void {
+ // 读不懂的 sidecar 一个字节都不能覆盖:那是更新客户端的状态,写回去就是
+ // 用空状态销毁它。
+ if (next.incompatible || this.data?.incompatible) return;
+ const filePath = getDataFilePath();
+ const merged = this.mergeWithOnDiskState(next, filePath);
+ try {
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ const tmp = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
+ fs.writeFileSync(tmp, JSON.stringify(toPersistedShape(merged)), 'utf-8');
+ fs.renameSync(tmp, filePath);
+ } catch (error) {
+ // sidecar 是词典的正本,写不下去就不能报告成功:调用方据此回滚并把失败暴露
+ // 给用户。早先这里只记一条 warn 就当没事 —— 于是「频次/别名涨了但只存进了
+ // 投影文件」,重启后回收又刻意不认领频次与别名,那次增长就永久丢了。
+ log.warn('dictionary sync state write failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ // 内存状态仍然提交:本进程后续的合并不能基于过期状态。
+ this.data = merged;
+ throw new VoiceDictionarySyncWriteError(error);
+ }
+ this.data = merged;
+ }
+}
+
+/** mutate 前的回滚点:状态、时钟和 key 基线必须一起进退。 */
+export interface SyncRollbackPoint {
+ state: VoiceDictionarySyncState;
+ clock: HlcClock;
+ lastMaterializedKeys: string[];
+}
+
+/**
+ * 落盘形状。只写稳定字段 —— `incompatible`、`lostSidecarWithProjection` 这些是
+ * **本次加载**的判断结果,写进文件就变成了会被后续进程读回来的持久事实。
+ */
+function toPersistedShape(data: StoredSyncData): Record<string, unknown> {
+ return {
+ version: data.version,
+ nodeId: data.nodeId,
+ clock: data.clock,
+ state: data.state,
+ lastMaterializedKeys: data.lastMaterializedKeys,
+ };
+}
+
+/** 盘上的同步状态来自更新的客户端,本进程不能安全地改它。 */
+export class VoiceDictionarySyncUnavailableError extends Error {
+ constructor() {
+ super('dictionary sync state was written by a newer client');
+ this.name = 'VoiceDictionarySyncUnavailableError';
+ }
+}
+
+/** 同步状态写盘失败;词典正本没落地,调用方必须回滚并上报。 */
+export class VoiceDictionarySyncWriteError extends Error {
+ constructor(cause: unknown) {
+ super(`dictionary sync state write failed: ${cause instanceof Error ? cause.message : String(cause)}`);
+ this.name = 'VoiceDictionarySyncWriteError';
+ }
+}
+
+export const voiceDictionarySyncStore = new VoiceDictionarySyncStore();
+
+function createInitialData(): StoredSyncData {
+ const clock = createHlcClock(randomUUID(), Date.now());
+ return {
+ version: 1,
+ nodeId: clock.nodeId,
+ clock: { wallMs: clock.wallMs, counter: clock.counter },
+ state: createEmptySyncState(),
+ lastMaterializedKeys: [],
+ };
+}
+
+/** 外层 wrapper 的结构版本。与 CRDT `state.version` 各自演进,升级时都要照顾到。 */
+const STORED_SYNC_DATA_VERSION = 1;
+
+function normalizeStoredData(raw: unknown): StoredSyncData {
+ if (!raw || typeof raw !== 'object') return createInitialData();
+ const candidate = raw as Partial<StoredSyncData>;
+ const nodeId = typeof candidate.nodeId === 'string' && candidate.nodeId.trim()
+ ? candidate.nodeId.trim()
+ : randomUUID();
+ // 两层版本都要看:外层 wrapper(nodeId / clock / lastMaterializedKeys 这些字段的
+ // 结构版本)和内层 CRDT state 版本是各自演进的。只看内层的话,一个写了
+ // wrapper v2、state 仍是 v1 的更新客户端会被当成可写的 v1 数据,下一次
+ // `toPersistedShape()` 按 v1 序列化就把它的 v2 字段全丢了。
+ const incompatible = isNewerVersion(candidate.state) || isNewerStoredVersion(candidate.version);
+ const state = normalizeState(candidate.state);
+ return {
+ version: STORED_SYNC_DATA_VERSION,
+ incompatible,
+ nodeId,
+ clock: {
+ wallMs: readNonNegative(candidate.clock?.wallMs),
+ counter: readNonNegative(candidate.clock?.counter),
+ },
+ state,
+ lastMaterializedKeys: Array.isArray(candidate.lastMaterializedKeys)
+ ? candidate.lastMaterializedKeys.filter((key): key is string => typeof key === 'string')
+ : [],
+ };
+}
+
+/**
+ * 盘上状态是否来自更新的客户端。
+ *
+ * 只认「版本号明确更高」这一种情况 —— 结构坏了(缺字段、被截断)属于损坏,照常
+ * 重建即可;而版本更高是合法数据,必须原样留着。
+ */
+/** 外层 wrapper 的版本号是否高于本进程能写的版本。 */
+function isNewerStoredVersion(version: unknown): boolean {
+ return typeof version === 'number' && version > STORED_SYNC_DATA_VERSION;
+}
+
+function isNewerVersion(raw: unknown): boolean {
+ if (!raw || typeof raw !== 'object') return false;
+ const version = (raw as { version?: unknown }).version;
+ return typeof version === 'number' && version > VOICE_DICTIONARY_SYNC_VERSION;
+}
+
+/**
+ * 归一化一份状态(盘上的或隧道来的)。
+ *
+ * 走 core 的**深度**校验:只看顶层的话,一个缺 `counters` 的化身能一路通过校验被
+ * 持久化,然后在物化时才抛 —— 而这份中毒的 sidecar 每次重启都会被重新接受,词典
+ * 修改与同步会一直坏下去,直到有人手工删文件。结构不合法就整份丢弃,重新开始。
+ */
+function normalizeState(raw: unknown): VoiceDictionarySyncState {
+ return isValidSyncState(raw) ? adoptDictionaryMaps(raw) : createEmptySyncState();
+}
+
+/**
+ * 把 `JSON.parse` 出来的普通对象重建成无原型字典。
+ *
+ * 词条主键、化身 tag、别名键、节点 id 都直接当对象键用,而 `constructor`、
+ * `toString`、`__proto__` 都是合法的技术术语 —— 用户完全可能把它们加进词典。带着
+ * `Object.prototype` 的对象上,`state.records['constructor']` 会取到继承来的函数,
+ * 后面 `listLiveIncarnations()` 拿它当记录用就直接抛,而且这条路径每次重启都会重现。
+ *
+ * 校验只保证形状对,不保证原型干净;所以每一份从盘上或隧道里来的状态都要过这里。
+ */
+function adoptDictionaryMaps(state: VoiceDictionarySyncState): VoiceDictionarySyncState {
+ const records = createDictionaryMap<DictionaryRecord>();
+ for (const [key, record] of Object.entries(state.records)) {
+ const incarnations = createDictionaryMap<DictionaryIncarnation>();
+ for (const [tag, incarnation] of Object.entries(record.incarnations)) {
+ const aliases = createDictionaryMap<SyncAliasState>();
+ for (const [aliasKey, alias] of Object.entries(incarnation.aliases)) {
+ aliases[aliasKey] = { ...alias, counters: adoptCounters(alias.counters) };
+ }
+ incarnations[tag] = {
+ ...incarnation,
+ counters: adoptCounters(incarnation.counters),
+ aliases,
+ };
+ }
+ const tombstones = createDictionaryMap<string>();
+ for (const [tag, stamp] of Object.entries(record.tombstones)) tombstones[tag] = stamp;
+ records[key] = { incarnations, tombstones };
+ }
+ const suppressed = createDictionaryMap<DictionarySuppression>();
+ for (const [key, value] of Object.entries(state.suppressed)) suppressed[key] = { ...value };
+ return { version: state.version, records, suppressed };
+}
+
+/** 计数桶的键是 nodeId,同样来自不可信输入。 */
+function adoptCounters(counters: Record<string, number>): Record<string, number> {
+ const adopted = createDictionaryMap<number>();
+ for (const [nodeId, value] of Object.entries(counters)) adopted[nodeId] = value;
+ return adopted;
+}
+
+/** 去掉快照里的频次与别名计数,只保留存在性(用于 sidecar 丢失后的重建)。 */
+function stripCountsFromSnapshot(snapshot: LocalDictionarySnapshot): LocalDictionarySnapshot {
+ return {
+ entries: snapshot.entries.map((entry) => ({ text: entry.text, source: entry.source })),
+ suppressedTexts: snapshot.suppressedTexts,
+ candidates: snapshot.candidates?.map((candidate) => ({ text: candidate.text })),
+ };
+}
+
+function readNonNegative(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
+}
+
+function sameKeys(a: ReadonlyArray<string>, b: ReadonlyArray<string>): boolean {
+ return a.length === b.length && a.every((key, index) => key === b[index]);
+}
+
+/**
+ * 合并结果与原状态是否等价。
+ *
+ * 用 `isDeepStrictEqual` 而不是 `JSON.stringify` 比较:每收到一帧远端状态都要比一次,
+ * 词典状态可能上百 KB,序列化两份字符串再比对会在 main 线程上制造无谓的 CPU 与 GC
+ * 压力,而深比较可以在第一个差异处就返回。
+ */
+function isSameState(a: VoiceDictionarySyncState, b: VoiceDictionarySyncState): boolean {
+ return a === b || isDeepStrictEqual(a, b);
+}
+
+function getDataFilePath(): string {
+ const ownerId = getActiveAppSession().dataOwnerId;
+ return ownerId ? ownerScopedUserDataPath(DATA_FILE_NAME) : path.join(app.getPath('userData'), DATA_FILE_NAME);
+}
diff --git a/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts b/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts
index be6a5e6bcb..e741a8cb68 100644
--- a/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts
+++ b/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts
@@ -2,18 +2,30 @@ import { app, BrowserWindow, ipcMain } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
-import type { DictationDictionaryLearningAction } from '@cindy/voice-input-core';
+import {
+ addManualEntry,
+ deleteTerms,
+ dictionaryTermKey,
+ recordLearningEvent,
+ renameTerm,
+ termKeyFromMaterializedId,
+ type DictationDictionaryLearningAction,
+ type MaterializedDictionary,
+} from '@cindy/voice-input-core';
import { createLogger } from '../logger.js';
import { ownerScopedUserDataPath, getActiveAppSession } from '../appSessionState.js';
import { throwIpcError } from '../utils/ipcValidate.js';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { voiceDictionarySyncStore } from './VoiceDictionarySyncStore.js';
import {
- applyVoiceInputDictionaryLearningActions,
+ DEFAULT_DICTIONARY_SYNC_ENABLED,
+ MAX_VOICE_INPUT_DICTIONARY_ALIASES,
+ MAX_VOICE_INPUT_DICTIONARY_ENTRIES,
+ MAX_VOICE_INPUT_DICTIONARY_ENTRY_CHARS,
compactVoiceInputHistoryIfNeeded,
createVoiceInputHistoryEntry,
- deleteVoiceInputDictionaryEntriesFromSettings,
getDefaultVoiceInputSettings,
- getNewAutomaticDictionaryEntries,
normalizeVoiceInputDataSnapshot,
normalizeVoiceInputHistory,
normalizeVoiceInputSettings,
@@ -31,6 +43,19 @@ let ipcRegistered = false;
type StoredVoiceInputData = VoiceInputDataSnapshot & {
version: 1;
legacyRendererStorageMigrated?: boolean;
+ /**
+ * 这份投影是否由「带同步的版本」写出来的。
+ *
+ * 用来区分两种表面完全一样的情形 —— sidecar 不在、投影里却有词典:
+ * - **首次迁移**(没有这个标记):存量用户刚升级上来。词典里的频次全是本机积累的,
+ * 整份认领(含频次)才对,丢了就是把用户长期积累的排序权重清零。
+ * - **sidecar 丢失**(有这个标记):本机曾经同步过。频次里含有别的设备合并进来的
+ * 部分,重新播种会让同一批事件在两个节点桶里各记一遍;而且本机丢了身份历史,
+ * 直接认领会越过对端墓碑把删掉的词复活。
+ *
+ * 靠状态本身分不出这两者(都是空 sidecar + 有内容的投影),必须留一个持久印记。
+ */
+ dictionarySyncInitialized?: boolean;
};
type LegacyRendererDataPayload = {
@@ -74,27 +99,71 @@ export class VoiceInputDataStore {
updateSettings(patch: unknown): VoiceInputSettings {
const current = this.load();
+ const syncJustEnabled = isRecord(patch)
+ && patch.dictionarySyncEnabled === true
+ && current.settings.dictionarySyncEnabled === false;
+ // 词典三件套的真相在同步状态里,不接受整份覆盖 —— 那会绕过 CRDT,让本地写入
+ // 在下一次物化时被静默丢掉。词典变更一律走下面的语义化入口。
const nextSettings = normalizeVoiceInputSettings({
...current.settings,
- ...(isRecord(patch) ? patch : {}),
+ ...stripDictionaryFields(patch),
}, process.platform);
this.replaceState({
...current,
settings: nextSettings,
});
+ // 刚打开同步开关:对端可能早已在线,既没有 presence 事件也没有词典变更,
+ // 不主动推一次就要等到兜底心跳才收敛。
+ if (syncJustEnabled) notifyDictionaryChanged({ immediate: true });
return cloneSettings(nextSettings);
}
deleteDictionaryEntries(entryIds: string[]): VoiceInputSettings {
- const current = this.load();
- const nextSettings = deleteVoiceInputDictionaryEntriesFromSettings(current.settings, entryIds);
- if (nextSettings !== current.settings) {
- this.replaceState({
- ...current,
- settings: nextSettings,
- });
- }
- return cloneSettings(nextSettings);
+ const state = voiceDictionarySyncStore.getState();
+ const termKeys = entryIds
+ .map((entryId) => termKeyFromMaterializedId(state, entryId))
+ .filter((key): key is string => Boolean(key));
+ if (termKeys.length === 0) return cloneSettings(this.load().settings);
+ return this.applyDictionaryMutation((current, clock) =>
+ deleteTerms(current, clock, { termKeys, nowMs: Date.now() }),
+ );
+ }
+
+ addManualDictionaryEntry(text: string): VoiceInputSettings {
+ return this.applyDictionaryMutation((current, clock) =>
+ addManualEntry(current, clock, { text, nowMs: Date.now() }),
+ );
+ }
+
+ /** CSV 导入:整批按手动词条认领,单条失败不影响其余。 */
+ importManualDictionaryEntries(texts: string[]): VoiceInputSettings {
+ // 已有多少条也要算进上限:否则对着一份满词典反复导入,记录数可以无限增长,
+ // 撑过物化上限与 relay 单帧上限(同步会因此永久停摆)。
+ const existing = this.load().settings.dictionaryEntries.length;
+ const budget = Math.max(0, MAX_VOICE_INPUT_DICTIONARY_ENTRIES - existing);
+ if (budget === 0) return cloneSettings(this.load().settings);
+ const accepted = texts.slice(0, budget);
+ return this.applyDictionaryMutation((current, clock) => {
+ let state = current;
+ let nextClock = clock;
+ let changed = false;
+ const nowMs = Date.now();
+ for (const text of accepted) {
+ const result = addManualEntry(state, nextClock, { text, nowMs });
+ state = result.state;
+ nextClock = result.clock;
+ changed = changed || result.changed;
+ }
+ return { state, clock: nextClock, changed };
+ });
+ }
+
+ renameDictionaryEntry(entryId: string, nextText: string): VoiceInputSettings {
+ const termKey = termKeyFromMaterializedId(voiceDictionarySyncStore.getState(), entryId);
+ if (!termKey) return cloneSettings(this.load().settings);
+ return this.applyDictionaryMutation((current, clock) =>
+ renameTerm(current, clock, { termKey, nextText, nowMs: Date.now() }),
+ );
}
recordDictionaryLearningActions(actions: DictationDictionaryLearningAction[]): {
@@ -102,23 +171,116 @@ export class VoiceInputDataStore {
newAutomaticEntries: Array<Pick<VoiceInputDictionaryEntry, 'id' | 'text'>>;
} {
const current = this.load();
- const appliedSettings = applyVoiceInputDictionaryLearningActions(current.settings, actions);
- if (appliedSettings === current.settings) {
+ if (!current.settings.refinementEnabled || !current.settings.autoDictionaryEnabled) {
return { settings: cloneSettings(current.settings), newAutomaticEntries: [] };
}
- const nextSettings = normalizeVoiceInputSettings(appliedSettings, process.platform);
- const newAutomaticEntries = getNewAutomaticDictionaryEntries(
- current.settings.dictionaryEntries,
- nextSettings.dictionaryEntries,
+ const previousEntryKeys = new Set(
+ current.settings.dictionaryEntries
+ .filter((entry) => entry.source === 'automatic')
+ .map((entry) => dictionaryTermKey(entry.text)),
);
- this.replaceState({
- ...current,
- settings: nextSettings,
+
+ const nextSettings = this.applyDictionaryMutation((state, clock) => {
+ let nextState = state;
+ let nextClock = clock;
+ let changed = false;
+ const nowMs = Date.now();
+ for (const action of actions) {
+ // 与单机学习路径一致:低置信度或没有别名证据的建议不进词典。
+ if (action.confidence === 'low') continue;
+ const aliases = action.aliases ?? [];
+ if (aliases.length === 0) continue;
+ const result = recordLearningEvent(nextState, nextClock, {
+ text: action.term,
+ aliases,
+ stage: action.action === 'add_candidate' ? 'candidate' : 'entry',
+ nowMs,
+ });
+ nextState = result.state;
+ nextClock = result.clock;
+ changed = changed || result.changed;
+ }
+ return { state: nextState, clock: nextClock, changed };
});
- return {
- settings: cloneSettings(nextSettings),
- newAutomaticEntries,
- };
+
+ const newAutomaticEntries = nextSettings.dictionaryEntries
+ .filter((entry) => entry.source === 'automatic')
+ .filter((entry) => !previousEntryKeys.has(dictionaryTermKey(entry.text)))
+ .map((entry) => ({ id: entry.id, text: entry.text }));
+ return { settings: cloneSettings(nextSettings), newAutomaticEntries };
+ }
+
+ /**
+ * 合并远端设备送来的同步状态。返回是否引入了新信息(调用方据此决定要不要回传
+ * 自己的状态)。
+ */
+ mergeRemoteDictionaryState(remote: unknown): boolean {
+ // 与本地变更同样是两段写入,同样需要回滚点:sidecar 已经吸收了远端状态而
+ // 投影文件写失败时,重投同一帧会因为「合并没有引入新信息」直接返回 false,
+ // 投影就永远停在旧内容上。
+ const rollbackPoint = voiceDictionarySyncStore.snapshotForRollback();
+ try {
+ // mergeRemote 自己写盘失败时也会先推进内存状态再抛 —— 不圈进 try 的话,重投
+ // 同一帧会因为「合并没有引入新信息」直接返回 false,投影永远停在旧内容上。
+ const materialized = voiceDictionarySyncStore.mergeRemote(remote);
+ if (!materialized) return false;
+ this.commitMaterializedDictionary(materialized);
+ } catch (error) {
+ voiceDictionarySyncStore.rollbackTo(rollbackPoint);
+ throw error;
+ }
+ return true;
+ }
+
+ /**
+ * 执行一次词典变更并把物化结果落回 settings。
+ *
+ * 物化结果是**只读投影**:写回 settings 之后绝不能再被反向读成本地增量,否则
+ * 合并进来的远端计数会被重复记账,词典频次随同步次数膨胀。日常路径永远是
+ * 「操作 → 状态 → 物化 → settings」这一个方向。
+ */
+ private applyDictionaryMutation(
+ apply: Parameters<typeof voiceDictionarySyncStore.mutate>[0],
+ ): VoiceInputSettings {
+ // 两段写入必须整体成败:同步状态先行、词典文件随后。第二段失败时状态会领先于
+ // 用户看到的内容,而重试通常是 no-op(sidecar 里已经有这次操作),UI 会一直停在
+ // 旧内容直到重启 —— 所以失败就把 sidecar 回滚,让重试真的能重来。
+ if (voiceDictionarySyncStore.isIncompatible()) {
+ // 读不懂盘上的同步状态时不能改词典:基于空状态物化会把现有词典覆盖成空。
+ // 明确报错(IPC 会转成 INTERNAL),而不是假装成功。
+ throw new VoiceInputDataStoreWriteError(
+ new Error('dictionary sync state was written by a newer client; upgrade to edit the dictionary'),
+ );
+ }
+ const rollbackPoint = voiceDictionarySyncStore.snapshotForRollback();
+ try {
+ // mutate 自己写盘失败时也会先推进内存状态再抛 —— 不把它圈进 try 的话,
+ // 重试会因为「sidecar 里已经有这次操作」变成 no-op,投影一直停在旧内容。
+ const materialized = voiceDictionarySyncStore.mutate(apply);
+ if (!materialized) return cloneSettings(this.load().settings);
+ return cloneSettings(this.commitMaterializedDictionary(materialized));
+ } catch (error) {
+ voiceDictionarySyncStore.rollbackTo(rollbackPoint);
+ throw error;
+ }
+ }
+
+ private commitMaterializedDictionary(materialized: MaterializedDictionary): VoiceInputSettings {
+ const current = this.load();
+ const nextSettings = normalizeVoiceInputSettings(
+ { ...current.settings, ...projectMaterializedDictionary(materialized) },
+ process.platform,
+ );
+ // 顺序要紧:sidecar(状态 + key 基线)全部写完,最后才写投影并广播。
+ //
+ // 反过来的话,`markMaterialized` 抛错时投影文件已经落盘、UI 也已经更新,而调用方
+ // 的 catch 只回滚 sidecar —— 用户看到「保存失败」,盘上却留着这次改动,重启后
+ // 降级回收还会拿这份投影去对照被回滚的 CRDT,把它当成「旧版本客户端做的改动」
+ // 重新认领回来。现在任一段失败时投影都还没写,回滚后两边一致。
+ voiceDictionarySyncStore.markMaterialized(materialized);
+ this.replaceState({ ...current, dictionarySyncInitialized: true, settings: nextSettings });
+ notifyDictionaryChanged();
+ return nextSettings;
}
recordHistory(text: string): string | null {
@@ -191,15 +353,91 @@ export class VoiceInputDataStore {
}
}
+ // 先把迁移来的词典认领进同步状态,再提交。
+ //
+ // load() 早在处理 payload 之前就跑过了,那时词典文件还是空的,于是 sidecar 也
+ // 被初始化成空 —— 如果直接 replaceState,词条只进了 settings,而下一次词典变更
+ // 或收到远端状态都会用空 sidecar 物化出空词典,把刚迁移的内容盖掉。
+ const migrated = this.reconcileMigratedDictionary(settings);
+
this.replaceState({
...current,
legacyRendererStorageMigrated: true,
- settings,
+ settings: migrated,
history: compactVoiceInputHistoryIfNeeded(history),
});
return this.getSnapshot();
}
+ /** 同步状态里是否已经有词典 —— 有就说明这不是首次安装。 */
+ private hasSyncedDictionary(): boolean {
+ try {
+ if (voiceDictionarySyncStore.isIncompatible()) return true;
+ return voiceDictionarySyncStore.materialize().entries.length > 0;
+ } catch {
+ // 读不出来就按「有」处理:宁可少回收一次,也不能误删。
+ return true;
+ }
+ }
+
+ /**
+ * 只把同步状态物化到 settings,不做回收、不写盘。
+ *
+ * 用于词典文件读失败(损坏 / 权限 / 临时不可读)的场景:此时手上的 settings 是
+ * 默认空值,拿它去回收等于宣告「用户删光了词典」。只读投影既能让用户继续看到
+ * 同步状态里的词典,又不会把损坏扩散到正本。
+ */
+ private projectDictionaryWithoutReconcile(state: StoredVoiceInputData): StoredVoiceInputData {
+ try {
+ if (voiceDictionarySyncStore.isIncompatible()) return state;
+ const materialized = voiceDictionarySyncStore.materialize();
+ return {
+ ...state,
+ settings: normalizeVoiceInputSettings(
+ { ...state.settings, ...projectMaterializedDictionary(materialized) },
+ process.platform,
+ ),
+ };
+ } catch (error) {
+ log.warn('dictionary projection failed while the data file was unreadable', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return state;
+ }
+ }
+
+ /** 把一份来自旧存储的 settings 词典认领进 CRDT,返回物化后的 settings。 */
+ private reconcileMigratedDictionary(settings: VoiceInputSettings): VoiceInputSettings {
+ if (voiceDictionarySyncStore.isIncompatible()) return settings;
+ try {
+ voiceDictionarySyncStore.reconcile({
+ entries: settings.dictionaryEntries.map((entry) => ({
+ text: entry.text,
+ source: entry.source,
+ frequency: entry.frequency,
+ aliases: entry.aliases.map((alias) => ({ text: alias.text, count: alias.count })),
+ })),
+ suppressedTexts: settings.suppressedAutomaticDictionaryTexts,
+ candidates: settings.dictionaryCandidates.map((candidate) => ({
+ text: candidate.text,
+ evidenceCount: candidate.evidenceCount,
+ aliases: candidate.aliases.map((alias) => ({ text: alias.text, count: alias.count })),
+ })),
+ }, { syncEnabled: settings.dictionarySyncEnabled });
+ const materialized = voiceDictionarySyncStore.materialize();
+ voiceDictionarySyncStore.markMaterialized(materialized);
+ return normalizeVoiceInputSettings(
+ { ...settings, ...projectMaterializedDictionary(materialized) },
+ process.platform,
+ );
+ } catch (error) {
+ log.warn('legacy renderer dictionary reconcile failed, keeping migrated settings as-is', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return settings;
+ }
+ }
+
private load(): StoredVoiceInputData {
const ownerId = getActiveAppSession().dataOwnerId;
if (this.state && this.stateOwnerId !== ownerId) this.state = null;
@@ -210,14 +448,23 @@ export class VoiceInputDataStore {
const raw = fs.readFileSync(filePath, 'utf-8');
const parsed = JSON.parse(raw) as unknown;
const snapshot = normalizeVoiceInputDataSnapshot(parsed, process.platform);
+ const stampedOnDisk = isRecord(parsed) && parsed.dictionarySyncInitialized === true;
this.state = {
version: 1,
legacyRendererStorageMigrated: isRecord(parsed) && parsed.legacyRendererStorageMigrated === true,
+ dictionarySyncInitialized: stampedOnDisk,
...snapshot,
};
+ const hydrated = this.hydrateDictionaryFromSyncState(this.state);
+ this.state = hydrated;
+ // 首次迁移刚落下印记时立刻写盘一次。只留在内存里的话,这次启动如果没有任何
+ // 词典写入,盘上的投影就还是「没有印记」—— 下次 sidecar 真丢了会被再次误判成
+ // 首次迁移,于是越过对端墓碑重建,别的设备上删掉的词就复活了。
+ if (hydrated.dictionarySyncInitialized && !stampedOnDisk) this.save(hydrated);
return this.state;
} catch (error) {
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ const missing = (error as NodeJS.ErrnoException).code === 'ENOENT';
+ if (!missing) {
log.warn('voice input data read failed, using defaults', {
error: error instanceof Error ? error.message : String(error),
});
@@ -227,14 +474,102 @@ export class VoiceInputDataStore {
settings: getDefaultVoiceInputSettings(process.platform),
history: [],
};
+ // 读不到投影文件时手上的 settings 是默认空值,拿它去回收等于宣告「用户把
+ // 词典删光了」——lastMaterializedKeys 里的每一条都会被打上墓碑并持久化,
+ // 投影文件的丢失就此升级成 CRDT 正本的永久损毁。
+ //
+ // 「文件不存在」和「文件损坏」在这一点上没有区别:只要 sidecar 里还有内容,
+ // 就说明这不是首次安装,而是投影没了。只有 sidecar 也是空的(真·首次安装)
+ // 才走回收 —— 那时回收本来也没有可删的东西。
+ this.state = this.hasSyncedDictionary()
+ ? this.projectDictionaryWithoutReconcile(this.state)
+ : this.hydrateDictionaryFromSyncState(this.state);
return this.state;
}
}
+ /**
+ * 让内存里的词典与同步状态对齐。
+ *
+ * 顺带承担两件一次性工作:
+ * - **首次迁移**:同步状态为空、上次物化主键也为空时,回收会把词典文件里已有的
+ * 词条整份认领进来 —— 存量用户升级后词典原样保留,不需要单独的迁移代码路径。
+ * - **降级回收**:旧版本客户端直接改过词典文件时,把那些改动认领回状态。
+ *
+ * 只在 `load()` 里跑,不在运行期跑:运行期的写入全部走 `applyDictionaryMutation`,
+ * 物化是单向投影,绝不反向推断。
+ */
+ private hydrateDictionaryFromSyncState(state: StoredVoiceInputData): StoredVoiceInputData {
+ try {
+ // 盘上的同步状态来自更新的客户端:本进程读不懂,直接用词典文件里的内容跑,
+ // 一个字节都不碰 sidecar。照常走下去会把读不懂的状态当空状态物化出空词典,
+ // 再覆盖写回,把用户的词典连同所有设备的合并历史一起销毁。
+ if (voiceDictionarySyncStore.isIncompatible()) {
+ log.warn('dictionary sync state was written by a newer client, running without sync');
+ return state;
+ }
+ // 先让 store 判断:sidecar 是丢了,还是首次安装 / 首次迁移。
+ // 判据是投影里有没有「本机曾经同步过」的印记 —— 只看状态空不空分不出来。
+ //
+ // 候选词与抑制列表同样是权威投影数据:一个用户完全可能只有候选(自动学习刚
+ // 起步)或只有抑制项(把自动学来的词都删了)。漏算它们的话,这台机器丢了
+ // sidecar 会被当成首次迁移,把候选证据数按本机新证据重新播种 —— 与保留着
+ // 原状态的对端合并时,同一批证据就在两个节点桶里各记了一遍。
+ const hasProjectedDictionary =
+ state.settings.dictionaryEntries.length > 0 ||
+ state.settings.dictionaryCandidates.length > 0 ||
+ state.settings.suppressedAutomaticDictionaryTexts.length > 0;
+ if (hasProjectedDictionary && state.dictionarySyncInitialized) {
+ voiceDictionarySyncStore.noteProjectionHasDictionary();
+ }
+ voiceDictionarySyncStore.reconcile({
+ // 带上频次与别名:首次迁移时状态是空的,这些都是用户长期积累的东西 ——
+ // 频次是排序权重,别名更是纠错能力的主体(「web coding → Vibe Coding」
+ // 这类映射全靠它)。不带上就等于把存量用户的词典能力清零,而且下一次
+ // 物化写回文件后永久丢失。seedTerm 只对状态里不存在的词条生效,不会重复记账。
+ entries: state.settings.dictionaryEntries.map((entry) => ({
+ text: entry.text,
+ source: entry.source,
+ frequency: entry.frequency,
+ aliases: entry.aliases.map((alias) => ({ text: alias.text, count: alias.count })),
+ })),
+ suppressedTexts: state.settings.suppressedAutomaticDictionaryTexts,
+ candidates: state.settings.dictionaryCandidates.map((candidate) => ({
+ text: candidate.text,
+ evidenceCount: candidate.evidenceCount,
+ aliases: candidate.aliases.map((alias) => ({ text: alias.text, count: alias.count })),
+ })),
+ }, { syncEnabled: state.settings.dictionarySyncEnabled });
+ voiceDictionarySyncStore.collectGarbage();
+ // 认领被挂起时(sidecar 丢了、还在等对端墓碑)状态里暂时没有这些词。物化会
+ // 是空的,拿它覆盖 settings 就等于让用户的词典先消失一次;保留文件内容不动。
+ if (voiceDictionarySyncStore.hasPendingRecovery()) return state;
+ const materialized = voiceDictionarySyncStore.materialize();
+ voiceDictionarySyncStore.markMaterialized(materialized);
+ return {
+ ...state,
+ // 印记跟着第一次成功物化落下:之后再看到「空 sidecar + 有词典的投影」,
+ // 就能确定是 sidecar 丢了,而不是又一次首次迁移。
+ dictionarySyncInitialized: true,
+ settings: normalizeVoiceInputSettings(
+ { ...state.settings, ...projectMaterializedDictionary(materialized) },
+ process.platform,
+ ),
+ };
+ } catch (error) {
+ // 同步状态坏了不能让词典功能整体不可用:退回文件里的词典继续跑。
+ log.warn('dictionary sync hydration failed, falling back to on-disk dictionary', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return state;
+ }
+ }
+
private replaceState(next: StoredVoiceInputData): void {
const normalizedState: StoredVoiceInputData = {
version: 1,
legacyRendererStorageMigrated: next.legacyRendererStorageMigrated,
+ dictionarySyncInitialized: next.dictionarySyncInitialized,
settings: normalizeVoiceInputSettings(next.settings, process.platform),
history: compactVoiceInputHistoryIfNeeded(normalizeVoiceInputHistory(next.history)),
};
@@ -273,6 +608,82 @@ export class VoiceInputDataStoreWriteError extends Error {
export const voiceInputDataStore = new VoiceInputDataStore();
+/**
+ * 词典变更监听。同步驱动订阅它来触发广播 —— 用回调而不是让 store 直接 import
+ * driver,避免两个模块互相 import 形成加载期环。
+ */
+const dictionaryChangedListeners = new Set<DictionaryChangedListener>();
+
+/**
+ * `immediate` = 这次变更希望立刻广播,不要走去抖(用户刚打开同步开关)。
+ */
+export type DictionaryChangedListener = (options?: { immediate?: boolean }) => void;
+
+export function onVoiceInputDictionaryChanged(listener: DictionaryChangedListener): () => void {
+ dictionaryChangedListeners.add(listener);
+ return () => dictionaryChangedListeners.delete(listener);
+}
+
+/** 一次 advice 能提交的动作条数上限。真实模型建议远低于此,超出的一律是异常来源。 */
+const MAX_DICTIONARY_LEARNING_ACTIONS = 32;
+
+/** 归一化待删除的词条 id:丢掉非字符串,并按词典总量上限截断。 */
+function sanitizeDictionaryEntryIds(input: unknown): string[] {
+ if (!Array.isArray(input)) return [];
+ const ids: string[] = [];
+ for (const candidate of input) {
+ if (typeof candidate !== 'string' || !candidate) continue;
+ ids.push(candidate);
+ if (ids.length >= MAX_VOICE_INPUT_DICTIONARY_ENTRIES) break;
+ }
+ return ids;
+}
+
+/**
+ * 归一化单条动作的别名。
+ *
+ * 光过滤非字符串不够:32 条动作的上限挡不住「一条动作带十万个别名」—— 每个唯一
+ * 别名都会被写进 CRDT 正本,main 线程被同步写盘卡住,sidecar 也会涨过 relay 单帧
+ * 上限让同步永久停摆。条数与单条长度都要卡。
+ */
+function sanitizeLearningAliases(raw: unknown): string[] {
+ if (!Array.isArray(raw)) return [];
+ const aliases: string[] = [];
+ for (const candidate of raw) {
+ if (typeof candidate !== 'string') continue;
+ const alias = candidate.trim();
+ if (!alias || alias.length > MAX_VOICE_INPUT_DICTIONARY_ENTRY_CHARS) continue;
+ aliases.push(alias);
+ if (aliases.length >= MAX_VOICE_INPUT_DICTIONARY_ALIASES) break;
+ }
+ return aliases;
+}
+
+/**
+ * 归一化 renderer 提交的学习动作。
+ *
+ * 入参是未经校验的 IPC payload:形状不对的条目直接丢掉,整批也要有条数上限 ——
+ * 这些动作会逐条写进 CRDT 正本,一批脏数据就是一批永久记录。
+ */
+export function sanitizeDictionaryLearningActions(input: unknown): DictationDictionaryLearningAction[] {
+ if (!Array.isArray(input)) return [];
+ const actions: DictationDictionaryLearningAction[] = [];
+ for (const candidate of input) {
+ if (!candidate || typeof candidate !== 'object') continue;
+ const action = candidate as Partial<DictationDictionaryLearningAction>;
+ if (typeof action.action !== 'string' || typeof action.term !== 'string') continue;
+ const term = action.term.trim();
+ if (!term || term.length > MAX_VOICE_INPUT_DICTIONARY_ENTRY_CHARS) continue;
+ actions.push({
+ ...(action as DictationDictionaryLearningAction),
+ term,
+ aliases: sanitizeLearningAliases(action.aliases),
+ });
+ if (actions.length >= MAX_DICTIONARY_LEARNING_ACTIONS) break;
+ }
+ return actions;
+}
+
export function registerVoiceInputDataStoreIpc(): void {
if (ipcRegistered) return;
ipcRegistered = true;
@@ -297,17 +708,73 @@ export function registerVoiceInputDataStoreIpc(): void {
}
});
- ipcMain.handle('voice-input:dictionary:delete-entries', (_event, entryIds: string[]): VoiceInputSettings => {
+ ipcMain.handle('voice-input:dictionary:delete-entries', (event, entryIds: unknown): VoiceInputSettings => {
try {
- return voiceInputDataStore.deleteDictionaryEntries(entryIds);
+ // 删除现在会写 CRDT 墓碑并传播到用户的每一台电脑,和 add/import/rename 是
+ // 同一级别的写操作 —— 守卫不能只加在新增那几个上。超长数组也要挡:逐条
+ // map 的开销全落在 main 线程。
+ assertTrustedAppRendererEvent(event);
+ return voiceInputDataStore.deleteDictionaryEntries(sanitizeDictionaryEntryIds(entryIds));
} catch (error) {
throwVoiceInputDataStoreIpcError(error);
}
});
- ipcMain.handle('voice-input:dictionary-learning:record-actions', (_event, actions: DictationDictionaryLearningAction[]) => {
+ // 词典的增改都是语义化操作,不接受 renderer 整份覆盖词条数组:同步状态是词典的
+ // 真相,整份覆盖既表达不了「用户到底做了什么」,也会在下一次物化时被丢掉。
+ ipcMain.handle('voice-input:dictionary:add-entry', (event, text: unknown): VoiceInputSettings => {
try {
- return voiceInputDataStore.recordDictionaryLearningActions(actions);
+ // 词典写入会改用户的持久数据 —— 只接受可信的主 renderer,不能让任意子框架 /
+ // WebView 拿到这几个全局 channel 就能改词典。
+ assertTrustedAppRendererEvent(event);
+ return voiceInputDataStore.addManualDictionaryEntry(typeof text === 'string' ? text : '');
+ } catch (error) {
+ throwVoiceInputDataStoreIpcError(error);
+ }
+ });
+
+ ipcMain.handle('voice-input:dictionary:import-entries', (event, texts: unknown): VoiceInputSettings => {
+ try {
+ assertTrustedAppRendererEvent(event);
+ // renderer 直连时可以绕开 CSV UI 的容量裁决,这里必须自己兜底。三重上限
+ // 缺一不可:只限入参条数的话,对着已经装满的词典再灌 1000 条照样能撑爆
+ // sidecar,而超长单条也能用少量条目做到同一件事。
+ const list = Array.isArray(texts)
+ ? texts
+ .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_ENTRIES)
+ : [];
+ return voiceInputDataStore.importManualDictionaryEntries(list);
+ } catch (error) {
+ throwVoiceInputDataStoreIpcError(error);
+ }
+ });
+
+ ipcMain.handle(
+ 'voice-input:dictionary:rename-entry',
+ (event, payload: { entryId?: unknown; text?: unknown }): VoiceInputSettings => {
+ try {
+ assertTrustedAppRendererEvent(event);
+ const entryId = typeof payload?.entryId === 'string' ? payload.entryId : '';
+ const text = typeof payload?.text === 'string' ? payload.text : '';
+ if (!entryId) return voiceInputDataStore.getSettings();
+ return voiceInputDataStore.renameDictionaryEntry(entryId, text);
+ } catch (error) {
+ throwVoiceInputDataStoreIpcError(error);
+ }
+ },
+ );
+
+ ipcMain.handle('voice-input:dictionary-learning:record-actions', (event, actions: unknown) => {
+ try {
+ // 这个 handler 直接往词典正本里写。没有守卫的话,任意子帧(webview、插件面板)
+ // 都能提交一大批唯一的 add_entry:主进程被同步写盘卡住,sidecar 也被撑过物化
+ // 上限和 relay 单帧上限,同步会因此永久停摆。
+ assertTrustedAppRendererEvent(event);
+ return voiceInputDataStore.recordDictionaryLearningActions(
+ sanitizeDictionaryLearningActions(actions),
+ );
} catch (error) {
throwVoiceInputDataStoreIpcError(error);
}
@@ -402,6 +869,76 @@ function cloneHistory(history: VoiceInputHistoryEntry[]): VoiceInputHistoryEntry
return JSON.parse(JSON.stringify(history)) as VoiceInputHistoryEntry[];
}
+function notifyDictionaryChanged(options?: { immediate?: boolean }): void {
+ dictionaryChangedListeners.forEach((listener) => {
+ try {
+ listener(options);
+ } catch {
+ // 监听者(同步驱动)出问题不能影响词典本身的写入。
+ }
+ });
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
+
+/** 把 CRDT 物化结果投影成 settings 的词典三件套(两边字段形状本就一致)。 */
+function projectMaterializedDictionary(
+ materialized: MaterializedDictionary,
+): Pick<
+ VoiceInputSettings,
+ 'dictionaryEntries' | 'dictionaryCandidates' | 'suppressedAutomaticDictionaryTexts'
+> {
+ return {
+ dictionaryEntries: materialized.entries.map((entry) => ({
+ id: entry.id,
+ text: entry.text,
+ source: entry.source,
+ frequency: entry.frequency,
+ aliases: entry.aliases.map((alias) => ({ ...alias })),
+ createdAt: entry.createdAt,
+ updatedAt: entry.updatedAt,
+ })),
+ dictionaryCandidates: materialized.candidates.map((candidate) => ({
+ text: candidate.text,
+ evidenceCount: candidate.evidenceCount,
+ aliases: candidate.aliases.map((alias) => ({ ...alias })),
+ createdAt: candidate.createdAt,
+ updatedAt: candidate.updatedAt,
+ })),
+ suppressedAutomaticDictionaryTexts: [...materialized.suppressedTexts],
+ };
+}
+
+/**
+ * 词典字段一律从通用 settings patch 里剥掉,防止绕过 CRDT 的整份覆盖。
+ *
+ * 同步开关额外转写:UI 传的是有效值,持久化只认 override(见
+ * `configuration-and-overrides.md` §2),所以在这里把它翻译成显式自定义标记。
+ */
+function stripDictionaryFields(patch: unknown): Record<string, unknown> {
+ if (!isRecord(patch)) return {};
+ const next = { ...patch };
+ delete next.dictionaryEntries;
+ delete next.dictionaryCandidates;
+ delete next.suppressedAutomaticDictionaryTexts;
+ if (typeof next.dictionarySyncEnabled === 'boolean') {
+ // 用户在开关上做的每一次显式选择都记成 override,**包括**恰好等于当前默认值的
+ // 那次。规则 §2 要求「已自定义的用户保留自己的选择」:一个曾经关掉、后来又特意
+ // 打开的用户是明确表过态的,如果因为「和今天的默认一样」就把 override 删掉,
+ // 将来默认改成 false 会把他静默关掉。
+ //
+ // 规则 §5 禁止的是**没有用户表达时**把默认值固化回配置(比如 agent 代改),
+ // 不是禁止记录用户的显式选择。清除 override 只由下面的「恢复默认」负责。
+ next.dictionarySyncEnabledOverride = next.dictionarySyncEnabled;
+ delete next.dictionarySyncEnabled;
+ } else if (next.dictionarySyncEnabled === null) {
+ // 显式传 null = 恢复默认。规则要求「恢复默认」是删除 override 重新跟随版本
+ // 默认值,而不是写入一份静态快照;传 undefined 做不到这件事,因为 patch 是
+ // 展开合并的,undefined 会被现有值盖掉。
+ next.dictionarySyncEnabledOverride = null;
+ delete next.dictionarySyncEnabled;
+ }
+ return next;
+}
diff --git a/apps/desktop/src/main/voice-input/__tests__/dictionarySyncDriver.test.ts b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncDriver.test.ts
new file mode 100644
index 0000000000..80bce7a53a
--- /dev/null
+++ b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncDriver.test.ts
@@ -0,0 +1,254 @@
+/**
+ * 词典对等同步驱动的传输策略。
+ *
+ * 这一层不碰合并语义(那在 voice-input-core 里),只回答三个问题:什么时候发、
+ * 发给谁、收到什么才处理。盯住的边界:
+ * - 用户关掉开关后必须彻底静默(既不发也不合并);
+ * - 只发给桌面 —— 手机在后台收不到 push,给它发是纯浪费;
+ * - 认不出的帧结构直接忽略,坏帧不能污染本机词典。
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ addManualEntry,
+ createEmptySyncState,
+ createHlcClock,
+ versionVectorDominates,
+} from '@cindy/voice-input-core';
+
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }),
+}));
+
+const syncEnabled = { value: true };
+const mergeRemoteDictionaryState = vi.fn<(remote: unknown) => boolean>(() => true);
+vi.mock('../VoiceInputDataStore.js', () => ({
+ voiceInputDataStore: {
+ getSettings: () => ({ dictionarySyncEnabled: syncEnabled.value }),
+ mergeRemoteDictionaryState: (remote: unknown) => mergeRemoteDictionaryState(remote),
+ },
+}));
+
+const syncState = { version: 1 as const, records: {}, suppressed: {} };
+/** 让个别用例把状态换成超大对象,验证帧上限把关。 */
+const stateOverride: { value: unknown } = { value: null };
+vi.mock('../VoiceDictionarySyncStore.js', () => ({
+ voiceDictionarySyncStore: {
+ getState: () => stateOverride.value ?? syncState,
+ materialize: () => ({
+ entries: [
+ {
+ id: 'dict-sync-cindy',
+ text: 'Cindy',
+ source: 'manual' as const,
+ frequency: 2,
+ aliases: [{ text: 'sindy', count: 1, lastSeenAt: 5 }],
+ createdAt: 1,
+ updatedAt: 2,
+ },
+ ],
+ candidates: [],
+ suppressedTexts: [],
+ }),
+ },
+}));
+
+const {
+ handleDesktopPeerOnline,
+ handleIncomingDictionaryState,
+ initVoiceDictionarySync,
+ isDesktopPlatform,
+ readDictionaryProjectionForMobile,
+ shouldExchangeDictionaryWith,
+ stopVoiceDictionarySync,
+} = await import('../dictionarySyncDriver.js');
+
+const sendState = vi.fn();
+const onlineDesktops: string[] = [];
+
+beforeEach(() => {
+ syncEnabled.value = true;
+ sendState.mockClear();
+ mergeRemoteDictionaryState.mockClear();
+ mergeRemoteDictionaryState.mockReturnValue(true);
+ onlineDesktops.length = 0;
+ stateOverride.value = null;
+ initVoiceDictionarySync({
+ sendState: (deviceId, payload) => sendState(deviceId, payload),
+ listOnlineDesktopDevices: () => [...onlineDesktops],
+ });
+});
+
+afterEach(() => {
+ stopVoiceDictionarySync();
+});
+
+describe('设备平台判定', () => {
+ it('只把桌面平台当作同步对端', () => {
+ expect(isDesktopPlatform('darwin')).toBe(true);
+ expect(isDesktopPlatform('win32')).toBe(true);
+ expect(isDesktopPlatform('linux')).toBe(true);
+ // 手机在后台不维持 WebSocket,收不到 push —— 它走主动拉取。
+ expect(isDesktopPlatform('ios')).toBe(false);
+ expect(isDesktopPlatform('android')).toBe(false);
+ expect(isDesktopPlatform(undefined)).toBe(false);
+ });
+});
+
+describe('对端准入判定', () => {
+ const desktop = { online: true, platform: 'darwin', revoked: false };
+
+ it('在线的未撤销电脑才交换词典', () => {
+ expect(shouldExchangeDictionaryWith(desktop)).toBe(true);
+ });
+
+ it('撤销过的设备一律排除 —— 撤销的意图是不再交换数据,不只是不许操作', () => {
+ expect(shouldExchangeDictionaryWith({ ...desktop, revoked: true })).toBe(false);
+ });
+
+ it('离线设备不发:relay 不暂存离线消息', () => {
+ expect(shouldExchangeDictionaryWith({ ...desktop, online: false })).toBe(false);
+ // 离线 + 已撤销也要挡住,不能靠某一个条件兜底。
+ expect(shouldExchangeDictionaryWith({ online: false, platform: 'darwin', revoked: true })).toBe(false);
+ });
+
+ it('手机不走这条通道', () => {
+ expect(shouldExchangeDictionaryWith({ ...desktop, platform: 'ios' })).toBe(false);
+ expect(shouldExchangeDictionaryWith({ ...desktop, platform: null })).toBe(false);
+ });
+});
+
+describe('出站', () => {
+ it('对端桌面上线时立即单发一次当前状态,并索取回发', () => {
+ handleDesktopPeerOnline('peer-1');
+ expect(sendState).toHaveBeenCalledTimes(1);
+ // requestReply:对端离线期间本机可能已落后于它,而它合并后若发现自己是超集
+ // 就不会主动回发 —— 必须显式索取,否则要等到它下次编辑或半小时兜底。
+ expect(sendState).toHaveBeenCalledWith('peer-1', {
+ frameVersion: 1,
+ state: syncState,
+ requestReply: true,
+ });
+ });
+
+ it('开关关闭后既不主动发送也不处理入站', () => {
+ syncEnabled.value = false;
+ handleDesktopPeerOnline('peer-1');
+ handleIncomingDictionaryState('peer-1', { frameVersion: 1, state: syncState });
+ expect(sendState).not.toHaveBeenCalled();
+ expect(mergeRemoteDictionaryState).not.toHaveBeenCalled();
+ });
+
+ it('单个对端发送失败不影响其它对端', () => {
+ onlineDesktops.push('peer-1', 'peer-2');
+ sendState.mockImplementationOnce(() => {
+ throw new Error('relay offline');
+ });
+ // 合并引入新信息 → 回发;这里借回发路径触发一次广播语义的失败隔离。
+ handleIncomingDictionaryState('peer-1', { frameVersion: 1, state: syncState });
+ expect(() => handleDesktopPeerOnline('peer-2')).not.toThrow();
+ });
+});
+
+describe('入站', () => {
+ it('合并引入新信息时回发本机状态,完成双向收敛', () => {
+ handleIncomingDictionaryState('peer-1', { frameVersion: 1, state: syncState });
+ expect(mergeRemoteDictionaryState).toHaveBeenCalledWith(syncState);
+ expect(sendState).toHaveBeenCalledWith('peer-1', { frameVersion: 1, state: syncState });
+ });
+
+ it('合并没有引入新信息时不回发,避免两台设备互相弹球', () => {
+ mergeRemoteDictionaryState.mockReturnValue(false);
+ handleIncomingDictionaryState('peer-1', { frameVersion: 1, state: syncState });
+ expect(sendState).not.toHaveBeenCalled();
+ });
+
+ it('帧结构认不出时直接忽略', () => {
+ handleIncomingDictionaryState('peer-1', undefined);
+ handleIncomingDictionaryState('peer-1', { frameVersion: 2, state: syncState });
+ handleIncomingDictionaryState('peer-1', { frameVersion: 1 });
+ handleIncomingDictionaryState('peer-1', 'not-an-object');
+ expect(mergeRemoteDictionaryState).not.toHaveBeenCalled();
+ });
+
+ it('合并抛错时吞掉,不让坏帧打断本机词典功能', () => {
+ mergeRemoteDictionaryState.mockImplementation(() => {
+ throw new Error('corrupt state');
+ });
+ expect(() => handleIncomingDictionaryState('peer-1', { frameVersion: 1, state: syncState })).not.toThrow();
+ expect(sendState).not.toHaveBeenCalled();
+ });
+});
+
+describe('回发协商', () => {
+ it('对端索取回发时,即使本次合并没有引入新信息也要回', () => {
+ // 场景:A 关掉同步期间 B 学了新词,A 重新打开并广播自己的陈旧状态。B 合并后
+ // 发现自己已是超集(changed=false),若不看 requestReply 就不会回发,A 永远
+ // 追不上 —— 直到 B 下次编辑或半小时兜底。
+ mergeRemoteDictionaryState.mockReturnValue(false);
+ handleIncomingDictionaryState('peer-1', {
+ frameVersion: 1,
+ state: syncState,
+ requestReply: true,
+ });
+ expect(sendState).toHaveBeenCalledTimes(1);
+ });
+
+ it('回发本身不再索取回发,避免两端来回弹球', () => {
+ mergeRemoteDictionaryState.mockReturnValue(false);
+ handleIncomingDictionaryState('peer-1', {
+ frameVersion: 1,
+ state: syncState,
+ requestReply: true,
+ });
+ expect(sendState).toHaveBeenCalledWith('peer-1', { frameVersion: 1, state: syncState });
+ });
+});
+
+describe('帧大小上限', () => {
+ it('状态超过 relay 单帧上限时不发送,并留下明确日志', () => {
+ // relay 拒收超限帧且 sendEnvelope 会抛;不自己把关的话,词典一旦长到越线,
+ // 此后每次广播都抛异常,同步会永久静默停摆。
+ const huge: Record<string, unknown> = {};
+ const filler = 'x'.repeat(2_000);
+ for (let index = 0; index < 2_000; index += 1) huge[`term-${index}`] = filler;
+ stateOverride.value = { version: 1, records: huge, suppressed: {} };
+
+ onlineDesktops.push('peer-1');
+ handleDesktopPeerOnline('peer-1');
+ expect(sendState).not.toHaveBeenCalled();
+ });
+
+ it('正常大小的状态照常发送', () => {
+ handleDesktopPeerOnline('peer-1');
+ expect(sendState).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('手机只读投影', () => {
+ it('只投影润色用得上的字段,不含同步元数据', () => {
+ const projection = readDictionaryProjectionForMobile();
+ expect(projection.entries).toEqual([
+ { text: 'Cindy', frequency: 2, aliases: [{ text: 'sindy', count: 1 }] },
+ ]);
+ // 除了词条和版本向量,不该漏出节点 id、化身、墓碑等同步内部结构。
+ expect(Object.keys(projection).sort()).toEqual(['entries']);
+ });
+
+ it('带上版本向量,让手机按包含关系而不是响应到达顺序挑快照', () => {
+ const first = addManualEntry(createEmptySyncState(), createHlcClock('node-a', 1_000), {
+ text: 'Cindy',
+ nowMs: 1_000,
+ });
+ stateOverride.value = first.state;
+ const before = readDictionaryProjectionForMobile().stateVector;
+ expect(before && Object.keys(before)).toEqual(['node-a']);
+
+ const second = addManualEntry(first.state, first.clock, { text: 'Orca', nowMs: 9_000 });
+ stateOverride.value = second.state;
+ const after = readDictionaryProjectionForMobile().stateVector!;
+ // 向量对合并单调:后一份必须包含前一份,否则手机会一直停在旧快照上。
+ expect(versionVectorDominates(after, before!)).toBe(true);
+ expect(versionVectorDominates(before!, after)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/voice-input/__tests__/dictionarySyncStore.test.ts b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncStore.test.ts
new file mode 100644
index 0000000000..165758dd63
--- /dev/null
+++ b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncStore.test.ts
@@ -0,0 +1,834 @@
+/**
+ * 词典同步落盘层与词典写入路径的接线。
+ *
+ * 重点盯三件事:
+ * 1. 存量用户升级后词典不丢(首次迁移借回收路径完成,不需要单独的迁移代码);
+ * 2. 旧版本客户端直接改过词典文件时,改动能被认领回来;
+ * 3. **运行期的物化回写绝不能被反向读成本地增量** —— 那会让合并进来的远端计数
+ * 被重复记账,词典频次随同步次数膨胀。
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { VoiceDictionarySyncState } from '@cindy/voice-input-core';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+let tempDir = '';
+
+const activeOwnerId = vi.hoisted(() => ({ value: 'owner-1' }));
+
+function setActiveOwner(ownerId: string): void {
+ activeOwnerId.value = ownerId;
+}
+
+vi.mock('electron', () => ({
+ app: { getPath: () => tempDir },
+ ipcMain: { handle: vi.fn(), on: vi.fn() },
+ BrowserWindow: { getAllWindows: () => [] },
+}));
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }),
+}));
+vi.mock('../../appSessionState.js', () => ({
+ getActiveAppSession: () => ({ dataOwnerId: activeOwnerId.value }),
+ ownerScopedUserDataPath: (...parts: string[]) => path.join(tempDir, 'owners', 'owner-1', ...parts),
+}));
+vi.mock('../../utils/ipcValidate.js', () => ({
+ throwIpcError: (code: string, message: string) => {
+ throw new Error(`[${code}] ${message}`);
+ },
+}));
+
+const { voiceDictionarySyncStore } = await import('../VoiceDictionarySyncStore.js');
+const { sanitizeDictionaryLearningActions, voiceInputDataStore } = await import(
+ '../VoiceInputDataStore.js'
+);
+const { addManualEntry, createEmptySyncState, createHlcClock, deleteTerms, recordLearningEvent } = await import(
+ '@cindy/voice-input-core'
+);
+
+const DATA_FILE = 'voice-input-data.v1.json';
+const SYNC_FILE = 'voice-dictionary-sync.v1.json';
+
+function ownerPath(fileName: string): string {
+ return path.join(tempDir, 'owners', 'owner-1', fileName);
+}
+
+function writeDictionaryFile(settings: Record<string, unknown>): void {
+ const filePath = ownerPath(DATA_FILE);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(
+ filePath,
+ JSON.stringify({ version: 1, settings, history: [] }),
+ 'utf-8',
+ );
+}
+
+function readDictionaryFile(): { dictionaryEntries: Array<{ text: string; source: string; frequency: number }> } {
+ return JSON.parse(fs.readFileSync(ownerPath(DATA_FILE), 'utf-8')).settings;
+}
+
+/** 每个用例都要拿到全新的 store 内存状态:两个 store 都按 ownerId 缓存。 */
+function resetStoreCaches(): void {
+ activeOwnerId.value = 'owner-1';
+ (voiceDictionarySyncStore as unknown as { data: unknown; dataOwnerId: unknown }).data = null;
+ (voiceDictionarySyncStore as unknown as { data: unknown; dataOwnerId: unknown }).dataOwnerId = null;
+ (voiceDictionarySyncStore as unknown as { pendingRecovery: unknown }).pendingRecovery = null;
+ (voiceInputDataStore as unknown as { state: unknown; stateOwnerId: unknown }).state = null;
+ (voiceInputDataStore as unknown as { state: unknown; stateOwnerId: unknown }).stateOwnerId = null;
+}
+
+beforeEach(() => {
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-dict-sync-'));
+ resetStoreCaches();
+});
+
+afterEach(() => {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+});
+
+describe('词典同步落盘 —— 首次迁移', () => {
+ it('存量词典在首次加载时被整份认领进同步状态,内容不丢', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [
+ { id: 'legacy-1', text: 'Vibe Coding', source: 'manual', frequency: 3, aliases: [] },
+ { id: 'legacy-2', text: 'LiteLLM', source: 'automatic', frequency: 5, aliases: [] },
+ ],
+ dictionaryCandidates: [
+ { text: 'Orca', evidenceCount: 2, aliases: [], createdAt: 1, updatedAt: 1 },
+ ],
+ suppressedAutomaticDictionaryTexts: ['Cindy'],
+ });
+
+ const settings = voiceInputDataStore.getSettings();
+ expect(settings.dictionaryEntries.map((entry) => entry.text).sort()).toEqual([
+ 'LiteLLM',
+ 'Vibe Coding',
+ ]);
+ expect(settings.dictionaryEntries.find((entry) => entry.text === 'Vibe Coding')?.source).toBe('manual');
+ expect(settings.dictionaryCandidates.map((item) => item.text)).toEqual(['Orca']);
+ expect(settings.suppressedAutomaticDictionaryTexts).toEqual(['Cindy']);
+ // 同步状态已建立,sidecar 落盘。
+ expect(fs.existsSync(ownerPath(SYNC_FILE))).toBe(true);
+ });
+
+ it('空词典的新用户不会凭空产生词条', () => {
+ writeDictionaryFile({ dictionaryEntries: [], dictionaryCandidates: [] });
+ expect(voiceInputDataStore.getSettings().dictionaryEntries).toEqual([]);
+ });
+});
+
+describe('词典同步落盘 —— 写入路径', () => {
+ it('手动添加、改写、删除都落到同步状态并回投影到词典文件', () => {
+ writeDictionaryFile({ dictionaryEntries: [] });
+ voiceInputDataStore.getSettings();
+
+ voiceInputDataStore.addManualDictionaryEntry('litellm');
+ expect(readDictionaryFile().dictionaryEntries.map((entry) => entry.text)).toEqual(['litellm']);
+
+ const entryId = voiceInputDataStore.getSettings().dictionaryEntries[0].id;
+ voiceInputDataStore.renameDictionaryEntry(entryId, 'LiteLLM');
+ expect(readDictionaryFile().dictionaryEntries.map((entry) => entry.text)).toEqual(['LiteLLM']);
+
+ voiceInputDataStore.deleteDictionaryEntries([entryId]);
+ expect(readDictionaryFile().dictionaryEntries).toEqual([]);
+ });
+
+ it('通用 settings 更新不能整份覆盖词典(会绕过同步状态)', () => {
+ writeDictionaryFile({ dictionaryEntries: [] });
+ voiceInputDataStore.addManualDictionaryEntry('Cindy');
+
+ voiceInputDataStore.updateSettings({
+ language: 'zh-CN',
+ dictionaryEntries: [
+ { id: 'x', text: '注入词条', source: 'manual', frequency: 1, aliases: [], createdAt: 1, updatedAt: 1 },
+ ],
+ suppressedAutomaticDictionaryTexts: ['Cindy'],
+ });
+
+ const settings = voiceInputDataStore.getSettings();
+ expect(settings.language).toBe('zh-CN');
+ expect(settings.dictionaryEntries.map((entry) => entry.text)).toEqual(['Cindy']);
+ expect(settings.suppressedAutomaticDictionaryTexts).toEqual([]);
+ });
+
+ it('自动学习按 action 记录证据,低置信度与无别名的建议被丢弃', () => {
+ writeDictionaryFile({ dictionaryEntries: [], refinementEnabled: true, autoDictionaryEnabled: true });
+ voiceInputDataStore.getSettings();
+
+ const result = voiceInputDataStore.recordDictionaryLearningActions([
+ { action: 'add_entry', term: 'Vibe Coding', aliases: ['web coding'], type: 'phrase', confidence: 'high' },
+ { action: 'add_entry', term: '低置信', aliases: ['低置心'], type: 'other', confidence: 'low' },
+ { action: 'add_entry', term: '无证据', aliases: [], type: 'other', confidence: 'high' },
+ ]);
+
+ expect(result.settings.dictionaryEntries.map((entry) => entry.text)).toEqual(['Vibe Coding']);
+ expect(result.newAutomaticEntries.map((entry) => entry.text)).toEqual(['Vibe Coding']);
+ });
+});
+
+describe('词典同步落盘 —— 合并与回收', () => {
+ it('合并远端状态后物化落盘,且不会把远端计数重复记成本地增量', () => {
+ writeDictionaryFile({ dictionaryEntries: [] });
+ voiceInputDataStore.getSettings();
+
+ // 构造一份「远端设备学过 3 次」的状态。
+ let remote = createEmptySyncState();
+ let clock = createHlcClock('remote-node', 1_000);
+ for (let index = 0; index < 3; index += 1) {
+ const result = recordLearningEvent(remote, clock, {
+ text: 'Vibe Coding',
+ aliases: ['web coding'],
+ stage: 'entry',
+ nowMs: 1_000 + index,
+ });
+ remote = result.state;
+ clock = result.clock;
+ }
+
+ expect(voiceInputDataStore.mergeRemoteDictionaryState(remote)).toBe(true);
+ expect(readDictionaryFile().dictionaryEntries[0].frequency).toBe(3);
+
+ // 同一份状态再合并任意多次都不该改变频次(幂等)。
+ for (let round = 0; round < 5; round += 1) {
+ voiceInputDataStore.mergeRemoteDictionaryState(remote);
+ }
+ expect(readDictionaryFile().dictionaryEntries[0].frequency).toBe(3);
+
+ // 关键:重新加载(触发回收路径)之后,合并进来的 3 次不能被当成本地新增再记一遍。
+ resetStoreCaches();
+ expect(voiceInputDataStore.getSettings().dictionaryEntries[0].frequency).toBe(3);
+ resetStoreCaches();
+ expect(voiceInputDataStore.getSettings().dictionaryEntries[0].frequency).toBe(3);
+ });
+
+ it('旧版本客户端在词典文件里的增删能被认领回同步状态', () => {
+ writeDictionaryFile({ dictionaryEntries: [] });
+ voiceInputDataStore.addManualDictionaryEntry('Cindy');
+ voiceInputDataStore.addManualDictionaryEntry('Orca');
+
+ // 模拟降级:旧版本直接重写词典文件(删掉 Orca、加了 device-link)。
+ writeDictionaryFile({
+ dictionaryEntries: [
+ { id: 'a', text: 'Cindy', source: 'manual', frequency: 1, aliases: [] },
+ { id: 'b', text: 'device-link', source: 'manual', frequency: 1, aliases: [] },
+ ],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ resetStoreCaches();
+
+ const settings = voiceInputDataStore.getSettings();
+ expect(settings.dictionaryEntries.map((entry) => entry.text).sort()).toEqual([
+ 'Cindy',
+ 'device-link',
+ ]);
+ });
+
+ it('更新版本的 sidecar 原样保留,词典也不被清空', () => {
+ // 降级场景:用户装过更新的客户端,sidecar 里是 v2 状态。旧客户端读不懂,
+ // 但绝不能把它当空状态物化出空词典再覆盖写回 —— 那会同时销毁用户的词典和
+ // 所有设备的合并历史。
+ writeDictionaryFile({
+ dictionaryEntries: [
+ { id: 'a', text: 'Vibe Coding', source: 'manual', frequency: 3, aliases: [] },
+ { id: 'b', text: 'LiteLLM', source: 'automatic', frequency: 2, aliases: [] },
+ ],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ const syncPath = ownerPath(SYNC_FILE);
+ const futureSidecar = JSON.stringify({
+ version: 1,
+ nodeId: 'future-node',
+ clock: { wallMs: 9_000, counter: 3 },
+ state: { version: 2, records: { future: { magic: true } }, suppressed: {} },
+ lastMaterializedKeys: ['vibe coding', 'litellm'],
+ });
+ fs.mkdirSync(path.dirname(syncPath), { recursive: true });
+ fs.writeFileSync(syncPath, futureSidecar, 'utf-8');
+ resetStoreCaches();
+
+ // 词典照常可用(来自词典文件,不是空的)。
+ const settings = voiceInputDataStore.getSettings();
+ expect(settings.dictionaryEntries.map((entry) => entry.text).sort()).toEqual([
+ 'LiteLLM',
+ 'Vibe Coding',
+ ]);
+ // sidecar 逐字节未动。
+ expect(fs.readFileSync(syncPath, 'utf-8')).toBe(futureSidecar);
+
+ // 词典写入必须明确失败(而不是静默无效或覆盖成空),sidecar 一个字节都不动。
+ expect(() => voiceInputDataStore.addManualDictionaryEntry('Orca')).toThrow();
+ expect(fs.readFileSync(syncPath, 'utf-8')).toBe(futureSidecar);
+ });
+
+ it('同步状态文件损坏时回退到词典文件,不让词典功能整体失效', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: 'Cindy', source: 'manual', frequency: 1, aliases: [] }],
+ });
+ const syncPath = ownerPath(SYNC_FILE);
+ fs.mkdirSync(path.dirname(syncPath), { recursive: true });
+ fs.writeFileSync(syncPath, '{ this is not json', 'utf-8');
+ resetStoreCaches();
+
+ expect(voiceInputDataStore.getSettings().dictionaryEntries.map((entry) => entry.text)).toEqual([
+ 'Cindy',
+ ]);
+ });
+});
+
+describe('词典同步开关 —— 只持久化用户 override', () => {
+ it('未自定义时配置里不留该字段,用户随版本跟随默认值', () => {
+ writeDictionaryFile({ dictionaryEntries: [] });
+ // 任何一次无关设置保存都不该把当前默认值固化进用户配置。
+ voiceInputDataStore.updateSettings({ language: 'zh-CN' });
+
+ const raw = JSON.parse(fs.readFileSync(ownerPath(DATA_FILE), 'utf-8')).settings;
+ expect(raw.dictionarySyncEnabledOverride).toBeUndefined();
+ // 有效值仍然是默认值。
+ expect(voiceInputDataStore.getSettings().dictionarySyncEnabled).toBe(true);
+ });
+
+ it('用户显式关闭后记录 override,并在重载后保持', () => {
+ writeDictionaryFile({ dictionaryEntries: [] });
+ voiceInputDataStore.updateSettings({ dictionarySyncEnabled: false });
+
+ const raw = JSON.parse(fs.readFileSync(ownerPath(DATA_FILE), 'utf-8')).settings;
+ expect(raw.dictionarySyncEnabledOverride).toBe(false);
+
+ resetStoreCaches();
+ expect(voiceInputDataStore.getSettings().dictionarySyncEnabled).toBe(false);
+ });
+
+ it('存量配置里的有效值:与默认不同才认作用户选择', () => {
+ // 本 PR 早期版本把有效值直接写进了配置。false 只可能来自用户主动关闭。
+ writeDictionaryFile({ dictionaryEntries: [], dictionarySyncEnabled: false });
+ expect(voiceInputDataStore.getSettings().dictionarySyncEnabled).toBe(false);
+
+ // 而 true 与当时默认相同,无法区分「用户选的」和「默认」,按规则不猜意图。
+ resetStoreCaches();
+ writeDictionaryFile({ dictionaryEntries: [], dictionarySyncEnabled: true });
+ voiceInputDataStore.updateSettings({ language: 'en' });
+ const raw = JSON.parse(fs.readFileSync(ownerPath(DATA_FILE), 'utf-8')).settings;
+ expect(raw.dictionarySyncEnabledOverride).toBeUndefined();
+ });
+});
+
+describe('词典同步落盘 —— 数据丢失防线', () => {
+ it('词典文件损坏时只读投影,绝不把整份词典墓碑掉', () => {
+ // 先正常建立同步状态。
+ writeDictionaryFile({
+ dictionaryEntries: [
+ { id: 'a', text: 'Vibe Coding', source: 'manual', frequency: 3, aliases: [] },
+ { id: 'b', text: 'LiteLLM', source: 'automatic', frequency: 2, aliases: [] },
+ ],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ const sidecarBefore = fs.readFileSync(ownerPath(SYNC_FILE), 'utf-8');
+
+ // 投影文件损坏(不是缺失)。此时 settings 退化成默认空值,如果照常跑回收,
+ // lastMaterializedKeys 里的每一条都会被判成用户删除 —— 一次读失败就此升级成
+ // CRDT 正本的永久损毁。
+ fs.writeFileSync(ownerPath(DATA_FILE), '{ not json', 'utf-8');
+ resetStoreCaches();
+
+ const settings = voiceInputDataStore.getSettings();
+ expect(settings.dictionaryEntries.map((entry) => entry.text).sort()).toEqual([
+ 'LiteLLM',
+ 'Vibe Coding',
+ ]);
+ // sidecar 未被改写,更没有墓碑。
+ expect(fs.readFileSync(ownerPath(SYNC_FILE), 'utf-8')).toBe(sidecarBefore);
+ const sync = JSON.parse(sidecarBefore);
+ for (const record of Object.values(sync.state.records) as Array<{ tombstones: object }>) {
+ expect(Object.keys(record.tombstones)).toEqual([]);
+ }
+ });
+
+ it('sidecar 来自更新客户端时拒绝词典写入,而不是覆盖成空', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: 'Vibe Coding', source: 'manual', frequency: 3, aliases: [] }],
+ });
+ const syncPath = ownerPath(SYNC_FILE);
+ const futureSidecar = JSON.stringify({
+ version: 1,
+ nodeId: 'future-node',
+ clock: { wallMs: 9_000, counter: 3 },
+ state: { version: 99, records: {}, suppressed: {} },
+ lastMaterializedKeys: ['vibe coding'],
+ });
+ fs.mkdirSync(path.dirname(syncPath), { recursive: true });
+ fs.writeFileSync(syncPath, futureSidecar, 'utf-8');
+ resetStoreCaches();
+
+ // 词典可读。
+ expect(voiceInputDataStore.getSettings().dictionaryEntries.map((e) => e.text)).toEqual([
+ 'Vibe Coding',
+ ]);
+ // 写入必须明确失败 —— 早先会基于空状态物化,把现有词典覆盖成空。
+ expect(() => voiceInputDataStore.addManualDictionaryEntry('Orca')).toThrow();
+ expect(readDictionaryFile().dictionaryEntries.map((e) => e.text)).toEqual(['Vibe Coding']);
+ expect(fs.readFileSync(syncPath, 'utf-8')).toBe(futureSidecar);
+ });
+});
+
+describe('词典同步落盘 —— 第六轮收口', () => {
+ it('投影文件被删除时同样只读物化,不把整份词典墓碑掉', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: 'Vibe Coding', source: 'manual', frequency: 3, aliases: [] }],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ const sidecarBefore = fs.readFileSync(ownerPath(SYNC_FILE), 'utf-8');
+
+ // 删除(不是损坏)投影文件 —— 与损坏一样,不能被当成「用户删光了词典」。
+ fs.rmSync(ownerPath(DATA_FILE));
+ resetStoreCaches();
+
+ expect(voiceInputDataStore.getSettings().dictionaryEntries.map((e) => e.text)).toEqual([
+ 'Vibe Coding',
+ ]);
+ expect(fs.readFileSync(ownerPath(SYNC_FILE), 'utf-8')).toBe(sidecarBefore);
+ });
+
+ it('sidecar 丢失后重建不把已同步的频次当作本机新证据', () => {
+ // 投影里的频次含有别的设备合并进来的部分;当成本机计数重新播种的话,
+ // 与那台设备再同步时同一份事件会在两个节点桶里各记一遍,频次凭空翻倍。
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: 'Cindy', source: 'automatic', frequency: 9, aliases: [] }],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ fs.rmSync(ownerPath(SYNC_FILE));
+ resetStoreCaches();
+
+ // 认领先被挂起(等对端墓碑),此时 UI 照常显示投影文件里的内容。
+ const during = voiceInputDataStore.getSettings();
+ expect(during.dictionaryEntries.map((e) => e.text)).toEqual(['Cindy']);
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(true);
+
+ // 认领落地之后:存在性保留,计数不重新播种。
+ voiceDictionarySyncStore.flushPendingRecovery('local-edit');
+ const materialized = voiceDictionarySyncStore.materialize();
+ expect(materialized.entries.map((entry) => entry.text)).toEqual(['Cindy']);
+ expect(materialized.entries[0].frequency).toBe(1);
+ });
+
+ it('导入把已有词条数算进上限,不能对着满词典无限追加', () => {
+ writeDictionaryFile({ dictionaryEntries: [] });
+ voiceInputDataStore.getSettings();
+
+ voiceInputDataStore.importManualDictionaryEntries(
+ Array.from({ length: 1_200 }, (_, index) => `term-${index}`),
+ );
+ const first = voiceInputDataStore.getSettings().dictionaryEntries.length;
+ expect(first).toBe(1_000);
+
+ // 再导入一批:已经满了,不应该继续增长。
+ voiceInputDataStore.importManualDictionaryEntries(
+ Array.from({ length: 500 }, (_, index) => `extra-${index}`),
+ );
+ expect(voiceInputDataStore.getSettings().dictionaryEntries.length).toBe(1_000);
+ });
+
+ it('同步开关可以恢复默认(删除 override 而不是写静态快照)', () => {
+ writeDictionaryFile({ dictionaryEntries: [] });
+ voiceInputDataStore.updateSettings({ dictionarySyncEnabled: false });
+ expect(JSON.parse(fs.readFileSync(ownerPath(DATA_FILE), 'utf-8')).settings.dictionarySyncEnabledOverride)
+ .toBe(false);
+
+ voiceInputDataStore.updateSettings({ dictionarySyncEnabled: null });
+ const raw = JSON.parse(fs.readFileSync(ownerPath(DATA_FILE), 'utf-8')).settings;
+ expect(raw.dictionarySyncEnabledOverride).toBeUndefined();
+ expect(voiceInputDataStore.getSettings().dictionarySyncEnabled).toBe(true);
+ });
+});
+
+describe('词典同步落盘 —— 第七轮收口', () => {
+ it('sidecar 丢失时挂起认领,等合并过对端再落地,不复活对端删掉的词', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [
+ { id: 'a', text: 'Cindy', source: 'manual', frequency: 3, aliases: [] },
+ { id: 'b', text: 'Orca', source: 'manual', frequency: 2, aliases: [] },
+ ],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+
+ // 对端删掉了 Cindy。先把对端状态留下来,再模拟本机 sidecar 丢失。
+ const peer = JSON.parse(fs.readFileSync(ownerPath(SYNC_FILE), 'utf-8')) as {
+ state: VoiceDictionarySyncState;
+ nodeId: string;
+ clock: { wallMs: number; counter: number };
+ };
+ const peerAfterDelete = deleteTerms(
+ peer.state,
+ { ...peer.clock, nodeId: peer.nodeId },
+ { termKeys: ['cindy'], nowMs: Date.now() + 1_000 },
+ );
+
+ fs.rmSync(ownerPath(SYNC_FILE));
+ resetStoreCaches();
+
+ // 认领被挂起:UI 仍然看得到投影文件里的词典,一个都没少。
+ const duringRecovery = voiceInputDataStore.getSettings();
+ expect(duringRecovery.dictionaryEntries.map((entry) => entry.text).sort()).toEqual([
+ 'Cindy',
+ 'Orca',
+ ]);
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(true);
+
+ // 与对端合并 —— 墓碑到齐,挂起的认领这时落地。
+ voiceInputDataStore.mergeRemoteDictionaryState(peerAfterDelete.state);
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(false);
+
+ const after = voiceInputDataStore.getSettings();
+ // 对端删掉的词不复活,没删的正常认领回来。
+ expect(after.dictionaryEntries.map((entry) => entry.text)).toEqual(['Orca']);
+ });
+
+ it('挂起期间用户编辑词典,认领就地落地,不会被空状态覆盖成空', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: 'Cindy', source: 'manual', frequency: 3, aliases: [] }],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ fs.rmSync(ownerPath(SYNC_FILE));
+ resetStoreCaches();
+ voiceInputDataStore.getSettings();
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(true);
+
+ const settings = voiceInputDataStore.addManualDictionaryEntry('Orca');
+ expect(settings.dictionaryEntries.map((entry) => entry.text).sort()).toEqual(['Cindy', 'Orca']);
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(false);
+ });
+
+ it('sidecar 只写稳定字段,本次加载的判断结果不落盘', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: 'Cindy', source: 'manual', frequency: 1, aliases: [] }],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ voiceInputDataStore.addManualDictionaryEntry('Orca');
+
+ const raw = JSON.parse(fs.readFileSync(ownerPath(SYNC_FILE), 'utf-8')) as Record<string, unknown>;
+ expect(Object.keys(raw).sort()).toEqual([
+ 'clock',
+ 'lastMaterializedKeys',
+ 'nodeId',
+ 'state',
+ 'version',
+ ]);
+ });
+
+ it('物化登记失败时投影与 key 基线一起回滚', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: 'Cindy', source: 'manual', frequency: 1, aliases: [] }],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ const baseline = (
+ JSON.parse(fs.readFileSync(ownerPath(SYNC_FILE), 'utf-8')) as { lastMaterializedKeys: string[] }
+ ).lastMaterializedKeys;
+
+ // 让第二段写入失败。
+ const spy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
+ throw new Error('EIO');
+ });
+ expect(() => voiceInputDataStore.addManualDictionaryEntry('Orca')).toThrow();
+ spy.mockRestore();
+
+ const after = JSON.parse(fs.readFileSync(ownerPath(SYNC_FILE), 'utf-8')) as {
+ lastMaterializedKeys: string[];
+ };
+ // key 基线必须退回去:留着新基线,下次回收会拿它对照回滚后的状态,把这次变更反向执行。
+ expect(after.lastMaterializedKeys).toEqual(baseline);
+ });
+});
+
+describe('首次迁移与 sidecar 丢失必须分得开', () => {
+ it('首次迁移整份接管频次;之后 sidecar 丢了才按恢复处理', () => {
+ // 1. 存量用户升级:投影里有词典、没有同步印记 → 整份认领,频次原样保留。
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: 'Claude code', source: 'manual', frequency: 4, aliases: [] }],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ const migrated = voiceInputDataStore.getSettings();
+ expect(migrated.dictionaryEntries[0].frequency).toBe(4);
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(false);
+ // 印记必须落盘,否则下次 sidecar 丢失会被再次误判成首次迁移。
+ expect(
+ (JSON.parse(fs.readFileSync(ownerPath(DATA_FILE), 'utf-8')) as { dictionarySyncInitialized?: boolean })
+ .dictionarySyncInitialized,
+ ).toBe(true);
+
+ // 2. 同一台机器随后丢了 sidecar:这次是恢复,认领要挂起等对端。
+ fs.rmSync(ownerPath(SYNC_FILE));
+ resetStoreCaches();
+ voiceInputDataStore.getSettings();
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(true);
+ });
+});
+
+describe('词典同步落盘 —— 第八轮收口', () => {
+ it('收到内容相同的对端状态也会落地挂起的恢复', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: 'Cindy', source: 'manual', frequency: 2, aliases: [] }],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ fs.rmSync(ownerPath(SYNC_FILE));
+ resetStoreCaches();
+ voiceInputDataStore.getSettings();
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(true);
+
+ // 对端是台新机器,词典为空 —— 合并引入不了任何新信息,但它是一份合法状态。
+ // 不在这里落地的话,本机会一直只显示投影、对外发空状态,直到用户手动改词典。
+ voiceInputDataStore.mergeRemoteDictionaryState(createEmptySyncState());
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(false);
+ expect(voiceDictionarySyncStore.materialize().entries.map((entry) => entry.text)).toEqual([
+ 'Cindy',
+ ]);
+ });
+
+ it('切换账号会丢掉上一个账号挂起的恢复', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: '账号A的词', source: 'manual', frequency: 1, aliases: [] }],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ fs.rmSync(ownerPath(SYNC_FILE));
+ resetStoreCaches();
+ voiceInputDataStore.getSettings();
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(true);
+
+ // 切到账号 B。挂起的快照属于 A,留着的话 B 的第一次编辑就会把 A 的词写进 B 的词典。
+ setActiveOwner('owner-2');
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(false);
+
+ const settings = voiceInputDataStore.addManualDictionaryEntry('账号B的词');
+ expect(settings.dictionaryEntries.map((entry) => entry.text)).toEqual(['账号B的词']);
+ });
+});
+
+describe('词典同步落盘 —— 第九轮收口', () => {
+ it('从盘上读回的状态是无原型字典 —— 原型名词条不会取到继承来的值', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [
+ { id: 'a', text: 'constructor', source: 'manual', frequency: 1, aliases: [] },
+ ],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ // 重新从盘上加载:JSON.parse 出来的对象带 Object.prototype。
+ resetStoreCaches();
+
+ const state = voiceDictionarySyncStore.getState();
+ expect(Object.getPrototypeOf(state.records)).toBeNull();
+ expect(Object.getPrototypeOf(state.suppressed)).toBeNull();
+ // 不存在的原型名键必须是 undefined,而不是继承来的函数。
+ expect(state.records['toString']).toBeUndefined();
+
+ // 而且此时还能正常给这类词做变更,不会拿函数当记录用。
+ const settings = voiceInputDataStore.addManualDictionaryEntry('toString');
+ expect(settings.dictionaryEntries.map((entry) => entry.text).sort()).toEqual([
+ 'constructor',
+ 'toString',
+ ]);
+ });
+
+ it('坏帧不算「收到对端状态」,不会提前落地挂起的恢复', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: 'Cindy', source: 'manual', frequency: 1, aliases: [] }],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ fs.rmSync(ownerPath(SYNC_FILE));
+ resetStoreCaches();
+ voiceInputDataStore.getSettings();
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(true);
+
+ // 结构坏的帧、版本更高的帧都会被归一化成空状态 —— 但它们不是「对端词典是空的」,
+ // 拿它们当信号会在真正的墓碑到齐之前播种新化身。
+ voiceInputDataStore.mergeRemoteDictionaryState({ version: 1, records: 'nope' });
+ voiceInputDataStore.mergeRemoteDictionaryState({ version: 99, records: {}, suppressed: {} });
+ voiceInputDataStore.mergeRemoteDictionaryState(null);
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(true);
+ });
+
+ it('恢复落地失败时挂起项要留着 —— 否则重试会把整份词典覆盖掉', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [
+ { id: 'a', text: 'Cindy', source: 'manual', frequency: 1, aliases: [] },
+ { id: 'b', text: 'Orca', source: 'manual', frequency: 1, aliases: [] },
+ ],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ fs.rmSync(ownerPath(SYNC_FILE));
+ resetStoreCaches();
+ voiceInputDataStore.getSettings();
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(true);
+
+ const spy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
+ throw new Error('EIO');
+ });
+ expect(() => voiceInputDataStore.addManualDictionaryEntry('新词')).toThrow();
+ spy.mockRestore();
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(true);
+
+ // 重试:恢复的词典和新编辑都在。
+ const settings = voiceInputDataStore.addManualDictionaryEntry('新词');
+ expect(settings.dictionaryEntries.map((entry) => entry.text).sort()).toEqual([
+ 'Cindy',
+ 'Orca',
+ '新词',
+ ]);
+ });
+
+ it('只有候选词的用户丢了 sidecar 也按恢复处理', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [],
+ dictionaryCandidates: [{ text: 'Cindy', evidenceCount: 3, aliases: [] }],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+ fs.rmSync(ownerPath(SYNC_FILE));
+ resetStoreCaches();
+ voiceInputDataStore.getSettings();
+
+ // 漏算候选的话这里会被当成首次迁移,把证据数按本机新证据重新播种。
+ expect(voiceDictionarySyncStore.hasPendingRecovery()).toBe(true);
+ });
+
+ it('学习动作在进 store 之前就被裁剪:动作条数、别名条数与单条长度都有上限', () => {
+ // 防线必须在 IPC 入口,而不是等 store 内部截断 —— 遍历十万个别名这件事本身
+ // 就会卡住 main 线程,即使最终只留下 8 个。
+ const sanitized = sanitizeDictionaryLearningActions([
+ ...Array.from({ length: 100 }, (_, index) => ({
+ action: 'add_entry',
+ term: `term-${index}`,
+ aliases: [
+ ...Array.from({ length: 5_000 }, (_, aliasIndex) => `alias-${aliasIndex}`),
+ 'x'.repeat(5_000),
+ 123,
+ ' ',
+ ],
+ })),
+ { action: 'add_entry' }, // 缺 term
+ { term: 'no-action' }, // 缺 action
+ null,
+ 'not-an-object',
+ { action: 'add_entry', term: 'y'.repeat(5_000) }, // term 超长
+ ]);
+
+ expect(sanitized.length).toBe(32);
+ for (const action of sanitized) {
+ expect(action.aliases?.length).toBeLessThanOrEqual(8);
+ expect(action.aliases?.every((alias) => alias.length <= 120)).toBe(true);
+ expect(action.term.length).toBeLessThanOrEqual(120);
+ }
+ });
+});
+
+describe('词典同步落盘 —— 第十轮收口', () => {
+ it('另一个进程写过盘之后再落盘,不会覆盖掉对方的词条', () => {
+ writeDictionaryFile({
+ dictionaryEntries: [{ id: 'a', text: 'Cindy', source: 'manual', frequency: 1, aliases: [] }],
+ dictionaryCandidates: [],
+ suppressedAutomaticDictionaryTexts: [],
+ });
+ voiceInputDataStore.getSettings();
+
+ // 模拟共享 userData 的另一个进程:它读到同一份 sidecar,加了一个词并写回。
+ const raw = JSON.parse(fs.readFileSync(ownerPath(SYNC_FILE), 'utf-8')) as {
+ state: VoiceDictionarySyncState;
+ nodeId: string;
+ clock: { wallMs: number; counter: number };
+ lastMaterializedKeys: string[];
+ version: number;
+ };
+ const other = addManualEntry(
+ raw.state,
+ { wallMs: raw.clock.wallMs + 1_000, counter: 0, nodeId: 'other-process' },
+ { text: '另一个进程加的词', nowMs: Date.now() },
+ );
+ fs.writeFileSync(
+ ownerPath(SYNC_FILE),
+ JSON.stringify({ ...raw, state: other.state }),
+ 'utf-8',
+ );
+
+ // 本进程手上还是旧快照,现在做一次自己的变更。
+ const settings = voiceInputDataStore.addManualDictionaryEntry('本进程加的词');
+
+ // 两边的词都要在 —— 直接覆盖写的话,另一个进程那条就没了。
+ expect(settings.dictionaryEntries.map((entry) => entry.text).sort()).toEqual([
+ 'Cindy',
+ 'istanbul'.replace('istanbul', '另一个进程加的词'),
+ '本进程加的词',
+ ].sort());
+ });
+
+ it('wrapper 版本更高的 sidecar 一个字节都不碰', () => {
+ fs.mkdirSync(path.dirname(ownerPath(SYNC_FILE)), { recursive: true });
+ const future = JSON.stringify({
+ version: 99,
+ nodeId: 'future-node',
+ clock: { wallMs: 1, counter: 0 },
+ state: { version: 1, records: {}, suppressed: {} },
+ lastMaterializedKeys: [],
+ futureOnlyField: 'must survive',
+ });
+ fs.writeFileSync(ownerPath(SYNC_FILE), future, 'utf-8');
+ writeDictionaryFile({ dictionaryEntries: [] });
+ resetStoreCaches();
+
+ voiceInputDataStore.getSettings();
+ expect(() => voiceInputDataStore.addManualDictionaryEntry('Cindy')).toThrow();
+ expect(fs.readFileSync(ownerPath(SYNC_FILE), 'utf-8')).toBe(future);
+ });
+
+ it('删除词条的 IPC 与新增走同一套守卫', () => {
+ const source = fs.readFileSync(
+ path.join(__dirname, '..', 'VoiceInputDataStore.ts'),
+ 'utf-8',
+ );
+ const handler = source.slice(source.indexOf("'voice-input:dictionary:delete-entries'"));
+ const body = handler.slice(0, handler.indexOf('});'));
+ expect(body).toContain('assertTrustedAppRendererEvent');
+ expect(body).toContain('sanitizeDictionaryEntryIds');
+ });
+
+ it('用户显式打开同步会被记成 override,即使它和当前默认值相同', () => {
+ writeDictionaryFile({ dictionaryEntries: [] });
+ voiceInputDataStore.updateSettings({ dictionarySyncEnabled: false });
+ voiceInputDataStore.updateSettings({ dictionarySyncEnabled: true });
+
+ // 曾经关掉、后来特意打开的用户是明确表过态的:以后默认改成 false 不该把他关掉。
+ const raw = JSON.parse(fs.readFileSync(ownerPath(DATA_FILE), 'utf-8')).settings;
+ expect(raw.dictionarySyncEnabledOverride).toBe(true);
+
+ // 只有显式的「恢复默认」才清掉 override。
+ voiceInputDataStore.updateSettings({ dictionarySyncEnabled: null });
+ expect(
+ JSON.parse(fs.readFileSync(ownerPath(DATA_FILE), 'utf-8')).settings.dictionarySyncEnabledOverride,
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts b/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts
new file mode 100644
index 0000000000..83052fb952
--- /dev/null
+++ b/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts
@@ -0,0 +1,264 @@
+/**
+ * 词典在本账号桌面设备之间的对等同步驱动。
+ *
+ * 传输走 device-link 的 push 帧:relay 只按 dst 转发,不解析、不落盘,所以词典内容
+ * (含人名、内部项目名、代号)全程不进服务端存储。push 不在 relay 的 CONTROL_KINDS
+ * 里,因此桌面之间交换词典**不要求**对方打开「允许被控」。
+ *
+ * ## 为什么可以不管丢帧
+ *
+ * relay 不暂存离线消息,目标不在线就直接失败。这里完全不做重试、ack 或补偿 ——
+ * 交换的是整份 CRDT 状态,合并幂等且可交换,这次没送到,下次任一触发时机再送一次
+ * 就收敛。为此触发点铺了三层:对端上线、本地变更(去抖)、以及长周期兜底。
+ *
+ * 手机不参与这条通道:移动端在后台不维持 WebSocket,收不到 push。它改用
+ * `device-link:voice:dictionary:get` 主动向在线桌面拉一份只读快照。
+ */
+
+import { MAX_FRAME_BYTES } from '@cindy/device-link';
+import { buildStateVersionVector, type VoiceDictionarySyncState } from '@cindy/voice-input-core';
+
+import { createLogger } from '../logger.js';
+import { voiceDictionarySyncStore } from './VoiceDictionarySyncStore.js';
+import { voiceInputDataStore } from './VoiceInputDataStore.js';
+
+const log = createLogger('voice-input:dictionary-sync-driver');
+
+/** push 帧 channel。payload 形状见 {@link DictionarySyncFramePayload}。 */
+export const DL_VOICE_DICTIONARY_SYNC_CHANNEL = 'device-link:voice:dictionary:sync-state';
+
+/** 本地变更后的去抖窗口:连续学习/编辑合并成一次广播。 */
+const BROADCAST_DEBOUNCE_MS = 8_000;
+/** 兜底心跳:即便没有任何本地变更,也定期交换一次,收敛因丢帧错过的状态。 */
+const BROADCAST_INTERVAL_MS = 30 * 60 * 1000;
+/** 桌面平台白名单:手机(ios/android)不参与 push 同步。 */
+const DESKTOP_PLATFORMS = new Set(['darwin', 'win32', 'linux']);
+/**
+ * 单帧状态的字节上限,留出信封与编码余量。
+ *
+ * relay 对超过 {@link MAX_FRAME_BYTES} 的帧直接拒绝,而 `sendEnvelope` 是抛错的 ——
+ * 词典一旦大到越线,此后每一次广播都抛,同步会永久静默停摆。1000 条词条 × 8 个
+ * 别名 × 120 字符,加上 CRDT 的化身、计数器、墓碑元数据,中文按 3 字节算完全可能
+ * 越线,所以必须在发送前自己把关。
+ */
+const MAX_STATE_FRAME_BYTES = Math.floor(MAX_FRAME_BYTES * 0.9);
+
+export interface DictionarySyncFramePayload {
+ /** 帧结构版本;收到不认识的版本直接忽略,不猜着解析。 */
+ frameVersion: 1;
+ state: VoiceDictionarySyncState;
+ /**
+ * 请求对端无条件回发一次自己的状态。
+ *
+ * 平时只在「合并引入了新信息」时回发,省掉无谓的往返。但有一种情形必须显式索取:
+ * 发送方自己落后了(比如同步关了一段时间,期间对端学了新词)。这时对端合并完
+ * 发现自己已是超集、`changed === false`,就不会回发,发送方要一直等到对端下次
+ * 编辑或半小时兜底才追得上。
+ */
+ requestReply?: boolean;
+}
+
+export interface DictionarySyncTransport {
+ /** 发一帧状态给指定设备(尽力而为,失败只记日志)。 */
+ sendState(deviceId: string, payload: DictionarySyncFramePayload): void;
+ /** 当前在线的同账号**桌面**设备。 */
+ listOnlineDesktopDevices(): string[];
+}
+
+let transport: DictionarySyncTransport | null = null;
+let debounceTimer: NodeJS.Timeout | null = null;
+let intervalTimer: NodeJS.Timeout | null = null;
+
+export function isDesktopPlatform(platform: string | undefined | null): boolean {
+ return typeof platform === 'string' && DESKTOP_PLATFORMS.has(platform);
+}
+
+/**
+ * 是否与某台设备交换词典。
+ *
+ * 判定收敛成这一个函数,因为它有三个独立入口(presence 上线即发、入站帧受理、
+ * 广播时的对端列表),分散写条件必然漏——最初就漏在 presence 那条上,导致词典
+ * 会推给用户明确撤销过的设备。
+ *
+ * - 必须在线:relay 不暂存离线消息,发了也白发;
+ * - 必须是电脑:手机在后台收不到 push,走主动拉取;
+ * - 撤销过的设备一律排除:撤销的意图是「不再跟这台设备交换数据」,不只是
+ * 「不许它操作我」。
+ */
+export function shouldExchangeDictionaryWith(device: {
+ online: boolean;
+ platform: string | undefined | null;
+ revoked: boolean;
+}): boolean {
+ return device.online && !device.revoked && isDesktopPlatform(device.platform);
+}
+
+export function initVoiceDictionarySync(next: DictionarySyncTransport): void {
+ transport = next;
+ if (intervalTimer) clearInterval(intervalTimer);
+ intervalTimer = setInterval(() => broadcastToAllPeers('interval'), BROADCAST_INTERVAL_MS);
+ // 定时器不该让 app 因为它而活着(Electron main 里 unref 是良好习惯)。
+ intervalTimer.unref?.();
+}
+
+export function stopVoiceDictionarySync(): void {
+ transport = null;
+ if (debounceTimer) clearTimeout(debounceTimer);
+ if (intervalTimer) clearInterval(intervalTimer);
+ debounceTimer = null;
+ intervalTimer = null;
+}
+
+/** 对端桌面上线:立刻单发一次,让它尽快拿到本机状态(它也会回发自己的)。 */
+export function handleDesktopPeerOnline(deviceId: string): void {
+ if (!isSyncEnabled()) return;
+ // 对端刚上线,它离线期间本机的状态可能已经落后于它 —— 一并索取回发。
+ sendStateTo(deviceId, 'peer-online', { requestReply: true });
+}
+
+/**
+ * 立即广播一次当前状态,不走去抖。
+ *
+ * 用于用户刚打开同步开关这类显式操作:此时对端可能早就在线,既不会有 presence
+ * 事件也不会有词典变更,不立刻发一次就要干等到兜底心跳(半小时)才收敛。
+ */
+export function broadcastDictionaryNow(): void {
+ if (debounceTimer) {
+ clearTimeout(debounceTimer);
+ debounceTimer = null;
+ }
+ // 索取回发:本机可能在关闭同步期间落后了,而对端不会主动告诉我们。
+ broadcastToAllPeers('sync-enabled', { requestReply: true });
+}
+
+/** 本地词典变更:去抖后广播。连续学习事件不会打出一连串帧。 */
+export function notifyLocalDictionaryChanged(): void {
+ if (!isSyncEnabled()) return;
+ if (debounceTimer) clearTimeout(debounceTimer);
+ debounceTimer = setTimeout(() => {
+ debounceTimer = null;
+ broadcastToAllPeers('local-change');
+ }, BROADCAST_DEBOUNCE_MS);
+ debounceTimer.unref?.();
+}
+
+/**
+ * 处理对端送来的状态帧。
+ *
+ * 合并后若本机状态比对方更全(合并引入了新信息),回发一次自己的状态,让对方也收敛
+ * —— 两轮之内双方一致,不需要版本协商。
+ */
+export function handleIncomingDictionaryState(src: string, payload: unknown): void {
+ if (!isSyncEnabled()) return;
+ const frame = payload as Partial<DictionarySyncFramePayload> | undefined;
+ if (!frame || frame.frameVersion !== 1 || !frame.state) return;
+
+ let changed = false;
+ try {
+ changed = voiceInputDataStore.mergeRemoteDictionaryState(frame.state);
+ } catch (error) {
+ log.warn('merging remote dictionary state failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return;
+ }
+ // 回发条件:本机合并出了新东西(对端未必有),或者对端明确索取(它可能落后于我们
+ // 而自己并不知道)。requestReply 的回发不再索取,避免两端来回弹球。
+ if (changed || frame.requestReply === true) {
+ if (changed) log.info(`merged dictionary state from ${src.slice(0, 8)}`);
+ sendStateTo(src, changed ? 'merge-reply' : 'reply-requested');
+ }
+}
+
+/**
+ * 供 mobile 拉取的只读投影。
+ *
+ * 内容是词条文本 + 频次 + 别名,外加一个 `stateVector`(版本向量)—— 手机同时拉
+ * 多台电脑时靠它判断哪份快照包含了另一份。除此之外不外泄任何同步内部结构:化身、
+ * 墓碑、抑制项、时钟都不出去,手机也不参与合并。
+ *
+ * 同样受「在我的设备之间同步」开关约束:用户关掉之后,词典就不该再离开这台电脑 ——
+ * 只让电脑之间停下、却继续把整份词典交给手机,与开关的承诺不符。关闭时返回空表
+ * (而不是报错),手机侧照常降级到无词典,不打断语音输入。
+ */
+export function readDictionaryProjectionForMobile(): {
+ entries: Array<{ text: string; frequency: number; aliases: Array<{ text: string; count: number }> }>;
+ stateVector?: Record<string, string>;
+} {
+ if (!isSyncEnabled()) return { entries: [] };
+ const entries = voiceDictionarySyncStore.materialize().entries.map((entry) => ({
+ text: entry.text,
+ frequency: entry.frequency,
+ aliases: entry.aliases.map((alias) => ({ text: alias.text, count: alias.count })),
+ }));
+ // 版本向量对合并单调(逐节点取 max),所以「逐节点 ≥」等价于「已经见过对方的
+ // 全部事件」—— 这才是手机可以拿一份替代另一份的条件,而不是谁的时间戳大。
+ const vector = buildStateVersionVector(voiceDictionarySyncStore.getState());
+ return Object.keys(vector).length > 0 ? { entries, stateVector: vector } : { entries };
+}
+
+function broadcastToAllPeers(reason: string, options?: { requestReply?: boolean }): void {
+ if (!isSyncEnabled() || !transport) return;
+ const peers = transport.listOnlineDesktopDevices();
+ if (peers.length === 0) return;
+ const payload = buildFrame(options);
+ if (!payload) return;
+ for (const deviceId of peers) {
+ try {
+ transport.sendState(deviceId, payload);
+ } catch (error) {
+ // 丢一帧无所谓:状态合并幂等,下一次触发会补上。
+ log.warn(`dictionary state push failed (${reason}) to ${deviceId.slice(0, 8)}`, {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+}
+
+function sendStateTo(deviceId: string, reason: string, options?: { requestReply?: boolean }): void {
+ if (!transport) return;
+ const payload = buildFrame(options);
+ if (!payload) return;
+ try {
+ transport.sendState(deviceId, payload);
+ } catch (error) {
+ log.warn(`dictionary state push failed (${reason}) to ${deviceId.slice(0, 8)}`, {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
+
+function buildFrame(options?: { requestReply?: boolean }): DictionarySyncFramePayload | null {
+ const state = voiceDictionarySyncStore.getState();
+ const payload: DictionarySyncFramePayload = { frameVersion: 1, state };
+ if (options?.requestReply) payload.requestReply = true;
+ const bytes = Buffer.byteLength(JSON.stringify(payload), 'utf8');
+ if (bytes <= MAX_STATE_FRAME_BYTES) return payload;
+ // 超限:发出去只会被 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',
+ );
+ return null;
+}
+
+function isSyncEnabled(): boolean {
+ try {
+ return voiceInputDataStore.getSettings().dictionarySyncEnabled;
+ } catch {
+ return false;
+ }
+}
+
+export const __testing = {
+ reset(): void {
+ stopVoiceDictionarySync();
+ },
+ flushDebounce(): void {
+ if (!debounceTimer) return;
+ clearTimeout(debounceTimer);
+ debounceTimer = null;
+ broadcastToAllPeers('test-flush');
+ },
+};
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index e29d11d87d..a8e42d8d72 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1042,6 +1042,12 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('voice-input:settings:update-shortcut', shortcut),
deleteDictionaryEntries: (entryIds: string[]): Promise<unknown> =>
ipcRenderer.invoke('voice-input:dictionary:delete-entries', entryIds),
+ addDictionaryEntry: (text: string): Promise<unknown> =>
+ ipcRenderer.invoke('voice-input:dictionary:add-entry', text),
+ importDictionaryEntries: (texts: string[]): Promise<unknown> =>
+ ipcRenderer.invoke('voice-input:dictionary:import-entries', texts),
+ renameDictionaryEntry: (entryId: string, text: string): Promise<unknown> =>
+ ipcRenderer.invoke('voice-input:dictionary:rename-entry', { entryId, text }),
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.tsx
index 2ab51c10f7..05be53720b 100644
--- a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx
@@ -10,10 +10,10 @@ import { Tip } from '@/components/ui/tooltip';
import { useAuth } from '@/contexts/AuthContext';
import { SUPPORTED_LOCALES } from '@/i18n';
import { cn } from '@/lib/utils';
+import { dictionaryTermKey } from '@cindy/voice-input-core';
import {
MAX_VOICE_INPUT_REFINEMENT_INSTRUCTIONS_CHARS,
MAX_VOICE_INPUT_DICTIONARY_CSV_BYTES,
- createManualVoiceInputDictionaryEntry,
getVoiceInputSettings,
mergeVoiceInputDictionaryCsvTerms,
normalizeVoiceInputDictionaryEntryText,
@@ -1059,7 +1059,10 @@ export function VoiceInputSection() {
setRefinementEnabled,
setRefinementInstructions,
setAutoDictionaryEnabled,
- setDictionaryEntries,
+ setDictionarySyncEnabled,
+ addDictionaryEntry: addDictionarySettingEntry,
+ importDictionaryEntries: importDictionarySettingEntries,
+ renameDictionaryEntry: renameDictionarySettingEntry,
deleteDictionaryEntry: deleteDictionarySettingEntry,
setShortcut,
} = useVoiceInputSettings();
@@ -1568,12 +1571,15 @@ export function VoiceInputSection() {
);
const addDictionaryEntry = useCallback(() => {
- const entry = createManualVoiceInputDictionaryEntry(newDictionaryEntryText);
- if (!entry) return;
- setDictionaryEntries([...settings.dictionaryEntries, entry]);
- setNewDictionaryEntryText('');
- setAddingDictionaryEntry(false);
- }, [newDictionaryEntryText, setDictionaryEntries, settings.dictionaryEntries]);
+ const text = normalizeVoiceInputDictionaryEntryText(newDictionaryEntryText);
+ if (!text) return;
+ // 等主进程确认写入成功再清草稿关面板:失败时保留用户输入,别让他重打一遍。
+ void addDictionarySettingEntry(text).then((ok) => {
+ if (!ok) return;
+ setNewDictionaryEntryText('');
+ setAddingDictionaryEntry(false);
+ });
+ }, [addDictionarySettingEntry, newDictionaryEntryText]);
const closeDictionaryEntryDialog = useCallback(() => {
setAddingDictionaryEntry(false);
@@ -1624,7 +1630,20 @@ export function VoiceInputSection() {
return;
}
- setDictionaryEntries(merged.entries);
+ // 容量与去重裁决仍由 mergeVoiceInputDictionaryCsvTerms 负责(下面的统计文案依赖
+ // 它的计数),但写入只提交「本次真正新增的词条文本」,由主进程按手动词条认领。
+ // 去重键必须与同步主键同一套折叠(locale 无关),否则土耳其语这类 locale 下
+ // 会出现「明明已存在却被当成新增」或反之,导入结果与实际合并结果对不上。
+ const existingKeys = new Set(
+ settings.dictionaryEntries.map((entry) => dictionaryTermKey(entry.text)),
+ );
+ const imported = await importDictionarySettingEntries(
+ merged.entries
+ .filter((entry) => !existingKeys.has(dictionaryTermKey(entry.text)))
+ .map((entry) => entry.text),
+ );
+ // 写入失败时错误提示已经弹过了,不能再报一次"导入成功"。
+ if (!imported) return;
closeDictionaryEntryDialog();
const skippedCount =
parsed.duplicateRowCount +
@@ -1644,7 +1663,7 @@ export function VoiceInputSection() {
);
}, [
closeDictionaryEntryDialog,
- setDictionaryEntries,
+ importDictionarySettingEntries,
settings.dictionaryEntries,
t,
]);
@@ -1662,33 +1681,22 @@ export function VoiceInputSection() {
const saveEditingDictionaryEntry = useCallback(() => {
if (!editingDictionaryEntryId) return;
const text = normalizeVoiceInputDictionaryEntryText(editingDictionaryEntryText);
+ // 清空文本仍然等于删除该词条(与改动前的交互一致)。
if (!text) {
- setDictionaryEntries(
- settings.dictionaryEntries.filter((entry) => entry.id !== editingDictionaryEntryId),
- );
- cancelEditingDictionaryEntry();
+ void deleteDictionarySettingEntry(editingDictionaryEntryId).then((ok) => {
+ if (ok) cancelEditingDictionaryEntry();
+ });
return;
}
- const now = Date.now();
- setDictionaryEntries(
- settings.dictionaryEntries.map((entry) =>
- entry.id === editingDictionaryEntryId
- ? {
- ...entry,
- text,
- source: 'manual',
- updatedAt: now,
- }
- : entry,
- ),
- );
- cancelEditingDictionaryEntry();
+ void renameDictionarySettingEntry(editingDictionaryEntryId, text).then((ok) => {
+ if (ok) cancelEditingDictionaryEntry();
+ });
}, [
cancelEditingDictionaryEntry,
+ deleteDictionarySettingEntry,
editingDictionaryEntryId,
editingDictionaryEntryText,
- setDictionaryEntries,
- settings.dictionaryEntries,
+ renameDictionarySettingEntry,
]);
const deleteDictionaryEntry = useCallback(
@@ -1952,6 +1960,23 @@ export function VoiceInputSection() {
/>
</div>
+ <div className="flex items-center justify-between gap-4 rounded-[12px] border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] px-3 py-2.5">
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <p className="text-13 font-medium text-[var(--settings-section-title)]">
+ {t('settings.voiceInput.refinement.dictionary.deviceSync.label')}
+ </p>
+ <p className="text-12 leading-[1.35] text-[var(--settings-section-sublabel)] opacity-70">
+ {t('settings.voiceInput.refinement.dictionary.deviceSync.hint')}
+ </p>
+ </div>
+
+ <Switch
+ checked={settings.dictionarySyncEnabled}
+ onCheckedChange={setDictionarySyncEnabled}
+ aria-label={t('settings.voiceInput.refinement.dictionary.deviceSync.ariaLabel')}
+ />
+ </div>
+
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex rounded-full bg-[var(--settings-btn-secondary-bg)] p-1">
{DICTIONARY_FILTERS.map((filter) => (
diff --git a/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts b/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts
index 7f46ef4841..928eeb27af 100644
--- a/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts
+++ b/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts
@@ -162,8 +162,12 @@ export function useVoiceInputSettings(): {
setRefinementEnabled: (enabled: boolean) => void;
setRefinementInstructions: (instructions: string) => void;
setAutoDictionaryEnabled: (enabled: boolean) => void;
- setDictionaryEntries: (entries: VoiceInputDictionaryEntry[]) => void;
- deleteDictionaryEntry: (entryId: string) => void;
+ setDictionarySyncEnabled: (enabled: boolean) => void;
+ /** 这几个返回持久化结果:成功才收口 UI(关对话框、清草稿、提示成功)。 */
+ addDictionaryEntry: (text: string) => Promise<boolean>;
+ importDictionaryEntries: (texts: string[]) => Promise<boolean>;
+ renameDictionaryEntry: (entryId: string, text: string) => Promise<boolean>;
+ deleteDictionaryEntry: (entryId: string) => Promise<boolean>;
recordDictionaryLearningActions: (actions: DictationDictionaryLearningAction[]) => void;
setShortcut: (shortcut: VoiceInputShortcut | null) => Promise<VoiceInputShortcutUpdateResult>;
} {
@@ -226,20 +230,55 @@ export function useVoiceInputSettings(): {
[updateSettings],
);
- const setDictionaryEntries = useCallback(
- (dictionaryEntries: VoiceInputDictionaryEntry[]) => updateSettings({ dictionaryEntries }),
+ const setDictionarySyncEnabled = useCallback(
+ (dictionarySyncEnabled: boolean) => updateSettings({ dictionarySyncEnabled }),
[updateSettings],
);
- const deleteDictionaryEntry = useCallback((entryId: string) => {
- void window.electronAPI.voiceInput
- .deleteDictionaryEntries([entryId])
- .then(setSettings)
- .catch((error) => {
- log.warn('voice input dictionary delete failed:', error instanceof Error ? error.message : String(error));
- toast.error(formatVoiceInputPersistenceError(t, error));
- });
- }, [t]);
+ // 词典的增改删都是语义化操作:主进程按「用户做了什么」更新同步状态,再把物化
+ // 结果回投影成 settings。整份覆盖词条数组表达不了用户意图,也会被下一次物化冲掉。
+ /**
+ * 返回 Promise 而不是 fire-and-forget:调用方要等持久化真的成功再关对话框、清
+ * 草稿、弹成功提示。主进程会在投影文件写不下去、或同步状态来自更新客户端时
+ * 拒绝写入 —— 那时 UI 却已经宣告成功,用户以为加上了,重启后发现没有。
+ */
+ const runDictionaryMutation = useCallback(
+ (mutate: () => Promise<unknown>): Promise<boolean> =>
+ mutate()
+ .then((next) => {
+ setSettings(next as VoiceInputSettings);
+ return true;
+ })
+ .catch((error) => {
+ log.warn('voice input dictionary update failed:', error instanceof Error ? error.message : String(error));
+ toast.error(formatVoiceInputPersistenceError(t, error));
+ return false;
+ }),
+ [t],
+ );
+
+ const addDictionaryEntry = useCallback(
+ (text: string) => runDictionaryMutation(() => window.electronAPI.voiceInput.addDictionaryEntry(text)),
+ [runDictionaryMutation],
+ );
+
+ const importDictionaryEntries = useCallback(
+ (texts: string[]) =>
+ runDictionaryMutation(() => window.electronAPI.voiceInput.importDictionaryEntries(texts)),
+ [runDictionaryMutation],
+ );
+
+ const renameDictionaryEntry = useCallback(
+ (entryId: string, text: string) =>
+ runDictionaryMutation(() => window.electronAPI.voiceInput.renameDictionaryEntry(entryId, text)),
+ [runDictionaryMutation],
+ );
+
+ const deleteDictionaryEntry = useCallback(
+ (entryId: string) =>
+ runDictionaryMutation(() => window.electronAPI.voiceInput.deleteDictionaryEntries([entryId])),
+ [runDictionaryMutation],
+ );
const recordDictionaryLearningActions = useCallback((actions: DictationDictionaryLearningAction[]) => {
void recordVoiceInputDictionaryLearningActions(actions);
@@ -276,7 +315,10 @@ export function useVoiceInputSettings(): {
setRefinementEnabled,
setRefinementInstructions,
setAutoDictionaryEnabled,
- setDictionaryEntries,
+ setDictionarySyncEnabled,
+ addDictionaryEntry,
+ importDictionaryEntries,
+ renameDictionaryEntry,
deleteDictionaryEntry,
recordDictionaryLearningActions,
setShortcut,
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 0c35d623da..67942a8224 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -894,6 +894,11 @@
"externalAppMacOnly": "Auto-learning after pasting into external apps is currently macOS-only. In-app voice input is unaffected.",
"ariaLabel": "Toggle dictionary auto-learning"
},
+ "deviceSync": {
+ "label": "Sync across my devices",
+ "hint": "Your dictionary merges automatically between computers that are online at the same time. Entries are sent device to device and never stored on a server.",
+ "ariaLabel": "Toggle dictionary sync across devices"
+ },
"add": "New term",
"save": "Save",
"cancel": "Cancel",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 6f04efa7fb..5c5b5ebc6c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -894,6 +894,11 @@
"externalAppMacOnly": "外部アプリへ貼り付けた後の自動学習は現在 macOS のみ対応です。アプリ内の音声入力には影響しません。",
"ariaLabel": "辞書の自動学習を切り替え"
},
+ "deviceSync": {
+ "label": "自分のデバイス間で同期",
+ "hint": "同時にオンラインのパソコン同士で辞書を自動的に統合します。内容はデバイス間で直接やり取りし、サーバーには保存しません。",
+ "ariaLabel": "辞書のデバイス間同期を切り替え"
+ },
"add": "新しい語",
"save": "保存",
"cancel": "キャンセル",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index a05e2bfbab..b48d0792fd 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -894,6 +894,11 @@
"externalAppMacOnly": "외부 앱에 붙여넣은 뒤의 자동 학습은 현재 macOS에서만 지원됩니다. 앱 내부 음성 입력에는 영향이 없습니다.",
"ariaLabel": "사전 자동 학습 전환"
},
+ "deviceSync": {
+ "label": "내 기기 간 동기화",
+ "hint": "동시에 온라인 상태인 컴퓨터끼리 사전을 자동으로 병합합니다. 내용은 기기 간에 직접 전송되며 서버에 저장되지 않습니다.",
+ "ariaLabel": "사전 기기 간 동기화 전환"
+ },
"add": "새 단어",
"save": "저장",
"cancel": "취소",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 2de9b384a5..d6e300f654 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -894,6 +894,11 @@
"externalAppMacOnly": "外部 App 粘贴后的自动学习目前仅支持 macOS;App 内语音输入不受影响。",
"ariaLabel": "切换词典自动学习"
},
+ "deviceSync": {
+ "label": "在我的设备之间同步",
+ "hint": "词典会在同时在线的电脑之间自动合并,内容端到端传输,不经服务器保存。",
+ "ariaLabel": "切换词典跨设备同步"
+ },
"add": "新词",
"save": "保存",
"cancel": "取消",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 64de73038c..fc8562609e 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1350,6 +1350,9 @@ interface ElectronAPI {
| { ok: false; error: string; errorCode?: VoiceInputGlobalErrorCode }
>;
deleteDictionaryEntries: (entryIds: string[]) => Promise<VoiceInputSettingsData>;
+ addDictionaryEntry: (text: string) => Promise<VoiceInputSettingsData>;
+ importDictionaryEntries: (texts: string[]) => Promise<VoiceInputSettingsData>;
+ renameDictionaryEntry: (entryId: string, text: string) => Promise<VoiceInputSettingsData>;
recordDictionaryLearningActions: (actions: VoiceInputDictionaryLearningAction[]) => Promise<{
settings: VoiceInputSettingsData;
newAutomaticEntries: Array<{ id: string; text: string }>;
diff --git a/apps/desktop/src/shared/voiceInputData.ts b/apps/desktop/src/shared/voiceInputData.ts
index 2b1a7a3e2d..52880fe206 100644
--- a/apps/desktop/src/shared/voiceInputData.ts
+++ b/apps/desktop/src/shared/voiceInputData.ts
@@ -76,6 +76,23 @@ export interface VoiceInputSettings {
refinementEnabled: boolean;
refinementInstructions: string;
autoDictionaryEnabled: boolean;
+ /**
+ * 是否在本账号的桌面设备之间自动同步词典(**有效值** = 默认 + 用户 override)。
+ *
+ * 刻意不复用 device-link 的「允许被控」开关:那个开关的语义是「允许别的设备操作
+ * 我这台电脑」,而词典同步是自己设备之间的数据流动,两者该分开决定。
+ *
+ * 读这个字段即可;写请走 {@link dictionarySyncEnabledOverride}。
+ */
+ dictionarySyncEnabled: boolean;
+ /**
+ * 用户对上面那个开关的显式选择;`undefined` = 从未自定义,跟随当前版本默认值。
+ *
+ * 按 `docs/dev-rules/configuration-and-overrides.md` §2,持久化只记录 override,
+ * 不把默认值固化进用户配置 —— 否则任何一次无关的设置保存都会把所有用户永久钉死
+ * 在当时的默认值上,以后改默认值也带不动他们,「恢复默认」也失去意义。
+ */
+ dictionarySyncEnabledOverride?: boolean | null;
dictionaryEntries: VoiceInputDictionaryEntry[];
dictionaryCandidates: VoiceInputDictionaryCandidate[];
suppressedAutomaticDictionaryTexts: string[];
@@ -98,6 +115,9 @@ export type VoiceInputDictionaryLearningEvidence = Pick<
'source' | 'rawTranscriptText' | 'beforeText' | 'afterText' | 'context'
>;
+/** 词典跨设备同步的系统默认值。改这里即可让未自定义的用户随版本跟随。 */
+export const DEFAULT_DICTIONARY_SYNC_ENABLED = true;
+
export const MAX_VOICE_INPUT_REFINEMENT_INSTRUCTIONS_CHARS = 1_000;
export const MAX_VOICE_INPUT_DICTIONARY_ENTRIES = 1_000;
export const MAX_VOICE_INPUT_DICTIONARY_CANDIDATES = 200;
@@ -405,6 +425,8 @@ export function getDefaultVoiceInputSettings(
refinementEnabled: true,
refinementInstructions: DEFAULT_VOICE_INPUT_REFINEMENT_INSTRUCTIONS,
autoDictionaryEnabled: true,
+ // 有效值 = 默认;override 缺省不写(见 dictionarySyncEnabledOverride 注释)。
+ dictionarySyncEnabled: DEFAULT_DICTIONARY_SYNC_ENABLED,
dictionaryEntries: [],
dictionaryCandidates: [],
suppressedAutomaticDictionaryTexts: [],
@@ -457,6 +479,10 @@ export function normalizeVoiceInputSettings(
typeof candidate.autoDictionaryEnabled === 'boolean'
? candidate.autoDictionaryEnabled
: defaults.autoDictionaryEnabled,
+ // 只认 override 字段。历史数据里可能存过有效值(本 PR 早期版本),那时无法
+ // 区分「用户选的」和「当时的默认」——按规则 §3 只做一次性兼容:仅当它与当前
+ // 默认不同时才当作用户的显式选择,相同则视为未自定义。
+ ...normalizeDictionarySyncOverride(candidate),
dictionaryEntries: normalizeVoiceInputDictionaryEntries(
candidate.dictionaryEntries ?? (candidate as { customDictionary?: unknown }).customDictionary,
),
@@ -854,6 +880,36 @@ export function createVoiceInputHistoryEntry(text: string, timestamp = Date.now(
};
}
+/**
+ * 把持久化里的 override 归一成 { 有效值, override? }。
+ *
+ * 返回的对象直接展开进 settings:没有 override 时**不产生该字段**,这样它不会被
+ * 写回用户配置。
+ */
+function normalizeDictionarySyncOverride(
+ candidate: Partial<VoiceInputSettings>,
+): Pick<VoiceInputSettings, 'dictionarySyncEnabled'> & { dictionarySyncEnabledOverride?: boolean } {
+ // null = 用户要求恢复默认:丢掉 override,重新跟随当前版本默认值。
+ if (candidate.dictionarySyncEnabledOverride === null) {
+ return { dictionarySyncEnabled: DEFAULT_DICTIONARY_SYNC_ENABLED };
+ }
+ const override = typeof candidate.dictionarySyncEnabledOverride === 'boolean'
+ ? candidate.dictionarySyncEnabledOverride
+ : legacyDictionarySyncOverride(candidate.dictionarySyncEnabled);
+ if (override === undefined) return { dictionarySyncEnabled: DEFAULT_DICTIONARY_SYNC_ENABLED };
+ return { dictionarySyncEnabled: override, dictionarySyncEnabledOverride: override };
+}
+
+/**
+ * 一次性兼容:本 PR 早期版本把有效值直接写进了配置,没有自定义标记。
+ * 规则 §3 不允许靠旧值猜意图,所以只在它与当前默认**不同**时才认作显式选择——
+ * 那种值只可能来自用户主动关闭;与默认相同的一律当作未自定义。
+ */
+function legacyDictionarySyncOverride(value: unknown): boolean | undefined {
+ if (typeof value !== 'boolean') return undefined;
+ return value === DEFAULT_DICTIONARY_SYNC_ENABLED ? undefined : value;
+}
+
function isVoiceInputLanguage(value: unknown): value is VoiceInputLanguage {
if (value === 'auto') return true;
return typeof value === 'string' && (SUPPORTED_LOCALES as readonly string[]).includes(value);
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 00e4004434..669b36a0a6 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -334,6 +334,10 @@ import {
recordMobileVoiceInputHistoryForHost,
updateMobileVoiceInputHistoryEntryForHost,
} from '@/session/mobileVoiceHistoryStore';
+import {
+ hydrateMobileVoiceDictionary,
+ refreshMobileVoiceDictionary,
+} from '@/session/mobileVoiceDictionaryCache';
import {
playMobileVoiceInputEndCue,
} from '@/session/mobileVoiceCue';
@@ -3439,9 +3443,13 @@ export default function SessionScreen() {
// Claim the connection prewarmed at pressIn (if any): its credential is
// already resolved and its ASR WebSocket already connecting, so the
// handshake overlaps the press gesture instead of following it.
+ // 词典快照拉取不进 await:它只影响润色提示的丰富度,拉不到(桌面离线、老版本
+ // 被控端)就用上次缓存,绝不为它推迟开麦。本次拉到的内容供下一次润色使用。
+ void refreshMobileVoiceDictionary(deviceId, () => maker.getVoiceDictionary());
const [prewarmedVoice, localVoiceInputHistory] = await Promise.all([
takePrewarmedMobileVoiceAsr(deviceId) ?? Promise.resolve(null),
getMobileVoiceInputHistoryForHost(deviceId),
+ hydrateMobileVoiceDictionary(deviceId),
]);
claimedPrewarm = prewarmedVoice;
const credential = prewarmedVoice?.credential
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 4d25cfa60e..d74f0a1214 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -228,6 +228,10 @@ import {
recordMobileVoiceInputHistoryForHost,
updateMobileVoiceInputHistoryEntryForHost,
} from '@/session/mobileVoiceHistoryStore';
+import {
+ hydrateMobileVoiceDictionary,
+ refreshMobileVoiceDictionary,
+} from '@/session/mobileVoiceDictionaryCache';
import {
playMobileVoiceInputEndCue,
} from '@/session/mobileVoiceCue';
@@ -1474,9 +1478,13 @@ export default function NewRemoteSessionScreen() {
// Claim the connection prewarmed at pressIn (if any): its credential is
// already resolved and its ASR WebSocket already connecting, so the
// handshake overlaps the press gesture instead of following it.
+ // 词典快照拉取不进 await:它只影响润色提示的丰富度,拉不到(桌面离线、老版本
+ // 被控端)就用上次缓存,绝不为它推迟开麦。
+ void refreshMobileVoiceDictionary(selectedDeviceId, () => maker.getVoiceDictionary());
const [prewarmedVoice, localVoiceInputHistory] = await Promise.all([
takePrewarmedMobileVoiceAsr(selectedDeviceId) ?? Promise.resolve(null),
getMobileVoiceInputHistoryForHost(selectedDeviceId),
+ hydrateMobileVoiceDictionary(selectedDeviceId),
]);
claimedPrewarm = prewarmedVoice;
const credential = prewarmedVoice?.credential
diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsx
index e6182c0901..6de07c7f49 100644
--- a/apps/mobile/app/settings.tsx
+++ b/apps/mobile/app/settings.tsx
@@ -5,6 +5,7 @@ import { useUpdates } from 'expo-updates';
import { useRouter } from 'expo-router';
import { Children, Fragment, isValidElement, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import {
+ FlatList,
Image,
Linking,
Platform,
@@ -63,6 +64,20 @@ import {
syncPushRegistration,
writePushEnabled,
} from '@/notifications/pushNotifications';
+import {
+ hydrateMobileVoiceDictionary,
+ readCachedMobileVoiceDictionarySnapshot,
+ refreshMobileVoiceDictionary,
+} from '@/session/mobileVoiceDictionaryCache';
+import {
+ buildMobileVoiceDictionaryEntryViews,
+ collectMobileVoiceDictionaryHosts,
+ patchMobileVoiceDictionaryHosts,
+ type MobileVoiceDictionaryEntryView,
+ type MobileVoiceDictionaryHost,
+} from '@/session/mobileVoiceDictionaryView';
+import { DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL } from '@cindy/maker-shared/device-link-contract';
+import type { MobileVoiceDictionarySnapshotResult } from '@cindy/maker-shared/device-link-contract';
import { buildMobileUpdateInfoRows, currentMobileOtaVersion } from '@/settings/updateInfo';
import { shouldCheckBundleUpdate } from '@/update/bundleUpdate';
import {
@@ -91,7 +106,8 @@ export default function SettingsScreen() {
const auth = useAuth();
const { t } = useTranslation();
const { locale, setLocale } = useLocale();
- const { status } = useDeviceLink();
+ const deviceLink = useDeviceLink();
+ const { lastPresenceSnapshot, status } = deviceLink;
const [copiedRowId, setCopiedRowId] = useState<string | null>(null);
const [loggingOut, setLoggingOut] = useState(false);
const [accountDeletionAvailable, setAccountDeletionAvailable] =
@@ -111,6 +127,12 @@ export default function SettingsScreen() {
const [analyticsReady, setAnalyticsReady] = useState(false);
const [analyticsMessage, setAnalyticsMessage] = useState<string | null>(null);
const updateCheckInFlightRef = useRef(false);
+ // 语音词典:手机只读展示被控桌面的词典快照(正本在桌面,手机不参与合并)。
+ const [dictionaryScreenOpen, setDictionaryScreenOpen] = useState(false);
+ const [desktopDevices, setDesktopDevices] = useState<readonly MobileVoiceDictionaryHost[]>([]);
+ const [dictionaryRefreshing, setDictionaryRefreshing] = useState(false);
+ /** 缓存在模块里,组件用这个计数强制重渲染(每次刷新完成 +1)。 */
+ const [dictionaryRevision, setDictionaryRevision] = useState(0);
const [selfDeviceName, setSelfDeviceName] = useState<string | null>(null);
const [selfDeviceNameDraft, setSelfDeviceNameDraft] = useState('');
const [selfDeviceNameEditing, setSelfDeviceNameEditing] = useState(false);
@@ -178,6 +200,8 @@ export default function SettingsScreen() {
useEffect(() => {
if (!auth.isAuthenticated || !auth.deviceId) {
setSelfDeviceName(null);
+ // 登出/未登录才清空电脑列表 —— 拉取失败不清(见下面 catch 的说明)。
+ setDesktopDevices([]);
return;
}
@@ -190,9 +214,15 @@ export default function SettingsScreen() {
if (cancelled) return;
const self = res.devices.find((device) => device.deviceId === auth.deviceId);
setSelfDeviceName(self?.name?.trim() || null);
+ // 同一份设备清单顺带筛出电脑:词典正本在电脑上,手机按电脑分别展示。
+ setDesktopDevices(collectMobileVoiceDictionaryHosts(res.devices));
})
.catch(() => {
- if (!cancelled) setSelfDeviceName(null);
+ if (cancelled) return;
+ setSelfDeviceName(null);
+ // 电脑列表刻意不清空:这只是一次拉取失败(断网、超时),不代表用户没有电脑。
+ // 清掉的话词典页会显示成「还没有电脑」,连带 hydrate/refresh 也没有 host 可
+ // 跑 —— 明明本地还有一份可用的离线缓存。真正该清空的时机是登出。
});
return () => {
@@ -578,6 +608,66 @@ export default function SettingsScreen() {
}
}, [analyticsBusy, resumeAnalyticsReporting, t]);
+ // REST 设备清单是「打开设置页那一刻」的快照,之后电脑上线/下线不会反映进来。
+ // 设置页可能开着很久,不跟 presence 的话:某台电脑上线了,这里仍认为全部离线,
+ // 刷新按钮直接 return,用户只能退出重进才能拉词典。
+ useEffect(() => {
+ if (!lastPresenceSnapshot) return;
+ setDesktopDevices((current) => patchMobileVoiceDictionaryHosts(current, lastPresenceSnapshot));
+ }, [lastPresenceSnapshot]);
+
+ /**
+ * 向所有在线电脑各拉一次词典快照。
+ *
+ * 它们本来就该收敛到同一份内容,拉多台只是为了容错(某台是旧版本、某台正好断线)。
+ * 失败一律静默:电脑离线、没开「允许被控」、老版本不认识这个 channel 都是常态,
+ * 页面继续显示上次缓存,不弹错。
+ */
+ const refreshVoiceDictionary = useCallback(() => {
+ const online = desktopDevices.filter((host) => host.online);
+ if (online.length === 0) return;
+ setDictionaryRefreshing(true);
+ void Promise.all(
+ online.map((host) => refreshMobileVoiceDictionary(
+ host.deviceId,
+ () => deviceLink.invoke<MobileVoiceDictionarySnapshotResult>(
+ host.deviceId,
+ DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL,
+ [],
+ ),
+ { force: true },
+ )),
+ ).finally(() => {
+ setDictionaryRefreshing(false);
+ // 缓存写在模块里,组件靠这个计数触发重渲染。
+ setDictionaryRevision((value) => value + 1);
+ });
+ }, [desktopDevices, deviceLink]);
+
+ const openVoiceDictionary = useCallback(() => {
+ setDictionaryScreenOpen(true);
+ // 进页面先把盘上缓存读进内存(离线也有内容可看),再拉一次最新的。
+ void Promise.all(desktopDevices.map((host) => hydrateMobileVoiceDictionary(host.deviceId)))
+ .then(() => setDictionaryRevision((value) => value + 1))
+ .catch(() => undefined);
+ refreshVoiceDictionary();
+ }, [desktopDevices, refreshVoiceDictionary]);
+
+ // dictionaryRevision 只作为依赖存在:缓存是模块级的,刷新完成后靠它触发重算。
+ const dictionaryEntries = useMemo(
+ () =>
+ buildMobileVoiceDictionaryEntryViews(
+ desktopDevices.map((host) => readCachedMobileVoiceDictionarySnapshot(host.deviceId)),
+ ),
+ [desktopDevices, dictionaryRevision],
+ );
+
+ const dictionaryStatus = desktopDevices.length === 0
+ ? 'no-desktops'
+ : desktopDevices.some((host) => host.online)
+ ? 'ready'
+ : 'all-offline';
+
const avatarLabel = (overview.header.name.trim()[0] ?? '?').toUpperCase();
const updateBusy = updatePhase === 'checking' || updatePhase === 'downloading';
const updateButtonLabel = updatePhase === 'checking' ? t('settings.version.checking')
@@ -588,6 +678,18 @@ export default function SettingsScreen() {
: 'settings.version.checkAction',
);
+ if (dictionaryScreenOpen) {
+ return (
+ <VoiceDictionaryScreen
+ entries={dictionaryEntries}
+ onBack={() => setDictionaryScreenOpen(false)}
+ onRefresh={refreshVoiceDictionary}
+ refreshing={dictionaryRefreshing}
+ status={dictionaryStatus}
+ />
+ );
+ }
+
if (selfDeviceNameEditing) {
return (
<RenameSelfDeviceScreen
@@ -719,6 +821,23 @@ export default function SettingsScreen() {
</SettingsGroup>
) : null}
+ {/* 语音词典:只读查看电脑上的词典(正本在电脑,增删改回电脑做) */}
+ <SettingsGroup
+ footer={t('settings.voiceDictionary.hint')}
+ title={t('settings.voiceDictionary.sectionTitle')}
+ >
+ {[
+ <ActionInfoRow
+ accessibilityLabel={t('settings.voiceDictionary.openAccessibility')}
+ key="voice-dictionary"
+ label={t('settings.voiceDictionary.label')}
+ onPress={openVoiceDictionary}
+ testID="settings.voiceDictionary.row"
+ value={t('settings.voiceDictionary.entryCount', { count: dictionaryEntries.length })}
+ />,
+ ]}
+ </SettingsGroup>
+
{/* 显示语言:默认跟随系统,手动选择即持久化 override(恢复跟随系统 = 清除 override) */}
<SettingsGroup
footer={t('settings.language.hint')}
@@ -1038,6 +1157,110 @@ function ActionInfoRow({
);
}
+/**
+ * 语音词典查看页(只读)。
+ *
+ * 词典对用户是**一份**:同账号下所有开启同步的电脑收敛到同一份内容,「这条词来自
+ * 哪台电脑」是实现细节,不该出现在界面上 —— 同一台机器换名或重装就会多出一个分组,
+ * 列表立刻没法看。所以这里把所有电脑的快照合并成单一列表。
+ *
+ * 正本在电脑上,手机只拉快照用于润色,因此没有任何编辑入口:增删改一律回电脑做,
+ * 避免手机维护一份会分叉的副本。
+ */
+function VoiceDictionaryScreen({
+ entries,
+ onBack,
+ onRefresh,
+ refreshing,
+ status,
+}: {
+ entries: readonly MobileVoiceDictionaryEntryView[];
+ onBack(): void;
+ onRefresh(): void;
+ refreshing: boolean;
+ status: 'ready' | 'no-desktops' | 'all-offline';
+}) {
+ const styles = useThemedStyles(makeStyles);
+ const { t } = useTranslation();
+
+ const footer = status === 'no-desktops'
+ ? t('settings.voiceDictionary.noDesktops')
+ : status === 'all-offline'
+ ? t('settings.voiceDictionary.offlineHint')
+ : t('settings.voiceDictionary.readOnlyHint');
+
+ return (
+ <SafeAreaView style={styles.safeArea} testID="settings.voiceDictionary.screen">
+ <ScreenHeader
+ backTestID="settings.voiceDictionary.backButton"
+ onBack={onBack}
+ title={t('settings.voiceDictionary.screenTitle')}
+ />
+ {/*
+ 词典上限是 1000 条,用 ScrollView 会把每一行都实例化出来 —— 低端机上首屏卡顿
+ 且常驻内存。这里换成虚拟化列表,只挂载可见行;卡片视觉靠 header/item/footer
+ 三段样式拼出来(FlatList 没法在外面包一层带圆角的 View 还保持自身滚动)。
+ */}
+ <FlatList
+ ListFooterComponent={
+ <>
+ <View style={styles.listCardBottom} />
+ <Text style={styles.groupFooter}>{footer}</Text>
+ </>
+ }
+ ListHeaderComponent={
+ <>
+ <View style={styles.groupTitleRow}>
+ <Text style={styles.groupTitle}>{t('settings.voiceDictionary.sectionTitle')}</Text>
+ </View>
+ <View style={styles.listCardTop}>
+ <Pressable
+ accessibilityLabel={t('settings.voiceDictionary.refreshAccessibility')}
+ accessibilityRole="button"
+ onPress={onRefresh}
+ style={({ pressed }) => [styles.row, pressed && styles.pressed]}
+ testID="settings.voiceDictionary.refresh"
+ >
+ <View style={styles.rowLine}>
+ <Text style={styles.rowLabel}>
+ {t('settings.voiceDictionary.entryCount', { count: entries.length })}
+ </Text>
+ <Text style={styles.rowValue} numberOfLines={1}>
+ {refreshing
+ ? t('settings.voiceDictionary.refreshing')
+ : t('settings.voiceDictionary.refresh')}
+ </Text>
+ </View>
+ </Pressable>
+ </View>
+ </>
+ }
+ contentContainerStyle={styles.listContent}
+ data={entries}
+ keyExtractor={(entry) => entry.key}
+ renderItem={({ item }) => (
+ <View style={styles.listCardMiddle}>
+ <View style={styles.divider} />
+ <View style={styles.row} testID={`settings.voiceDictionary.entry.${item.key}`}>
+ <View style={styles.rowLine}>
+ <Text style={styles.rowLabel} numberOfLines={2}>{item.text}</Text>
+ </View>
+ {item.aliases.length > 0 ? (
+ <Text style={styles.rowDetail} numberOfLines={2}>
+ {t('settings.voiceDictionary.aliases', {
+ aliases: item.aliases.join(t('settings.voiceDictionary.aliasSeparator')),
+ })}
+ </Text>
+ ) : null}
+ </View>
+ </View>
+ )}
+ testID="settings.voiceDictionary.scroll"
+ />
+ </SafeAreaView>
+ );
+}
+
function RenameSelfDeviceScreen({
draft,
message,
@@ -1189,6 +1412,34 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
overflow: 'hidden',
},
divider: { backgroundColor: colors.border, height: StyleSheet.hairlineWidth, marginLeft: spacing.lg },
+ // —— 虚拟化列表拼出的卡片三段 ——
+ listContent: { paddingBottom: spacing.xxl, paddingHorizontal: spacing.lg, paddingTop: spacing.lg },
+ listCardTop: {
+ backgroundColor: colors.surfaceElevated,
+ borderColor: colors.border,
+ borderTopLeftRadius: radius.container,
+ borderTopRightRadius: radius.container,
+ borderWidth: StyleSheet.hairlineWidth,
+ marginTop: spacing.sm,
+ overflow: 'hidden',
+ },
+ listCardMiddle: {
+ backgroundColor: colors.surfaceElevated,
+ borderColor: colors.border,
+ borderLeftWidth: StyleSheet.hairlineWidth,
+ borderRightWidth: StyleSheet.hairlineWidth,
+ },
+ listCardBottom: {
+ backgroundColor: colors.surfaceElevated,
+ borderBottomLeftRadius: radius.container,
+ borderBottomRightRadius: radius.container,
+ borderColor: colors.border,
+ borderBottomWidth: StyleSheet.hairlineWidth,
+ borderLeftWidth: StyleSheet.hairlineWidth,
+ borderRightWidth: StyleSheet.hairlineWidth,
+ height: radius.container,
+ marginBottom: spacing.sm,
+ },
// —— 行 ——
row: { gap: 3, justifyContent: 'center', minHeight: 52, paddingHorizontal: spacing.lg, paddingVertical: spacing.md },
rowLine: { alignItems: 'center', flexDirection: 'row', gap: spacing.md },
diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index 217cc4452b..45aebceaa1 100644
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@ -52,6 +52,7 @@ describe('mobile maker transport', () => {
'device-link:media:fetch',
'device-link:voice:transcribe',
'device-link:voice:dictionary-learning',
+ 'device-link:voice:dictionary:get',
'maker:get-pending-interactions',
'maker:resolve-interaction',
'maker:get-context-usage',
@@ -274,6 +275,7 @@ describe('mobile maker transport', () => {
beforeText: 'XDMaker',
afterText: 'XDMaker',
});
+ await maker.getVoiceDictionary();
await maker.input.stop('s1', { pauseQueue: true });
await maker.input.compact('s1');
await maker.input.retryLastError('s1');
@@ -314,6 +316,7 @@ describe('mobile maker transport', () => {
beforeText: 'XDMaker',
afterText: 'XDMaker',
}]],
+ ['device-link:voice:dictionary:get', []],
['maker:input:stop', ['s1', { pauseQueue: true }]],
['maker:input:compact', ['s1']],
['maker:input:retry-last-error', ['s1']],
diff --git a/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts b/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts
new file mode 100644
index 0000000000..56a7bcfaab
--- /dev/null
+++ b/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts
@@ -0,0 +1,356 @@
+/**
+ * 手机端词典缓存的降级行为。
+ *
+ * 手机拿的是被控桌面的只读快照,拉不到的情形很常见(桌面离线、老版本被控端不认识
+ * 这个 channel、隧道抖动)。这一层的硬要求是:**任何失败都只降级到上次缓存,绝不
+ * 抛错打断语音输入**,也绝不为了拉词典让开麦等待。
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { MobileVoiceDictionarySnapshotResult } from '@cindy/maker-shared/device-link-contract';
+
+const storage = new Map<string, string>();
+vi.mock('@react-native-async-storage/async-storage', () => ({
+ default: {
+ getItem: async (key: string) => storage.get(key) ?? null,
+ setItem: async (key: string, value: string) => {
+ storage.set(key, value);
+ },
+ removeItem: async (key: string) => {
+ storage.delete(key);
+ },
+ },
+}));
+
+vi.mock('@/session/mobileVoiceHistoryStore', () => ({
+ listMobileVoiceHistoryHosts: async () => [] as string[],
+}));
+
+const {
+ __resetMobileVoiceDictionaryCacheForTests,
+ setMobileVoiceDictionaryAccountScope,
+ clearAllMobileVoiceDictionaryCaches,
+ hydrateMobileVoiceDictionary,
+ readCachedMobileVoiceDictionary,
+ readCachedMobileVoiceDictionarySnapshot,
+ refreshMobileVoiceDictionary,
+} = await import('@/session/mobileVoiceDictionaryCache');
+
+const HOST = 'desktop-1';
+
+beforeEach(() => {
+ storage.clear();
+ __resetMobileVoiceDictionaryCacheForTests();
+ setMobileVoiceDictionaryAccountScope('');
+});
+
+describe('mobileVoiceDictionaryCache', () => {
+ it('拉取成功后缓存并落盘,重启后能恢复', async () => {
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: true,
+ entries: [{ text: 'Vibe Coding', frequency: 3, aliases: [{ text: 'web coding', count: 2 }] }],
+ }));
+
+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([
+ { text: 'Vibe Coding', frequency: 3, aliases: [{ text: 'web coding', count: 2 }] },
+ ]);
+
+ // 模拟 App 重启:内存清空,只剩盘上数据。
+ __resetMobileVoiceDictionaryCacheForTests();
+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);
+ await hydrateMobileVoiceDictionary(HOST);
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('Vibe Coding');
+ });
+
+ it('拉取失败沿用上次缓存,不抛错', async () => {
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: true,
+ entries: [{ text: 'Cindy', frequency: 1 }],
+ }));
+
+ // 桌面离线 / 隧道抛错。
+ await expect(
+ refreshMobileVoiceDictionary(HOST, async () => {
+ throw new Error('DEVICE_OFFLINE');
+ }, { force: true }),
+ ).resolves.toBeUndefined();
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('Cindy');
+
+ // 老版本被控端不认识该 channel。
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: false,
+ error: 'CHANNEL_NOT_ALLOWED',
+ }), { force: true });
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('Cindy');
+ });
+
+ it('从没拉到过时返回空词典,润色照常进行', async () => {
+ await refreshMobileVoiceDictionary(HOST, async () => ({ ok: false, error: 'offline' }));
+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);
+ });
+
+ it('短时间内不重复拉取,force 可以强制刷新', async () => {
+ const fetchSnapshot = vi.fn(async () => ({ ok: true as const, entries: [{ text: 'Cindy' }] }));
+ await refreshMobileVoiceDictionary(HOST, fetchSnapshot);
+ await refreshMobileVoiceDictionary(HOST, fetchSnapshot);
+ expect(fetchSnapshot).toHaveBeenCalledTimes(1);
+
+ await refreshMobileVoiceDictionary(HOST, fetchSnapshot, { force: true });
+ expect(fetchSnapshot).toHaveBeenCalledTimes(2);
+ });
+
+ it('不同被控桌面的词典互不串味', async () => {
+ await refreshMobileVoiceDictionary(HOST, async () => ({ ok: true, entries: [{ text: 'Cindy' }] }));
+ await refreshMobileVoiceDictionary('desktop-2', async () => ({
+ ok: true,
+ entries: [{ text: 'Orca' }],
+ }));
+
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('Cindy');
+ expect(readCachedMobileVoiceDictionary('desktop-2')[0].text).toBe('Orca');
+ });
+
+ it('账号边界清理:抹掉内存与盘上缓存,下一个账号读不到上一个账号的词条', async () => {
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: true,
+ entries: [{ text: '内部项目代号' }],
+ }));
+ await refreshMobileVoiceDictionary('desktop-2', async () => ({
+ ok: true,
+ entries: [{ text: 'Cindy' }],
+ }));
+ expect(readCachedMobileVoiceDictionary(HOST)).toHaveLength(1);
+
+ await clearAllMobileVoiceDictionaryCaches();
+
+ // 内存清空。
+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);
+ expect(readCachedMobileVoiceDictionary('desktop-2')).toEqual([]);
+ // 盘上也清空 —— 否则下个账号一 hydrate 就把上个账号的词典读回来。
+ await hydrateMobileVoiceDictionary(HOST);
+ await hydrateMobileVoiceDictionary('desktop-2');
+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);
+ expect(readCachedMobileVoiceDictionary('desktop-2')).toEqual([]);
+ expect([...storage.keys()].filter((key) => key.includes('mobileVoiceDictionary'))).toEqual([]);
+ });
+
+ it('清理会丢弃在途请求的结果,不让登出瞬间返回的响应写回缓存', async () => {
+ let release: (value: MobileVoiceDictionarySnapshotResult) => void = () => {};
+ const pending = new Promise<MobileVoiceDictionarySnapshotResult>((resolve) => {
+ release = resolve;
+ });
+ const inFlight = refreshMobileVoiceDictionary(HOST, () => pending);
+
+ await clearAllMobileVoiceDictionaryCaches();
+ release({ ok: true, entries: [{ text: '上个账号的词' }] });
+ await inFlight;
+
+ // 在途响应即使晚到,也不该让上个账号的词典复活到内存里被润色读走。
+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);
+ });
+
+ it('并发刷新多台电脑时 host 索引不丢条目 —— 丢了登出就清理不到', async () => {
+ const hosts = ['d1', 'd2', 'd3', 'd4', 'd5'];
+ await Promise.all(hosts.map((host) => refreshMobileVoiceDictionary(
+ host,
+ async () => ({ ok: true, entries: [{ text: `term-${host}` }] }),
+ )));
+
+ const index = JSON.parse(storage.get('xdt.mobileVoiceDictionary.v2.hosts') ?? '[]') as string[];
+ expect([...index].sort()).toEqual(hosts);
+
+ // 索引完整 → 登出能把每一份快照都删掉。
+ await clearAllMobileVoiceDictionaryCaches();
+ expect([...storage.keys()].filter((key) => key.includes('mobileVoiceDictionary'))).toEqual([]);
+ });
+
+ it('清理期间落盘的写入会自我回收,不在盘上留下上个账号的快照', async () => {
+ let release: (value: MobileVoiceDictionarySnapshotResult) => void = () => {};
+ const pending = new Promise<MobileVoiceDictionarySnapshotResult>((resolve) => {
+ release = resolve;
+ });
+ const inFlight = refreshMobileVoiceDictionary(HOST, () => pending);
+
+ await clearAllMobileVoiceDictionaryCaches();
+ release({ ok: true, entries: [{ text: '上个账号的词' }] });
+ await inFlight;
+
+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);
+ // 关键:落盘发生在清理之后也要被回收,否则下个账号 hydrate 就读回来了。
+ expect([...storage.keys()].filter((key) => key.includes('mobileVoiceDictionary'))).toEqual([]);
+ });
+
+ it('异常回包被归一化,不会把坏数据塞进润色上下文', async () => {
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: true,
+ entries: [
+ { text: ' ' },
+ { text: 'Cindy', frequency: -5, aliases: [{ text: '' }, { text: 'sindy', count: 0 }] },
+ null,
+ 'not-an-object',
+ ] as never,
+ }));
+
+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([
+ { text: 'Cindy', frequency: 1, aliases: [{ text: 'sindy', count: 1 }] },
+ ]);
+ });
+});
+
+describe('账号分区', () => {
+ it('切换账号后读不到上一个账号的快照 —— 即使清理没删干净', async () => {
+ setMobileVoiceDictionaryAccountScope('user-a');
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: true,
+ entries: [{ text: '内部项目代号' }],
+ }));
+ expect(readCachedMobileVoiceDictionary(HOST)).toHaveLength(1);
+
+ // 故意不调用清理:模拟索引读失败等「没删干净」的现实情况。
+ setMobileVoiceDictionaryAccountScope('user-b');
+ await hydrateMobileVoiceDictionary(HOST);
+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);
+
+ // 切回去仍然读得到自己的那份(分区而不是丢弃)。
+ setMobileVoiceDictionaryAccountScope('user-a');
+ await hydrateMobileVoiceDictionary(HOST);
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('内部项目代号');
+ });
+
+ it('索引读不出来时不删索引 —— 否则剩下的快照永远清不掉', async () => {
+ setMobileVoiceDictionaryAccountScope('user-a');
+ await refreshMobileVoiceDictionary(HOST, async () => ({ ok: true, entries: [{ text: 'Cindy' }] }));
+ // 索引损坏。
+ storage.set('xdt.mobileVoiceDictionary.v2.hosts', '{not json');
+
+ await clearAllMobileVoiceDictionaryCaches();
+ expect(storage.get('xdt.mobileVoiceDictionary.v2.hosts')).toBe('{not json');
+ });
+});
+
+describe('登出清理与分区切换的时序', () => {
+ it('分区已被切回匿名之后再清理,仍能删掉登出账号的快照', async () => {
+ setMobileVoiceDictionaryAccountScope('user-a');
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: true,
+ entries: [{ text: '内部项目代号' }],
+ }));
+ expect([...storage.keys()].some((key) => key.includes('user-a'))).toBe(true);
+
+ // AuthContext 的实际顺序:先切分区(applyUser(null)),清理才异步跑起来。
+ setMobileVoiceDictionaryAccountScope('');
+ await clearAllMobileVoiceDictionaryCaches();
+
+ expect([...storage.keys()].filter((key) => key.includes('mobileVoiceDictionary'))).toEqual([]);
+ });
+});
+
+describe('账号切走之后落地的旧请求', () => {
+ it('写进自己那个分区,不落到新账号的键上', async () => {
+ setMobileVoiceDictionaryAccountScope('user-a');
+ let release: (value: MobileVoiceDictionarySnapshotResult) => void = () => {};
+ const pending = new Promise<MobileVoiceDictionarySnapshotResult>((resolve) => {
+ release = resolve;
+ });
+ const inFlight = refreshMobileVoiceDictionary(HOST, () => pending);
+
+ // 请求还在飞,用户切到了另一个账号。
+ setMobileVoiceDictionaryAccountScope('user-b');
+ release({ ok: true, entries: [{ text: '账号A的词' }] });
+ await inFlight;
+
+ // 不该出现在 user-b 的分区里。
+ expect([...storage.keys()].some((key) => key.includes('user-b'))).toBe(false);
+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);
+ });
+
+ it('过期任务的补偿删除不会删掉新账号已经提交的快照', async () => {
+ setMobileVoiceDictionaryAccountScope('user-a');
+ let release: (value: MobileVoiceDictionarySnapshotResult) => void = () => {};
+ const pending = new Promise<MobileVoiceDictionarySnapshotResult>((resolve) => {
+ release = resolve;
+ });
+ const stale = refreshMobileVoiceDictionary(HOST, () => pending);
+
+ // 切到 user-b 并且它已经为同一台电脑写好了快照。
+ setMobileVoiceDictionaryAccountScope('user-b');
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: true,
+ entries: [{ text: '账号B的词' }],
+ }));
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('账号B的词');
+
+ // user-a 的请求现在才落地,它的自我回收只能删自己那份。
+ release({ ok: true, entries: [{ text: '账号A的词' }] });
+ await stale;
+
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('账号B的词');
+ // 盘上也还在 —— 否则重启或内存失效后 user-b 的词典就空了。
+ __resetMobileVoiceDictionaryCacheForTests();
+ setMobileVoiceDictionaryAccountScope('user-b');
+ await hydrateMobileVoiceDictionary(HOST);
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('账号B的词');
+ });
+});
+
+describe('在途请求的去重范围', () => {
+ it('新账号的刷新不会等在上一个账号那个必被丢弃的请求上', async () => {
+ setMobileVoiceDictionaryAccountScope('user-a');
+ let release: (value: MobileVoiceDictionarySnapshotResult) => void = () => {};
+ const pending = new Promise<MobileVoiceDictionarySnapshotResult>((resolve) => {
+ release = resolve;
+ });
+ const stale = refreshMobileVoiceDictionary(HOST, () => pending);
+ // 让 user-a 的任务真正登记进在途表(它挂在 fetchSnapshot 上)。
+ await Promise.resolve();
+
+ setMobileVoiceDictionaryAccountScope('user-b');
+ // 这一步以前会死等 user-a 的请求 —— 而那份响应按代际检查注定被丢弃。
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: true,
+ entries: [{ text: '账号B的词' }],
+ }));
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('账号B的词');
+
+ release({ ok: true, entries: [{ text: '账号A的词' }] });
+ await stale;
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('账号B的词');
+ });
+});
+
+describe('版本向量的入站校验', () => {
+ const STAMP_A = '0000000rs4.0000.node-a';
+
+ it('非规范 HLC 的时间戳被丢掉,不会在字典序比较里永远胜出', async () => {
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: true,
+ entries: [{ text: 'Cindy' }],
+ stateVector: { 'node-a': '~~~~', 'node-b': 42, 'node-c': '' },
+ } as never));
+
+ // 整份向量都不可用 → 当作「没有向量」,退回按拉取时间比较。
+ expect(readCachedMobileVoiceDictionarySnapshot(HOST).stateVector).toBeUndefined();
+ });
+
+ it('时间戳自带的 nodeId 与键对不上时丢弃该项', async () => {
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: true,
+ entries: [{ text: 'Cindy' }],
+ stateVector: { 'node-a': STAMP_A, 'node-b': STAMP_A },
+ }));
+
+ const vector = readCachedMobileVoiceDictionarySnapshot(HOST).stateVector;
+ expect(vector && Object.keys(vector)).toEqual(['node-a']);
+ });
+
+ it('合法向量原样保留并能落盘恢复', async () => {
+ await refreshMobileVoiceDictionary(HOST, async () => ({
+ ok: true,
+ entries: [{ text: 'Cindy' }],
+ stateVector: { 'node-a': STAMP_A },
+ }));
+ __resetMobileVoiceDictionaryCacheForTests();
+ await hydrateMobileVoiceDictionary(HOST);
+ expect(readCachedMobileVoiceDictionarySnapshot(HOST).stateVector).toEqual({ 'node-a': STAMP_A });
+ });
+});
diff --git a/apps/mobile/src/__tests__/mobileVoiceDictionaryView.test.ts b/apps/mobile/src/__tests__/mobileVoiceDictionaryView.test.ts
new file mode 100644
index 0000000000..17594e752a
--- /dev/null
+++ b/apps/mobile/src/__tests__/mobileVoiceDictionaryView.test.ts
@@ -0,0 +1,247 @@
+/**
+ * 手机端词典展示模型。
+ *
+ * 手机上的词典是只读投影 —— 这里盯的是「别把不该显示的设备显示出来」和「顺序
+ * 在两次打开之间保持稳定」,后者在设备同名或频次并列时最容易出问题。
+ */
+
+import { describe, expect, it } from 'vitest';
+import type { DeviceView } from '@cindy/device-link';
+
+import {
+ buildMobileVoiceDictionaryEntryViews,
+ collectMobileVoiceDictionaryHosts,
+ isDesktopDevice,
+} from '@/session/mobileVoiceDictionaryView';
+
+function device(overrides: Partial<DeviceView>): DeviceView {
+ return {
+ deviceId: 'device-1',
+ name: 'MacBook',
+ platform: 'darwin',
+ appVersion: '1.0.0',
+ lastSeenAt: null,
+ online: true,
+ busy: false,
+ remoteControlEnabled: true,
+ isSelf: false,
+ ...overrides,
+ } as DeviceView;
+}
+
+describe('collectMobileVoiceDictionaryHosts', () => {
+ it('只保留其它设备中的电脑', () => {
+ const hosts = collectMobileVoiceDictionaryHosts([
+ device({ deviceId: 'mac', platform: 'darwin' }),
+ device({ deviceId: 'win', platform: 'win32' }),
+ device({ deviceId: 'linux', platform: 'linux' }),
+ // 手机不持有词典正本,不该出现在列表里。
+ device({ deviceId: 'iphone', platform: 'ios' }),
+ device({ deviceId: 'android', platform: 'android' }),
+ // 自己更不该出现。
+ device({ deviceId: 'self', platform: 'ios', isSelf: true }),
+ device({ deviceId: 'unknown', platform: null }),
+ ]);
+
+ expect(hosts.map((host) => host.deviceId).sort()).toEqual(['linux', 'mac', 'win']);
+ });
+
+ it('在线的排前面,其余按名称稳定排序', () => {
+ const hosts = collectMobileVoiceDictionaryHosts([
+ device({ deviceId: 'b', name: 'Studio', online: false }),
+ device({ deviceId: 'a', name: 'Air', online: false }),
+ device({ deviceId: 'c', name: 'Pro', online: true }),
+ ]);
+ expect(hosts.map((host) => host.name)).toEqual(['Pro', 'Air', 'Studio']);
+ });
+
+ it('同名设备按 deviceId 兜底,顺序不会在两次打开之间抖动', () => {
+ const input = [
+ device({ deviceId: 'zzz', name: 'MacBook' }),
+ device({ deviceId: 'aaa', name: 'MacBook' }),
+ ];
+ expect(collectMobileVoiceDictionaryHosts(input).map((host) => host.deviceId)).toEqual([
+ 'aaa',
+ 'zzz',
+ ]);
+ expect(collectMobileVoiceDictionaryHosts([...input].reverse()).map((host) => host.deviceId)).toEqual([
+ 'aaa',
+ 'zzz',
+ ]);
+ });
+
+ it('设备没有名字时回退到 deviceId 前缀,不显示空标题', () => {
+ const [host] = collectMobileVoiceDictionaryHosts([
+ device({ deviceId: 'abcdef1234567890', name: ' ' }),
+ ]);
+ expect(host.name).toBe('abcdef12');
+ });
+
+ it('平台判定只认桌面三件套', () => {
+ expect(isDesktopDevice('darwin')).toBe(true);
+ expect(isDesktopDevice('ios')).toBe(false);
+ expect(isDesktopDevice(null)).toBe(false);
+ });
+});
+
+describe('buildMobileVoiceDictionaryEntryViews', () => {
+ const snap = (
+ entries: Array<{ text: string; frequency?: number; aliases?: Array<{ text: string; count?: number }> }>,
+ fetchedAt = 1_000,
+ ) => ({ entries, fetchedAt });
+
+ it('按频次降序,并列时按文本稳定排序', () => {
+ const views = buildMobileVoiceDictionaryEntryViews([snap([
+ { text: 'Orca', frequency: 2 },
+ { text: 'Cindy', frequency: 9 },
+ { text: 'Alpha', frequency: 2 },
+ ])]);
+ expect(views.map((view) => view.text)).toEqual(['Cindy', 'Alpha', 'Orca']);
+ });
+
+ it('别名按观察次数降序并截断', () => {
+ const [view] = buildMobileVoiceDictionaryEntryViews(
+ [snap([
+ {
+ text: 'Vibe Coding',
+ frequency: 3,
+ aliases: [
+ { text: 'rare', count: 1 },
+ { text: 'common', count: 9 },
+ { text: 'mid', count: 4 },
+ ],
+ },
+ ])],
+ { maxAliases: 2 },
+ );
+ expect(view.aliases).toEqual(['common', 'mid']);
+ });
+
+ it('丢弃空文本并按归一化主键去重', () => {
+ const views = buildMobileVoiceDictionaryEntryViews([snap([
+ { text: ' ' },
+ { text: 'Cindy', frequency: 5 },
+ { text: 'cindy', frequency: 1 },
+ ])]);
+ expect(views.map((view) => view.text)).toEqual(['Cindy']);
+ });
+
+ it('没有任何成功拉取过的快照时返回空列表', () => {
+ expect(buildMobileVoiceDictionaryEntryViews([])).toEqual([]);
+ // fetchedAt=0 表示从没拉到过,不能当成"词典是空的"来用。
+ expect(buildMobileVoiceDictionaryEntryViews([{ entries: [{ text: 'X' }], fetchedAt: 0 }])).toEqual([]);
+ });
+});
+
+describe('buildMobileVoiceDictionaryEntryViews — 多台电脑取最新那份', () => {
+ it('用最新快照,不与旧快照取并集', () => {
+ const views = buildMobileVoiceDictionaryEntryViews([
+ { entries: [{ text: 'Cindy' }, { text: 'Orca' }], fetchedAt: 1_000 },
+ { entries: [{ text: 'Cindy' }], fetchedAt: 5_000 },
+ ]);
+ expect(views.map((view) => view.text)).toEqual(['Cindy']);
+ });
+
+ it('在别处删掉的词不会被离线电脑的旧缓存复活', () => {
+ // 这正是并集的致命处:用户在在线电脑上删了 Orca,离线电脑的三天前缓存还留着它,
+ // 并集会让它在手机上永远删不掉。
+ const stale = { entries: [{ text: 'Cindy', frequency: 9 }, { text: 'Orca', frequency: 4 }], fetchedAt: 1_000 };
+ const fresh = { entries: [{ text: 'Cindy', frequency: 2 }], fetchedAt: 9_000 };
+ const views = buildMobileVoiceDictionaryEntryViews([stale, fresh]);
+ expect(views.map((view) => view.text)).toEqual(['Cindy']);
+ });
+
+ it('最新快照为空时就显示空 —— 那代表词典真的被清空了', () => {
+ const views = buildMobileVoiceDictionaryEntryViews([
+ { entries: [{ text: 'Cindy' }], fetchedAt: 1_000 },
+ { entries: [], fetchedAt: 9_000 },
+ ]);
+ expect(views).toEqual([]);
+ });
+
+ it('只有一台拉到过时就用它,顺序与来源无关', () => {
+ const never = { entries: [], fetchedAt: 0 };
+ const ok = { entries: [{ text: 'Cindy' }, { text: 'Orca' }], fetchedAt: 3_000 };
+ expect(buildMobileVoiceDictionaryEntryViews([never, ok]).map((v) => v.text).sort())
+ .toEqual(['Cindy', 'Orca']);
+ expect(buildMobileVoiceDictionaryEntryViews([ok, never]).map((v) => v.text).sort())
+ .toEqual(['Cindy', 'Orca']);
+ });
+});
+
+describe('新鲜度判定', () => {
+ it('一方包含另一方时选包含者,不被响应到达顺序左右', () => {
+ // B 已经合并过 A 的事件(向量逐节点 ≥),但它的响应更慢:按到达时间会挑错。
+ const views = buildMobileVoiceDictionaryEntryViews([
+ { entries: [{ text: '旧词' }], fetchedAt: 9_000, stateVector: { a: '0000000100.0000.a' } },
+ {
+ entries: [{ text: '新词' }, { text: '旧词' }],
+ fetchedAt: 1_000,
+ stateVector: { a: '0000000100.0000.a', b: '0000000200.0000.b' },
+ },
+ ]);
+ expect(views.map((view) => view.text).sort()).toEqual(['新词', '旧词'].sort());
+ });
+
+ it('互不包含(真并发)时退回按拉取时间取较新的', () => {
+ // A 加了 foo、B 加了 bar,谁都不包含谁 —— 没有正确答案,取较新的那份。
+ const views = buildMobileVoiceDictionaryEntryViews([
+ { entries: [{ text: 'foo' }], fetchedAt: 1_000, stateVector: { a: '0000000100.0000.a' } },
+ { entries: [{ text: 'bar' }], fetchedAt: 9_000, stateVector: { b: '0000000101.0000.b' } },
+ ]);
+ expect(views.map((view) => view.text)).toEqual(['bar']);
+ });
+
+ it('最大 HLC 更大但并不包含对方时,不能因此被当成完整答案', () => {
+ // 这正是只比最大时间戳会犯的错:B 的 HLC 更大,但它没有 A 的词。
+ const views = buildMobileVoiceDictionaryEntryViews([
+ {
+ entries: [{ text: 'foo' }, { text: 'bar' }],
+ fetchedAt: 9_000,
+ stateVector: { a: '0000000100.0000.a', b: '0000000101.0000.b' },
+ },
+ { entries: [{ text: 'bar' }], fetchedAt: 1_000, stateVector: { b: '0000000101.0000.b' } },
+ ]);
+ expect(views.map((view) => view.text).sort()).toEqual(['bar', 'foo']);
+ });
+
+ it('对端不上报水位时退回按拉取时间比较', () => {
+ const views = buildMobileVoiceDictionaryEntryViews([
+ { entries: [{ text: '旧词' }], fetchedAt: 1_000 },
+ { entries: [{ text: '新词' }], fetchedAt: 9_000 },
+ ]);
+ expect(views.map((view) => view.text)).toEqual(['新词']);
+ });
+
+ it('只有一台带版本向量时认它 —— 老版本不该压过能自证更完整的快照', () => {
+ const views = buildMobileVoiceDictionaryEntryViews([
+ { entries: [{ text: '老版本' }], fetchedAt: 9_999 },
+ { entries: [{ text: '带向量' }], fetchedAt: 1_000, stateVector: { a: '0000000100.0000.a' } },
+ ]);
+ expect(views.map((view) => view.text)).toEqual(['带向量']);
+ });
+});
+
+describe('词条主键', () => {
+ it('与桌面 CRDT 主键同一套归一化 —— 只差空白的两条要合并成一行', () => {
+ const views = buildMobileVoiceDictionaryEntryViews([
+ {
+ entries: [
+ { text: 'Vibe Coding', frequency: 3 },
+ { text: 'vibe coding', frequency: 1 },
+ { text: ' Vibe Coding ', frequency: 1 },
+ ],
+ fetchedAt: 1_000,
+ },
+ ]);
+ expect(views).toHaveLength(1);
+ expect(views[0].key).toBe('vibe coding');
+ });
+
+ it('归一化之后为空的词条被丢掉,不会产生空 key', () => {
+ const views = buildMobileVoiceDictionaryEntryViews([
+ { entries: [{ text: ' ' }, { text: 'Cindy' }], fetchedAt: 1_000 },
+ ]);
+ expect(views.map((view) => view.text)).toEqual(['Cindy']);
+ });
+});
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index 216f545e61..1158fe1d68 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -70,6 +70,10 @@ import { resetComposerPaletteCache } from '@/session/composerPaletteCache';
import { clearCachedHomeListSnapshot } from '@/session/mobileHomeListCache';
import { clearCachedSessionMessages } from '@/session/mobileSessionMessageCache';
import { clearAllMobileVoiceCredentials } from '@/session/mobileVoiceCredentialStore';
+import {
+ clearAllMobileVoiceDictionaryCaches,
+ setMobileVoiceDictionaryAccountScope,
+} from '@/session/mobileVoiceDictionaryCache';
import { clearAllMobileVoiceInputHistories } from '@/session/mobileVoiceHistoryStore';
import { visualMockApiFetch, visualMockUser } from '@/debug/visualMock';
import {
@@ -670,6 +674,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
else void clearTapdbUser();
}, [initialized, user?.id]);
+ // 词典缓存的落盘键按账号分区。登出清理是尽力而为的(索引可能读不出来),分区让
+ // 「没删干净」不再等于「下个账号能读到上个账号的词条并发给润色模型」。
+ useEffect(() => {
+ setMobileVoiceDictionaryAccountScope(user?.id ?? '');
+ }, [user?.id]);
+
const completeOAuthCallback = useCallback(
(callbackUrl: string): Promise<void> => {
if (browserCompletionRef.current) return browserCompletionRef.current;
@@ -997,6 +1007,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// 覆盖历史穿透凭据、服务模式与 BYOK key 三类存量存储键(功能已删除)。
await clearAllMobileVoiceCredentials().catch(() => undefined);
await clearAllMobileVoiceInputHistories().catch(() => undefined);
+ // 词典缓存按 host 设备分区、不含账号身份:同一台电脑在两个账号下是同一个
+ // deviceId,不清就会让下一个账号读到上一个账号的词条并发给润色模型。
+ await clearAllMobileVoiceDictionaryCaches().catch(() => undefined);
await clearCachedSessionMessages().catch(() => undefined);
// 首页设备+会话快照与消息缓存一样属于账号数据,登出必须清掉。
await clearCachedHomeListSnapshot().catch(() => undefined);
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 041990bff4..26a92b5a5e 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -11,6 +11,7 @@ import type {
} from '@/session/sessionReferences';
import {
DEVICE_LINK_MEDIA_FETCH_CHANNEL,
+ DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL,
DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL,
DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL,
MOBILE_REMOTE_INVOKE_CHANNELS,
@@ -23,6 +24,7 @@ import type {
MobileSessionAgentSwitchIntent,
MobileSessionAgentSwitchResult,
MobileVoiceDictionaryLearningRequest,
+ MobileVoiceDictionarySnapshotResult,
MobileVoiceDictionaryLearningResult,
} from '@cindy/maker-shared/device-link-contract';
import type { ProviderView } from '@cindy/model-providers/registry';
@@ -394,6 +396,11 @@ export interface MobileMakerTransport {
fetchRemoteMedia(url: string, opts?: { skipCache?: boolean; thumbnail?: boolean }): Promise<MobileRemoteMediaFetchResult>;
transcribeVoice(input: MobileVoiceTranscribeRequest): Promise<MobileVoiceTranscribeResult>;
recordVoiceDictionaryLearning(input: MobileVoiceDictionaryLearningRequest): Promise<MobileVoiceDictionaryLearningResult>;
+ /**
+ * 拉取被控桌面的语音词典只读快照。老被控端不识别该 channel 会回
+ * CHANNEL_NOT_ALLOWED,调用方据此静默回退到「无词典」,不打断语音输入。
+ */
+ getVoiceDictionary(): Promise<MobileVoiceDictionarySnapshotResult>;
getPendingInteractions(sessionId: string): Promise<PendingInteraction[]>;
resolveInteraction(requestId: string, decision: Record<string, unknown>): Promise<void>;
getContextUsage(sessionId: string, createOpts?: Record<string, unknown>): Promise<unknown>;
@@ -581,6 +588,7 @@ export function createMobileMakerTransport({
),
transcribeVoice: (input) => call(DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL, [input]),
recordVoiceDictionaryLearning: (input) => call(DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL, [input]),
+ getVoiceDictionary: () => call(DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL, []),
getPendingInteractions: (sessionId) => call('maker:get-pending-interactions', [sessionId]),
resolveInteraction: (requestId, decision) =>
call('maker:resolve-interaction', [requestId, decision]),
diff --git a/apps/mobile/src/i18n/locales/en/settings.json b/apps/mobile/src/i18n/locales/en/settings.json
index 232abf115f..3f4a4cdcec 100644
--- a/apps/mobile/src/i18n/locales/en/settings.json
+++ b/apps/mobile/src/i18n/locales/en/settings.json
@@ -111,6 +111,22 @@
"done": "Copied",
"accessibility": "Copy {{label}}"
},
+ "voiceDictionary": {
+ "sectionTitle": "Voice dictionary",
+ "label": "View dictionary",
+ "hint": "Your dictionary lives on your computers and syncs between them automatically. This is a read-only view — add or remove terms on a computer.",
+ "openAccessibility": "View voice dictionary",
+ "screenTitle": "Voice dictionary",
+ "entryCount": "{{count}} terms",
+ "aliasSeparator": ", ",
+ "aliases": "Often misheard as: {{aliases}}",
+ "refresh": "Refresh",
+ "refreshing": "Refreshing…",
+ "refreshAccessibility": "Refresh dictionary",
+ "readOnlyHint": "Read-only here — add or remove terms on a computer.",
+ "offlineHint": "None of your computers are online. Showing what was last synced to your phone.",
+ "noDesktops": "No computers yet. Sign in on a computer with the same account and your dictionary will show up here."
+ },
"deviceNameEditor": {
"screenTitle": "Device Name",
"placeholder": "Phone name",
diff --git a/apps/mobile/src/i18n/locales/ja/settings.json b/apps/mobile/src/i18n/locales/ja/settings.json
index 356fb101f5..9399cebfbc 100644
--- a/apps/mobile/src/i18n/locales/ja/settings.json
+++ b/apps/mobile/src/i18n/locales/ja/settings.json
@@ -111,6 +111,22 @@
"done": "コピー済み",
"accessibility": "{{label}}をコピー"
},
+ "voiceDictionary": {
+ "sectionTitle": "音声辞書",
+ "label": "辞書を見る",
+ "hint": "辞書はパソコンに保存され、お使いのパソコン間で自動的に同期されます。スマホでは閲覧のみで、追加や削除はパソコンで行ってください。",
+ "openAccessibility": "音声辞書を見る",
+ "screenTitle": "音声辞書",
+ "entryCount": "{{count}} 語",
+ "aliasSeparator": "、",
+ "aliases": "よくある誤認識:{{aliases}}",
+ "refresh": "更新",
+ "refreshing": "更新中…",
+ "refreshAccessibility": "辞書を更新",
+ "readOnlyHint": "スマホでは閲覧のみです。追加や削除はパソコンで行ってください。",
+ "offlineHint": "現在オンラインのパソコンがありません。前回スマホに同期された内容を表示しています。",
+ "noDesktops": "同期できるパソコンがまだありません。同じアカウントでパソコンにログインすると、辞書がここに表示されます。"
+ },
"deviceNameEditor": {
"screenTitle": "デバイス名",
"placeholder": "この端末の名前",
diff --git a/apps/mobile/src/i18n/locales/ko/settings.json b/apps/mobile/src/i18n/locales/ko/settings.json
index 16b5e331a2..18041ad51a 100644
--- a/apps/mobile/src/i18n/locales/ko/settings.json
+++ b/apps/mobile/src/i18n/locales/ko/settings.json
@@ -111,6 +111,22 @@
"done": "복사됨",
"accessibility": "{{label}} 복사"
},
+ "voiceDictionary": {
+ "sectionTitle": "음성 사전",
+ "label": "사전 보기",
+ "hint": "사전은 컴퓨터에 저장되며 내 컴퓨터끼리 자동으로 동기화됩니다. 휴대폰에서는 보기만 가능하고, 추가와 삭제는 컴퓨터에서 해주세요.",
+ "openAccessibility": "음성 사전 보기",
+ "screenTitle": "음성 사전",
+ "entryCount": "{{count}}개 단어",
+ "aliasSeparator": ", ",
+ "aliases": "자주 잘못 인식됨: {{aliases}}",
+ "refresh": "새로고침",
+ "refreshing": "새로고치는 중…",
+ "refreshAccessibility": "사전 새로고침",
+ "readOnlyHint": "휴대폰에서는 보기만 가능합니다. 추가와 삭제는 컴퓨터에서 해주세요.",
+ "offlineHint": "온라인 상태인 컴퓨터가 없습니다. 마지막으로 휴대폰에 동기화된 내용을 표시합니다.",
+ "noDesktops": "아직 동기화할 컴퓨터가 없습니다. 같은 계정으로 컴퓨터에 로그인하면 사전이 여기에 표시됩니다."
+ },
"deviceNameEditor": {
"screenTitle": "기기 이름",
"placeholder": "이 기기 이름",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/settings.json b/apps/mobile/src/i18n/locales/zh-CN/settings.json
index 7e61d4c2bc..7fff688aab 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/settings.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/settings.json
@@ -111,6 +111,22 @@
"done": "已复制",
"accessibility": "复制{{label}}"
},
+ "voiceDictionary": {
+ "sectionTitle": "语音词典",
+ "label": "查看词典",
+ "hint": "词典保存在电脑上,并在你的电脑之间自动同步;手机只能查看,添加和删除请回电脑操作。",
+ "openAccessibility": "查看语音词典",
+ "screenTitle": "语音词典",
+ "entryCount": "{{count}} 个词条",
+ "aliasSeparator": "、",
+ "aliases": "常被听成:{{aliases}}",
+ "refresh": "刷新",
+ "refreshing": "刷新中…",
+ "refreshAccessibility": "刷新词典",
+ "readOnlyHint": "手机只能查看,添加和删除请回电脑操作。",
+ "offlineHint": "电脑当前都不在线,显示的是上次同步到手机的内容。",
+ "noDesktops": "还没有可同步的电脑。在电脑上登录同一账号后,词典会自动出现在这里。"
+ },
"deviceNameEditor": {
"screenTitle": "设备名称",
"placeholder": "本机名称",
diff --git a/apps/mobile/src/session/mobileVoiceController.ts b/apps/mobile/src/session/mobileVoiceController.ts
index 05cfd3eaa2..2e2ecb4ee8 100644
--- a/apps/mobile/src/session/mobileVoiceController.ts
+++ b/apps/mobile/src/session/mobileVoiceController.ts
@@ -27,6 +27,7 @@ import {
type MobileVoiceDraftInsertion,
} from '@/session/mobileVoiceInput';
import { startMobileRealtimeAudio } from '@/session/mobileRealtimeAudio';
+import { readCachedMobileVoiceDictionary } from '@/session/mobileVoiceDictionaryCache';
type StartRealtimeAudio = (options: {
sampleRate: number;
@@ -670,6 +671,9 @@ function createMobileRefiner(
contextProvider: () => buildMobileVoiceRefinementContext(credential, {
refinementContext: options.refinementContext,
localVoiceInputHistory: options.localVoiceInputHistory,
+ // 词典来自被控桌面的只读快照缓存(拉取在开麦时异步触发)。桌面离线或还没
+ // 拉到时是空数组 —— 润色照常进行,只是少了术语提示。
+ dictionaryEntries: readCachedMobileVoiceDictionary(credential.hostDeviceId),
}),
});
}
diff --git a/apps/mobile/src/session/mobileVoiceDictionaryCache.ts b/apps/mobile/src/session/mobileVoiceDictionaryCache.ts
new file mode 100644
index 0000000000..6920f135e7
--- /dev/null
+++ b/apps/mobile/src/session/mobileVoiceDictionaryCache.ts
@@ -0,0 +1,370 @@
+/**
+ * 手机端的语音词典缓存。
+ *
+ * 词典的正本在桌面(桌面之间用 CRDT 对等同步),手机只拉一份只读快照:移动端在
+ * 后台不维持 WebSocket,收不到对等同步的 push 帧,持有可写副本只会分叉。
+ *
+ * 按 host 设备分别缓存并落盘,原因是「桌面此刻不在线」也要能用:润色需要的词典
+ * 来自上次成功拉取的结果,而不是每次都必须现拉。拉取失败(桌面离线、老版本被控端
+ * 回 CHANNEL_NOT_ALLOWED)一律静默降级到缓存,绝不打断语音输入。
+ *
+ * 落盘走 AsyncStorage 而不是 SecureStore:一份词典快照可能上百 KB,而 SecureStore
+ * 背后是平台钥匙串,大值会被拒绝(且这里刻意吞掉写入错误),结果是缓存只在内存里
+ * 有效、进程一死就没了,说好的离线兜底名存实亡。词典是用户内容不是密钥材料,
+ * SecureStore 留给真正的凭证。
+ */
+
+import AsyncStorage from '@react-native-async-storage/async-storage';
+import { hlcNodeId, isCanonicalHlc } from '@cindy/voice-input-core';
+import { listMobileVoiceHistoryHosts } from '@/session/mobileVoiceHistoryStore';
+import type {
+ MobileVoiceCredentialSyncDictionaryEntry,
+ MobileVoiceDictionarySnapshotResult,
+} from '@cindy/maker-shared/device-link-contract';
+
+// v2 起键里带账号:登出清理是尽力而为的(AsyncStorage 不能按前缀枚举,索引也可能
+// 读不出来),只靠清理保证账号隔离等于把用户词条的去向押在一次可能失败的删除上。
+// 键带账号之后,即使某份快照没删掉,下一个账号也读不到它。
+const STORAGE_KEY_PREFIX = 'xdt.mobileVoiceDictionary.v2';
+const LEGACY_STORAGE_KEY_PREFIX = 'xdt.mobileVoiceDictionary.v1';
+const STORAGE_INDEX_KEY = `${STORAGE_KEY_PREFIX}.hosts`;
+const LEGACY_STORAGE_INDEX_KEY = `${LEGACY_STORAGE_KEY_PREFIX}.hosts`;
+
+/**
+ * 当前账号标识。登录/登出时由 AuthContext 设置。
+ *
+ * 空串是合法状态(未登录):此时读写都退回到一个独立分区,不会和任何账号的数据
+ * 互相看见。
+ */
+let accountScope = '';
+
+/**
+ * 本会话见过的所有账号分区。
+ *
+ * 登出时 `applyUser(null)` 会先把分区切回匿名,清理才异步跑起来 —— 清理入口读到的
+ * 已经是匿名分区,只删匿名那份的话,正在登出的那个账号的快照会原封不动留在盘上。
+ * 记下见过的分区,清理时逐个删。
+ */
+const knownScopes = new Set<string>(['']);
+
+/** 设置账号分区。切换账号时同时递增代际,丢弃在途请求。 */
+export function setMobileVoiceDictionaryAccountScope(accountId: string): void {
+ const next = typeof accountId === 'string' ? accountId.trim() : '';
+ knownScopes.add(next);
+ if (next === accountScope) return;
+ accountScope = next;
+ cacheEpoch += 1;
+ memoryCache.clear();
+ inFlight.clear();
+}
+/** 与桌面词典上限一致;手机侧只是防御性截断,避免异常大的回包撑爆存储。 */
+const MAX_ENTRIES = 1_000;
+const MAX_ALIASES_PER_ENTRY = 8;
+/** 同一 host 的最小重拉间隔:词典变化慢,没必要每次开麦都打一次 invoke。 */
+const REFETCH_INTERVAL_MS = 5 * 60 * 1000;
+
+type CachedDictionary = {
+ entries: MobileVoiceCredentialSyncDictionaryEntry[];
+ fetchedAt: number;
+ /** 被控端上报的版本向量;老版本不带,此时只能退回按 fetchedAt 比较。 */
+ stateVector?: Record<string, string>;
+};
+
+const memoryCache = new Map<string, CachedDictionary>();
+/**
+ * 在途请求。键带账号分区 —— 只按 host 去重的话,账号切走之后新账号的刷新会拿到
+ * 上一个账号那个还挂着的请求并一直等它,而那个请求的结果按代际检查又必然被丢弃:
+ * 新账号什么也拿不到,调用方却以为刷新过了。
+ */
+const inFlight = new Map<string, Promise<void>>();
+/**
+ * 缓存代际。账号边界清理时递增,在途请求据此判断自己是否已经过期。
+ *
+ * 只把 inFlight 清空是不够的:那只是丢掉了 Promise 的引用,请求本身还在飞,回来
+ * 时照样会写进内存缓存 —— 于是上个账号的词典在登出之后又被复活。
+ */
+let cacheEpoch = 0;
+
+export function readCachedMobileVoiceDictionary(
+ hostDeviceId: string,
+): MobileVoiceCredentialSyncDictionaryEntry[] {
+ return memoryCache.get(normalizeHostDeviceId(hostDeviceId))?.entries ?? [];
+}
+
+/** 上次成功拉取的时间(unix ms);从未拉到过返回 null。设置页据此区分「没有词典」与「还没拉过」。 */
+export function readMobileVoiceDictionaryFetchedAt(hostDeviceId: string): number | null {
+ const cached = memoryCache.get(normalizeHostDeviceId(hostDeviceId));
+ return cached && cached.fetchedAt > 0 ? cached.fetchedAt : null;
+}
+
+/**
+ * 读一台电脑的缓存快照(含拉取时间)。
+ *
+ * 展示层要靠 fetchedAt 挑出最新那份 —— 离线电脑的旧缓存不能和新鲜数据混在一起,
+ * 否则已经删掉的词会被旧快照带回来。
+ */
+export function readCachedMobileVoiceDictionarySnapshot(hostDeviceId: string): {
+ entries: MobileVoiceCredentialSyncDictionaryEntry[];
+ fetchedAt: number;
+ stateVector?: Record<string, string>;
+} {
+ const cached = memoryCache.get(normalizeHostDeviceId(hostDeviceId));
+ return {
+ entries: cached?.entries ?? [],
+ fetchedAt: cached?.fetchedAt ?? 0,
+ stateVector: cached?.stateVector,
+ };
+}
+
+/** 从盘上恢复缓存(App 启动或首次用到该 host 时调用一次)。 */
+export async function hydrateMobileVoiceDictionary(hostDeviceId: string): Promise<void> {
+ const host = normalizeHostDeviceId(hostDeviceId);
+ if (memoryCache.has(host)) return;
+ // 磁盘读同样要受代际保护:登出可能恰好发生在 getItem 在途时,读回来再写内存
+ // 就把上个账号的词典复活了。
+ const epoch = cacheEpoch;
+ const scope = accountScope;
+ try {
+ const raw = await AsyncStorage.getItem(storageKeyForHost(host, scope));
+ if (!raw) return;
+ if (epoch !== cacheEpoch) return;
+ const parsed = JSON.parse(raw) as Partial<CachedDictionary>;
+ const restored = {
+ entries: normalizeEntries(parsed?.entries),
+ fetchedAt: typeof parsed?.fetchedAt === 'number' ? parsed.fetchedAt : 0,
+ stateVector: normalizeStateVector(parsed?.stateVector),
+ };
+ // 开麦路径会并发跑 hydrate 与 refresh。磁盘读晚于网络响应返回时,不能用旧
+ // 快照盖掉刚拉到的新数据 —— 只在内存仍为空、或盘上确实更新时才写。
+ const current = memoryCache.get(host);
+ if (current && current.fetchedAt >= restored.fetchedAt) return;
+ memoryCache.set(host, restored);
+ } catch {
+ // 缓存读坏了就当没有:下一次拉取会重建。
+ }
+}
+
+/**
+ * 需要时刷新缓存。
+ *
+ * fire-and-forget 语义:调用方不必 await,拿当前缓存直接用就行 —— 这次拉到的
+ * 内容供下一次润色使用,不会为了词典把开麦流程卡住。
+ */
+export async function refreshMobileVoiceDictionary(
+ hostDeviceId: string,
+ fetchSnapshot: () => Promise<MobileVoiceDictionarySnapshotResult>,
+ options?: { force?: boolean },
+): Promise<void> {
+ const host = normalizeHostDeviceId(hostDeviceId);
+ if (!host) return;
+ // epoch 与分区都必须在第一个 await 之前取。
+ //
+ // epoch 取晚了会读到清理后的新值,于是这份属于上个账号的响应被判成"仍然有效"。
+ // 分区取晚了更糟:下面每一次算 key 都发生在若干个挂起点之后,拿到的是**当前**
+ // 分区 —— 账号在这期间切走的话,旧账号的响应会写进新账号的分区,而末尾那次
+ // 补偿删除又会把新账号刚写的快照删掉。两者都只能在入口锁定。
+ const epoch = cacheEpoch;
+ const scope = accountScope;
+ await hydrateMobileVoiceDictionary(host);
+
+ const cached = memoryCache.get(host);
+ if (!options?.force && cached && Date.now() - cached.fetchedAt < REFETCH_INTERVAL_MS) return;
+
+ const inFlightKey = `${scope}\u0000${host}`;
+ const existing = inFlight.get(inFlightKey);
+ if (existing) return existing;
+
+ const task = (async () => {
+ try {
+ const result = await fetchSnapshot();
+ if (!result?.ok) return;
+ // 请求期间发生过账号边界清理:这份数据属于上一个账号,丢弃。
+ if (epoch !== cacheEpoch) return;
+ const next: CachedDictionary = {
+ entries: normalizeEntries(result.entries),
+ fetchedAt: Date.now(),
+ stateVector: normalizeStateVector(result.stateVector),
+ };
+ memoryCache.set(host, next);
+ // 顺序很关键:**先登记索引,再写快照**。两个写不是原子的,进程随时可能死在
+ // 中间 —— 索引里多一条(快照还没写)只是清理时删一个不存在的 key,无害;
+ // 反过来快照落了盘而索引没登记,登出就枚举不到它,下个账号用同一台电脑会
+ // hydrate 到上个账号的词典。宁可多登记,不可漏登记。
+ // 索引登记失败就不要写快照:写了也是枚举不到的孤儿,登出删不掉,下个账号
+ // 用同一台电脑会 hydrate 到上个账号的词典。缓存只在内存里有效即可。
+ try {
+ await addHostToIndex(host);
+ } catch {
+ return;
+ }
+ await AsyncStorage.setItem(storageKeyForHost(host, scope), JSON.stringify(next)).catch(
+ () => undefined,
+ );
+ // 落盘与索引写入都是异步的,清理完全可能发生在这中间 —— 那样这份属于上个
+ // 账号的快照会在删除之后重新出现在盘上。写完再确认一次代际,过期就自己清掉。
+ if (epoch !== cacheEpoch) {
+ memoryCache.delete(host);
+ // 只删自己刚写的那一份(按入口锁定的分区),不碰新账号已经提交的快照。
+ await AsyncStorage.removeItem(storageKeyForHost(host, scope)).catch(() => undefined);
+ }
+ } catch {
+ // 桌面离线、老被控端不识别该 channel、隧道抖动 —— 一律沿用现有缓存。
+ } finally {
+ inFlight.delete(inFlightKey);
+ }
+ })();
+ inFlight.set(inFlightKey, task);
+ return task;
+}
+
+/**
+ * 账号边界清理:退出登录 / 切换账号时抹掉所有词典缓存。
+ *
+ * 缓存键只按 host 设备分区,不含账号身份 —— 同一台电脑在账号 A 和账号 B 下是同
+ * 一个 deviceId。不清理的话,账号 B 会读到账号 A 留下的词条,并经润色上下文发给
+ * 模型,属于跨账号的数据泄漏。与语音凭证、语音历史挂在同一条登出链路上
+ * (`AuthContext` 调用 `clearAllMobileVoiceCredentials` 的地方)。
+ *
+ * 内存与在途请求一并清掉:登出瞬间可能有 refresh 正在返回,只清盘会被它写回来。
+ */
+export async function clearAllMobileVoiceDictionaryCaches(): Promise<void> {
+ cacheEpoch += 1;
+ memoryCache.clear();
+ inFlight.clear();
+ // SecureStore 不能枚举键,只能从可推导的 host 集合尽力清理:本模块自己的索引,
+ // 并集语音历史的 host 索引(用过语音输入的 host 必定拉取过词典)。
+ const [ownHosts, historyHosts] = await Promise.all([
+ readHostIndex(),
+ listMobileVoiceHistoryHosts().catch(() => [] as string[]),
+ ]);
+ const hosts = [...new Set([...(ownHosts.hosts ?? []), ...historyHosts])];
+ // 逐个已知分区删:清理往往在分区已经被切回匿名之后才跑到这里,只删当前分区会把
+ // 正在登出的那个账号的快照留在盘上。
+ const scopes = [...knownScopes];
+ await Promise.all(
+ hosts.flatMap((host) => [
+ ...scopes.map((scope) =>
+ AsyncStorage.removeItem(storageKeyForHost(host, scope)).catch(() => undefined),
+ ),
+ // v1 的键不带账号,是真正会被下个账号读到的那一份 —— 一并尽力删掉。
+ AsyncStorage.removeItem(legacyStorageKeyForHost(host)).catch(() => undefined),
+ ]),
+ );
+ // 索引读失败时**不能**删索引:那等于把「还有哪些快照没删」的唯一线索也丢掉,
+ // 剩下的快照就永远清不掉了。留着,下次登出或下次写入时还有机会补删。
+ if (ownHosts.readable) {
+ await AsyncStorage.removeItem(STORAGE_INDEX_KEY).catch(() => undefined);
+ await AsyncStorage.removeItem(LEGACY_STORAGE_INDEX_KEY).catch(() => undefined);
+ }
+}
+
+/**
+ * 读 host 索引。
+ *
+ * `readable` 区分「索引确实是空的」和「读不出来/坏了」—— 后者当成空列表处理会让
+ * 清理误以为无事可做,还顺手把索引删掉,剩下的快照就此失去唯一的枚举线索。
+ */
+async function readHostIndex(): Promise<{ hosts: string[]; readable: boolean }> {
+ try {
+ const raw = await AsyncStorage.getItem(STORAGE_INDEX_KEY);
+ if (!raw) return { hosts: [], readable: true };
+ const parsed = JSON.parse(raw) as unknown;
+ if (!Array.isArray(parsed)) return { hosts: [], readable: false };
+ return {
+ hosts: parsed.filter((item): item is string => typeof item === 'string'),
+ readable: true,
+ };
+ } catch {
+ return { hosts: [], readable: false };
+ }
+}
+
+/**
+ * 索引写入串行队列。
+ *
+ * 设置页会并发刷新多台在线电脑,每个 `addHostToIndex` 都是 read-modify-write:
+ * 并发时后写的会覆盖先写的,某些 host 的缓存键就不在索引里了。而索引是登出清理
+ * 唯一的枚举来源 —— 漏掉的那份快照删不掉,下一个账号用同一台电脑就会 hydrate 到
+ * 上个账号的词典并发给润色模型。
+ */
+let hostIndexQueue: Promise<void> = Promise.resolve();
+
+function addHostToIndex(hostDeviceId: string): Promise<void> {
+ hostIndexQueue = hostIndexQueue
+ .catch(() => undefined)
+ .then(async () => {
+ const index = await readHostIndex();
+ if (index.hosts.includes(hostDeviceId)) return;
+ await AsyncStorage.setItem(STORAGE_INDEX_KEY, JSON.stringify([...index.hosts, hostDeviceId]));
+ });
+ return hostIndexQueue;
+}
+
+export function __resetMobileVoiceDictionaryCacheForTests(): void {
+ cacheEpoch += 1;
+ memoryCache.clear();
+ inFlight.clear();
+}
+
+function normalizeEntries(raw: unknown): MobileVoiceCredentialSyncDictionaryEntry[] {
+ if (!Array.isArray(raw)) return [];
+ const entries: MobileVoiceCredentialSyncDictionaryEntry[] = [];
+ for (const item of raw) {
+ if (!item || typeof item !== 'object') continue;
+ const candidate = item as Partial<MobileVoiceCredentialSyncDictionaryEntry>;
+ const text = typeof candidate.text === 'string' ? candidate.text.trim() : '';
+ if (!text) continue;
+ entries.push({
+ text,
+ frequency: readPositiveInt(candidate.frequency),
+ aliases: Array.isArray(candidate.aliases)
+ ? candidate.aliases
+ .map((alias) => {
+ const aliasText = typeof alias?.text === 'string' ? alias.text.trim() : '';
+ return aliasText ? { text: aliasText, count: readPositiveInt(alias?.count) } : null;
+ })
+ .filter((alias): alias is { text: string; count: number } => alias !== null)
+ .slice(0, MAX_ALIASES_PER_ENTRY)
+ : [],
+ });
+ if (entries.length >= MAX_ENTRIES) break;
+ }
+ return entries;
+}
+
+function readPositiveInt(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 1;
+}
+
+/**
+ * 归一化被控端上报的版本向量;形状不对一律当作「没有」,退回按拉取时间比较。
+ *
+ * 新鲜度判断靠的是字符串字典序,而那只在时间戳是规范 HLC(定长前缀)时才等于时间序。
+ * 混进一个 `~~~~`(`~` 的码位高于所有 base36 字符)就会在每一次比较里永远胜出,
+ * 手机从此长期停在错误的快照上,表现成「怎么刷新都不更新」。所以逐项按规范形状过滤,
+ * 并要求时间戳自带的 nodeId 与它的键一致 —— 对不上说明这份向量本身就不自洽。
+ */
+function normalizeStateVector(raw: unknown): Record<string, string> | undefined {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
+ // nodeId 来自远端。用普通 {} 的话,一个叫 __proto__ 的键会走原型 setter,
+ // 后面的包含性比较读到的就不是写进去的东西。
+ const vector = Object.create(null) as Record<string, string>;
+ for (const [nodeId, stamp] of Object.entries(raw as Record<string, unknown>)) {
+ if (!nodeId || typeof stamp !== 'string' || !isCanonicalHlc(stamp)) continue;
+ if (hlcNodeId(stamp) !== nodeId) continue;
+ vector[nodeId] = stamp;
+ }
+ return Object.keys(vector).length > 0 ? vector : undefined;
+}
+
+function storageKeyForHost(hostDeviceId: string, scope: string = accountScope): string {
+ return `${STORAGE_KEY_PREFIX}.${scope || 'anonymous'}.${hostDeviceId}`;
+}
+
+function legacyStorageKeyForHost(hostDeviceId: string): string {
+ return `${LEGACY_STORAGE_KEY_PREFIX}.${hostDeviceId}`;
+}
+
+function normalizeHostDeviceId(hostDeviceId: string): string {
+ return typeof hostDeviceId === 'string' ? hostDeviceId.trim() : '';
+}
diff --git a/apps/mobile/src/session/mobileVoiceDictionaryView.ts b/apps/mobile/src/session/mobileVoiceDictionaryView.ts
new file mode 100644
index 0000000000..38a2ba59af
--- /dev/null
+++ b/apps/mobile/src/session/mobileVoiceDictionaryView.ts
@@ -0,0 +1,190 @@
+/**
+ * 手机端语音词典展示模型(纯函数,不碰 UI 与网络)。
+ *
+ * 手机上的词典是**只读投影**:正本在电脑上,电脑之间用 CRDT 对等同步,手机拉一份
+ * 快照用于润色。这里只负责「拿哪些电脑的词典」和「怎么排列词条」,让设置页那一层
+ * 只剩渲染。
+ */
+
+import type { DeviceView, PresenceSnapshot } from '@cindy/device-link';
+import { dictionaryTermKey } from '@cindy/voice-input-core';
+import type { MobileVoiceCredentialSyncDictionaryEntry } from '@cindy/maker-shared/device-link-contract';
+
+/** 桌面平台白名单:词典只存在于电脑上,手机之间不互相同步。 */
+const DESKTOP_PLATFORMS = new Set(['darwin', 'win32', 'linux']);
+
+export interface MobileVoiceDictionaryHost {
+ deviceId: string;
+ name: string;
+ online: boolean;
+}
+
+/**
+ * 从设备清单里筛出可能持有词典的电脑。
+ *
+ * 排除自己(手机没有词典正本)与非桌面平台;在线的排前面,便于用户先看到当前
+ * 能拉到最新内容的那台。同名设备按 deviceId 兜底排序,保证顺序稳定。
+ */
+export function collectMobileVoiceDictionaryHosts(
+ devices: readonly DeviceView[],
+): MobileVoiceDictionaryHost[] {
+ const mapped = devices
+ .filter((device) => !device.isSelf && isDesktopDevice(device.platform))
+ .map((device) => ({
+ deviceId: device.deviceId,
+ name: device.name?.trim() || device.deviceId.slice(0, 8),
+ online: Boolean(device.online),
+ }))
+ ;
+ return sortHosts(mapped);
+}
+
+/** 在线优先,其次按名称,最后用 deviceId 兜底 —— 顺序必须在多次渲染间稳定。 */
+function sortHosts(hosts: MobileVoiceDictionaryHost[]): MobileVoiceDictionaryHost[] {
+ return [...hosts].sort((a, b) => {
+ if (a.online !== b.online) return a.online ? -1 : 1;
+ return a.name.localeCompare(b.name) || (a.deviceId < b.deviceId ? -1 : 1);
+ });
+}
+
+/**
+ * 用一条 presence 事件修正电脑清单。
+ *
+ * 设备清单来自打开页面那一刻的 REST 快照;presence 是之后的增量真相。没见过的
+ * 电脑要补进来(上线后才注册的),已知设备只更新在线状态与名字。返回原数组表示
+ * 没有变化,避免无谓重渲染。
+ */
+export function patchMobileVoiceDictionaryHosts(
+ hosts: readonly MobileVoiceDictionaryHost[],
+ snapshot: PresenceSnapshot,
+): readonly MobileVoiceDictionaryHost[] {
+ // 无变化时返回原引用:presence 事件很密集(手机、其它电脑的上下线都会来),
+ // 每次都造新数组会让设置页无谓重渲染。
+ if (!snapshot?.deviceId || !isDesktopDevice(snapshot.platform)) return hosts;
+ const name = snapshot.deviceName?.trim() || snapshot.deviceId.slice(0, 8);
+ const index = hosts.findIndex((host) => host.deviceId === snapshot.deviceId);
+ if (index < 0) {
+ return sortHosts([...hosts, { deviceId: snapshot.deviceId, name, online: Boolean(snapshot.online) }]);
+ }
+ const previous = hosts[index];
+ if (previous.online === Boolean(snapshot.online) && previous.name === name) return hosts;
+ const next = [...hosts];
+ next[index] = { ...previous, name, online: Boolean(snapshot.online) };
+ return sortHosts(next);
+}
+
+export function isDesktopDevice(platform: string | null | undefined): boolean {
+ return typeof platform === 'string' && DESKTOP_PLATFORMS.has(platform);
+}
+
+export interface MobileVoiceDictionaryEntryView {
+ /** React key:归一化文本在一份词典里唯一。 */
+ key: string;
+ text: string;
+ /** 别名(误识别写法),已按观察次数降序;没有则为空数组。 */
+ aliases: string[];
+}
+
+/** 一台电脑的词典快照 + 它的拉取时间。 */
+export interface MobileVoiceDictionarySnapshot {
+ entries: readonly MobileVoiceCredentialSyncDictionaryEntry[];
+ /** 成功拉取的时间(unix ms);从未拉到过为 0。 */
+ fetchedAt: number;
+ /** 被控端上报的版本向量 `{nodeId: 最大 HLC}`;老版本被控端没有。 */
+ stateVector?: Record<string, string>;
+}
+
+/**
+ * 从各台电脑的缓存里挑出用户该看到的**那一份**词典。
+ *
+ * ## 为什么是「取最新」而不是「取并集」
+ *
+ * 所有电脑收敛到同一份词典,所以任意一份新鲜快照就是完整答案。而并集是错的:
+ * 一台电脑离线、缓存停在三天前,另一台在线且刚同步过——如果这期间删掉或改名了
+ * 某个词,并集会把那个旧词永久加回列表(频次取 max 更让旧值直接赢)。用户在电脑
+ * 上删了词,手机上却怎么刷新都还在。
+ *
+ * 取最新那份则天然表达了删除:新快照里没有,就是没有。
+ *
+ * 新鲜度按被控端上报的**版本向量**判断:一份状态的向量逐节点 ≥ 另一份,才说明它
+ * 已经见过对方的全部事件、可以放心替代对方。用响应到达时间是错的(并发请求里慢的
+ * 那个反而显得"更新"),只比最大 HLC 也是错的 —— 两台电脑各自加了不同的词、还没
+ * 互相同步时谁都不包含谁,按最大值挑会漏掉另一份里的词。
+ *
+ * 真正并发(互不包含)时没有"正确答案":两份都不完整。此时退回按拉取时间取较新的
+ * 那份,并依赖桌面之间 8 秒内的自动交换收敛 —— 下次刷新就能拿到合并后的完整状态。
+ */
+/**
+ * 两份快照谁更适合作为"那一份"。
+ *
+ * 带版本向量的一律优先于不带的(老版本被控端不上报,不该压过一个能证明自己更完整
+ * 的快照)。两份都带时:一方包含另一方就选包含者;互不包含(真并发)时没有正确答案,
+ * 退回按拉取时间取较新的。
+ */
+function isFresherThan(
+ candidate: MobileVoiceDictionarySnapshot,
+ best: MobileVoiceDictionarySnapshot,
+): boolean {
+ if (candidate.stateVector && best.stateVector) {
+ const candidateDominates = dominates(candidate.stateVector, best.stateVector);
+ const bestDominates = dominates(best.stateVector, candidate.stateVector);
+ if (candidateDominates !== bestDominates) return candidateDominates;
+ return candidate.fetchedAt > best.fetchedAt;
+ }
+ if (candidate.stateVector) return true;
+ if (best.stateVector) return false;
+ return candidate.fetchedAt > best.fetchedAt;
+}
+
+/** `a` 是否已经见过 `b` 的全部事件(逐节点 ≥)。HLC 定长前缀,字符串比较即时间序。 */
+function dominates(a: Record<string, string>, b: Record<string, string>): boolean {
+ for (const [nodeId, stamp] of Object.entries(b)) {
+ const mine = a[nodeId];
+ if (mine === undefined || mine < stamp) return false;
+ }
+ return true;
+}
+
+export function buildMobileVoiceDictionaryEntryViews(
+ snapshots: ReadonlyArray<MobileVoiceDictionarySnapshot>,
+ options?: { maxAliases?: number },
+): MobileVoiceDictionaryEntryView[] {
+ const maxAliases = options?.maxAliases ?? 3;
+ const freshest = snapshots.reduce<MobileVoiceDictionarySnapshot | null>((best, snapshot) => {
+ if (!snapshot || snapshot.fetchedAt <= 0) return best;
+ return !best || isFresherThan(snapshot, best) ? snapshot : best;
+ }, null);
+ if (!freshest) return [];
+
+ const seen = new Set<string>();
+ const views: Array<MobileVoiceDictionaryEntryView & { frequency: number }> = [];
+ for (const entry of freshest.entries ?? []) {
+ const text = entry?.text?.trim();
+ if (!text) continue;
+ // 直接用桌面 CRDT 那支主键函数,而不是自己 toLowerCase:它还做了空白归一等
+ // 处理,自己写一份迟早会和桌面漂移 —— 那样只差一个空格的两条会在手机上重复
+ // 显示,React key 也跟着不稳。
+ const key = dictionaryTermKey(text);
+ if (!key) continue;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ views.push({
+ key,
+ text,
+ frequency: readPositive(entry.frequency),
+ aliases: [...(entry.aliases ?? [])]
+ .filter((alias) => alias?.text?.trim())
+ .sort((a, b) => readPositive(b.count) - readPositive(a.count) || a.text.localeCompare(b.text))
+ .slice(0, maxAliases)
+ .map((alias) => alias.text.trim()),
+ });
+ }
+
+ return views
+ .sort((a, b) => b.frequency - a.frequency || a.text.localeCompare(b.text))
+ .map(({ key, text, aliases }) => ({ key, text, aliases }));
+}
+
+function readPositive(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 1;
+}
diff --git a/apps/mobile/src/session/mobileVoiceInput.ts b/apps/mobile/src/session/mobileVoiceInput.ts
index 887ecb25a1..65dd600004 100644
--- a/apps/mobile/src/session/mobileVoiceInput.ts
+++ b/apps/mobile/src/session/mobileVoiceInput.ts
@@ -12,6 +12,7 @@ import {
type TextModelClient,
} from '@cindy/voice-input-core';
import type { StoredMobileVoiceCredential } from '@/session/mobileVoiceCredentialStore';
+import type { MobileVoiceCredentialSyncDictionaryEntry as MobileVoiceDictionaryEntry } from '@cindy/maker-shared/device-link-contract';
import { redactMobileVoiceCredentialText } from '@/session/mobileVoiceCredentialRedaction';
import {
composerVoiceStateLabel,
@@ -230,10 +231,16 @@ export function buildMobileVoiceRefinementContext(
sourceLanguage?: string;
refinementContext?: DictationRefinementContext;
localVoiceInputHistory?: readonly string[];
+ /**
+ * 从被控桌面拉来的词典快照。托管路径的 credential 本身不带词典
+ * (`createMobileCindyVoiceCredential` 只填语言与开关),词典改由
+ * `mobileVoiceDictionaryCache` 单独拉取并缓存。
+ */
+ dictionaryEntries?: readonly MobileVoiceDictionaryEntry[];
} = {},
): DictationRefinementContext {
const settings = credential.settings;
- const dictionaryEntries = settings?.dictionaryEntries ?? [];
+ const dictionaryEntries = options.dictionaryEntries ?? settings?.dictionaryEntries ?? [];
const history = mergeMobileVoiceHistories(settings?.voiceInputHistory, options.localVoiceInputHistory);
const uiLanguage = options.refinementContext?.uiLanguage?.trim()
|| options.uiLanguage?.trim()
@@ -635,7 +642,7 @@ function hasReadableStreamBody(value: unknown): value is ReadableStream<Uint8Arr
}
function formatMobileVoiceDictionary(
- entries: NonNullable<StoredMobileVoiceCredential['settings']>['dictionaryEntries'] | undefined,
+ entries: readonly MobileVoiceDictionaryEntry[] | undefined,
): string {
return (entries ?? [])
.map((entry) => entry.text.trim())
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index b399b46d1a..09c4a1a325 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -136,6 +136,10 @@
OAuth 2.0 Device Authorization Grant 中由用户在另一设备验证页输入的一次性代码。当前先采用各语言直译,作为待产品裁决术语登记,避免后续界面出现“设备代码/配对码/认证码”等多套说法。
+### Voice dictionary
+
+语音输入的用户自定义术语表(人名、产品名、代号与其常见误识别写法),在同账号的电脑之间自动同步、手机只读查看。当前先采用四语直译并登记为待讨论术语,避免与「自定义词典」「术语表」「用户词库」等说法混用。
+
## 怎么加一条术语
1. 在 `i18n/glossary.json` 的 `terms` 里加条目,`note` 必填——写清楚**为什么**这么定,
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 28a2eaa8c8..e6d5aa5b2e 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -13,26 +13,35 @@
],
"terms": [
{
- "id": "content-update",
- "status": "proposed",
- "en": "Content Update",
+ "id": "active",
+ "status": "decided",
+ "en": "Active",
"translations": {
- "zh-CN": "内容更新",
- "ja": "コンテンツ更新",
- "ko": "콘텐츠 업데이트"
+ "zh-CN": "活跃",
+ "ja": "アクティブ",
+ "ko": "활성"
},
- "note": "指不更换 TestFlight 或商店安装包、可通过 OTA 下发的 JS 与资源更新。当前先采用四语直译并登记为待讨论术语,避免与整包更新或测试版本更新混称。"
- },
- {
- "id": "device-code",
- "status": "proposed",
- "en": "Device Code",
- "translations": {
- "zh-CN": "设备码",
- "ja": "デバイスコード",
- "ko": "기기 코드"
+ "checkCase": false,
+ "alsoAllowed": {
+ "zh-CN": [
+ {
+ "text": "生效中",
+ "when": "计费语境(\"no active subscription\"→没有生效中的订阅),指订阅状态而非活跃度"
+ }
+ ]
},
- "note": "OAuth 2.0 Device Authorization Grant 中由用户在另一设备验证页输入的一次性代码。当前先采用各语言直译,作为待产品裁决术语登记,避免后续界面出现“设备代码/配对码/认证码”等多套说法。"
+ "forbidden": {
+ "zh-CN": [
+ {
+ "text": "活动",
+ "whenEn": "Active"
+ }
+ ]
+ },
+ "note": "对话 / 设备状态用「活跃」(现状 21:7)。mobile/devices 同一屏上筛选 chip 写「活跃」、指标磁贴写「活动」。条件禁用:「活动」是 Activity 的正确译法,无条件禁会误伤「活动记录」这类。豁免 Windows Computer Use 提示:那里的 active desktop 指「当前接收输入、显示目标应用的 Windows 桌面」,是 OS 概念,中文既定说法为「当前活动桌面」,与产品的活跃度无关。",
+ "exempt": [
+ "desktop:settings.computerUse.directControl.permissions.windowsHint"
+ ]
},
{
"id": "cindy-codex-home",
@@ -69,232 +78,262 @@
]
},
{
- "id": "subagent",
+ "id": "author",
"status": "decided",
- "en": "Subagent",
+ "en": "Author",
"translations": {
- "zh-CN": "Subagent",
- "ja": "サブエージェント",
- "ko": "하위 에이전트"
+ "zh-CN": "作者",
+ "ja": "作成者",
+ "ko": "작성자"
},
+ "checkCase": false,
"forbidden": {
"zh-CN": [
{
- "text": "代理",
- "whenEn": "Subagent"
+ "text": "提交者",
+ "whenEn": "Author"
+ },
+ {
+ "text": "提出者",
+ "whenEn": "Author"
}
]
},
- "note": "Agent 的派生概念,中文跟随 Agent 保留英文原词,不译「子代理」。「代理」在此条下按 whenEn=Subagent 登记:同一个中文词在 Agent / Subagent / Proxy 三处各有来源,只有按英文源区分,自动替换才知道该换成哪个词。ja / ko 沿用既有音译。"
+ "note": "中文用「作者」(现状 9:4)。典型的同模块自相矛盾:issueTracker 同一个页面里,assignee.labelAuthor 写「提交者」、list.filterAuthor 写「提出者」、visibility.onlyAuthorCanChange 写「作者」——同一个字段三种叫法。条件禁用避免误伤 Committer / Reporter 等其它英文词的正确译法。"
},
{
- "id": "proxy",
+ "id": "automation",
"status": "decided",
- "en": "Proxy",
+ "en": "Automation",
"translations": {
- "zh-CN": "Proxy",
- "ja": "プロキシ",
- "ko": "프록시"
+ "zh-CN": "自动化",
+ "ja": "自動化",
+ "ko": "자동화"
},
- "forbidden": {
+ "alsoAllowed": {
"zh-CN": [
{
- "text": "代理",
- "whenEn": "Proxy"
+ "text": "自动任务",
+ "when": "指单条自动化实例(一个定时跑的任务)时"
+ },
+ {
+ "text": "自动化任务",
+ "when": "需要与模块名区分、强调它是一条任务时"
+ },
+ {
+ "text": "自动操作",
+ "when": "Computer Use 语境——「自动操作电脑 / 浏览器」,指代操控设备而非定时任务"
}
]
},
- "note": "网络代理,中文保留英文原词(2026-07 裁决:Agent 与 Proxy 都不叫「代理」)。本条只管英文源为 Proxy 的那些——Agent / Subagent 的「代理」误译各自登记在自己条目下。ja / ko 沿用既有音译。whenEn 的匹配走 makeSourceTermMatcher,复数按英语真实形态展开:Proxy 的复数是 proxies,原先只认「加 s」,英文源写 system proxies 时这条条件禁用会整个跳过。"
+ "forbidden": {
+ "ja": [
+ "オートメーション"
+ ],
+ "ko": [
+ "오토메이션"
+ ]
+ },
+ "note": "模块名 / 能力名用「自动化」(现状 88 处主流);指单条实例时用「自动任务」,这是刻意保留的场景差异——一刀切会写出「查看你的自动化」这类别扭中文。特别注意 Automation 在本产品里指两个不同概念:scheduler 的定时任务,以及 settings.computerUse 的操控电脑能力;后者用「自动操作电脑 / 浏览器」,改成「自动化电脑」反而不通。因此不设 forbidden。(2026-07 修正:ja 原声明 オートメーション 仅 37/121,主流是 自動化;ko 的 자동화 75/121 本就正确。)豁免通讯录授权提示的两个 key:那里指的是 macOS 系统设置里的面板名,日文官方标签是「オートメーション」而非产品术语「自動化」——照产品术语改会让用户按提示在系统设置里找不到对应项,授权恢复路径直接断掉。zh-CN 的「自动化」与 ko 的「자동화」恰好就是各自的 macOS 官方标签,不受影响。",
+ "exempt": [
+ "desktop:settings.contacts.import.permissionDenied",
+ "desktop:settings.contacts.ipcError.PERMISSION_DENIED"
+ ]
},
{
- "id": "plugin",
+ "id": "balance",
"status": "decided",
- "en": "Plugin",
+ "en": "Balance",
"translations": {
- "zh-CN": "插件",
- "ja": "プラグイン",
- "ko": "플러그인"
+ "zh-CN": "余额",
+ "ja": "残高",
+ "ko": "잔액"
},
+ "checkCase": false,
"forbidden": {
"zh-CN": [
- "Plugin",
- "plugin"
+ {
+ "text": "额度",
+ "whenEn": "Balance"
+ }
]
},
- "note": "中文一律「插件」,不保留英文原词(现状 94:4)。历史上 Ghost / Plugin 两种叫法并存,对外统一为「插件」。",
- "exempt": []
+ "note": "账户余额用「余额」。原先被并入「额度」(可用额度 / 额度更新于 / 剩余额度),与 Credits、Quota 混同。Balance 是「账上还剩多少」,Credits 是「可购买消耗的计数单位」,Quota 是「周期内上限」——三者是不同层面的量,中文必须分开。"
},
{
- "id": "project",
+ "id": "chat",
"status": "decided",
- "en": "Project",
+ "en": "Chat",
"translations": {
- "zh-CN": "项目",
- "ja": "プロジェクト",
- "ko": "프로젝트"
+ "zh-CN": "对话",
+ "ja": "チャット",
+ "ko": "채팅"
},
+ "checkCase": false,
"forbidden": {
"zh-CN": [
- "Project"
+ "聊天"
]
},
- "note": "中文一律「项目」(现状 119:15)。同一个侧边栏里筛选叫「项目」、批量操作提示叫「Project」是既有 bug。小写 project 不入 forbidden——它常出现在路径与文件名里(project.json)。",
- "exempt": []
- },
- {
- "id": "worker",
- "status": "decided",
- "en": "Worker",
- "translations": {
- "zh-CN": "Worker",
- "ja": "Worker",
- "ko": "Worker"
- },
- "forbidden": {},
- "note": "Orca 协同角色名,四语统一保留英文。这里只钉大小写形态:首字母大写 Worker。小写 worker 由 guard 的大小写规则单独覆盖(desktop 26:13 混用、mobile 一律小写)。"
+ "note": "在本产品里 Chat 与 Session 指同一个东西,中文统一叫「对话」(2026-07 裁决),不再区分「聊天 / 会话 / 对话」三套说法。原先 22 处「聊天」(聊天正文、聊天区、聊天记录…)已一并改为「对话」。ja / ko 保留各自既有译法,两语没有中文这种三词混用问题。"
},
{
- "id": "session",
+ "id": "collaboration",
"status": "decided",
- "en": "Session",
+ "en": "Collaboration",
"translations": {
- "zh-CN": "对话",
- "ja": "セッション",
- "ko": "세션"
+ "zh-CN": "协同",
+ "ja": "協同",
+ "ko": "협업"
},
"checkCase": false,
"forbidden": {
"zh-CN": [
- "会话"
+ {
+ "text": "协作",
+ "whenEn": "Collaboration"
+ }
]
},
- "note": "面向用户一律叫「对话」——「会话」太生硬难懂(2026-07 裁决)。代码与内部标识仍用 Session,本条只约束 UI 文案。Chat 合并到同一个词,见 chat 条目。落地时把 440 处「会话」+ 22 处「聊天」统一改为「对话」。ja / ko 沿用既有音译,不受本条约束。豁免的 6 处是同形异义的技术 session(登录态、WebSocket 语音连接),与产品对话无关——同类的还有 Linux Computer Use 提示里的「桌面会话」——那是 OS 桌面会话(窗口读取与输入自动化的授权范围)。注意 login.errors 的「绑定会话」指账号绑定态,scheduler 的「绑定对话」才是产品对话,两者同名不同义,靠 key 精确区分。还豁免 archiveWorkerConfirmDesc:归档 Worker 时 orcaTeamService.archiveWorker() 先关掉它的 SDK 运行时 session,再归档存下来的产品对话——一句话里是两个生命周期,统称「对话」会让用户以为聊天记录也被停掉了。还豁免 stopBashTitle:它停后台任务但显式保留底层 session 进程,「对话进程」是个不存在的东西,还会模糊它与相邻的「关闭后台进程」的区别。另豁免 4 个 toggleHint 与 forkErrors.unsupportedHistory:英文原文明确区分 agent session(Agent 运行实例)与 conversation(产品对话),两者合并成「对话」会把语义说错——开关其实对「同一对话内重启的 Agent 会话」也生效,写成「只对新建对话生效」等于告诉用户要新开对话。unsupportedHistory 失效的是历史引擎 session,产品对话仍在。内置工具的两条 toast 同理豁免:英文是 takes effect on next session,指下一个 Agent 会话;写成「下次对话生效」会与紧邻的 toggleHint(说重启 Agent 会话即可)自相矛盾,让用户以为必须新开一个对话。personalization 说明也豁免:那三处英文全是 runtime session——设置在 Agent 会话创建时被快照,而终端直跑 / 其他 IDE 里的 Claude Code 根本不是 Cindy 的产品对话,受 SessionStart hook 管。称它们「对话」等于凭空造出 Cindy 之外的产品对话。「Claude Code 会话」四处同样豁免:英文是 Claude Code sessions,指 CC 子进程 / SDK 运行实例(调试日志由 XDT_CC_DEBUG_NET 在下一个 CC 会话启动时生效),不是存下来的产品对话。称它「对话」会让用户以为要新开一个对话才生效。subagentModels.hint 同样豁免:英文是 apply to new sessions,指 Agent 运行实例——runtime-configs 用 live getter 暴露该设置、buildClaudeEnv() 在 Agent 会话启动时快照,所以在同一个对话里重启 runtime 就能生效。写成「从新建对话开始生效」会让用户以为必须新开对话。切换 Agent 引擎的确认文案与 Codex 延迟生效提示同样豁免:英文分别是 the original engine’s session 与 new Codex sessions,指引擎的运行实例——切回原引擎时续接的是它的 runtime session,存下来的产品对话从没变过;Codex 那条重启后对下一个 Codex 运行实例生效,同一对话里重启也算。统称「对话」会让用户以为每个引擎各有一个对话、或必须新开对话。stopConfirmDesc 与 lspMode 的两条 toast 同样豁免:英文源分别是 The Worker session will be destroyed 与 takes effect in new sessions,指的都是 Agent 运行实例——结束协同时 disableOrcaInternal() 关掉 Worker 的 SDK 运行时后会把它存下来的对话标为 archived、聊天记录仍在,LSP 开关则在下一个 Agent 会话启动时才被读到。称它们「对话」会让用户以为聊天记录被销毁、或必须新开一个对话,与紧邻的归档确认文案自相矛盾。",
+ "note": "Orca 多 Agent 功能名,中文用「协同」(现状 21:2)。可见 bug:设置导航项写「协作」,点进去页面标题写「协同」。条件禁用:settings.contacts 里的「协作经历」是 collaboration history,属另一个语义,英文源不含独立 Collaboration 一词时不判违规。",
"exempt": [
- "desktop:chat.backgroundActivity.stopBashTitle",
- "desktop:chat.remoteError.REMOTE_COMPAT_MODE_UNSUPPORTED",
- "desktop:chat.rewind.errors.remoteNotSupported",
- "desktop:chat.systemCard.context.noLiveSession",
- "desktop:chat.userMessage.forkErrors.unsupportedHistory",
- "desktop:login.errors.INVALID_BIND_TICKET",
- "desktop:login.errors.INVALID_LOGIN_TICKET",
- "desktop:newChat.chatInput.agentSwitch.confirmation.description",
- "desktop:newChat.collaboration.archiveWorkerConfirmDesc",
- "desktop:newChat.collaboration.stopConfirmDesc",
- "desktop:settings.about.debugLogDescription",
- "desktop:settings.builtinTools.toast.disabled",
- "desktop:settings.builtinTools.toast.enabled",
- "desktop:settings.builtinTools.toggleHint",
- "desktop:settings.computerUse.android.toggleHint",
- "desktop:settings.computerUse.browser.toggleHint",
- "desktop:settings.computerUse.codexRefreshDeferred",
- "desktop:settings.computerUse.directControl.permissions.linuxHint",
- "desktop:settings.computerUse.directControl.toggleHint",
- "desktop:settings.lspMode.toast.disabled",
- "desktop:settings.lspMode.toast.enabled",
- "desktop:settings.personalization.placeholder",
- "desktop:settings.subagentModels.hint",
- "mobile/composer:voice.invalidSession",
- "mobile/composer:voice.missingConnectionProvider",
- "mobile/composer:voice.missingRefinerTargetProvider",
- "mobile/composer:voice.sessionExpiredOrForbidden",
- "mobile/composer:voice.sessionNotConnected"
+ "desktop:settings.contacts."
]
},
{
- "id": "chat",
+ "id": "collapse",
"status": "decided",
- "en": "Chat",
+ "en": "Collapse",
"translations": {
- "zh-CN": "对话",
- "ja": "チャット",
- "ko": "채팅"
+ "zh-CN": "收起",
+ "ja": "折りたたむ",
+ "ko": "접기"
},
"checkCase": false,
"forbidden": {
"zh-CN": [
- "聊天"
+ {
+ "text": "折叠",
+ "whenEn": "Collapse"
+ }
]
},
- "note": "在本产品里 Chat 与 Session 指同一个东西,中文统一叫「对话」(2026-07 裁决),不再区分「聊天 / 会话 / 对话」三套说法。原先 22 处「聊天」(聊天正文、聊天区、聊天记录…)已一并改为「对话」。ja / ko 保留各自既有译法,两语没有中文这种三词混用问题。"
+ "note": "中文用「收起」(现状 29:7),与反义词「展开」(Expand,29/30 已统一)配对。ccAgent 与 rightSidebar 内部各自「收起 / 折叠」混用,是同模块自相矛盾。条件禁用:「折叠」在别处可能是正常中文,只在英文源含 Collapse 时判违规。"
},
{
- "id": "thread",
+ "id": "content-update",
+ "status": "proposed",
+ "en": "Content Update",
+ "translations": {
+ "zh-CN": "内容更新",
+ "ja": "コンテンツ更新",
+ "ko": "콘텐츠 업데이트"
+ },
+ "note": "指不更换 TestFlight 或商店安装包、可通过 OTA 下发的 JS 与资源更新。当前先采用四语直译并登记为待讨论术语,避免与整包更新或测试版本更新混称。"
+ },
+ {
+ "id": "credits",
"status": "decided",
- "en": "Thread",
+ "en": "Credits",
"translations": {
- "zh-CN": "对话",
- "ja": "スレッド",
- "ko": "스레드"
+ "zh-CN": "点数",
+ "ja": "クレジット",
+ "ko": "크레딧"
},
"checkCase": false,
"alsoAllowed": {
"zh-CN": [
{
- "text": "thread",
- "when": "指 Codex 的 thread 这一外部系统概念时(导入历史、thread 上下文),保留英文"
+ "text": "credits",
+ "when": "指第三方服务自身的 credits(如 Codex / ChatGPT 订阅余量),保留其原生叫法"
},
{
- "text": "评论",
- "when": "指 GitHub PR 的 review thread 时,用「review 评论」"
+ "text": "重置次数",
+ "when": "reset credits——指可用的配额重置次数,与计费点数无关"
}
]
},
"forbidden": {
"zh-CN": [
- "线程"
+ {
+ "text": "额度",
+ "whenEn": "Credit"
+ }
]
},
- "note": "全仓仅 8 处,按语境分四类,是「同一个词必须分场合翻译」的典型:①指产品内的对话 → 跟随 session 叫「对话」(已落地 3 处);②Codex 外部概念 → 保留 thread;③GitHub PR review thread →「review 评论」;④比喻用法 \"persistent work thread\" → 原译「工作线程」,中文有 OS 线程歧义,已改写为「持续推进的工作对话」。「线程」一律禁用。"
+ "note": "计费点数用「点数」。清理前中文「额度」同时对应 Balance / Credits / Quota 三个英文概念,是计费面板里最容易误导用户的一处:同一个 billing 页面里「点数」和「额度」并存,而「额度」在别处又指配额。裁决把三者拆开——Credits =「点数」、Quota =「配额」、Balance =「余额」,「额度」整体退出。「额度」的禁用按英文源拆成三条条件禁用,分别挂在 credits / quota / balance 下。不能无条件禁:同一个「额度」在不同 key 里分别对应 Credits / Quota / Balance,目标译法不唯一,无条件禁只会让自动替换随机挑一个——xAI 的 subscription quota 就是这样被改成「订阅点数」的。第三方原生 credits 与 reset credits 属不同概念,走 alsoAllowed。whenEn 写单数 Credit:匹配本来就带可选复数 s,单数能同时覆盖 Credit / Credits,写成复数反而漏掉全部单数用法(Promotional Credit Details、credit snapshot 等 8 个 key 原先完全不受约束)。"
},
{
- "id": "skill",
- "status": "decided",
- "en": "Skill",
+ "id": "device-code",
+ "status": "proposed",
+ "en": "Device Code",
"translations": {
- "zh-CN": "技能",
- "ja": "スキル",
- "ko": "스킬"
+ "zh-CN": "设备码",
+ "ja": "デバイスコード",
+ "ko": "기기 코드"
},
- "alsoAllowed": {
+ "note": "OAuth 2.0 Device Authorization Grant 中由用户在另一设备验证页输入的一次性代码。当前先采用各语言直译,作为待产品裁决术语登记,避免后续界面出现“设备代码/配对码/认证码”等多套说法。"
+ },
+ {
+ "id": "directory",
+ "status": "decided",
+ "en": "Directory",
+ "translations": {
+ "zh-CN": "目录",
+ "ja": "ディレクトリ",
+ "ko": "디렉터리"
+ },
+ "checkCase": false,
+ "forbidden": {},
+ "note": "Directory 用「目录」(现状 96:4),Folder 用「文件夹」(37:20),两个英文词在中文里也分开。**本条刻意不设 forbidden**:英文侧自己就在一句话里混用二者(\"not a folder. Choose a project directory.\"、\"re-select the working directory and wait for the folder badge\"),而条件禁用是句子级匹配,区分不了句内哪个中文词对应哪个英文词——实测 4 处命中全是假阳性,那 4 条中文其实译得完全正确。要真正管住这对词,得先清理英文侧的 path / folder / directory 混用。此条目保留为文档指引,供人查阅。"
+ },
+ {
+ "id": "dismiss",
+ "status": "decided",
+ "en": "Dismiss",
+ "translations": {
+ "zh-CN": "关闭",
+ "ja": "閉じる",
+ "ko": "닫기"
+ },
+ "checkCase": false,
+ "forbidden": {
"zh-CN": [
{
- "text": "Skill",
- "when": "技术语境下指代具体的 skill 文件 / 目录结构时,可保留英文"
+ "text": "忽略",
+ "whenEn": "Dismiss"
+ },
+ {
+ "text": "知道了",
+ "whenEn": "Dismiss"
}
]
},
- "forbidden": {
- "ja": [
- "技能"
- ],
- "ko": [
- "기술"
- ]
- },
- "note": "中文用「技能」(现状 32:26 领先),偶尔保留英文 Skill 也允许,故 zh-CN 不设 forbidden——硬性禁用会逼出别扭的中文。ja / ko 则禁用 技能 / 기술:那是与 スキル / 스킬 并存的同义漂移,且只出现在 skillhub 内部(3 / 3 处)。ko 的 기술 是多义词(技术 / 记述 / 技能),两处非 Skill 义已按 key 豁免。SkillHub 作为产品名单独登记在 skillhub 条目。(2026-07 补充:alsoAllowed 允许保留英文,那就必须是规范形态 Skill——caseStandardFor 会把这类条目一并纳入大小写检查,skillhub 里原有 10 处小写 skill 已统一。)",
- "exempt": [
- "desktop:localDbFatal.details",
- "desktop:issueTracker.create.descriptionPlaceholder"
- ]
+ "note": "中文用「关闭」(现状 6:4)。同一个 chat 模块里,errorBanner 写「关闭错误提示」、interruptedBanner 写「忽略此中断提示」。条件禁用:「忽略」是 Ignore 的正确译法、「知道了」是 Got it 的正确译法,只在英文源为 Dismiss 时才算违规。"
},
{
- "id": "skillhub",
+ "id": "effort",
"status": "decided",
- "en": "SkillHub",
+ "en": "Effort",
"translations": {
- "zh-CN": "SkillHub",
- "ja": "SkillHub",
- "ko": "SkillHub"
+ "zh-CN": "推理强度",
+ "ja": "推論強度",
+ "ko": "추론 강도"
},
"forbidden": {
- "ja": [
- "スキルハブ"
+ "zh-CN": [
+ "思考强度",
+ "思考深度",
+ "推理深度",
+ "努力程度",
+ "推理力度"
],
- "ko": [
- "스킬 허브"
+ "ja": [
+ "推論レベル",
+ "推論の強度"
]
},
- "note": "产品名,四语一律保留英文原样(暂定保留,未来若做中文名再改)。注意与 skill 条目区分:侧边栏 tab 现在叫「技能」但实际指 SkillHub,创建面板的「技能」指 Skills——这是既有 bug,两者不是一个东西不该同名,清理存量时需一并处理。"
+ "note": "模型的推理投入档位(low/medium/high/…)。用「推理强度」有三重依据:①同类工具 i18n 里断层第一(GitHub 代码搜索共现量级 1452,第二名「思考强度」431);②OpenAI 简中帮助中心即用此词;③跨 provider 中立——Cindy 的 create_worker 用一个 effort 同时映射 Codex reasoning effort 与 Claude thinking 预算,而 Anthropic 官方简中叫「努力程度」、OpenAI 叫「推理强度」,需要不偏向任一方的词。禁用项各有硬理由:「思考深度」「推理深度」会与国内产品普遍的「深度思考」开关撞车,且语义错误(低 effort 是想得少,不是想得浅);「努力程度」在中文里强烈指向人的绩效评价;「推理等级/级别」未入禁用但不推荐——Cindy 已有 model tier 概念,「等级」易被读成模型档位。"
},
{
"id": "issue",
@@ -327,6 +366,41 @@
"desktop:scheduler.editor.script.capabilityDescs.jira_read"
]
},
+ {
+ "id": "plugin",
+ "status": "decided",
+ "en": "Plugin",
+ "translations": {
+ "zh-CN": "插件",
+ "ja": "プラグイン",
+ "ko": "플러그인"
+ },
+ "forbidden": {
+ "zh-CN": [
+ "Plugin",
+ "plugin"
+ ]
+ },
+ "note": "中文一律「插件」,不保留英文原词(现状 94:4)。历史上 Ghost / Plugin 两种叫法并存,对外统一为「插件」。",
+ "exempt": []
+ },
+ {
+ "id": "project",
+ "status": "decided",
+ "en": "Project",
+ "translations": {
+ "zh-CN": "项目",
+ "ja": "プロジェクト",
+ "ko": "프로젝트"
+ },
+ "forbidden": {
+ "zh-CN": [
+ "Project"
+ ]
+ },
+ "note": "中文一律「项目」(现状 119:15)。同一个侧边栏里筛选叫「项目」、批量操作提示叫「Project」是既有 bug。小写 project 不入 forbidden——它常出现在路径与文件名里(project.json)。",
+ "exempt": []
+ },
{
"id": "provider",
"status": "decided",
@@ -373,60 +447,23 @@
]
},
{
- "id": "effort",
- "status": "decided",
- "en": "Effort",
- "translations": {
- "zh-CN": "推理强度",
- "ja": "推論強度",
- "ko": "추론 강도"
- },
- "forbidden": {
- "zh-CN": [
- "思考强度",
- "思考深度",
- "推理深度",
- "努力程度",
- "推理力度"
- ],
- "ja": [
- "推論レベル",
- "推論の強度"
- ]
- },
- "note": "模型的推理投入档位(low/medium/high/…)。用「推理强度」有三重依据:①同类工具 i18n 里断层第一(GitHub 代码搜索共现量级 1452,第二名「思考强度」431);②OpenAI 简中帮助中心即用此词;③跨 provider 中立——Cindy 的 create_worker 用一个 effort 同时映射 Codex reasoning effort 与 Claude thinking 预算,而 Anthropic 官方简中叫「努力程度」、OpenAI 叫「推理强度」,需要不偏向任一方的词。禁用项各有硬理由:「思考深度」「推理深度」会与国内产品普遍的「深度思考」开关撞车,且语义错误(低 effort 是想得少,不是想得浅);「努力程度」在中文里强烈指向人的绩效评价;「推理等级/级别」未入禁用但不推荐——Cindy 已有 model tier 概念,「等级」易被读成模型档位。"
- },
- {
- "id": "credits",
+ "id": "proxy",
"status": "decided",
- "en": "Credits",
+ "en": "Proxy",
"translations": {
- "zh-CN": "点数",
- "ja": "クレジット",
- "ko": "크레딧"
- },
- "checkCase": false,
- "alsoAllowed": {
- "zh-CN": [
- {
- "text": "credits",
- "when": "指第三方服务自身的 credits(如 Codex / ChatGPT 订阅余量),保留其原生叫法"
- },
- {
- "text": "重置次数",
- "when": "reset credits——指可用的配额重置次数,与计费点数无关"
- }
- ]
+ "zh-CN": "Proxy",
+ "ja": "プロキシ",
+ "ko": "프록시"
},
"forbidden": {
"zh-CN": [
{
- "text": "额度",
- "whenEn": "Credit"
+ "text": "代理",
+ "whenEn": "Proxy"
}
]
},
- "note": "计费点数用「点数」。清理前中文「额度」同时对应 Balance / Credits / Quota 三个英文概念,是计费面板里最容易误导用户的一处:同一个 billing 页面里「点数」和「额度」并存,而「额度」在别处又指配额。裁决把三者拆开——Credits =「点数」、Quota =「配额」、Balance =「余额」,「额度」整体退出。「额度」的禁用按英文源拆成三条条件禁用,分别挂在 credits / quota / balance 下。不能无条件禁:同一个「额度」在不同 key 里分别对应 Credits / Quota / Balance,目标译法不唯一,无条件禁只会让自动替换随机挑一个——xAI 的 subscription quota 就是这样被改成「订阅点数」的。第三方原生 credits 与 reset credits 属不同概念,走 alsoAllowed。whenEn 写单数 Credit:匹配本来就带可选复数 s,单数能同时覆盖 Credit / Credits,写成复数反而漏掉全部单数用法(Promotional Credit Details、credit snapshot 等 8 个 key 原先完全不受约束)。"
+ "note": "网络代理,中文保留英文原词(2026-07 裁决:Agent 与 Proxy 都不叫「代理」)。本条只管英文源为 Proxy 的那些——Agent / Subagent 的「代理」误译各自登记在自己条目下。ja / ko 沿用既有音译。whenEn 的匹配走 makeSourceTermMatcher,复数按英语真实形态展开:Proxy 的复数是 proxies,原先只认「加 s」,英文源写 system proxies 时这条条件禁用会整个跳过。"
},
{
"id": "quota",
@@ -456,245 +493,232 @@
}
},
{
- "id": "balance",
+ "id": "running",
"status": "decided",
- "en": "Balance",
+ "en": "Running",
"translations": {
- "zh-CN": "余额",
- "ja": "残高",
- "ko": "잔액"
+ "zh-CN": "运行中",
+ "ja": "実行中",
+ "ko": "실행 중"
},
"checkCase": false,
- "forbidden": {
+ "alsoAllowed": {
"zh-CN": [
{
- "text": "额度",
- "whenEn": "Balance"
+ "text": "正在运行",
+ "when": "完整句子里作谓语时(\"Agent 正在运行\"),不是状态标签"
}
]
},
- "note": "账户余额用「余额」。原先被并入「额度」(可用额度 / 额度更新于 / 剩余额度),与 Credits、Quota 混同。Balance 是「账上还剩多少」,Credits 是「可购买消耗的计数单位」,Quota 是「周期内上限」——三者是不同层面的量,中文必须分开。"
- },
- {
- "id": "automation",
- "status": "decided",
- "en": "Automation",
- "translations": {
- "zh-CN": "自动化",
- "ja": "自動化",
- "ko": "자동화"
- },
- "alsoAllowed": {
+ "forbidden": {
"zh-CN": [
{
- "text": "自动任务",
- "when": "指单条自动化实例(一个定时跑的任务)时"
- },
- {
- "text": "自动化任务",
- "when": "需要与模块名区分、强调它是一条任务时"
+ "text": "执行中",
+ "whenEn": "Running"
},
{
- "text": "自动操作",
- "when": "Computer Use 语境——「自动操作电脑 / 浏览器」,指代操控设备而非定时任务"
+ "text": "进行中",
+ "whenEn": "Running"
}
]
},
- "forbidden": {
- "ja": [
- "オートメーション"
- ],
- "ko": [
- "오토메이션"
- ]
- },
- "note": "模块名 / 能力名用「自动化」(现状 88 处主流);指单条实例时用「自动任务」,这是刻意保留的场景差异——一刀切会写出「查看你的自动化」这类别扭中文。特别注意 Automation 在本产品里指两个不同概念:scheduler 的定时任务,以及 settings.computerUse 的操控电脑能力;后者用「自动操作电脑 / 浏览器」,改成「自动化电脑」反而不通。因此不设 forbidden。(2026-07 修正:ja 原声明 オートメーション 仅 37/121,主流是 自動化;ko 的 자동화 75/121 本就正确。)豁免通讯录授权提示的两个 key:那里指的是 macOS 系统设置里的面板名,日文官方标签是「オートメーション」而非产品术语「自動化」——照产品术语改会让用户按提示在系统设置里找不到对应项,授权恢复路径直接断掉。zh-CN 的「自动化」与 ko 的「자동화」恰好就是各自的 macOS 官方标签,不受影响。",
- "exempt": [
- "desktop:settings.contacts.import.permissionDenied",
- "desktop:settings.contacts.ipcError.PERMISSION_DENIED"
- ]
+ "note": "状态标签用「运行中」(现状 16:9)。条件禁用是必需的——「进行中」是 In Progress 的正确译法、「执行中」在别处也可能对,无条件禁会大面积误伤。mobile/devices 的自动化面板上「运行中 / 执行中 / 重跑中」三种写法同屏出现。"
},
{
- "id": "usage",
+ "id": "session",
"status": "decided",
- "en": "Usage",
+ "en": "Session",
"translations": {
- "zh-CN": "用量",
- "ja": "使用量",
- "ko": "사용량"
+ "zh-CN": "对话",
+ "ja": "セッション",
+ "ko": "세션"
},
+ "checkCase": false,
"forbidden": {
"zh-CN": [
- "使用情况",
- "使用表现"
- ],
- "ja": [
- "使用状況",
- "利用状況"
- ],
- "ko": [
- "사용 현황"
+ "会话"
]
},
- "note": "中文用「用量」(现状 37:6 压倒性)。「使用情况」「使用表现」是同义漂移,禁用。注意 usage 在英文里也有「用法」义(如 CLI usage),那属于另一个概念,不在本条约束范围。豁免遥测说明两处:那里的 usage 指「启动与留存情况」这类使用行为,不是计费口径的用量指标。硬套成「用量」会写出「启动与留存用量」这种不通的话——zh-CN 用的是「留存情况」+「使用环境」,ja/ko 的「継続利用状況」「지속 사용 현황」同理。",
+ "note": "面向用户一律叫「对话」——「会话」太生硬难懂(2026-07 裁决)。代码与内部标识仍用 Session,本条只约束 UI 文案。Chat 合并到同一个词,见 chat 条目。落地时把 440 处「会话」+ 22 处「聊天」统一改为「对话」。ja / ko 沿用既有音译,不受本条约束。豁免的 6 处是同形异义的技术 session(登录态、WebSocket 语音连接),与产品对话无关——同类的还有 Linux Computer Use 提示里的「桌面会话」——那是 OS 桌面会话(窗口读取与输入自动化的授权范围)。注意 login.errors 的「绑定会话」指账号绑定态,scheduler 的「绑定对话」才是产品对话,两者同名不同义,靠 key 精确区分。还豁免 archiveWorkerConfirmDesc:归档 Worker 时 orcaTeamService.archiveWorker() 先关掉它的 SDK 运行时 session,再归档存下来的产品对话——一句话里是两个生命周期,统称「对话」会让用户以为聊天记录也被停掉了。还豁免 stopBashTitle:它停后台任务但显式保留底层 session 进程,「对话进程」是个不存在的东西,还会模糊它与相邻的「关闭后台进程」的区别。另豁免 4 个 toggleHint 与 forkErrors.unsupportedHistory:英文原文明确区分 agent session(Agent 运行实例)与 conversation(产品对话),两者合并成「对话」会把语义说错——开关其实对「同一对话内重启的 Agent 会话」也生效,写成「只对新建对话生效」等于告诉用户要新开对话。unsupportedHistory 失效的是历史引擎 session,产品对话仍在。内置工具的两条 toast 同理豁免:英文是 takes effect on next session,指下一个 Agent 会话;写成「下次对话生效」会与紧邻的 toggleHint(说重启 Agent 会话即可)自相矛盾,让用户以为必须新开一个对话。personalization 说明也豁免:那三处英文全是 runtime session——设置在 Agent 会话创建时被快照,而终端直跑 / 其他 IDE 里的 Claude Code 根本不是 Cindy 的产品对话,受 SessionStart hook 管。称它们「对话」等于凭空造出 Cindy 之外的产品对话。「Claude Code 会话」四处同样豁免:英文是 Claude Code sessions,指 CC 子进程 / SDK 运行实例(调试日志由 XDT_CC_DEBUG_NET 在下一个 CC 会话启动时生效),不是存下来的产品对话。称它「对话」会让用户以为要新开一个对话才生效。subagentModels.hint 同样豁免:英文是 apply to new sessions,指 Agent 运行实例——runtime-configs 用 live getter 暴露该设置、buildClaudeEnv() 在 Agent 会话启动时快照,所以在同一个对话里重启 runtime 就能生效。写成「从新建对话开始生效」会让用户以为必须新开对话。切换 Agent 引擎的确认文案与 Codex 延迟生效提示同样豁免:英文分别是 the original engine’s session 与 new Codex sessions,指引擎的运行实例——切回原引擎时续接的是它的 runtime session,存下来的产品对话从没变过;Codex 那条重启后对下一个 Codex 运行实例生效,同一对话里重启也算。统称「对话」会让用户以为每个引擎各有一个对话、或必须新开对话。stopConfirmDesc 与 lspMode 的两条 toast 同样豁免:英文源分别是 The Worker session will be destroyed 与 takes effect in new sessions,指的都是 Agent 运行实例——结束协同时 disableOrcaInternal() 关掉 Worker 的 SDK 运行时后会把它存下来的对话标为 archived、聊天记录仍在,LSP 开关则在下一个 Agent 会话启动时才被读到。称它们「对话」会让用户以为聊天记录被销毁、或必须新开一个对话,与紧邻的归档确认文案自相矛盾。",
"exempt": [
- "desktop:settings.about.analyticsDescription",
- "mobile/settings:legal.analyticsHint"
+ "desktop:chat.backgroundActivity.stopBashTitle",
+ "desktop:chat.remoteError.REMOTE_COMPAT_MODE_UNSUPPORTED",
+ "desktop:chat.rewind.errors.remoteNotSupported",
+ "desktop:chat.systemCard.context.noLiveSession",
+ "desktop:chat.userMessage.forkErrors.unsupportedHistory",
+ "desktop:login.errors.INVALID_BIND_TICKET",
+ "desktop:login.errors.INVALID_LOGIN_TICKET",
+ "desktop:newChat.chatInput.agentSwitch.confirmation.description",
+ "desktop:newChat.collaboration.archiveWorkerConfirmDesc",
+ "desktop:newChat.collaboration.stopConfirmDesc",
+ "desktop:settings.about.debugLogDescription",
+ "desktop:settings.builtinTools.toast.disabled",
+ "desktop:settings.builtinTools.toast.enabled",
+ "desktop:settings.builtinTools.toggleHint",
+ "desktop:settings.computerUse.android.toggleHint",
+ "desktop:settings.computerUse.browser.toggleHint",
+ "desktop:settings.computerUse.codexRefreshDeferred",
+ "desktop:settings.computerUse.directControl.permissions.linuxHint",
+ "desktop:settings.computerUse.directControl.toggleHint",
+ "desktop:settings.lspMode.toast.disabled",
+ "desktop:settings.lspMode.toast.enabled",
+ "desktop:settings.personalization.placeholder",
+ "desktop:settings.subagentModels.hint",
+ "mobile/composer:voice.invalidSession",
+ "mobile/composer:voice.missingConnectionProvider",
+ "mobile/composer:voice.missingRefinerTargetProvider",
+ "mobile/composer:voice.sessionExpiredOrForbidden",
+ "mobile/composer:voice.sessionNotConnected"
]
},
{
- "id": "collapse",
+ "id": "skill",
"status": "decided",
- "en": "Collapse",
+ "en": "Skill",
"translations": {
- "zh-CN": "收起",
- "ja": "折りたたむ",
- "ko": "접기"
+ "zh-CN": "技能",
+ "ja": "スキル",
+ "ko": "스킬"
},
- "checkCase": false,
- "forbidden": {
+ "alsoAllowed": {
"zh-CN": [
{
- "text": "折叠",
- "whenEn": "Collapse"
+ "text": "Skill",
+ "when": "技术语境下指代具体的 skill 文件 / 目录结构时,可保留英文"
}
]
},
- "note": "中文用「收起」(现状 29:7),与反义词「展开」(Expand,29/30 已统一)配对。ccAgent 与 rightSidebar 内部各自「收起 / 折叠」混用,是同模块自相矛盾。条件禁用:「折叠」在别处可能是正常中文,只在英文源含 Collapse 时判违规。"
+ "forbidden": {
+ "ja": [
+ "技能"
+ ],
+ "ko": [
+ "기술"
+ ]
+ },
+ "note": "中文用「技能」(现状 32:26 领先),偶尔保留英文 Skill 也允许,故 zh-CN 不设 forbidden——硬性禁用会逼出别扭的中文。ja / ko 则禁用 技能 / 기술:那是与 スキル / 스킬 并存的同义漂移,且只出现在 skillhub 内部(3 / 3 处)。ko 的 기술 是多义词(技术 / 记述 / 技能),两处非 Skill 义已按 key 豁免。SkillHub 作为产品名单独登记在 skillhub 条目。(2026-07 补充:alsoAllowed 允许保留英文,那就必须是规范形态 Skill——caseStandardFor 会把这类条目一并纳入大小写检查,skillhub 里原有 10 处小写 skill 已统一。)",
+ "exempt": [
+ "desktop:localDbFatal.details",
+ "desktop:issueTracker.create.descriptionPlaceholder"
+ ]
},
{
- "id": "author",
+ "id": "skillhub",
"status": "decided",
- "en": "Author",
+ "en": "SkillHub",
"translations": {
- "zh-CN": "作者",
- "ja": "作成者",
- "ko": "작성자"
+ "zh-CN": "SkillHub",
+ "ja": "SkillHub",
+ "ko": "SkillHub"
},
- "checkCase": false,
"forbidden": {
- "zh-CN": [
- {
- "text": "提交者",
- "whenEn": "Author"
- },
- {
- "text": "提出者",
- "whenEn": "Author"
- }
+ "ja": [
+ "スキルハブ"
+ ],
+ "ko": [
+ "스킬 허브"
]
},
- "note": "中文用「作者」(现状 9:4)。典型的同模块自相矛盾:issueTracker 同一个页面里,assignee.labelAuthor 写「提交者」、list.filterAuthor 写「提出者」、visibility.onlyAuthorCanChange 写「作者」——同一个字段三种叫法。条件禁用避免误伤 Committer / Reporter 等其它英文词的正确译法。"
+ "note": "产品名,四语一律保留英文原样(暂定保留,未来若做中文名再改)。注意与 skill 条目区分:侧边栏 tab 现在叫「技能」但实际指 SkillHub,创建面板的「技能」指 Skills——这是既有 bug,两者不是一个东西不该同名,清理存量时需一并处理。"
},
{
- "id": "collaboration",
+ "id": "subagent",
"status": "decided",
- "en": "Collaboration",
+ "en": "Subagent",
"translations": {
- "zh-CN": "协同",
- "ja": "協同",
- "ko": "협업"
+ "zh-CN": "Subagent",
+ "ja": "サブエージェント",
+ "ko": "하위 에이전트"
},
- "checkCase": false,
"forbidden": {
"zh-CN": [
{
- "text": "协作",
- "whenEn": "Collaboration"
+ "text": "代理",
+ "whenEn": "Subagent"
}
]
},
- "note": "Orca 多 Agent 功能名,中文用「协同」(现状 21:2)。可见 bug:设置导航项写「协作」,点进去页面标题写「协同」。条件禁用:settings.contacts 里的「协作经历」是 collaboration history,属另一个语义,英文源不含独立 Collaboration 一词时不判违规。",
- "exempt": [
- "desktop:settings.contacts."
- ]
+ "note": "Agent 的派生概念,中文跟随 Agent 保留英文原词,不译「子代理」。「代理」在此条下按 whenEn=Subagent 登记:同一个中文词在 Agent / Subagent / Proxy 三处各有来源,只有按英文源区分,自动替换才知道该换成哪个词。ja / ko 沿用既有音译。"
},
{
- "id": "running",
+ "id": "thread",
"status": "decided",
- "en": "Running",
+ "en": "Thread",
"translations": {
- "zh-CN": "运行中",
- "ja": "実行中",
- "ko": "실행 중"
+ "zh-CN": "对话",
+ "ja": "スレッド",
+ "ko": "스레드"
},
"checkCase": false,
"alsoAllowed": {
"zh-CN": [
{
- "text": "正在运行",
- "when": "完整句子里作谓语时(\"Agent 正在运行\"),不是状态标签"
+ "text": "thread",
+ "when": "指 Codex 的 thread 这一外部系统概念时(导入历史、thread 上下文),保留英文"
+ },
+ {
+ "text": "评论",
+ "when": "指 GitHub PR 的 review thread 时,用「review 评论」"
}
]
},
"forbidden": {
"zh-CN": [
- {
- "text": "执行中",
- "whenEn": "Running"
- },
- {
- "text": "进行中",
- "whenEn": "Running"
- }
+ "线程"
]
},
- "note": "状态标签用「运行中」(现状 16:9)。条件禁用是必需的——「进行中」是 In Progress 的正确译法、「执行中」在别处也可能对,无条件禁会大面积误伤。mobile/devices 的自动化面板上「运行中 / 执行中 / 重跑中」三种写法同屏出现。"
+ "note": "全仓仅 8 处,按语境分四类,是「同一个词必须分场合翻译」的典型:①指产品内的对话 → 跟随 session 叫「对话」(已落地 3 处);②Codex 外部概念 → 保留 thread;③GitHub PR review thread →「review 评论」;④比喻用法 \"persistent work thread\" → 原译「工作线程」,中文有 OS 线程歧义,已改写为「持续推进的工作对话」。「线程」一律禁用。"
},
{
- "id": "dismiss",
+ "id": "usage",
"status": "decided",
- "en": "Dismiss",
+ "en": "Usage",
"translations": {
- "zh-CN": "关闭",
- "ja": "閉じる",
- "ko": "닫기"
+ "zh-CN": "用量",
+ "ja": "使用量",
+ "ko": "사용량"
},
- "checkCase": false,
"forbidden": {
"zh-CN": [
- {
- "text": "忽略",
- "whenEn": "Dismiss"
- },
- {
- "text": "知道了",
- "whenEn": "Dismiss"
- }
+ "使用情况",
+ "使用表现"
+ ],
+ "ja": [
+ "使用状況",
+ "利用状況"
+ ],
+ "ko": [
+ "사용 현황"
]
},
- "note": "中文用「关闭」(现状 6:4)。同一个 chat 模块里,errorBanner 写「关闭错误提示」、interruptedBanner 写「忽略此中断提示」。条件禁用:「忽略」是 Ignore 的正确译法、「知道了」是 Got it 的正确译法,只在英文源为 Dismiss 时才算违规。"
+ "note": "中文用「用量」(现状 37:6 压倒性)。「使用情况」「使用表现」是同义漂移,禁用。注意 usage 在英文里也有「用法」义(如 CLI usage),那属于另一个概念,不在本条约束范围。豁免遥测说明两处:那里的 usage 指「启动与留存情况」这类使用行为,不是计费口径的用量指标。硬套成「用量」会写出「启动与留存用量」这种不通的话——zh-CN 用的是「留存情况」+「使用环境」,ja/ko 的「継続利用状況」「지속 사용 현황」同理。",
+ "exempt": [
+ "desktop:settings.about.analyticsDescription",
+ "mobile/settings:legal.analyticsHint"
+ ]
},
{
- "id": "active",
- "status": "decided",
- "en": "Active",
+ "id": "voice-dictionary",
+ "status": "proposed",
+ "en": "Voice dictionary",
"translations": {
- "zh-CN": "活跃",
- "ja": "アクティブ",
- "ko": "활성"
+ "zh-CN": "语音词典",
+ "ja": "音声辞書",
+ "ko": "음성 사전"
},
- "checkCase": false,
- "alsoAllowed": {
- "zh-CN": [
- {
- "text": "生效中",
- "when": "计费语境(\"no active subscription\"→没有生效中的订阅),指订阅状态而非活跃度"
- }
- ]
- },
- "forbidden": {
- "zh-CN": [
- {
- "text": "活动",
- "whenEn": "Active"
- }
- ]
+ "note": "语音输入的用户自定义术语表(人名、产品名、代号与其常见误识别写法),在同账号的电脑之间自动同步、手机只读查看。当前先采用四语直译并登记为待讨论术语,避免与「自定义词典」「术语表」「用户词库」等说法混用。"
+ },
+ {
+ "id": "worker",
+ "status": "decided",
+ "en": "Worker",
+ "translations": {
+ "zh-CN": "Worker",
+ "ja": "Worker",
+ "ko": "Worker"
},
- "note": "对话 / 设备状态用「活跃」(现状 21:7)。mobile/devices 同一屏上筛选 chip 写「活跃」、指标磁贴写「活动」。条件禁用:「活动」是 Activity 的正确译法,无条件禁会误伤「活动记录」这类。豁免 Windows Computer Use 提示:那里的 active desktop 指「当前接收输入、显示目标应用的 Windows 桌面」,是 OS 概念,中文既定说法为「当前活动桌面」,与产品的活跃度无关。",
- "exempt": [
- "desktop:settings.computerUse.directControl.permissions.windowsHint"
- ]
+ "forbidden": {},
+ "note": "Orca 协同角色名,四语统一保留英文。这里只钉大小写形态:首字母大写 Worker。小写 worker 由 guard 的大小写规则单独覆盖(desktop 26:13 混用、mobile 一律小写)。"
},
{
"id": "worktree",
@@ -722,19 +746,6 @@
"exempt": [
"desktop:sessionShare.import.useWorktreeHint"
]
- },
- {
- "id": "directory",
- "status": "decided",
- "en": "Directory",
- "translations": {
- "zh-CN": "目录",
- "ja": "ディレクトリ",
- "ko": "디렉터리"
- },
- "checkCase": false,
- "forbidden": {},
- "note": "Directory 用「目录」(现状 96:4),Folder 用「文件夹」(37:20),两个英文词在中文里也分开。**本条刻意不设 forbidden**:英文侧自己就在一句话里混用二者(\"not a folder. Choose a project directory.\"、\"re-select the working directory and wait for the folder badge\"),而条件禁用是句子级匹配,区分不了句内哪个中文词对应哪个英文词——实测 4 处命中全是假阳性,那 4 条中文其实译得完全正确。要真正管住这对词,得先清理英文侧的 path / folder / directory 混用。此条目保留为文档指引,供人查阅。"
}
]
}
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 98228a6f97..364fda098b 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -80,6 +80,29 @@ export const DL_VOICE_CREDENTIAL_SYNC_CHANNEL = 'device-link:voice:credential-sy
*/
export const DL_VOICE_DICTIONARY_LEARNING_CHANNEL = 'device-link:voice:dictionary-learning';
+/**
+ * 手机端拉取被控桌面的语音词典快照(只读)。
+ *
+ * 桌面之间的词典靠 push 帧对等同步,但手机在后台不维持 WebSocket、收不到 push,
+ * 所以改为需要时主动拉一份。返回的是**只读投影**:词条文本 + 频次 + 别名,外加一个
+ * 版本向量(`stateVector`)供手机判断多台电脑的快照谁包含谁。化身、墓碑、抑制项、
+ * 时钟都不外泄 —— 手机不参与合并,不持有可写状态,避免移动端词典分叉。
+ *
+ * 符合准入判据:不依赖 event.sender、无本机 UI 副作用、词典真相在被控端。
+ *
+ * ## 已知限制:与电脑之间的同步不一致
+ *
+ * invoke 属于 relay 的 CONTROL_KINDS,转发前会校验目标的 remoteControlEnabled;
+ * 而电脑之间的词典同步走 push,不受该开关限制。结果是同一个功能有两套前提:用户
+ * 开了「词典同步」后电脑之间就通了,手机却还要额外打开「允许同账号设备控制本机」
+ * ——那个开关的语义是「允许别人操作我」,和「读一份词典」并不对应,用户撞上时基本
+ * 猜不到该去开什么。
+ *
+ * 后续可改为推送:桌面在 presence 看到手机上线时主动 push 只读投影,零配置且与
+ * 电脑之间同一条通道;本 channel 保留作为手机主动刷新的兜底。
+ */
+export const DL_VOICE_DICTIONARY_GET_CHANNEL = 'device-link:voice:dictionary:get';
+
/**
* M3 核心集:远程会话全生命周期(新建/发消息/事件流/审批/中断/运行时切换)+ 基础读模型。
* M4 将扩展 scheduler / orca worker / rewind / usage 等完整控制面。
@@ -208,6 +231,9 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [
DL_VOICE_CREDENTIAL_SYNC_CHANNEL,
// voice dictionary learning evidence 回写(被控端 dispatch 拦截执行,不落 ipcMain handler)。
DL_VOICE_DICTIONARY_LEARNING_CHANNEL,
+ // 手机拉取被控桌面的词典只读快照(被控端 dispatch 拦截执行,不落 ipcMain handler;
+ // 老被控端不识别时回 CHANNEL_NOT_ALLOWED,手机据此回退到「无词典」而不是报错)。
+ DL_VOICE_DICTIONARY_GET_CHANNEL,
];
/**
diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.ts
index 0e5ec17221..1d335cc783 100644
--- a/packages/device-link/src/protocol.ts
+++ b/packages/device-link/src/protocol.ts
@@ -64,7 +64,8 @@ export type DeviceLinkErrorCode = RelayErrorCode
| 'VOICE_TRANSCRIBE_FAILED' // 出方向手机语音转写失败(被控端下载音频 / ASR 出错)
| 'VOICE_CREDENTIAL_SYNC_FAILED' // 手机语音云端 ASR/refine 临时 credential 同步失败(历史,新桌面已不再返回)
| 'VOICE_CREDENTIAL_SYNC_REMOVED' // 穿透 credential 同步能力已下线:手机语音改走 Cindy 官方托管服务,旧手机据此提示升级
- | 'VOICE_DICTIONARY_LEARNING_FAILED'; // 手机语音词典学习 evidence 回写失败
+ | 'VOICE_DICTIONARY_LEARNING_FAILED' // 手机语音词典学习 evidence 回写失败
+ | 'VOICE_DICTIONARY_GET_FAILED'; // 手机拉取被控桌面词典快照失败(读同步状态出错)
/** 带结构化错误码的异常,贯穿 client / host 两层 */
export class DeviceLinkError extends Error {
diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.ts
index 28c14ed439..b827b657ed 100644
--- a/packages/maker-shared/src/deviceLinkContract.ts
+++ b/packages/maker-shared/src/deviceLinkContract.ts
@@ -6,6 +6,7 @@ export const DEVICE_LINK_MEDIA_FETCH_CHANNEL = 'device-link:media:fetch';
export const DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL = 'device-link:voice:transcribe';
export const DEVICE_LINK_VOICE_CREDENTIAL_SYNC_CHANNEL = 'device-link:voice:credential-sync';
export const DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL = 'device-link:voice:dictionary-learning';
+export const DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL = 'device-link:voice:dictionary:get';
export type MobileVoiceCredentialSyncAsr = {
provider: string;
@@ -65,6 +66,31 @@ export type MobileVoiceCredentialSyncResult = {
settings?: MobileVoiceCredentialSyncSettings;
};
+/**
+ * 手机拉取被控桌面词典的只读快照。
+ *
+ * 手机不参与 CRDT 合并 —— 它在后台不维持 WebSocket,拿不到对等同步的 push 帧,
+ * 也不该持有一份会分叉的可写词典。这里只投影 refine 真正用得上的字段。
+ */
+export type MobileVoiceDictionarySnapshotResult =
+ | {
+ ok: true;
+ entries: MobileVoiceCredentialSyncDictionaryEntry[];
+ /**
+ * 该桌面同步状态的版本向量:`{ nodeId: 该节点的最大 HLC }`。
+ *
+ * 手机同时拉多台电脑时用它判断哪一份**包含**了另一份。不能用响应到达时间
+ * (并发请求里慢的那个反而显得"更新"),也不能只比最大 HLC —— 两台电脑各自
+ * 新增了不同的词、还没来得及互相同步时,最大 HLC 大的那份并不包含另一份,
+ * 拿它当完整答案会漏词。老版本被控端不带这个字段,手机退回按到达时间比较。
+ */
+ stateVector?: Record<string, string>;
+ }
+ | {
+ ok: false;
+ error: string;
+ };
+
export type MobileVoiceDictionaryLearningRequest = {
source: 'mobile';
rawTranscriptText?: string;
@@ -265,6 +291,7 @@ export const MOBILE_REMOTE_INVOKE_CHANNELS = [
DEVICE_LINK_MEDIA_FETCH_CHANNEL,
DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL,
DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL,
+ DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL,
'maker:get-pending-interactions',
'maker:resolve-interaction',
'maker:get-context-usage',
diff --git a/packages/voice-input-core/src/__tests__/dictionarySyncDelete.test.ts b/packages/voice-input-core/src/__tests__/dictionarySyncDelete.test.ts
new file mode 100644
index 0000000000..14d8fbbc82
--- /dev/null
+++ b/packages/voice-input-core/src/__tests__/dictionarySyncDelete.test.ts
@@ -0,0 +1,301 @@
+/**
+ * 删除语义矩阵。
+ *
+ * 删除是这套同步里最容易做错的一环:做浅了,一台设备删掉的词会被另一台的旧状态
+ * 复活;做深了(比如按主键记永久墓碑),用户删掉之后重新添加的同名词又会被自己
+ * 的旧墓碑压住。这里把两个方向的失败模式都钉住。
+ *
+ * 另外 desktop 单机语义在同步之后必须保持不变:
+ * - 删自动词条 → 写抑制集合,后台学习不再把它加回来;
+ * - 删手动词条 → 不写抑制集合,之后自动学习可以合法地重新学出来。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ DEFAULT_TOMBSTONE_TTL_MS,
+ addManualEntry,
+ createEmptySyncState,
+ createHlcClock,
+ deleteTerms,
+ gcTombstones,
+ materializeDictionary,
+ materializedEntryId,
+ mergeSyncStates,
+ recordLearningEvent,
+ termKeyFromMaterializedId,
+ type HlcClock,
+ type VoiceDictionarySyncState,
+} from '../dictionary-sync';
+
+interface Device {
+ state: VoiceDictionarySyncState;
+ clock: HlcClock;
+}
+
+function device(nodeId: string, wallMs = 1_000): Device {
+ return { state: createEmptySyncState(), clock: createHlcClock(nodeId, wallMs) };
+}
+
+function learn(
+ target: Device,
+ text: string,
+ nowMs: number,
+ stage: 'candidate' | 'entry' = 'entry',
+ aliases: string[] = [],
+): void {
+ const result = recordLearningEvent(target.state, target.clock, { text, aliases, stage, nowMs });
+ target.state = result.state;
+ target.clock = result.clock;
+}
+
+function addManual(target: Device, text: string, nowMs: number): void {
+ const result = addManualEntry(target.state, target.clock, { text, nowMs });
+ target.state = result.state;
+ target.clock = result.clock;
+}
+
+function remove(target: Device, termKey: string, nowMs: number): void {
+ const result = deleteTerms(target.state, target.clock, { termKeys: [termKey], nowMs });
+ target.state = result.state;
+ target.clock = result.clock;
+}
+
+function entryTexts(state: VoiceDictionarySyncState): string[] {
+ return materializeDictionary(state).entries.map((entry) => entry.text);
+}
+
+function candidateTexts(state: VoiceDictionarySyncState): string[] {
+ return materializeDictionary(state).candidates.map((candidate) => candidate.text);
+}
+
+describe('dictionary sync — 删除传播', () => {
+ it('一端删除,离线数天的另一端上线后同步消失', () => {
+ const a = device('a');
+ const b = device('b');
+ learn(a, 'LiteLLM', 1_000);
+ b.state = mergeSyncStates(b.state, a.state);
+ expect(entryTexts(b.state)).toEqual(['LiteLLM']);
+
+ remove(a, 'litellm', 2_000);
+ // B 离线三天后才收到 A 的状态。
+ b.state = mergeSyncStates(b.state, a.state);
+ expect(entryTexts(b.state)).toEqual([]);
+ // 反向合并同样不会把它带回来。
+ a.state = mergeSyncStates(a.state, b.state);
+ expect(entryTexts(a.state)).toEqual([]);
+ });
+
+ it('删除赢过离线期间的后台学习:被删化身上的新增计数一并失效', () => {
+ const a = device('a');
+ const b = device('b');
+ learn(a, 'LiteLLM', 1_000);
+ b.state = mergeSyncStates(b.state, a.state);
+
+ // A 删除的同时,B 在离线状态下对同一条词继续学习。
+ remove(a, 'litellm', 2_000);
+ learn(b, 'LiteLLM', 2_100);
+ learn(b, 'LiteLLM', 2_200);
+
+ const merged = mergeSyncStates(a.state, b.state);
+ expect(entryTexts(merged)).toEqual([]);
+ expect(materializeDictionary(mergeSyncStates(b.state, a.state))).toEqual(
+ materializeDictionary(merged),
+ );
+ });
+
+ it('删除手动词条同样跨设备传播 —— 这条路径只有墓碑一道保险', () => {
+ // 自动词条的删除有「墓碑 + 抑制」双保险,单看它测不出墓碑传播是否真的生效;
+ // 手动词条不写抑制,是墓碑传播的唯一验证路径。
+ const a = device('a');
+ const b = device('b');
+ addManual(a, 'Cindy', 1_000);
+ b.state = mergeSyncStates(b.state, a.state);
+ expect(entryTexts(b.state)).toEqual(['Cindy']);
+
+ remove(a, 'cindy', 2_000);
+ expect(materializeDictionary(a.state).suppressedTexts).toEqual([]);
+
+ b.state = mergeSyncStates(b.state, a.state);
+ expect(entryTexts(b.state)).toEqual([]);
+ });
+
+ it('删除自动词条会把抑制同步到全网,后台学习不再重建', () => {
+ const a = device('a');
+ const b = device('b');
+ learn(a, 'Orca', 1_000);
+ b.state = mergeSyncStates(b.state, a.state);
+ remove(a, 'orca', 2_000);
+ b.state = mergeSyncStates(b.state, a.state);
+
+ // B 收到抑制之后再学习:不重建。
+ learn(b, 'Orca', 3_000);
+ expect(entryTexts(b.state)).toEqual([]);
+ expect(candidateTexts(b.state)).toEqual([]);
+ expect(materializeDictionary(b.state).suppressedTexts).toEqual(['Orca']);
+ });
+
+ it('被抑制的词在别处残留自动化身时,学习不再改动状态(不触发无谓的写盘与广播)', () => {
+ const a = device('a');
+ const b = device('b');
+ learn(a, 'Orca', 1_000);
+ b.state = mergeSyncStates(b.state, a.state);
+ remove(a, 'orca', 2_000);
+
+ // B 先在本地独立学出一个自己的化身,再收到 A 的删除与抑制。
+ learn(b, 'Orca', 2_100);
+ b.state = mergeSyncStates(b.state, a.state);
+ expect(entryTexts(b.state)).toEqual([]);
+
+ const before = b.state;
+ const result = recordLearningEvent(b.state, b.clock, { text: 'Orca', stage: 'entry', nowMs: 3_000 });
+ expect(result.changed).toBe(false);
+ expect(result.state).toBe(before);
+ });
+
+ it('删除手动词条不写抑制,之后自动学习可以重新学出来', () => {
+ const a = device('a');
+ addManual(a, 'Cindy', 1_000);
+ remove(a, 'cindy', 2_000);
+ expect(entryTexts(a.state)).toEqual([]);
+ expect(materializeDictionary(a.state).suppressedTexts).toEqual([]);
+
+ learn(a, 'Cindy', 3_000);
+ expect(entryTexts(a.state)).toEqual(['Cindy']);
+ // 重新学出来的是全新化身,计数从零起。
+ expect(materializeDictionary(a.state).entries[0].frequency).toBe(1);
+ });
+
+ it('删除后重新手动添加同名词不会被旧墓碑压住', () => {
+ const a = device('a');
+ learn(a, 'Orca', 1_000);
+ learn(a, 'Orca', 1_100);
+ remove(a, 'orca', 2_000);
+ expect(entryTexts(a.state)).toEqual([]);
+
+ // 手动添加不受抑制集合限制 —— 用户显式要它回来。
+ addManual(a, 'Orca', 3_000);
+ const materialized = materializeDictionary(a.state);
+ expect(materialized.entries.map((entry) => entry.text)).toEqual(['Orca']);
+ expect(materialized.entries[0].source).toBe('manual');
+ // 旧化身的计数没有被带回来。
+ expect(materialized.entries[0].frequency).toBe(1);
+ });
+
+ it('删除与并发重新添加:add-wins,用户新表达的意图胜出', () => {
+ const a = device('a');
+ const b = device('b');
+ learn(a, 'Orca', 1_000);
+ b.state = mergeSyncStates(b.state, a.state);
+
+ remove(a, 'orca', 2_000);
+ addManual(b, 'Orca', 2_000); // B 并不知道 A 删了
+
+ const forward = mergeSyncStates(a.state, b.state);
+ const backward = mergeSyncStates(b.state, a.state);
+ expect(entryTexts(forward)).toEqual(['Orca']);
+ expect(materializeDictionary(forward)).toEqual(materializeDictionary(backward));
+ });
+
+ it('删除词条会一并带走同名候选词', () => {
+ const a = device('a');
+ learn(a, 'device-link', 1_000, 'candidate');
+ expect(candidateTexts(a.state)).toEqual(['device-link']);
+ remove(a, 'device-link', 2_000);
+ expect(candidateTexts(a.state)).toEqual([]);
+ expect(entryTexts(a.state)).toEqual([]);
+ });
+
+ it('删除操作的合并结果与合并顺序无关', () => {
+ const a = device('a');
+ const b = device('b');
+ const c = device('c');
+ learn(a, 'LiteLLM', 1_000);
+ learn(a, 'Orca', 1_010);
+ b.state = mergeSyncStates(b.state, a.state);
+ c.state = mergeSyncStates(c.state, a.state);
+
+ remove(b, 'litellm', 2_000);
+ learn(c, 'LiteLLM', 2_050);
+ addManual(c, 'Orca', 2_060);
+
+ const order1 = mergeSyncStates(mergeSyncStates(a.state, b.state), c.state);
+ const order2 = mergeSyncStates(mergeSyncStates(c.state, b.state), a.state);
+ const order3 = mergeSyncStates(a.state, mergeSyncStates(b.state, c.state));
+ expect(materializeDictionary(order1)).toEqual(materializeDictionary(order2));
+ expect(materializeDictionary(order1)).toEqual(materializeDictionary(order3));
+ });
+
+ it('重复投递删除状态不会把词条复活,也不会改变结果', () => {
+ const a = device('a');
+ const b = device('b');
+ learn(a, 'LiteLLM', 1_000);
+ b.state = mergeSyncStates(b.state, a.state);
+ const staleSnapshot = b.state; // 删除之前的旧快照,稍后反复送达
+ remove(a, 'litellm', 2_000);
+ b.state = mergeSyncStates(b.state, a.state);
+
+ for (let round = 0; round < 20; round += 1) {
+ b.state = mergeSyncStates(b.state, staleSnapshot);
+ }
+ expect(entryTexts(b.state)).toEqual([]);
+ });
+});
+
+describe('dictionary sync — 词条 id 与删除入口', () => {
+ it('物化 id 稳定且可翻译回合并主键', () => {
+ const a = device('a');
+ learn(a, 'Vibe Coding', 1_000);
+ const entry = materializeDictionary(a.state).entries[0];
+ expect(entry.id).toBe(materializedEntryId('vibe coding'));
+
+ const key = termKeyFromMaterializedId(a.state, entry.id);
+ expect(key).toBe('vibe coding');
+ remove(a, key!, 2_000);
+ expect(entryTexts(a.state)).toEqual([]);
+ });
+
+ it('未知 id 翻译为 null,不会误伤别的词条', () => {
+ const a = device('a');
+ learn(a, 'Vibe Coding', 1_000);
+ expect(termKeyFromMaterializedId(a.state, materializedEntryId('nonexistent'))).toBeNull();
+ expect(termKeyFromMaterializedId(a.state, 'dict-1700000000-legacy')).toBeNull();
+ expect(termKeyFromMaterializedId(a.state, ' ')).toBeNull();
+ });
+
+ it('同一个词在不同设备上物化出相同 id', () => {
+ const a = device('a');
+ const b = device('b', 9_999);
+ learn(a, 'Vibe Coding', 1_000);
+ learn(b, 'vibe coding', 5_000);
+ const idA = materializeDictionary(a.state).entries[0].id;
+ const idB = materializeDictionary(b.state).entries[0].id;
+ expect(idA).toBe(idB);
+ });
+});
+
+describe('dictionary sync — 墓碑回收', () => {
+ it('回收过期墓碑时连同被覆盖的化身一起删除,不会复活词条', () => {
+ const a = device('a');
+ learn(a, 'LiteLLM', 1_000);
+ remove(a, 'litellm', 2_000);
+
+ const collected = gcTombstones(a.state, {
+ nowMs: 2_000 + DEFAULT_TOMBSTONE_TTL_MS + 1,
+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,
+ });
+ expect(entryTexts(collected)).toEqual([]);
+ // 化身必须随墓碑一起消失 —— 只删墓碑会让词条立刻复活。
+ expect(Object.keys(collected.records['litellm']?.incarnations ?? {})).toEqual([]);
+ // 抑制不参与回收,自动词条仍然不会被后台学习重建。
+ expect(materializeDictionary(collected).suppressedTexts).toEqual(['LiteLLM']);
+ });
+
+ it('未到期的墓碑不被回收', () => {
+ const a = device('a');
+ learn(a, 'LiteLLM', 1_000);
+ remove(a, 'litellm', 2_000);
+ const collected = gcTombstones(a.state, { nowMs: 3_000, ttlMs: DEFAULT_TOMBSTONE_TTL_MS });
+ expect(collected).toEqual(a.state);
+ });
+});
diff --git a/packages/voice-input-core/src/__tests__/dictionarySyncFrameValidation.test.ts b/packages/voice-input-core/src/__tests__/dictionarySyncFrameValidation.test.ts
new file mode 100644
index 0000000000..cd30e628c8
--- /dev/null
+++ b/packages/voice-input-core/src/__tests__/dictionarySyncFrameValidation.test.ts
@@ -0,0 +1,151 @@
+/**
+ * 入站帧的时间戳必须是规范 HLC。
+ *
+ * 定序靠字符串字典序,前提是所有时间戳都符合定长格式。`~`(码位高于所有 base36
+ * 字符)构成的假时间戳会在每一次 LWW 比较里胜出,而且它会被持久化并继续同步出去 ——
+ * 那个字段此后在所有设备上都改不动了。这类帧必须在进合并之前就被挡住。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ addManualEntry,
+ buildStateVersionVector,
+ createEmptySyncState,
+ createHlcClock,
+ isCanonicalHlc,
+ isValidSyncState,
+ materializeDictionary,
+ mergeSyncStates,
+ renameTerm,
+ versionVectorDominates,
+} from '../dictionary-sync';
+
+function validState() {
+ const added = addManualEntry(createEmptySyncState(), createHlcClock('node-a', 1_000), {
+ text: 'Cindy',
+ nowMs: 1_000,
+ });
+ return JSON.parse(JSON.stringify(added.state)) as ReturnType<typeof createEmptySyncState>;
+}
+
+describe('规范 HLC', () => {
+ it('认得出合法与非法形状', () => {
+ expect(isCanonicalHlc('0000000rs4.0000.node-a')).toBe(true);
+ expect(isCanonicalHlc('~~~~')).toBe(false);
+ expect(isCanonicalHlc('0000000rs4.0000.')).toBe(false); // nodeId 为空
+ expect(isCanonicalHlc('0000000rs4.0000.a.b')).toBe(false); // nodeId 含 '.'
+ expect(isCanonicalHlc('0000000rs4.000.node-a')).toBe(false); // counter 段长度不对
+ expect(isCanonicalHlc('ZZZZZZZZZZ.0000.node-a')).toBe(false); // 大写不是 base36 输出
+ expect(isCanonicalHlc(42)).toBe(false);
+ });
+
+ it('假时间戳的帧整帧被拒,不会污染本机词典', () => {
+ const state = validState();
+ const key = Object.keys(state.records)[0];
+ const tag = Object.keys(state.records[key].incarnations)[0];
+ state.records[key].incarnations[tag].textStamp = '~~~~';
+
+ expect(isValidSyncState(state)).toBe(false);
+ });
+
+ it('化身键与自称 tag 不一致的帧被拒', () => {
+ const state = validState();
+ const key = Object.keys(state.records)[0];
+ const tag = Object.keys(state.records[key].incarnations)[0];
+ const incarnation = state.records[key].incarnations[tag];
+ delete state.records[key].incarnations[tag];
+ state.records[key].incarnations['0000000rs4.0001.node-b'] = incarnation;
+
+ expect(isValidSyncState(state)).toBe(false);
+ });
+
+ it('拒帧之后本机仍能正常改这个词 —— 假戳没有留下来', () => {
+ const added = addManualEntry(createEmptySyncState(), createHlcClock('node-a', 1_000), {
+ text: 'Cindy',
+ nowMs: 1_000,
+ });
+ const renamed = renameTerm(added.state, added.clock, {
+ termKey: 'cindy',
+ nextText: 'Cindy 客户端',
+ nowMs: 2_000,
+ });
+ expect(materializeDictionary(renamed.state).entries[0].text).toBe('Cindy 客户端');
+ });
+});
+
+describe('版本向量', () => {
+ it('合并后的状态包含两边 —— 逐节点 ≥ 双方', () => {
+ const a = addManualEntry(createEmptySyncState(), createHlcClock('node-a', 1_000), {
+ text: 'foo',
+ nowMs: 1_000,
+ });
+ const b = addManualEntry(createEmptySyncState(), createHlcClock('node-b', 2_000), {
+ text: 'bar',
+ nowMs: 2_000,
+ });
+ const merged = mergeSyncStates(a.state, b.state);
+
+ const vectorA = buildStateVersionVector(a.state);
+ const vectorB = buildStateVersionVector(b.state);
+ const vectorMerged = buildStateVersionVector(merged);
+
+ expect(versionVectorDominates(vectorMerged, vectorA)).toBe(true);
+ expect(versionVectorDominates(vectorMerged, vectorB)).toBe(true);
+ // 并发的两份互不包含 —— 这正是「只比最大 HLC」判不出来的情况。
+ expect(versionVectorDominates(vectorA, vectorB)).toBe(false);
+ expect(versionVectorDominates(vectorB, vectorA)).toBe(false);
+ });
+
+ it('向量对合并单调:再合并一次不会让它变小', () => {
+ const a = addManualEntry(createEmptySyncState(), createHlcClock('node-a', 1_000), {
+ text: 'foo',
+ nowMs: 1_000,
+ });
+ const once = buildStateVersionVector(a.state);
+ const twice = buildStateVersionVector(mergeSyncStates(a.state, a.state));
+ expect(versionVectorDominates(twice, once)).toBe(true);
+ expect(versionVectorDominates(once, twice)).toBe(true);
+ });
+});
+
+describe('数值字段的校验', () => {
+ function poison(mutate: (incarnation: Record<string, unknown>) => void) {
+ const state = validState();
+ const key = Object.keys(state.records)[0];
+ const tag = Object.keys(state.records[key].incarnations)[0];
+ mutate(state.records[key].incarnations[tag] as unknown as Record<string, unknown>);
+ return state;
+ }
+
+ it('时间戳必须有限 —— NaN / Infinity 会顺着 Math.min/max 污染整条词条', () => {
+ expect(isValidSyncState(poison((item) => { item.createdAt = Number.NaN; }))).toBe(false);
+ expect(isValidSyncState(poison((item) => { item.updatedAt = Number.POSITIVE_INFINITY; }))).toBe(false);
+ expect(isValidSyncState(poison((item) => { item.createdAt = -1; }))).toBe(false);
+ });
+
+ it('别名的 lastSeenAt 同样要求有限', () => {
+ const state = validState();
+ const key = Object.keys(state.records)[0];
+ const tag = Object.keys(state.records[key].incarnations)[0];
+ const incarnation = state.records[key].incarnations[tag];
+ incarnation.aliases = {
+ 'web coding': {
+ text: 'web coding',
+ textStamp: incarnation.textStamp,
+ counters: { 'node-a': 1 },
+ lastSeenAt: Number.NaN,
+ },
+ };
+ expect(isValidSyncState(state)).toBe(false);
+ });
+
+ it('计数必须是非负安全整数', () => {
+ expect(isValidSyncState(poison((item) => { item.counters = { 'node-a': -3 }; }))).toBe(false);
+ expect(isValidSyncState(poison((item) => { item.counters = { 'node-a': 1.5 }; }))).toBe(false);
+ expect(isValidSyncState(poison((item) => { item.counters = { 'node-a': Number.MAX_SAFE_INTEGER + 2 }; })))
+ .toBe(false);
+ // 0 是合法的:别名可能被减到 0 之后仍留在结构里。
+ expect(isValidSyncState(poison((item) => { item.counters = { 'node-a': 0 }; }))).toBe(true);
+ });
+});
diff --git a/packages/voice-input-core/src/__tests__/dictionarySyncMaterialize.test.ts b/packages/voice-input-core/src/__tests__/dictionarySyncMaterialize.test.ts
new file mode 100644
index 0000000000..f31dc0ba25
--- /dev/null
+++ b/packages/voice-input-core/src/__tests__/dictionarySyncMaterialize.test.ts
@@ -0,0 +1,176 @@
+/**
+ * 物化的确定性与上限行为。
+ *
+ * 上限裁决收在物化里而不是交给下游 normalize,是为了两件事:全网算出同一份结果,
+ * 以及**被挤出上限的词条绝不生成墓碑**。后者是一个真实的自伤风险:截断产生的
+ * 「词条消失」如果被回收逻辑当成用户删除,就会广播墓碑批量误删全网词条。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ DEFAULT_MATERIALIZE_LIMITS,
+ addManualEntry,
+ createEmptySyncState,
+ createHlcClock,
+ deleteTerms,
+ materializeDictionary,
+ mergeSyncStates,
+ recordLearningEvent,
+ type HlcClock,
+ type VoiceDictionarySyncState,
+} from '../dictionary-sync';
+
+interface Device {
+ state: VoiceDictionarySyncState;
+ clock: HlcClock;
+}
+
+function device(nodeId: string, wallMs = 1_000): Device {
+ return { state: createEmptySyncState(), clock: createHlcClock(nodeId, wallMs) };
+}
+
+function learn(target: Device, text: string, nowMs: number, aliases: string[] = []): void {
+ const result = recordLearningEvent(target.state, target.clock, {
+ text,
+ aliases,
+ stage: 'entry',
+ nowMs,
+ });
+ target.state = result.state;
+ target.clock = result.clock;
+}
+
+describe('dictionary sync — 物化上限', () => {
+ it('超出上限的词条只是不物化,不产生墓碑,状态里仍然保留', () => {
+ const a = device('a');
+ for (let index = 0; index < 6; index += 1) {
+ // 频次递减,确保裁决顺序确定。
+ for (let times = 0; times <= index; times += 1) learn(a, `term-${index}`, 1_000 + index * 10 + times);
+ }
+
+ const limits = { ...DEFAULT_MATERIALIZE_LIMITS, maxEntries: 3 };
+ const materialized = materializeDictionary(a.state, limits);
+ expect(materialized.entries.map((entry) => entry.text)).toEqual(['term-5', 'term-4', 'term-3']);
+
+ // 状态里 6 条都在,而且一个墓碑都没有。
+ expect(Object.keys(a.state.records)).toHaveLength(6);
+ for (const record of Object.values(a.state.records)) {
+ expect(Object.keys(record.tombstones)).toEqual([]);
+ }
+
+ // 频次涨回来就重新出现,不需要任何恢复逻辑。
+ for (let times = 0; times < 5; times += 1) learn(a, 'term-0', 2_000 + times);
+ expect(materializeDictionary(a.state, limits).entries.map((entry) => entry.text)).toContain('term-0');
+ });
+
+ it('上限裁决在不同设备上结果一致,与词条写入顺序无关', () => {
+ const a = device('a');
+ const b = device('b', 5_000);
+ const terms = ['alpha', 'bravo', 'charlie', 'delta'];
+ terms.forEach((term, index) => {
+ for (let times = 0; times <= index; times += 1) learn(a, term, 1_000 + index * 10 + times);
+ });
+ [...terms].reverse().forEach((term, index) => {
+ learn(b, term, 6_000 + index);
+ });
+
+ const limits = { ...DEFAULT_MATERIALIZE_LIMITS, maxEntries: 2 };
+ const merged1 = mergeSyncStates(a.state, b.state);
+ const merged2 = mergeSyncStates(b.state, a.state);
+ expect(materializeDictionary(merged1, limits)).toEqual(materializeDictionary(merged2, limits));
+ });
+
+ it('频次并列时按主键做确定性兜底排序', () => {
+ const a = device('a');
+ // 同一毫秒、同一频次:排序只能靠主键兜底,否则两台设备可能截出不同结果。
+ learn(a, 'zulu', 1_000);
+ learn(a, 'alpha', 1_000);
+ const limits = { ...DEFAULT_MATERIALIZE_LIMITS, maxEntries: 1 };
+ expect(materializeDictionary(a.state, limits).entries[0].text).toBe('alpha');
+ });
+
+ it('别名超过上限时按计数截断,并保持跨设备一致', () => {
+ const a = device('a');
+ const aliases = Array.from({ length: 12 }, (_, index) => `alias-${index}`);
+ // 让 alias-0 出现次数最多,其余递减。
+ aliases.forEach((alias, index) => {
+ for (let times = 0; times < aliases.length - index; times += 1) {
+ learn(a, 'Cindy', 1_000 + index * 20 + times, [alias]);
+ }
+ });
+ const materialized = materializeDictionary(a.state);
+ expect(materialized.entries[0].aliases).toHaveLength(DEFAULT_MATERIALIZE_LIMITS.maxAliases);
+ expect(materialized.entries[0].aliases[0].text).toBe('alias-0');
+ const counts = materialized.entries[0].aliases.map((alias) => alias.count);
+ expect([...counts].sort((x, y) => y - x)).toEqual(counts);
+ });
+});
+
+describe('dictionary sync — 物化语义', () => {
+ it('抑制只压制自动词条,手动词条照常显示', () => {
+ const a = device('a');
+ learn(a, 'Orca', 1_000);
+ const deleted = deleteTerms(a.state, a.clock, { termKeys: ['orca'], nowMs: 2_000 });
+ a.state = deleted.state;
+ a.clock = deleted.clock;
+ expect(materializeDictionary(a.state).suppressedTexts).toEqual(['Orca']);
+
+ // 抑制仍在,但用户手动把它加了回来 —— 手动词条不受抑制影响。
+ const added = addManualEntry(a.state, a.clock, { text: 'Orca', nowMs: 3_000 });
+ a.state = added.state;
+ const materialized = materializeDictionary(a.state);
+ expect(materialized.entries.map((entry) => entry.text)).toEqual(['Orca']);
+ expect(materialized.suppressedTexts).toEqual(['Orca']);
+ });
+
+ it('同一个词只出现在 entries 或 candidates 之一', () => {
+ const a = device('a');
+ const candidate = recordLearningEvent(a.state, a.clock, {
+ text: 'device-link',
+ stage: 'candidate',
+ nowMs: 1_000,
+ });
+ a.state = candidate.state;
+ a.clock = candidate.clock;
+ expect(materializeDictionary(a.state).candidates.map((item) => item.text)).toEqual(['device-link']);
+ expect(materializeDictionary(a.state).entries).toEqual([]);
+
+ const promoted = recordLearningEvent(a.state, a.clock, {
+ text: 'device-link',
+ stage: 'entry',
+ nowMs: 1_100,
+ });
+ a.state = promoted.state;
+ expect(materializeDictionary(a.state).candidates).toEqual([]);
+ expect(materializeDictionary(a.state).entries.map((item) => item.text)).toEqual(['device-link']);
+ });
+
+ it('一端手动确认过的词条,合并后来源保持 manual', () => {
+ const a = device('a');
+ const b = device('b', 4_000);
+ learn(a, 'Cindy', 1_000);
+ b.state = mergeSyncStates(b.state, a.state);
+ const added = addManualEntry(b.state, b.clock, { text: 'Cindy', nowMs: 5_000 });
+ b.state = added.state;
+
+ // 之后 A 继续自动学习,也不会把来源退回 automatic。
+ learn(a, 'Cindy', 6_000);
+ const merged = mergeSyncStates(a.state, b.state);
+ expect(materializeDictionary(merged).entries[0].source).toBe('manual');
+ });
+
+ it('展示文本取最新写法,且两端一致', () => {
+ const a = device('a');
+ const b = device('b', 4_000);
+ learn(a, 'litellm', 1_000);
+ b.state = mergeSyncStates(b.state, a.state);
+ const renamed = addManualEntry(b.state, b.clock, { text: 'LiteLLM', nowMs: 5_000 });
+ b.state = renamed.state;
+
+ const forward = materializeDictionary(mergeSyncStates(a.state, b.state));
+ const backward = materializeDictionary(mergeSyncStates(b.state, a.state));
+ expect(forward.entries[0].text).toBe('LiteLLM');
+ expect(forward).toEqual(backward);
+ });
+});
diff --git a/packages/voice-input-core/src/__tests__/dictionarySyncMerge.test.ts b/packages/voice-input-core/src/__tests__/dictionarySyncMerge.test.ts
new file mode 100644
index 0000000000..98cf15eccb
--- /dev/null
+++ b/packages/voice-input-core/src/__tests__/dictionarySyncMerge.test.ts
@@ -0,0 +1,377 @@
+/**
+ * 合并核心的性质测试。
+ *
+ * 这里刻意不是场景枚举,而是用固定种子的伪随机器把「多设备 × 随机事件 × 随机
+ * 同步拓扑 × 丢帧重帧乱序」跑成千上万种组合,断言两类性质:
+ *
+ * 1. 代数性质:幂等 / 可交换 / 可结合 —— 保证同步链路不需要可靠投递。
+ * 2. 守恒性质:任意同步历史之后,词条显示频次**恰好等于**全局真实事件数 ——
+ * 直接盯防「词典随同步次数重复增长」这一类 bug。
+ *
+ * 种子固定,失败可复现;不引入 fast-check 之类新依赖。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ addManualEntry,
+ createEmptySyncState,
+ createHlcClock,
+ findMaxHlc,
+ materializeDictionary,
+ mergeSyncStates,
+ observeHlc,
+ recordLearningEvent,
+ type HlcClock,
+ type VoiceDictionarySyncState,
+} from '../dictionary-sync';
+
+/** mulberry32:小、快、确定性好的种子伪随机器。 */
+function createRandom(seed: number): () => number {
+ let state = seed >>> 0;
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0;
+ let t = state;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+const TERMS = ['Vibe Coding', 'LiteLLM', 'Cindy', 'Orca', '语音输入', 'device-link'];
+const ALIASES: Record<string, string[]> = {
+ 'Vibe Coding': ['web coding', '外部 coding'],
+ LiteLLM: ['light LLM'],
+ Cindy: ['sindy', '辛迪'],
+ Orca: ['okra'],
+ 语音输入: ['语音数入'],
+ 'device-link': ['device link'],
+};
+
+interface Device {
+ id: string;
+ state: VoiceDictionarySyncState;
+ clock: HlcClock;
+}
+
+function createDevice(index: number): Device {
+ return {
+ id: `node-${index}`,
+ state: createEmptySyncState(),
+ clock: createHlcClock(`node-${index}`, 1_700_000_000_000),
+ };
+}
+
+/** 单向投递:把 from 的当前状态合进 to(模拟一帧 push 送达)。 */
+function deliver(to: Device, from: Device, nowMs: number): void {
+ const snapshot = from.state;
+ to.state = mergeSyncStates(to.state, snapshot);
+ const max = findMaxHlc(snapshot);
+ if (max) to.clock = observeHlc(to.clock, max, nowMs);
+}
+
+interface SimulationResult {
+ devices: Device[];
+ /** termKey → 全局真实学习事件数。 */
+ truth: Map<string, number>;
+}
+
+function simulate(seed: number, deviceCount: number, steps: number): SimulationResult {
+ const random = createRandom(seed);
+ const devices = Array.from({ length: deviceCount }, (_, index) => createDevice(index));
+ const truth = new Map<string, number>();
+ // 送达队列里保留旧快照,用来制造「乱序 + 迟到 + 重复投递」。
+ const inFlight: Array<{ to: number; state: VoiceDictionarySyncState }> = [];
+ let nowMs = 1_700_000_000_000;
+
+ for (let step = 0; step < steps; step += 1) {
+ nowMs += Math.floor(random() * 5);
+ const roll = random();
+ const deviceIndex = Math.floor(random() * deviceCount);
+ const device = devices[deviceIndex];
+
+ if (roll < 0.5) {
+ const term = TERMS[Math.floor(random() * TERMS.length)];
+ const stage = random() < 0.4 ? 'entry' : 'candidate';
+ const result = recordLearningEvent(device.state, device.clock, {
+ text: term,
+ aliases: ALIASES[term],
+ stage,
+ nowMs,
+ });
+ device.state = result.state;
+ device.clock = result.clock;
+ if (result.changed) {
+ const key = term.toLowerCase();
+ truth.set(key, (truth.get(key) ?? 0) + 1);
+ }
+ continue;
+ }
+
+ if (roll < 0.75) {
+ // 立即投递:模拟设备在线时的即时同步。
+ const targetIndex = Math.floor(random() * deviceCount);
+ if (targetIndex !== deviceIndex) deliver(devices[targetIndex], device, nowMs);
+ continue;
+ }
+
+ if (roll < 0.9) {
+ // 把当前快照丢进队列,稍后(可能很久之后)再送达,并且可能送多次。
+ const targetIndex = Math.floor(random() * deviceCount);
+ if (targetIndex !== deviceIndex) inFlight.push({ to: targetIndex, state: device.state });
+ continue;
+ }
+
+ if (inFlight.length > 0) {
+ const pick = Math.floor(random() * inFlight.length);
+ const frame = inFlight[pick];
+ devices[frame.to].state = mergeSyncStates(devices[frame.to].state, frame.state);
+ // 一半概率留在队列里,制造重复投递;另一半才真正出队(模拟丢帧则是永不出队)。
+ if (random() < 0.5) inFlight.splice(pick, 1);
+ }
+ }
+
+ // 收敛:全部两两同步若干轮,直到任意设备都见过所有状态。
+ for (let round = 0; round < deviceCount + 1; round += 1) {
+ for (const to of devices) {
+ for (const from of devices) {
+ if (to !== from) deliver(to, from, (nowMs += 1));
+ }
+ }
+ }
+
+ return { devices, truth };
+}
+
+function readTotals(state: VoiceDictionarySyncState): Map<string, number> {
+ const materialized = materializeDictionary(state);
+ const totals = new Map<string, number>();
+ for (const entry of materialized.entries) totals.set(entry.text.toLowerCase(), entry.frequency);
+ for (const candidate of materialized.candidates) {
+ totals.set(candidate.text.toLowerCase(), candidate.evidenceCount);
+ }
+ return totals;
+}
+
+describe('dictionary sync — 代数性质', () => {
+ const seeds = [1, 7, 42, 1337, 90210];
+
+ it('幂等:merge(a, a) === a', () => {
+ for (const seed of seeds) {
+ const { devices } = simulate(seed, 3, 120);
+ for (const device of devices) {
+ expect(mergeSyncStates(device.state, device.state)).toEqual(device.state);
+ }
+ }
+ });
+
+ it('可交换:merge(a, b) === merge(b, a)', () => {
+ for (const seed of seeds) {
+ const { devices } = simulate(seed, 3, 120);
+ const [a, b] = devices;
+ expect(mergeSyncStates(a.state, b.state)).toEqual(mergeSyncStates(b.state, a.state));
+ }
+ });
+
+ it('可结合:merge(merge(a, b), c) === merge(a, merge(b, c))', () => {
+ for (const seed of seeds) {
+ const { devices } = simulate(seed, 3, 120);
+ const [a, b, c] = devices;
+ expect(mergeSyncStates(mergeSyncStates(a.state, b.state), c.state)).toEqual(
+ mergeSyncStates(a.state, mergeSyncStates(b.state, c.state)),
+ );
+ }
+ });
+
+ it('收敛:任意同步历史之后所有设备物化结果一致', () => {
+ for (const seed of seeds) {
+ const { devices } = simulate(seed, 4, 400);
+ const reference = materializeDictionary(devices[0].state);
+ for (const device of devices.slice(1)) {
+ expect(materializeDictionary(device.state)).toEqual(reference);
+ }
+ }
+ });
+});
+
+describe('dictionary sync — 频次守恒(防重复增长)', () => {
+ it('显示频次恰好等于全局真实事件数,与同步次数、拓扑、重复投递无关', () => {
+ for (const seed of [3, 11, 29, 101, 555, 8_192]) {
+ const { devices, truth } = simulate(seed, 4, 600);
+ for (const device of devices) {
+ const totals = readTotals(device.state);
+ expect(totals.size).toBe(truth.size);
+ for (const [key, expected] of truth) {
+ expect(`${key}=${totals.get(key)}`).toBe(`${key}=${expected}`);
+ }
+ }
+ }
+ });
+
+ it('反复同步同一份状态不会让频次增长', () => {
+ const { devices, truth } = simulate(17, 3, 200);
+ const before = readTotals(devices[0].state);
+ for (let round = 0; round < 50; round += 1) {
+ devices[0].state = mergeSyncStates(devices[0].state, devices[1].state);
+ devices[1].state = mergeSyncStates(devices[1].state, devices[0].state);
+ }
+ const after = readTotals(devices[0].state);
+ expect(after).toEqual(before);
+ for (const [key, expected] of truth) expect(after.get(key)).toBe(expected);
+ });
+
+ it('两台设备各学同一个词 3 次,合并后是 6 次而不是 3 次或 12 次', () => {
+ let a = { state: createEmptySyncState(), clock: createHlcClock('a', 1_000) };
+ let b = { state: createEmptySyncState(), clock: createHlcClock('b', 1_000) };
+ for (let index = 0; index < 3; index += 1) {
+ const resultA = recordLearningEvent(a.state, a.clock, {
+ text: 'Vibe Coding',
+ aliases: ['web coding'],
+ stage: 'entry',
+ nowMs: 1_000 + index,
+ });
+ a = { state: resultA.state, clock: resultA.clock };
+ const resultB = recordLearningEvent(b.state, b.clock, {
+ text: 'Vibe Coding',
+ aliases: ['web coding'],
+ stage: 'entry',
+ nowMs: 1_000 + index,
+ });
+ b = { state: resultB.state, clock: resultB.clock };
+ }
+
+ const merged = mergeSyncStates(a.state, b.state);
+ expect(materializeDictionary(merged).entries[0].frequency).toBe(6);
+ // 再合并任意多轮仍是 6 —— 幂等,不随同步次数膨胀。
+ let repeated = merged;
+ for (let round = 0; round < 10; round += 1) {
+ repeated = mergeSyncStates(repeated, mergeSyncStates(a.state, b.state));
+ }
+ expect(materializeDictionary(repeated).entries[0].frequency).toBe(6);
+ });
+
+ it('候选晋升为正式词条不重复计数', () => {
+ // A 攒两次证据 → 同步给 B → 两端各自晋升一次。真实事件共 4 次。
+ let a = { state: createEmptySyncState(), clock: createHlcClock('a', 2_000) };
+ for (let index = 0; index < 2; index += 1) {
+ const result = recordLearningEvent(a.state, a.clock, {
+ text: 'Orca',
+ aliases: ['okra'],
+ stage: 'candidate',
+ nowMs: 2_000 + index,
+ });
+ a = { state: result.state, clock: result.clock };
+ }
+ let b = { state: mergeSyncStates(createEmptySyncState(), a.state), clock: createHlcClock('b', 2_010) };
+
+ const promotedA = recordLearningEvent(a.state, a.clock, { text: 'Orca', stage: 'entry', nowMs: 2_020 });
+ a = { state: promotedA.state, clock: promotedA.clock };
+ const promotedB = recordLearningEvent(b.state, b.clock, { text: 'Orca', stage: 'entry', nowMs: 2_021 });
+ b = { state: promotedB.state, clock: promotedB.clock };
+
+ const merged = mergeSyncStates(a.state, b.state);
+ const materialized = materializeDictionary(merged);
+ expect(materialized.candidates).toHaveLength(0);
+ expect(materialized.entries).toHaveLength(1);
+ expect(materialized.entries[0].frequency).toBe(4);
+ });
+
+ it('手动添加的词条频次为 1,重复添加不再增长', () => {
+ const clock = createHlcClock('a', 3_000);
+ const added = addManualEntry(createEmptySyncState(), clock, { text: 'Cindy', nowMs: 3_000 });
+ const materialized = materializeDictionary(added.state);
+ expect(materialized.entries).toHaveLength(1);
+ expect(materialized.entries[0].frequency).toBe(1);
+ expect(materialized.entries[0].source).toBe('manual');
+
+ // 手动添加已存在的词条不再 +1。
+ const again = addManualEntry(added.state, added.clock, { text: 'cindy', nowMs: 3_010 });
+ expect(materializeDictionary(again.state).entries[0].frequency).toBe(1);
+ });
+});
+
+describe('dictionary sync — 别名合并', () => {
+ it('别名计数同样守恒,且跨设备排序确定', () => {
+ let a = { state: createEmptySyncState(), clock: createHlcClock('a', 4_000) };
+ let b = { state: createEmptySyncState(), clock: createHlcClock('b', 4_000) };
+ for (let index = 0; index < 2; index += 1) {
+ const resultA = recordLearningEvent(a.state, a.clock, {
+ text: 'Vibe Coding',
+ aliases: ['web coding'],
+ stage: 'entry',
+ nowMs: 4_000 + index,
+ });
+ a = { state: resultA.state, clock: resultA.clock };
+ }
+ const resultB = recordLearningEvent(b.state, b.clock, {
+ text: 'Vibe Coding',
+ aliases: ['web coding', '外部 coding'],
+ stage: 'entry',
+ nowMs: 4_100,
+ });
+ b = { state: resultB.state, clock: resultB.clock };
+
+ const left = materializeDictionary(mergeSyncStates(a.state, b.state));
+ const right = materializeDictionary(mergeSyncStates(b.state, a.state));
+ expect(left).toEqual(right);
+ const aliases = left.entries[0].aliases;
+ expect(aliases.find((alias) => alias.text === 'web coding')?.count).toBe(3);
+ expect(aliases.find((alias) => alias.text === '外部 coding')?.count).toBe(1);
+ });
+
+ it('别名等于词条本身时被丢弃', () => {
+ const clock = createHlcClock('a', 5_000);
+ const result = recordLearningEvent(createEmptySyncState(), clock, {
+ text: 'Cindy',
+ aliases: ['cindy', 'sindy'],
+ stage: 'entry',
+ nowMs: 5_000,
+ });
+ const aliases = materializeDictionary(result.state).entries[0].aliases;
+ expect(aliases.map((alias) => alias.text)).toEqual(['sindy']);
+ });
+});
+
+describe('dictionary sync — 远端帧深度校验', () => {
+ it('接受结构完整的状态', async () => {
+ const { isValidSyncState } = await import('../dictionary-sync');
+ const { devices } = simulate(5, 2, 60);
+ expect(isValidSyncState(devices[0].state)).toBe(true);
+ expect(isValidSyncState(createEmptySyncState())).toBe(true);
+ });
+
+ it('拒绝畸形的嵌套结构 —— 只校验顶层会让坏帧一路持久化,重启后依旧中毒', async () => {
+ const { isValidSyncState } = await import('../dictionary-sync');
+ const base = { version: 1, records: {}, suppressed: {} };
+ const incarnation = {
+ tag: 'a', text: 'x', textStamp: 'a', source: 'manual', stage: 'entry',
+ counters: { n: 1 }, aliases: {}, createdAt: 1, updatedAt: 1,
+ };
+
+ // 顶层就不合法
+ expect(isValidSyncState(null)).toBe(false);
+ expect(isValidSyncState([])).toBe(false);
+ expect(isValidSyncState({ ...base, version: 2 })).toBe(false);
+ expect(isValidSyncState({ ...base, records: [] })).toBe(false);
+
+ // 顶层通过、嵌套结构坏掉 —— 这些正是会被持久化后才在物化时炸的形状
+ expect(isValidSyncState({ ...base, records: { k: {} } })).toBe(false);
+ expect(isValidSyncState({
+ ...base,
+ records: { k: { incarnations: { a: { ...incarnation, counters: undefined } }, tombstones: {} } },
+ })).toBe(false);
+ expect(isValidSyncState({
+ ...base,
+ records: { k: { incarnations: { a: { ...incarnation, stage: 'bogus' } }, tombstones: {} } },
+ })).toBe(false);
+ expect(isValidSyncState({
+ ...base,
+ records: { k: { incarnations: { a: { ...incarnation, aliases: { x: { text: 'y' } } } }, tombstones: {} } },
+ })).toBe(false);
+ expect(isValidSyncState({
+ ...base,
+ records: { k: { incarnations: {}, tombstones: { a: 123 } } },
+ })).toBe(false);
+ expect(isValidSyncState({ ...base, suppressed: { k: { text: 'x' } } })).toBe(false);
+ });
+});
diff --git a/packages/voice-input-core/src/__tests__/dictionarySyncPrototypeKeys.test.ts b/packages/voice-input-core/src/__tests__/dictionarySyncPrototypeKeys.test.ts
new file mode 100644
index 0000000000..bcee564dd4
--- /dev/null
+++ b/packages/voice-input-core/src/__tests__/dictionarySyncPrototypeKeys.test.ts
@@ -0,0 +1,212 @@
+/**
+ * 以 `Object.prototype` 成员名为文本的词条。
+ *
+ * `constructor`、`toString`、`valueOf`、`__proto__` 都是完全合法的技术术语,用户
+ * 完全可能把它们加进词典。而词条主键直接当对象键用,只要哪里用了 `in` 或裸取值,
+ * 这些词就会命中原型链:被当成"已存在"而静默丢弃,或者把一个继承来的函数当成
+ * 词条记录传下去。
+ *
+ * 这类 bug 平时跑不出来 —— 只有真有用户加了这么一个词才炸,所以必须有测试守着。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ DEFAULT_TOMBSTONE_TTL_MS,
+ addManualEntry,
+ buildStateVersionVector,
+ createEmptySyncState,
+ createHlcClock,
+ deleteTerms,
+ gcTombstones,
+ materializeDictionary,
+ mergeSyncStates,
+ recordLearningEvent,
+ reconcileFromLocalSnapshot,
+ versionVectorDominates,
+ type HlcClock,
+ type VoiceDictionarySyncState,
+} from '../dictionary-sync';
+
+/** 全是 Object.prototype 上真实存在的成员名。 */
+const PROTOTYPE_NAMES = [
+ 'constructor',
+ 'toString',
+ 'valueOf',
+ 'hasOwnProperty',
+ '__proto__',
+ 'isPrototypeOf',
+ 'propertyIsEnumerable',
+];
+
+interface Device {
+ state: VoiceDictionarySyncState;
+ clock: HlcClock;
+}
+
+function device(nodeId: string, wallMs = 1_000): Device {
+ return { state: createEmptySyncState(), clock: createHlcClock(nodeId, wallMs) };
+}
+
+describe('原型链成员名作为词条', () => {
+ it('能被手动添加,并且真的出现在词典里', () => {
+ const a = device('a');
+ for (const [index, name] of PROTOTYPE_NAMES.entries()) {
+ const result = addManualEntry(a.state, a.clock, { text: name, nowMs: 1_000 + index });
+ expect(result.changed).toBe(true);
+ a.state = result.state;
+ a.clock = result.clock;
+ }
+ const texts = materializeDictionary(a.state).entries.map((entry) => entry.text).sort();
+ expect(texts).toEqual([...PROTOTYPE_NAMES].sort());
+ });
+
+ it('能被自动学习记录,频次正常累积', () => {
+ const a = device('a');
+ for (let round = 0; round < 3; round += 1) {
+ const result = recordLearningEvent(a.state, a.clock, {
+ text: 'constructor',
+ aliases: ['construct or'],
+ stage: 'entry',
+ nowMs: 1_000 + round,
+ });
+ expect(result.changed).toBe(true);
+ a.state = result.state;
+ a.clock = result.clock;
+ }
+ const entry = materializeDictionary(a.state).entries[0];
+ expect(entry.text).toBe('constructor');
+ expect(entry.frequency).toBe(3);
+ });
+
+ it('能被删除,并且抑制集合对它生效', () => {
+ const a = device('a');
+ const learned = recordLearningEvent(a.state, a.clock, {
+ text: 'toString',
+ aliases: ['to string'],
+ stage: 'entry',
+ nowMs: 1_000,
+ });
+ a.state = learned.state;
+ a.clock = learned.clock;
+
+ const removed = deleteTerms(a.state, a.clock, { termKeys: ['tostring'], nowMs: 2_000 });
+ a.state = removed.state;
+ a.clock = removed.clock;
+ expect(materializeDictionary(a.state).entries).toEqual([]);
+ expect(materializeDictionary(a.state).suppressedTexts).toEqual(['toString']);
+
+ // 抑制生效:后台学习不会把它加回来。
+ const relearn = recordLearningEvent(a.state, a.clock, {
+ text: 'toString',
+ aliases: ['to string'],
+ stage: 'entry',
+ nowMs: 3_000,
+ });
+ expect(materializeDictionary(relearn.state).entries).toEqual([]);
+ });
+
+ it('跨设备合并不丢失', () => {
+ const a = device('a');
+ const b = device('b', 5_000);
+ const learnedA = recordLearningEvent(a.state, a.clock, {
+ text: '__proto__',
+ aliases: ['proto'],
+ stage: 'entry',
+ nowMs: 1_000,
+ });
+ a.state = learnedA.state;
+ const learnedB = recordLearningEvent(b.state, b.clock, {
+ text: 'valueOf',
+ aliases: ['value of'],
+ stage: 'entry',
+ nowMs: 6_000,
+ });
+ b.state = learnedB.state;
+
+ const merged = mergeSyncStates(a.state, b.state);
+ expect(materializeDictionary(merged).entries.map((entry) => entry.text).sort()).toEqual([
+ '__proto__',
+ 'valueOf',
+ ]);
+ // 合并可交换性对这些键同样成立。
+ expect(materializeDictionary(mergeSyncStates(b.state, a.state))).toEqual(
+ materializeDictionary(merged),
+ );
+ });
+
+ it('墓碑回收不会丢掉存活的原型名词条', () => {
+ // gcTombstones 重建 records;用普通 {} 的话,给 `__proto__` 赋值会走原型 setter,
+ // 这条合法词条会被静默丢掉,而且这个丢失还会被持久化并同步出去。
+ const a = device('a');
+ const kept = addManualEntry(a.state, a.clock, { text: '__proto__', nowMs: 1_000 });
+ a.state = kept.state;
+ a.clock = kept.clock;
+ const doomed = addManualEntry(a.state, a.clock, { text: 'Orca', nowMs: 1_100 });
+ a.state = doomed.state;
+ a.clock = doomed.clock;
+ const removed = deleteTerms(a.state, a.clock, { termKeys: ['orca'], nowMs: 2_000 });
+ a.state = removed.state;
+
+ const collected = gcTombstones(a.state, {
+ nowMs: 2_000 + DEFAULT_TOMBSTONE_TTL_MS + 1,
+ ttlMs: DEFAULT_TOMBSTONE_TTL_MS,
+ });
+ expect(materializeDictionary(collected).entries.map((entry) => entry.text)).toEqual(['__proto__']);
+ });
+
+ it('首次迁移时不会被当成「已存在」而静默丢弃', () => {
+ // 这正是原型链 bug 的杀伤面:seedTerm 用 `key in records` 判断存在性时,
+ // 空状态下 'constructor' in {} 恒为 true,整条词就被跳过了。
+ const result = reconcileFromLocalSnapshot(createEmptySyncState(), createHlcClock('a', 1_000), {
+ snapshot: {
+ entries: PROTOTYPE_NAMES.map((name, index) => ({
+ text: name,
+ source: 'manual' as const,
+ frequency: index + 2,
+ })),
+ suppressedTexts: [],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 2_000,
+ });
+
+ const materialized = materializeDictionary(result.state);
+ expect(materialized.entries.map((entry) => entry.text).sort()).toEqual(
+ [...PROTOTYPE_NAMES].sort(),
+ );
+ // 频次也得原样接管,不能退回 1。
+ for (const [index, name] of PROTOTYPE_NAMES.entries()) {
+ const entry = materialized.entries.find((item) => item.text === name);
+ expect(`${name}=${entry?.frequency}`).toBe(`${name}=${index + 2}`);
+ }
+ });
+});
+
+describe('版本向量的键也来自不可信输入', () => {
+ it('返回的是无原型字典 —— nodeId 叫 __proto__ 也不会读到原型链上的值', () => {
+ const state = addManualEntry(createEmptySyncState(), createHlcClock('__proto__', 1_000), {
+ text: 'Cindy',
+ nowMs: 1_000,
+ }).state;
+
+ const vector = buildStateVersionVector(state);
+ expect(Object.getPrototypeOf(vector)).toBeNull();
+ expect(vector['__proto__']).toBeTypeOf('string');
+ // 不存在的原型名键必须是 undefined,否则包含性比较会拿函数去比大小。
+ expect(vector['constructor']).toBeUndefined();
+ expect(vector['toString']).toBeUndefined();
+
+ // 包含性比较在这种 nodeId 下仍然自洽。
+ expect(versionVectorDominates(vector, vector)).toBe(true);
+ expect(versionVectorDominates(buildStateVersionVector(createEmptySyncState()), vector)).toBe(false);
+
+ // 序列化往返保真(投影要经隧道发给手机):`JSON.parse` 把 `__proto__` 建成
+ // own property 而不是走原型 setter,所以这个 nodeId 不会在传输中丢掉。
+ const roundTripped = JSON.parse(JSON.stringify(vector)) as Record<string, string>;
+ expect(Object.keys(roundTripped)).toEqual(['__proto__']);
+ expect(Object.getOwnPropertyDescriptor(roundTripped, '__proto__')?.value).toBe(
+ vector['__proto__'],
+ );
+ });
+});
diff --git a/packages/voice-input-core/src/__tests__/dictionarySyncReconcile.test.ts b/packages/voice-input-core/src/__tests__/dictionarySyncReconcile.test.ts
new file mode 100644
index 0000000000..e3fd1d22d7
--- /dev/null
+++ b/packages/voice-input-core/src/__tests__/dictionarySyncReconcile.test.ts
@@ -0,0 +1,450 @@
+/**
+ * 改写词条与降级回收。
+ *
+ * 回收是这套设计里唯一「拿文件反推变更」的路径,也是最容易把词典搞成指数膨胀的
+ * 地方。这里除了功能正确性,重点钉住两件事:回收之后再同步不放大,以及被上限挤
+ * 出物化的词条不会被误判成用户删除。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ DEFAULT_MATERIALIZE_LIMITS,
+ addManualEntry,
+ createEmptySyncState,
+ createHlcClock,
+ deleteTerms,
+ materializeDictionary,
+ mergeSyncStates,
+ recordLearningEvent,
+ reconcileFromLocalSnapshot,
+ renameTerm,
+ type HlcClock,
+ type VoiceDictionarySyncState,
+} from '../dictionary-sync';
+
+interface Device {
+ state: VoiceDictionarySyncState;
+ clock: HlcClock;
+}
+
+function device(nodeId: string, wallMs = 1_000): Device {
+ return { state: createEmptySyncState(), clock: createHlcClock(nodeId, wallMs) };
+}
+
+function learn(target: Device, text: string, nowMs: number): void {
+ const result = recordLearningEvent(target.state, target.clock, { text, stage: 'entry', nowMs });
+ target.state = result.state;
+ target.clock = result.clock;
+}
+
+function addManual(target: Device, text: string, nowMs: number): void {
+ const result = addManualEntry(target.state, target.clock, { text, nowMs });
+ target.state = result.state;
+ target.clock = result.clock;
+}
+
+function snapshotOf(state: VoiceDictionarySyncState) {
+ const materialized = materializeDictionary(state);
+ return {
+ entries: materialized.entries.map((entry) => ({ text: entry.text, source: entry.source })),
+ suppressedTexts: materialized.suppressedTexts,
+ };
+}
+
+function keysOf(state: VoiceDictionarySyncState): string[] {
+ return materializeDictionary(state).entries.map((entry) => entry.text.toLowerCase());
+}
+
+describe('dictionary sync — 改写词条', () => {
+ it('只改写法时保留频次与来源提升', () => {
+ const a = device('a');
+ learn(a, 'litellm', 1_000);
+ learn(a, 'litellm', 1_100);
+
+ const renamed = renameTerm(a.state, a.clock, { termKey: 'litellm', nextText: 'LiteLLM', nowMs: 2_000 });
+ a.state = renamed.state;
+ const entry = materializeDictionary(a.state).entries[0];
+ expect(entry.text).toBe('LiteLLM');
+ expect(entry.frequency).toBe(2);
+ expect(entry.source).toBe('manual');
+ });
+
+ it('改成另一个词时把频次与别名一并搬过去 —— 纠正写法不该丢掉学到的东西', () => {
+ const a = device('a');
+ for (let index = 0; index < 4; index += 1) {
+ const result = recordLearningEvent(a.state, a.clock, {
+ text: 'litellm',
+ aliases: ['light LLM'],
+ stage: 'entry',
+ nowMs: 1_000 + index,
+ });
+ a.state = result.state;
+ a.clock = result.clock;
+ }
+
+ const renamed = renameTerm(a.state, a.clock, {
+ termKey: 'litellm',
+ nextText: 'LiteLLM Proxy',
+ nowMs: 2_000,
+ });
+ a.state = renamed.state;
+
+ const entry = materializeDictionary(a.state).entries[0];
+ expect(entry.text).toBe('LiteLLM Proxy');
+ expect(entry.frequency).toBe(4);
+ expect(entry.aliases.map((alias) => [alias.text, alias.count])).toEqual([['light LLM', 4]]);
+ });
+
+ it('改成另一个词等价于删除加新增,且不写抑制', () => {
+ const a = device('a');
+ learn(a, 'Orca', 1_000);
+ const renamed = renameTerm(a.state, a.clock, { termKey: 'orca', nextText: 'Orca Team', nowMs: 2_000 });
+ a.state = renamed.state;
+ a.clock = renamed.clock;
+
+ expect(keysOf(a.state)).toEqual(['orca team']);
+ // 改名不是拒绝:抑制集合必须干净,否则新写法日后被自动学习到会被自己挡住。
+ expect(materializeDictionary(a.state).suppressedTexts).toEqual([]);
+ learn(a, 'Orca', 3_000);
+ expect(keysOf(a.state).sort()).toEqual(['orca', 'orca team']);
+ });
+
+ it('改写结果跨设备收敛', () => {
+ const a = device('a');
+ const b = device('b', 5_000);
+ learn(a, 'litellm', 1_000);
+ b.state = mergeSyncStates(b.state, a.state);
+ const renamed = renameTerm(a.state, a.clock, { termKey: 'litellm', nextText: 'LiteLLM', nowMs: 2_000 });
+ a.state = renamed.state;
+
+ expect(materializeDictionary(mergeSyncStates(a.state, b.state))).toEqual(
+ materializeDictionary(mergeSyncStates(b.state, a.state)),
+ );
+ expect(materializeDictionary(mergeSyncStates(b.state, a.state)).entries[0].text).toBe('LiteLLM');
+ });
+});
+
+describe('dictionary sync — 首次迁移保留频次', () => {
+ it('存量词典的频次与候选证据数被原样接管,不会被清零', () => {
+ // 首次迁移:状态是空的,文件里的数字全是本机长期积累的,原样接管才对。
+ const result = reconcileFromLocalSnapshot(createEmptySyncState(), createHlcClock('a', 1_000), {
+ snapshot: {
+ entries: [
+ { text: 'Claude code', source: 'automatic', frequency: 4 },
+ { text: 'Fable 5', source: 'automatic', frequency: 3 },
+ { text: 'Cindy', source: 'manual', frequency: 2 },
+ ],
+ suppressedTexts: [],
+ candidates: [{ text: 'Bug', evidenceCount: 2 }, { text: 'invoice', evidenceCount: 1 }],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 2_000,
+ });
+
+ const materialized = materializeDictionary(result.state);
+ expect(materialized.entries.map((entry) => [entry.text, entry.frequency])).toEqual([
+ ['Claude code', 4],
+ ['Fable 5', 3],
+ ['Cindy', 2],
+ ]);
+ expect(materialized.candidates.map((item) => [item.text, item.evidenceCount])).toEqual([
+ ['Bug', 2],
+ ['invoice', 1],
+ ]);
+ });
+
+ it('别名与其次数一并接管 —— 它们是纠错能力的主体,丢了词典就白学了', () => {
+ const result = reconcileFromLocalSnapshot(createEmptySyncState(), createHlcClock('a', 1_000), {
+ snapshot: {
+ entries: [
+ {
+ text: 'Vibe Coding',
+ source: 'automatic',
+ frequency: 4,
+ aliases: [
+ { text: 'web coding', count: 3 },
+ { text: '外部 coding', count: 1 },
+ ],
+ },
+ ],
+ suppressedTexts: [],
+ candidates: [
+ { text: 'Orca', evidenceCount: 2, aliases: [{ text: 'okra', count: 2 }] },
+ ],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 2_000,
+ });
+
+ const materialized = materializeDictionary(result.state);
+ const entry = materialized.entries[0];
+ expect(entry.frequency).toBe(4);
+ expect(entry.aliases.map((alias) => [alias.text, alias.count])).toEqual([
+ ['web coding', 3],
+ ['外部 coding', 1],
+ ]);
+ expect(materialized.candidates[0].aliases.map((alias) => alias.text)).toEqual(['okra']);
+ });
+
+ it('迁移进来的别名可以继续累积,并跨设备合并', () => {
+ const migrate = (nodeId: string) => reconcileFromLocalSnapshot(
+ createEmptySyncState(),
+ createHlcClock(nodeId, 1_000),
+ {
+ snapshot: {
+ entries: [{
+ text: 'Vibe Coding',
+ source: 'automatic',
+ frequency: 2,
+ aliases: [{ text: 'web coding', count: 2 }],
+ }],
+ suppressedTexts: [],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 2_000,
+ },
+ );
+
+ const a = migrate('a');
+ const bumped = recordLearningEvent(a.state, a.clock, {
+ text: 'Vibe Coding',
+ aliases: ['web coding'],
+ stage: 'entry',
+ nowMs: 3_000,
+ });
+ expect(materializeDictionary(bumped.state).entries[0].aliases[0].count).toBe(3);
+
+ // 两台各自迁移同一份词典再合并:别名取并集,计数不会因合并翻倍。
+ const b = migrate('b');
+ const merged = mergeSyncStates(bumped.state, b.state);
+ const aliases = materializeDictionary(merged).entries[0].aliases;
+ expect(aliases).toHaveLength(1);
+ expect(aliases[0].text).toBe('web coding');
+ });
+
+ it('缺失或异常的频次退回 1,不产生 0 或负数', () => {
+ const result = reconcileFromLocalSnapshot(createEmptySyncState(), createHlcClock('a', 1_000), {
+ snapshot: {
+ entries: [
+ { text: 'NoFreq', source: 'manual' },
+ { text: 'Negative', source: 'manual', frequency: -3 },
+ ],
+ suppressedTexts: [],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 2_000,
+ });
+ for (const entry of materializeDictionary(result.state).entries) {
+ expect(entry.frequency).toBe(1);
+ }
+ });
+
+ it('已存在的词条不会被文件里的频次覆盖 —— 那可能含有合并进来的远端计数', () => {
+ const a = device('a');
+ const b = device('b', 5_000);
+ for (let index = 0; index < 3; index += 1) learn(a, 'Cindy', 1_000 + index);
+ b.state = mergeSyncStates(b.state, a.state);
+ for (let index = 0; index < 2; index += 1) learn(b, 'Cindy', 6_000 + index);
+ a.state = mergeSyncStates(a.state, b.state);
+ expect(materializeDictionary(a.state).entries[0].frequency).toBe(5);
+
+ // 文件里写着 5(上次物化的结果)。即使把它当成「新增」喂回来,也不能再记一遍。
+ const result = reconcileFromLocalSnapshot(a.state, a.clock, {
+ snapshot: {
+ entries: [{ text: 'Cindy', source: 'automatic', frequency: 5 }],
+ suppressedTexts: [],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 9_000,
+ });
+ expect(materializeDictionary(result.state).entries[0].frequency).toBe(5);
+ });
+
+ it('迁移进来的频次可以继续正常增长与合并', () => {
+ const migrated = reconcileFromLocalSnapshot(createEmptySyncState(), createHlcClock('a', 1_000), {
+ snapshot: {
+ entries: [{ text: 'Cindy', source: 'automatic', frequency: 4 }],
+ suppressedTexts: [],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 2_000,
+ });
+ const a = { state: migrated.state, clock: migrated.clock };
+ learn(a, 'Cindy', 3_000);
+ expect(materializeDictionary(a.state).entries[0].frequency).toBe(5);
+
+ // 另一台设备各自迁移了同一份词典再学一次:两边各记各的桶,合并后求和。
+ const migratedB = reconcileFromLocalSnapshot(createEmptySyncState(), createHlcClock('b', 1_000), {
+ snapshot: {
+ entries: [{ text: 'Cindy', source: 'automatic', frequency: 4 }],
+ suppressedTexts: [],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 2_000,
+ });
+ const merged = mergeSyncStates(a.state, migratedB.state);
+ expect(materializeDictionary(merged).entries[0].frequency).toBe(9);
+ // 反复合并不再增长。
+ expect(
+ materializeDictionary(mergeSyncStates(merged, migratedB.state)).entries[0].frequency,
+ ).toBe(9);
+ });
+});
+
+describe('dictionary sync — 降级回收', () => {
+ it('认领旧版本期间新增的词条,手动与自动来源分别对待', () => {
+ const a = device('a');
+ learn(a, 'Cindy', 1_000);
+ const lastKeys = keysOf(a.state);
+
+ // 旧版本在文件里加了两条:一条手动、一条自动学习。
+ const result = reconcileFromLocalSnapshot(a.state, a.clock, {
+ snapshot: {
+ entries: [
+ { text: 'Cindy', source: 'automatic' },
+ { text: 'Orca', source: 'manual' },
+ { text: 'device-link', source: 'automatic' },
+ ],
+ suppressedTexts: [],
+ },
+ lastMaterializedKeys: lastKeys,
+ nowMs: 2_000,
+ });
+ a.state = result.state;
+ a.clock = result.clock;
+
+ const materialized = materializeDictionary(a.state);
+ expect(materialized.entries.map((entry) => entry.text).sort()).toEqual([
+ 'Cindy',
+ 'Orca',
+ 'device-link',
+ ]);
+ expect(materialized.entries.find((entry) => entry.text === 'Orca')?.source).toBe('manual');
+ expect(materialized.entries.find((entry) => entry.text === 'device-link')?.source).toBe('automatic');
+ });
+
+ it('认领旧版本期间的删除,并把文件里的抑制列表并回状态', () => {
+ const a = device('a');
+ learn(a, 'Cindy', 1_000);
+ learn(a, 'Orca', 1_100);
+ const lastKeys = keysOf(a.state);
+
+ const result = reconcileFromLocalSnapshot(a.state, a.clock, {
+ snapshot: {
+ entries: [{ text: 'Cindy', source: 'automatic' }],
+ suppressedTexts: ['Orca'],
+ },
+ lastMaterializedKeys: lastKeys,
+ nowMs: 2_000,
+ });
+ a.state = result.state;
+ a.clock = result.clock;
+
+ expect(keysOf(a.state)).toEqual(['cindy']);
+ expect(materializeDictionary(a.state).suppressedTexts).toEqual(['Orca']);
+ // 抑制生效:后台学习不会把它加回来。
+ learn(a, 'Orca', 3_000);
+ expect(keysOf(a.state)).toEqual(['cindy']);
+ });
+
+ it('被上限挤出物化的词条不会被误判成用户删除', () => {
+ const a = device('a');
+ for (let index = 0; index < 4; index += 1) {
+ for (let times = 0; times <= index; times += 1) learn(a, `term-${index}`, 1_000 + index * 10 + times);
+ }
+ const limits = { ...DEFAULT_MATERIALIZE_LIMITS, maxEntries: 2 };
+ const visible = materializeDictionary(a.state, limits);
+ expect(visible.entries).toHaveLength(2);
+
+ // 文件里只有物化出去的那两条 —— 回收必须以「上次物化的主键」为准,
+ // 否则被截断的另外两条会被当成删除,墓碑一广播就是全网批量误删。
+ const result = reconcileFromLocalSnapshot(a.state, a.clock, {
+ snapshot: {
+ entries: visible.entries.map((entry) => ({ text: entry.text, source: entry.source })),
+ suppressedTexts: [],
+ },
+ lastMaterializedKeys: visible.entries.map((entry) => entry.text.toLowerCase()),
+ nowMs: 5_000,
+ });
+
+ expect(materializeDictionary(result.state).entries).toHaveLength(4);
+ for (const record of Object.values(result.state.records)) {
+ expect(Object.keys(record.tombstones)).toEqual([]);
+ }
+ });
+
+ it('文件与状态一致时回收是空操作', () => {
+ const a = device('a');
+ learn(a, 'Cindy', 1_000);
+ addManual(a, 'Orca', 1_100);
+
+ const result = reconcileFromLocalSnapshot(a.state, a.clock, {
+ snapshot: snapshotOf(a.state),
+ lastMaterializedKeys: keysOf(a.state),
+ nowMs: 2_000,
+ });
+ expect(result.changed).toBe(false);
+ expect(materializeDictionary(result.state)).toEqual(materializeDictionary(a.state));
+ });
+
+ it('回收之后再同步不会放大频次', () => {
+ const a = device('a');
+ const b = device('b', 5_000);
+ for (let index = 0; index < 3; index += 1) learn(a, 'Cindy', 1_000 + index);
+ b.state = mergeSyncStates(b.state, a.state);
+ for (let index = 0; index < 2; index += 1) learn(b, 'Cindy', 6_000 + index);
+
+ // A 合并了 B 的状态并物化(此时文件里的频次是 5),随后跑一次回收。
+ a.state = mergeSyncStates(a.state, b.state);
+ expect(materializeDictionary(a.state).entries[0].frequency).toBe(5);
+
+ const result = reconcileFromLocalSnapshot(a.state, a.clock, {
+ snapshot: snapshotOf(a.state),
+ lastMaterializedKeys: keysOf(a.state),
+ nowMs: 7_000,
+ });
+ a.state = result.state;
+ a.clock = result.clock;
+
+ // 合并进来的远端计数不能被当成本地增量再记一遍。
+ expect(materializeDictionary(a.state).entries[0].frequency).toBe(5);
+ for (let round = 0; round < 5; round += 1) {
+ a.state = mergeSyncStates(a.state, b.state);
+ b.state = mergeSyncStates(b.state, a.state);
+ }
+ expect(materializeDictionary(a.state).entries[0].frequency).toBe(5);
+ expect(materializeDictionary(b.state).entries[0].frequency).toBe(5);
+ });
+
+ it('回收产生的删除会传播到其它设备', () => {
+ const a = device('a');
+ const b = device('b', 5_000);
+ addManual(a, 'Cindy', 1_000);
+ b.state = mergeSyncStates(b.state, a.state);
+
+ const result = reconcileFromLocalSnapshot(a.state, a.clock, {
+ snapshot: { entries: [], suppressedTexts: [] },
+ lastMaterializedKeys: ['cindy'],
+ nowMs: 2_000,
+ });
+ a.state = result.state;
+
+ b.state = mergeSyncStates(b.state, a.state);
+ expect(keysOf(b.state)).toEqual([]);
+ });
+});
+
+describe('dictionary sync — 删除抑制开关', () => {
+ it('suppressAutomatic 为 false 时不写抑制集合', () => {
+ const a = device('a');
+ learn(a, 'Orca', 1_000);
+ const result = deleteTerms(a.state, a.clock, {
+ termKeys: ['orca'],
+ nowMs: 2_000,
+ suppressAutomatic: false,
+ });
+ expect(materializeDictionary(result.state).entries).toEqual([]);
+ expect(materializeDictionary(result.state).suppressedTexts).toEqual([]);
+ });
+});
diff --git a/packages/voice-input-core/src/__tests__/dictionarySyncRecovery.test.ts b/packages/voice-input-core/src/__tests__/dictionarySyncRecovery.test.ts
new file mode 100644
index 0000000000..3dc0e0dbdc
--- /dev/null
+++ b/packages/voice-input-core/src/__tests__/dictionarySyncRecovery.test.ts
@@ -0,0 +1,153 @@
+/**
+ * 两条容易互相打架的恢复路径。
+ *
+ * - **降级回收**:老客户端直接改了词典文件。投影是刚写下的新证据,即使某个键上只剩
+ * 墓碑也要重建 —— 否则用户在老客户端加的词升级后凭空消失。
+ * - **sidecar 恢复**:本机丢了同步状态、投影还在。此时本机没有任何身份历史,重建
+ * 出来的化身自带新 tag,别的设备上「删掉这个词」的墓碑盖不住它 —— 越过墓碑重建
+ * 就是让删掉的词复活。
+ *
+ * 同一个 `seedTerm` 要同时满足这两条,靠的就是 `allowTombstonedRevival`。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ addManualEntry,
+ createEmptySyncState,
+ createHlcClock,
+ deleteTerms,
+ materializeDictionary,
+ mergeSyncStates,
+ reconcileFromLocalSnapshot,
+} from '../dictionary-sync';
+
+describe('墓碑与重建', () => {
+ it('降级回收允许越过墓碑重建(老客户端刚加回来的词)', () => {
+ const added = addManualEntry(createEmptySyncState(), createHlcClock('a', 1_000), {
+ text: 'Cindy',
+ nowMs: 1_000,
+ });
+ const removed = deleteTerms(added.state, added.clock, { termKeys: ['cindy'], nowMs: 2_000 });
+
+ const result = reconcileFromLocalSnapshot(removed.state, removed.clock, {
+ snapshot: { entries: [{ text: 'Cindy', source: 'manual', frequency: 3 }], suppressedTexts: [] },
+ lastMaterializedKeys: [],
+ nowMs: 3_000,
+ });
+
+ expect(materializeDictionary(result.state).entries.map((entry) => entry.text)).toEqual(['Cindy']);
+ });
+
+ it('sidecar 恢复不越过墓碑 —— 别的设备删掉的词不会复活', () => {
+ // 设备 B 删掉了这个词。
+ const added = addManualEntry(createEmptySyncState(), createHlcClock('b', 1_000), {
+ text: 'Cindy',
+ nowMs: 1_000,
+ });
+ const peerAfterDelete = deleteTerms(added.state, added.clock, {
+ termKeys: ['cindy'],
+ nowMs: 2_000,
+ });
+
+ // 设备 A 丢了 sidecar,只剩一份还写着这个词的投影文件。先合并对端(墓碑到齐),
+ // 再按恢复语义认领 —— 这正是延迟恢复要保证的顺序。
+ const merged = mergeSyncStates(createEmptySyncState(), peerAfterDelete.state);
+ const recovered = reconcileFromLocalSnapshot(merged, createHlcClock('a', 5_000), {
+ snapshot: { entries: [{ text: 'Cindy', source: 'manual', frequency: 9 }], suppressedTexts: [] },
+ lastMaterializedKeys: [],
+ nowMs: 5_000,
+ allowTombstonedRevival: false,
+ });
+
+ expect(materializeDictionary(recovered.state).entries).toEqual([]);
+ // 再与对端合并一次也不会复活(幂等,且没造出新化身)。
+ expect(materializeDictionary(mergeSyncStates(recovered.state, peerAfterDelete.state)).entries)
+ .toEqual([]);
+ });
+
+ it('恢复模式仍然认领对端没删过的词', () => {
+ const peer = addManualEntry(createEmptySyncState(), createHlcClock('b', 1_000), {
+ text: 'Orca',
+ nowMs: 1_000,
+ });
+ const recovered = reconcileFromLocalSnapshot(peer.state, createHlcClock('a', 5_000), {
+ snapshot: {
+ entries: [
+ { text: 'Orca', source: 'manual', frequency: 4 },
+ { text: 'Vibe Coding', source: 'manual', frequency: 2 },
+ ],
+ suppressedTexts: [],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 5_000,
+ allowTombstonedRevival: false,
+ });
+
+ expect(materializeDictionary(recovered.state).entries.map((entry) => entry.text).sort()).toEqual([
+ 'Orca',
+ 'Vibe Coding',
+ ]);
+ });
+
+ it('降级期间老客户端把候选词转正,回收要认下这次转正', () => {
+ // 状态里是候选。
+ const seeded = reconcileFromLocalSnapshot(createEmptySyncState(), createHlcClock('a', 1_000), {
+ snapshot: {
+ entries: [],
+ suppressedTexts: [],
+ candidates: [{ text: 'Cindy', evidenceCount: 2 }],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 1_000,
+ });
+ expect(materializeDictionary(seeded.state).candidates.map((item) => item.text)).toEqual(['Cindy']);
+
+ // 老客户端把它转正:文件里现在是正式词条,而这个键从没进过 lastMaterializedKeys。
+ const promoted = reconcileFromLocalSnapshot(seeded.state, seeded.clock, {
+ snapshot: {
+ entries: [{ text: 'Cindy', source: 'automatic', frequency: 2 }],
+ suppressedTexts: [],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 2_000,
+ });
+
+ const materialized = materializeDictionary(promoted.state);
+ expect(materialized.entries.map((entry) => entry.text)).toEqual(['Cindy']);
+ expect(materialized.candidates).toEqual([]);
+ // 只提升阶段,不补记证据。
+ expect(materialized.entries[0].frequency).toBe(2);
+ });
+});
+
+describe('上限裁决', () => {
+ it('手动词条不会被高频自动词条挤出上限,展示顺序仍按频次', () => {
+ let state = createEmptySyncState();
+ let clock = createHlcClock('a', 1_000);
+ // 先塞满 automatic 高频词。
+ for (let index = 0; index < 5; index += 1) {
+ const result = reconcileFromLocalSnapshot(state, clock, {
+ snapshot: {
+ entries: [{ text: `auto-${index}`, source: 'automatic', frequency: 50 + index }],
+ suppressedTexts: [],
+ },
+ lastMaterializedKeys: [],
+ nowMs: 1_000 + index,
+ });
+ state = result.state;
+ clock = result.clock;
+ }
+ // 一条低频手动词。
+ const manual = addManualEntry(state, clock, { text: '内部代号', nowMs: 2_000 });
+ state = manual.state;
+
+ const materialized = materializeDictionary(state, { maxEntries: 3 });
+ const texts = materialized.entries.map((entry) => entry.text);
+ expect(texts).toContain('内部代号');
+ expect(texts).toHaveLength(3);
+ // 展示顺序仍是频次降序:手动优先只决定谁被裁掉。
+ const frequencies = materialized.entries.map((entry) => entry.frequency);
+ expect([...frequencies].sort((a, b) => b - a)).toEqual(frequencies);
+ });
+});
diff --git a/packages/voice-input-core/src/__tests__/dictionarySyncRenameConcurrent.test.ts b/packages/voice-input-core/src/__tests__/dictionarySyncRenameConcurrent.test.ts
new file mode 100644
index 0000000000..0036c006b6
--- /dev/null
+++ b/packages/voice-input-core/src/__tests__/dictionarySyncRenameConcurrent.test.ts
@@ -0,0 +1,265 @@
+/**
+ * 并发改名与容量裁剪。
+ *
+ * 「不要有 Bug 造成词典重复增长」是这套同步最硬的约束。改名尤其危险:它是唯一一个
+ * 把已积累的证据搬到另一个键下的操作,搬的方式稍有不慎,两台设备各搬一次就翻倍。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ MAX_AUTOMATIC_CANDIDATE_RECORDS,
+ createEmptySyncState,
+ createHlcClock,
+ isCanonicalHlc,
+ isValidSyncState,
+ materializeDictionary,
+ mergeSyncStates,
+ pruneWeakAutomaticCandidates,
+ recordLearningEvent,
+ renameTerm,
+ seedTerm,
+} from '../dictionary-sync';
+
+describe('并发改名', () => {
+ it('两台已收敛的电脑把同一个词改成同一个新名,频次不翻倍', () => {
+ // 先造出一个频次 5、带别名的词,并让两台电脑都持有它。
+ let base = createEmptySyncState();
+ let clock = createHlcClock('node-a', 1_000);
+ for (let round = 0; round < 5; round += 1) {
+ const learned = recordLearningEvent(base, clock, {
+ text: 'web coding',
+ aliases: ['webcoding'],
+ stage: 'entry',
+ nowMs: 1_000 + round,
+ });
+ base = learned.state;
+ clock = learned.clock;
+ }
+ expect(materializeDictionary(base).entries[0].frequency).toBe(5);
+
+ // 两台电脑各自把它改名成 Vibe Coding —— 互相还没同步。
+ const a = renameTerm(base, createHlcClock('node-a', 5_000), {
+ termKey: 'web coding',
+ nextText: 'Vibe Coding',
+ nowMs: 5_000,
+ });
+ const b = renameTerm(base, createHlcClock('node-b', 6_000), {
+ termKey: 'web coding',
+ nextText: 'Vibe Coding',
+ nowMs: 6_000,
+ });
+
+ const merged = mergeSyncStates(a.state, b.state);
+ const entries = materializeDictionary(merged).entries;
+ expect(entries.map((entry) => entry.text)).toEqual(['Vibe Coding']);
+ // 关键:没有发生任何一次学习,频次就必须还是 5。
+ expect(entries[0].frequency).toBe(5);
+ // 别名也不能翻倍。
+ expect(entries[0].aliases.map((alias) => `${alias.text}:${alias.count}`)).toEqual(['webcoding:5']);
+ });
+
+ it('反复改名再改回来也不涨', () => {
+ let state = seedTerm(createEmptySyncState(), createHlcClock('node-a', 1_000), {
+ text: 'Cindy',
+ source: 'manual',
+ stage: 'entry',
+ count: 4,
+ nowMs: 1_000,
+ }).state;
+ let clock = createHlcClock('node-a', 2_000);
+
+ for (let round = 0; round < 5; round += 1) {
+ const forward = renameTerm(state, clock, {
+ termKey: 'cindy',
+ nextText: 'Cindy 客户端',
+ nowMs: 2_000 + round * 10,
+ });
+ const backward = renameTerm(forward.state, forward.clock, {
+ termKey: 'cindy 客户端',
+ nextText: 'Cindy',
+ nowMs: 2_005 + round * 10,
+ });
+ state = backward.state;
+ clock = backward.clock;
+ }
+
+ const entries = materializeDictionary(state).entries;
+ expect(entries.map((entry) => entry.text)).toEqual(['Cindy']);
+ expect(entries[0].frequency).toBe(4);
+ });
+
+ it('改名到一个已存在的词上,两边证据相加(那是两批独立证据)', () => {
+ let state = seedTerm(createEmptySyncState(), createHlcClock('node-a', 1_000), {
+ text: 'Cindy',
+ source: 'manual',
+ stage: 'entry',
+ count: 3,
+ nowMs: 1_000,
+ }).state;
+ state = seedTerm(state, createHlcClock('node-a', 1_100), {
+ text: 'sindy',
+ source: 'automatic',
+ stage: 'entry',
+ count: 2,
+ nowMs: 1_100,
+ }).state;
+
+ const renamed = renameTerm(state, createHlcClock('node-a', 2_000), {
+ termKey: 'sindy',
+ nextText: 'Cindy',
+ nowMs: 2_000,
+ });
+ const entries = materializeDictionary(renamed.state).entries;
+ expect(entries.map((entry) => entry.text)).toEqual(['Cindy']);
+ expect(entries[0].frequency).toBe(5);
+ });
+});
+
+describe('自动候选容量裁剪', () => {
+ it('超出硬上限时裁掉最弱的自动候选,不碰手动与正式词条', () => {
+ let state = createEmptySyncState();
+ let clock = createHlcClock('node-a', 1_000);
+
+ // 一条手动词条(频次 1,是最弱的)+ 一条正式的自动词条。
+ const manual = seedTerm(state, clock, {
+ text: '内部代号',
+ source: 'manual',
+ stage: 'entry',
+ count: 1,
+ nowMs: 1_000,
+ });
+ state = manual.state;
+ clock = manual.clock;
+ const entry = seedTerm(state, clock, {
+ text: '正式词',
+ source: 'automatic',
+ stage: 'entry',
+ count: 1,
+ nowMs: 1_001,
+ });
+ state = entry.state;
+ clock = entry.clock;
+
+ // 5 条自动候选,证据数各不相同。
+ for (let index = 0; index < 5; index += 1) {
+ const seeded = seedTerm(state, clock, {
+ text: `候选-${index}`,
+ source: 'automatic',
+ stage: 'candidate',
+ count: index + 1,
+ nowMs: 1_100 + index,
+ });
+ state = seeded.state;
+ clock = seeded.clock;
+ }
+
+ const pruned = pruneWeakAutomaticCandidates(state, clock, { maxRecords: 2, nowMs: 9_000 });
+ expect(pruned.changed).toBe(true);
+
+ const materialized = materializeDictionary(pruned.state);
+ // 手动与正式词条一条不少。
+ expect(materialized.entries.map((item) => item.text).sort()).toEqual(['内部代号', '正式词']);
+ // 只留下证据最多的两条候选。
+ expect(materialized.candidates.map((item) => item.text).sort()).toEqual(['候选-3', '候选-4']);
+ // 裁剪不写抑制:这些词日后再被学到应该能正常回来。
+ expect(materialized.suppressedTexts).toEqual([]);
+ });
+
+ it('没超上限时是空操作', () => {
+ const seeded = seedTerm(createEmptySyncState(), createHlcClock('node-a', 1_000), {
+ text: '候选',
+ source: 'automatic',
+ stage: 'candidate',
+ count: 1,
+ nowMs: 1_000,
+ });
+ const pruned = pruneWeakAutomaticCandidates(seeded.state, seeded.clock, { nowMs: 2_000 });
+ expect(pruned.changed).toBe(false);
+ expect(pruned.state).toBe(seeded.state);
+ expect(MAX_AUTOMATIC_CANDIDATE_RECORDS).toBeGreaterThan(200);
+ });
+
+ it('裁掉的候选重新被学到时能回来(没有被抑制永久压住)', () => {
+ let state = createEmptySyncState();
+ let clock = createHlcClock('node-a', 1_000);
+ for (let index = 0; index < 3; index += 1) {
+ const seeded = seedTerm(state, clock, {
+ text: `候选-${index}`,
+ source: 'automatic',
+ stage: 'candidate',
+ count: index + 1,
+ nowMs: 1_000 + index,
+ });
+ state = seeded.state;
+ clock = seeded.clock;
+ }
+ const pruned = pruneWeakAutomaticCandidates(state, clock, { maxRecords: 1, nowMs: 5_000 });
+ expect(materializeDictionary(pruned.state).candidates.map((item) => item.text)).toEqual(['候选-2']);
+
+ const relearned = recordLearningEvent(pruned.state, pruned.clock, {
+ text: '候选-0',
+ stage: 'candidate',
+ nowMs: 6_000,
+ });
+ expect(materializeDictionary(relearned.state).candidates.map((item) => item.text).sort()).toEqual([
+ '候选-0',
+ '候选-2',
+ ]);
+ });
+});
+
+describe('搬移 tag 的形状', () => {
+ it('改名产生的化身 tag 仍是规范 HLC —— 否则整份状态过不了入站校验', () => {
+ const seeded = seedTerm(createEmptySyncState(), createHlcClock('node-a', 1_000), {
+ text: 'web coding',
+ source: 'automatic',
+ stage: 'entry',
+ count: 3,
+ nowMs: 1_000,
+ });
+ const renamed = renameTerm(seeded.state, seeded.clock, {
+ termKey: 'web coding',
+ nextText: 'Vibe Coding',
+ nowMs: 2_000,
+ });
+
+ // 状态整体必须仍然合法:同步出去的每一帧都要过这道校验。
+ expect(isValidSyncState(renamed.state)).toBe(true);
+ for (const record of Object.values(renamed.state.records)) {
+ for (const tag of Object.keys(record.incarnations)) {
+ expect(`${tag} -> ${isCanonicalHlc(tag)}`).toBe(`${tag} -> true`);
+ }
+ }
+ });
+
+ it('反复改名不会让 tag 越来越长', () => {
+ let state = seedTerm(createEmptySyncState(), createHlcClock('node-a', 1_000), {
+ text: 'A',
+ source: 'manual',
+ stage: 'entry',
+ count: 1,
+ nowMs: 1_000,
+ }).state;
+ let clock = createHlcClock('node-a', 2_000);
+ const lengths = new Set<number>();
+
+ for (let round = 0; round < 6; round += 1) {
+ const from = round % 2 === 0 ? 'a' : 'b';
+ const to = round % 2 === 0 ? 'B' : 'A';
+ const renamed = renameTerm(state, clock, { termKey: from, nextText: to, nowMs: 3_000 + round });
+ state = renamed.state;
+ clock = renamed.clock;
+ for (const record of Object.values(state.records)) {
+ for (const tag of Object.keys(record.incarnations)) lengths.add(tag.length);
+ }
+ }
+
+ // 定长派生:所有 tag 长度都一样(原始 tag 的 nodeId 段长度恰好也可能不同,
+ // 这里只要求搬移之后不再增长)。
+ expect(Math.max(...lengths) - Math.min(...lengths)).toBeLessThanOrEqual(
+ 'node-a'.length - 'mv0000000'.length + 'mv0000000'.length,
+ );
+ expect(materializeDictionary(state).entries.map((entry) => entry.text)).toEqual(['A']);
+ });
+});
diff --git a/packages/voice-input-core/src/dictionary-sync/hlc.ts b/packages/voice-input-core/src/dictionary-sync/hlc.ts
new file mode 100644
index 0000000000..9651fd6350
--- /dev/null
+++ b/packages/voice-input-core/src/dictionary-sync/hlc.ts
@@ -0,0 +1,155 @@
+/**
+ * 混合逻辑时钟(Hybrid Logical Clock)。
+ *
+ * 词典同步没有中心裁决者,LWW 字段(词条显示文本等)只能靠时间戳定序。裸
+ * `Date.now()` 在这里是错的:一台设备的系统时钟往回拨(NTP 校正、用户改时间、
+ * 虚拟机快照恢复)之后,它此后的每一次编辑都会永远输给自己之前的旧编辑,而且
+ * 这种状态无法自愈。HLC 用「墙钟 + 逻辑计数器」保证本机产出的时间戳严格单调
+ * 递增,同时在收到远端更大的时间戳时把自己抬上去,让因果先后跨设备也成立。
+ *
+ * 时间戳序列化成定长前缀的字符串,字典序即时间序,可以直接进 JSON、直接比较、
+ * 直接当对象 key —— 化身 tag 用的就是它。
+ */
+
+/** 墙钟段:base36 定长 10 位,覆盖到公元 3 万年后,不会溢出变短破坏字典序。 */
+const WALL_RADIX_LENGTH = 10;
+/** 逻辑计数器段:base36 定长 4 位;同一毫秒内可容纳 36^4 ≈ 168 万次事件。 */
+const COUNTER_RADIX_LENGTH = 4;
+const COUNTER_MAX = 36 ** COUNTER_RADIX_LENGTH - 1;
+/** `<wall36>.<counter36>.` 的长度 —— 定长前缀部分,nodeId 从这之后开始。 */
+export const HLC_PREFIX_LENGTH = WALL_RADIX_LENGTH + 1 + COUNTER_RADIX_LENGTH + 1;
+
+/**
+ * 形如 `<wall36>.<counter36>.<nodeId>` 的时间戳。
+ *
+ * 前两段定长,所以字符串字典序 === (wall, counter) 字典序;nodeId 只在两者都
+ * 相同时参与 tie-break,保证全序且全网一致。同一 nodeId 产出的时间戳互不重复,
+ * 因此它同时可以直接当作全局唯一 id(化身 tag)。
+ */
+export type HlcTimestamp = string;
+
+/** 单个节点的时钟状态。持久化在同步 sidecar 里,重启后继续单调。 */
+export interface HlcClock {
+ wallMs: number;
+ counter: number;
+ /** 本设备的同步身份;必须全网唯一且跨重启稳定。 */
+ nodeId: string;
+}
+
+export function createHlcClock(nodeId: string, wallMs = 0): HlcClock {
+ const normalizedNodeId = nodeId.trim();
+ if (!normalizedNodeId) throw new Error('hlc nodeId is required');
+ if (normalizedNodeId.includes('.')) throw new Error('hlc nodeId must not contain "."');
+ return { wallMs: Math.max(0, Math.floor(wallMs)), counter: 0, nodeId: normalizedNodeId };
+}
+
+export function formatHlc(clock: HlcClock): HlcTimestamp {
+ const wall = Math.max(0, Math.floor(clock.wallMs)).toString(36).padStart(WALL_RADIX_LENGTH, '0');
+ const counter = Math.max(0, Math.floor(clock.counter)).toString(36).padStart(COUNTER_RADIX_LENGTH, '0');
+ return `${wall}.${counter}.${clock.nodeId}`;
+}
+
+/**
+ * 时间戳是否是本模块产出的规范形式。
+ *
+ * 定序靠的是**字符串字典序**,前提是所有参与比较的时间戳都符合定长格式。一个来自
+ * 坏帧或恶意对端的 `~~~~`(`~` 的码位高于所有 base36 字符)会在每一次 LWW 比较里
+ * 胜出,而且它是持久化的 —— 那个字段此后再也改不动了,用户在任何设备上改词条显示
+ * 文本都会被这个假时间戳压回去。同时它解析出的墙钟是 0,墓碑 TTL 也会算错。
+ *
+ * 所以入站帧里的每一个 tag 与 stamp 都必须先过这一关。
+ */
+export function isCanonicalHlc(value: unknown): value is HlcTimestamp {
+ if (typeof value !== 'string') return false;
+ const wallEnd = WALL_RADIX_LENGTH;
+ const counterEnd = wallEnd + 1 + COUNTER_RADIX_LENGTH;
+ if (value.length < counterEnd + 2) return false;
+ if (value[wallEnd] !== '.' || value[counterEnd] !== '.') return false;
+ if (!isBase36(value.slice(0, wallEnd)) || !isBase36(value.slice(wallEnd + 1, counterEnd))) {
+ return false;
+ }
+ const nodeId = value.slice(counterEnd + 1);
+ // nodeId 不能含 '.',否则同一个字符串能被解析出多种切分。
+ return nodeId.length > 0 && !nodeId.includes('.');
+}
+
+/** 读出产出该时间戳的 nodeId;不是规范形式时返回 null。 */
+export function hlcNodeId(stamp: HlcTimestamp): string | null {
+ if (!isCanonicalHlc(stamp)) return null;
+ return stamp.slice(WALL_RADIX_LENGTH + 1 + COUNTER_RADIX_LENGTH + 1);
+}
+
+function isBase36(segment: string): boolean {
+ for (const char of segment) {
+ const isDigit = char >= '0' && char <= '9';
+ const isLower = char >= 'a' && char <= 'z';
+ if (!isDigit && !isLower) return false;
+ }
+ return segment.length > 0;
+}
+
+/** 解析出墙钟毫秒;只用于墓碑 TTL 与展示,不参与定序(定序一律用字符串比较)。 */
+export function hlcWallMs(stamp: HlcTimestamp): number {
+ const wall = stamp.slice(0, WALL_RADIX_LENGTH);
+ const parsed = Number.parseInt(wall, 36);
+ return Number.isFinite(parsed) ? parsed : 0;
+}
+
+/** 全序比较。定长前缀让朴素字符串比较就是正确的时间序。 */
+export function compareHlc(a: HlcTimestamp, b: HlcTimestamp): number {
+ if (a === b) return 0;
+ return a < b ? -1 : 1;
+}
+
+export function maxHlc(a: HlcTimestamp, b: HlcTimestamp): HlcTimestamp {
+ return compareHlc(a, b) >= 0 ? a : b;
+}
+
+export function minHlc(a: HlcTimestamp, b: HlcTimestamp): HlcTimestamp {
+ return compareHlc(a, b) <= 0 ? a : b;
+}
+
+/**
+ * 产出本机下一个时间戳。返回新时钟而不是就地改,便于调用方在写盘成功后才提交。
+ *
+ * 墙钟没有前进(同一毫秒内连续事件,或系统时钟回拨)时递增逻辑计数器,因此本机
+ * 时间戳严格单调 —— 时钟回拨不会让新事件被判定为「旧」。
+ */
+export function tickHlc(clock: HlcClock, nowMs: number): { clock: HlcClock; stamp: HlcTimestamp } {
+ const now = Math.max(0, Math.floor(nowMs));
+ const next: HlcClock = now > clock.wallMs
+ ? { wallMs: now, counter: 0, nodeId: clock.nodeId }
+ : { wallMs: clock.wallMs, counter: clock.counter + 1, nodeId: clock.nodeId };
+ if (next.counter > COUNTER_MAX) {
+ // 同一毫秒挤满 168 万次事件:借下一毫秒继续,宁可让墙钟略微超前也不能让
+ // 计数器进位破坏定长前缀(那会让字典序不再等于时间序)。
+ return tickHlc({ wallMs: clock.wallMs + 1, counter: -1, nodeId: clock.nodeId }, now);
+ }
+ return { clock: next, stamp: formatHlc(next) };
+}
+
+/**
+ * 收到远端时间戳后抬高本地时钟,让本机之后产出的时间戳一定大于已观察到的一切。
+ * 每次合并远端状态后调用一次(传入该状态里最大的时间戳)。
+ */
+export function observeHlc(clock: HlcClock, remote: HlcTimestamp, nowMs: number): HlcClock {
+ const remoteWall = hlcWallMs(remote);
+ const remoteCounter = readCounter(remote);
+ const now = Math.max(0, Math.floor(nowMs));
+ const wallMs = Math.max(clock.wallMs, remoteWall, now);
+ if (wallMs > clock.wallMs && wallMs > remoteWall) {
+ return { wallMs, counter: 0, nodeId: clock.nodeId };
+ }
+ const counter = wallMs === clock.wallMs && wallMs === remoteWall
+ ? Math.max(clock.counter, remoteCounter)
+ : wallMs === remoteWall
+ ? remoteCounter
+ : clock.counter;
+ return { wallMs, counter, nodeId: clock.nodeId };
+}
+
+function readCounter(stamp: HlcTimestamp): number {
+ const start = WALL_RADIX_LENGTH + 1;
+ const parsed = Number.parseInt(stamp.slice(start, start + COUNTER_RADIX_LENGTH), 36);
+ return Number.isFinite(parsed) ? parsed : 0;
+}
diff --git a/packages/voice-input-core/src/dictionary-sync/index.ts b/packages/voice-input-core/src/dictionary-sync/index.ts
new file mode 100644
index 0000000000..7aaf606280
--- /dev/null
+++ b/packages/voice-input-core/src/dictionary-sync/index.ts
@@ -0,0 +1,21 @@
+/**
+ * 语音词典多设备同步核心(provider 无关、进程无关的纯逻辑)。
+ *
+ * 词典正本从「每台设备一份本地 JSON」变成「设备间对等收敛的 CRDT 状态」:桌面
+ * 之间经 device-link 的 push 帧交换整份状态,relay 只转发不解析,词典内容不经过
+ * 任何服务端存储。本包只负责状态与合并;落盘、传输、UI 接线在 desktop 侧。
+ *
+ * 入口按职责分四层:
+ * - `types` / `hlc` / `text`:状态模型、时间戳、主键归一化
+ * - `merge`:状态合并(幂等 / 可交换 / 可结合)
+ * - `mutate`:本地变更原语(计数增长的唯一入口)
+ * - `materialize`:确定性物化成词典设置三件套
+ */
+
+export * from './types';
+export * from './hlc';
+export * from './text';
+export * from './merge';
+export * from './mutate';
+export * from './materialize';
+export * from './reconcile';
diff --git a/packages/voice-input-core/src/dictionary-sync/materialize.ts b/packages/voice-input-core/src/dictionary-sync/materialize.ts
new file mode 100644
index 0000000000..246521c210
--- /dev/null
+++ b/packages/voice-input-core/src/dictionary-sync/materialize.ts
@@ -0,0 +1,219 @@
+/**
+ * 把 CRDT 状态物化成词典设置里的三件套(entries / candidates / suppressed)。
+ *
+ * 物化必须是**确定性**的:同一份状态在任何设备上算出的结果逐字节相同。上限裁决
+ * 因此收在这里,而不是交给下游的 normalize 去截断 —— 各设备各截各的会让「谁被
+ * 截掉」不一致,而截断产生的「词条消失」一旦被回收逻辑误判成用户删除,就会生成
+ * 墓碑广播出去,批量误删全网词条。
+ *
+ * 结论:**被上限挤出去的词条只是不物化,永远不生成墓碑**,它们留在状态里休眠,
+ * 频次涨回来自然会重新出现。
+ */
+
+import { compareHlc } from './hlc';
+import {
+ hasDictionaryKey,
+ listLiveIncarnations,
+ readCounterTotal,
+ type DictionaryIncarnation,
+ type DictionaryTermSource,
+ type VoiceDictionarySyncState,
+} from './types';
+
+/** 与 desktop `voiceInputData.ts` 的同名常量保持一致。 */
+export const DEFAULT_MATERIALIZE_LIMITS = {
+ maxEntries: 1_000,
+ maxCandidates: 200,
+ maxAliases: 8,
+} as const;
+
+export interface MaterializeLimits {
+ maxEntries: number;
+ maxCandidates: number;
+ maxAliases: number;
+}
+
+export interface MaterializedAlias {
+ text: string;
+ count: number;
+ lastSeenAt: number;
+}
+
+export interface MaterializedEntry {
+ id: string;
+ text: string;
+ source: DictionaryTermSource;
+ frequency: number;
+ aliases: MaterializedAlias[];
+ createdAt: number;
+ updatedAt: number;
+}
+
+export interface MaterializedCandidate {
+ text: string;
+ evidenceCount: number;
+ aliases: MaterializedAlias[];
+ createdAt: number;
+ updatedAt: number;
+}
+
+export interface MaterializedDictionary {
+ entries: MaterializedEntry[];
+ candidates: MaterializedCandidate[];
+ suppressedTexts: string[];
+}
+
+/**
+ * 物化出的词条 id。
+ *
+ * 由归一化主键确定性派生,而不是沿用某个化身的 tag:UI 拿 id 发起删除,id 必须
+ * 在「同一个词的化身来来去去」的过程中保持稳定,并且全网一致(否则同一条词在两
+ * 台设备上 React key 不同、删除请求也对不上)。
+ */
+export const MATERIALIZED_ID_PREFIX = 'dict-sync-';
+
+export function materializedEntryId(termKey: string): string {
+ return `${MATERIALIZED_ID_PREFIX}${termKey}`;
+}
+
+/** 跨存活化身取展示文本:LWW,时间戳相同时按化身 tag 兜底,保证全网一致。 */
+export function pickDisplayText(live: ReadonlyArray<DictionaryIncarnation>): string {
+ return live.reduce((best, item) => {
+ const order = compareHlc(item.textStamp, best.textStamp);
+ if (order > 0) return item;
+ if (order < 0) return best;
+ return item.tag > best.tag ? item : best;
+ }, live[0]).text;
+}
+
+export function materializeDictionary(
+ state: VoiceDictionarySyncState,
+ limits: MaterializeLimits = DEFAULT_MATERIALIZE_LIMITS,
+): MaterializedDictionary {
+ const entries: Array<MaterializedEntry & { key: string }> = [];
+ const candidates: Array<MaterializedCandidate & { key: string }> = [];
+
+ for (const [key, record] of Object.entries(state.records)) {
+ const live = listLiveIncarnations(record);
+ if (live.length === 0) continue;
+
+ const source: DictionaryTermSource = live.some((item) => item.source === 'manual')
+ ? 'manual'
+ : 'automatic';
+ // 抑制只压制自动学习的产物。用户手动添加过的同名词条不受影响 —— 与 desktop
+ // 单机语义一致(手动词条的删除本来就不写抑制集合)。
+ if (source === 'automatic' && hasDictionaryKey(state.suppressed, key)) continue;
+
+ 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 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);
+
+ if (stage === 'entry') {
+ entries.push({
+ key,
+ id: materializedEntryId(key),
+ text,
+ source,
+ frequency: total,
+ aliases,
+ createdAt,
+ updatedAt,
+ });
+ } else {
+ candidates.push({ key, text, evidenceCount: total, aliases, createdAt, updatedAt });
+ }
+ }
+
+ return {
+ entries: sortAndCap(
+ entries,
+ (item) => item.frequency,
+ limits.maxEntries,
+ (item) => (item.source === 'manual' ? 1 : 0),
+ ).map(stripKey),
+ candidates: sortAndCap(candidates, (item) => item.evidenceCount, limits.maxCandidates).map(stripKey),
+ suppressedTexts: Object.keys(state.suppressed)
+ .sort()
+ .map((key) => state.suppressed[key].text),
+ };
+}
+
+/**
+ * 跨存活化身合并别名。
+ *
+ * 同一别名在不同化身上的计数**相加** —— 它们是不同化身各自观察到的独立事件。
+ * (化身内部按节点分桶取 max 已经在合并阶段做完,这里不会重复计入同一事件。)
+ */
+function mergeLiveAliases(
+ live: ReadonlyArray<DictionaryIncarnation>,
+ maxAliases: number,
+): 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 existing = totals.get(aliasKey);
+ if (!existing) {
+ totals.set(aliasKey, {
+ text: alias.text,
+ textStamp: alias.textStamp,
+ count,
+ lastSeenAt: alias.lastSeenAt,
+ });
+ continue;
+ }
+ const newerText = compareHlc(alias.textStamp, existing.textStamp) > 0;
+ totals.set(aliasKey, {
+ text: newerText ? alias.text : existing.text,
+ textStamp: newerText ? alias.textStamp : existing.textStamp,
+ count: existing.count + count,
+ lastSeenAt: Math.max(existing.lastSeenAt, alias.lastSeenAt),
+ });
+ }
+ }
+
+ return [...totals.entries()]
+ .filter(([, alias]) => alias.count > 0)
+ // 排序尾键用别名主键:desktop 现有排序(count desc, lastSeenAt desc)在并列时
+ // 结果依赖数组原始顺序,跨设备不一致。这里补确定性尾键。
+ .sort(([keyA, a], [keyB, b]) => b.count - a.count || b.lastSeenAt - a.lastSeenAt || (keyA < keyB ? -1 : 1))
+ .slice(0, maxAliases)
+ .map(([, alias]) => ({ text: alias.text, count: alias.count, lastSeenAt: alias.lastSeenAt }));
+}
+
+/**
+ * 排序并裁到上限。
+ *
+ * `readRank`(数值大者优先)只决定**谁被裁掉**,不影响最终展示顺序:多设备合并后
+ * 存活词条可能超过上限,纯按频次裁会让用户手动加的低频词被自动学来的高频词挤掉 ——
+ * 那个词在所有设备上一起消失,而且它频次本来就低,再也涨不回来。手动词条是用户的
+ * 显式意图,必须先保下来;保下来之后仍按频次展示。
+ */
+function sortAndCap<T extends { key: string; updatedAt: number }>(
+ items: T[],
+ readWeight: (item: T) => number,
+ limit: number,
+ readRank: (item: T) => number = () => 0,
+): T[] {
+ const byWeight = (a: T, b: T): number =>
+ readWeight(b) - readWeight(a) || b.updatedAt - a.updatedAt || (a.key < b.key ? -1 : 1);
+ const capped = Math.max(0, limit);
+ const ordered = [...items].sort(byWeight);
+ if (ordered.length <= capped) return ordered;
+ const survivors = new Set(
+ [...ordered]
+ .sort((a, b) => readRank(b) - readRank(a) || byWeight(a, b))
+ .slice(0, capped)
+ .map((item) => item.key),
+ );
+ return ordered.filter((item) => survivors.has(item.key));
+}
+
+function stripKey<T extends { key: string }>(item: T): Omit<T, 'key'> {
+ const rest = { ...item } as Partial<T>;
+ delete rest.key;
+ return rest as Omit<T, 'key'>;
+}
diff --git a/packages/voice-input-core/src/dictionary-sync/merge.ts b/packages/voice-input-core/src/dictionary-sync/merge.ts
new file mode 100644
index 0000000000..370acc6576
--- /dev/null
+++ b/packages/voice-input-core/src/dictionary-sync/merge.ts
@@ -0,0 +1,264 @@
+/**
+ * 状态合并 —— 整个同步方案的正确性所在。
+ *
+ * 本模块的每个函数都必须满足三条代数性质(由 `dictionarySyncMerge.test.ts` 的
+ * 随机性质测试守护):
+ *
+ * 幂等 merge(a, a) = a
+ * 交换 merge(a, b) = merge(b, a)
+ * 结合 merge(merge(a, b), c) = merge(a, merge(b, c))
+ *
+ * 满足这三条,同步链路就不需要任何可靠投递保证:丢帧、重复投递、乱序、设备以
+ * 任意拓扑任意轮数互相合并,最终状态都相同。改这里的任何一行之前,先确认新逻辑
+ * 仍然满足这三条 —— 尤其**不要把任何计数改成相加**,那会破坏幂等并让词典频次
+ * 随同步次数膨胀。
+ */
+
+import { compareHlc, hlcNodeId, maxHlc, minHlc, type HlcTimestamp } from './hlc';
+import {
+ VOICE_DICTIONARY_SYNC_VERSION,
+ createDictionaryMap,
+ createEmptySyncState,
+ type DictionaryIncarnation,
+ type DictionaryRecord,
+ type DictionaryStage,
+ type DictionarySuppression,
+ type DictionaryTermSource,
+ type GCounter,
+ type SyncAliasState,
+ type VoiceDictionarySyncState,
+} from './types';
+
+/**
+ * 逐节点取 max。
+ *
+ * **不是相加** —— 相加会破坏幂等:A 和 B 各持 {A:3},相加后各得 6,再同步一轮
+ * 各得 12,如此指数膨胀。只有产生事件的节点会递增自己那一桶,所以对同一份事件
+ * 历史,逐节点 max 得到的正是每个节点的真实事件数,求和即全局真实总数。
+ */
+export function mergeCounters(a: GCounter, b: GCounter): GCounter {
+ const merged: GCounter = createDictionaryMap<number>();
+ for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
+ const left = normalizeCount(a[key]);
+ const right = normalizeCount(b[key]);
+ const value = Math.max(left, right);
+ 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);
+}
+
+/** LWW 寄存器:HLC 大者胜;完全相同的时间戳只可能来自同一次写入,取值也相同。 */
+function mergeLww<T>(
+ a: { value: T; stamp: HlcTimestamp },
+ b: { value: T; stamp: HlcTimestamp },
+): { value: T; stamp: HlcTimestamp } {
+ const order = compareHlc(a.stamp, b.stamp);
+ if (order > 0) return a;
+ if (order < 0) return b;
+ // 时间戳相等时按值排序做 tie-break:HLC 全局唯一,理论上走不到这里,但保证
+ // 合并对「构造出来的异常状态」也是确定性的,不会让两台设备算出不同结果。
+ return String(a.value) >= String(b.value) ? a : b;
+}
+
+function mergeAliasState(a: SyncAliasState, b: SyncAliasState): SyncAliasState {
+ const text = mergeLww({ value: a.text, stamp: a.textStamp }, { value: b.text, stamp: b.textStamp });
+ return {
+ text: text.value,
+ textStamp: text.stamp,
+ counters: mergeCounters(a.counters, b.counters),
+ lastSeenAt: Math.max(a.lastSeenAt, b.lastSeenAt),
+ };
+}
+
+function mergeAliases(
+ a: Record<string, SyncAliasState>,
+ b: Record<string, SyncAliasState>,
+): Record<string, SyncAliasState> {
+ const merged: Record<string, SyncAliasState> = 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] = mergeAliasState(left, right);
+ else merged[key] = left ?? right;
+ }
+ return merged;
+}
+
+/** manual-wins:用户手动确认过的词条不会因为后台自动学习退回 automatic。 */
+function mergeSource(a: DictionaryTermSource, b: DictionaryTermSource): DictionaryTermSource {
+ return a === 'manual' || b === 'manual' ? 'manual' : 'automatic';
+}
+
+/** entry-wins:任一端把候选晋升为正式词条,合并后全网都是正式词条。 */
+function mergeStage(a: DictionaryStage, b: DictionaryStage): DictionaryStage {
+ return a === 'entry' || b === 'entry' ? 'entry' : 'candidate';
+}
+
+/**
+ * 同 tag 的两份化身副本合并。tag 相同意味着它们源自同一次创建,差异只可能来自
+ * 各自后续观察到的事件。
+ */
+function mergeIncarnation(a: DictionaryIncarnation, b: DictionaryIncarnation): DictionaryIncarnation {
+ const text = mergeLww({ value: a.text, stamp: a.textStamp }, { value: b.text, stamp: b.textStamp });
+ return {
+ tag: a.tag,
+ text: text.value,
+ textStamp: text.stamp,
+ source: mergeSource(a.source, b.source),
+ stage: mergeStage(a.stage, b.stage),
+ counters: mergeCounters(a.counters, b.counters),
+ aliases: mergeAliases(a.aliases, b.aliases),
+ createdAt: Math.min(a.createdAt, b.createdAt),
+ updatedAt: Math.max(a.updatedAt, b.updatedAt),
+ };
+}
+
+function mergeRecord(a: DictionaryRecord, b: DictionaryRecord): DictionaryRecord {
+ const incarnations: Record<HlcTimestamp, DictionaryIncarnation> = createDictionaryMap<DictionaryIncarnation>();
+ for (const tag of new Set([...Object.keys(a.incarnations), ...Object.keys(b.incarnations)])) {
+ const left = a.incarnations[tag];
+ const right = b.incarnations[tag];
+ if (left && right) incarnations[tag] = mergeIncarnation(left, right);
+ else incarnations[tag] = left ?? right;
+ }
+
+ // 墓碑是只增集合:一旦某个化身被删,任何一方的合并结果里它都保持被删。
+ // 同 tag 的删除时间取 max —— 取 min 会让墓碑提前过 TTL 被回收,给「离线设备
+ // 回来复活旧化身」多开一道门。
+ const tombstones: Record<HlcTimestamp, HlcTimestamp> = createDictionaryMap<HlcTimestamp>();
+ for (const tag of new Set([...Object.keys(a.tombstones), ...Object.keys(b.tombstones)])) {
+ const left = a.tombstones[tag];
+ const right = b.tombstones[tag];
+ tombstones[tag] = left && right ? maxHlc(left, right) : (left ?? right);
+ }
+
+ return { incarnations, tombstones };
+}
+
+/** 抑制项取首次抑制时间(min),保证与合并顺序无关。 */
+function mergeSuppression(a: DictionarySuppression, b: DictionarySuppression): DictionarySuppression {
+ const order = compareHlc(a.stamp, b.stamp);
+ const stamp = minHlc(a.stamp, b.stamp);
+ const text = order === 0 ? (a.text >= b.text ? a.text : b.text) : order < 0 ? a.text : b.text;
+ return { text, stamp };
+}
+
+/**
+ * 合并两份完整状态。纯函数:两个入参都不被修改。
+ *
+ * 版本更高的一方原样返回(不猜着合并未知结构);两边版本都未知时返回空状态而不是
+ * 抛错 —— 同步链路上一个坏帧不该让本机词典功能挂掉。
+ */
+export function mergeSyncStates(
+ a: VoiceDictionarySyncState,
+ b: VoiceDictionarySyncState,
+): VoiceDictionarySyncState {
+ if (a.version !== VOICE_DICTIONARY_SYNC_VERSION || b.version !== VOICE_DICTIONARY_SYNC_VERSION) {
+ if (a.version === VOICE_DICTIONARY_SYNC_VERSION) return a;
+ if (b.version === VOICE_DICTIONARY_SYNC_VERSION) return b;
+ return createEmptySyncState();
+ }
+
+ const records: Record<string, DictionaryRecord> = createDictionaryMap<DictionaryRecord>();
+ for (const key of new Set([...Object.keys(a.records), ...Object.keys(b.records)])) {
+ const left = a.records[key];
+ const right = b.records[key];
+ if (left && right) records[key] = mergeRecord(left, right);
+ else records[key] = left ?? right;
+ }
+
+ const suppressed: Record<string, DictionarySuppression> = createDictionaryMap<DictionarySuppression>();
+ for (const key of new Set([...Object.keys(a.suppressed), ...Object.keys(b.suppressed)])) {
+ const left = a.suppressed[key];
+ const right = b.suppressed[key];
+ if (left && right) suppressed[key] = mergeSuppression(left, right);
+ else suppressed[key] = left ?? right;
+ }
+
+ return { version: VOICE_DICTIONARY_SYNC_VERSION, records, suppressed };
+}
+
+/** 合并多份状态(设备上线时一次性收敛)。空数组返回空状态。 */
+export function mergeAllSyncStates(
+ states: ReadonlyArray<VoiceDictionarySyncState>,
+): VoiceDictionarySyncState {
+ return states.reduce<VoiceDictionarySyncState>(
+ (acc, state) => mergeSyncStates(acc, state),
+ createEmptySyncState(),
+ );
+}
+
+/**
+ * 状态的版本向量:每个 nodeId 在这份状态里出现过的最大时间戳。
+ *
+ * 用来判断两份状态之间的**包含关系**,而不是谁的时间戳大。单看最大 HLC 是错的:
+ * 设备 A 在 HLC 100 加了 `foo`、设备 B 在 HLC 101 加了 `bar`,两份状态互不包含,
+ * 但按最大值比会宣称 B 更新 —— 拿 B 当"完整答案"就漏掉了 `foo`。
+ *
+ * 向量对合并单调:`merge(a, b)` 的向量逐节点取 max,所以「A 的向量逐节点 ≥ B」
+ * 等价于「A 已经见过 B 的全部事件」,这才是可以放心替代 B 的条件。
+ */
+export function buildStateVersionVector(state: VoiceDictionarySyncState): Record<string, string> {
+ const vector: Record<string, string> = Object.create(null) as Record<string, string>;
+ const observe = (stamp: HlcTimestamp | undefined): void => {
+ if (!stamp) return;
+ const nodeId = hlcNodeId(stamp);
+ if (!nodeId) return;
+ const current = vector[nodeId];
+ if (current === undefined || compareHlc(stamp, current) > 0) vector[nodeId] = stamp;
+ };
+ for (const record of Object.values(state.records)) {
+ for (const incarnation of Object.values(record.incarnations)) {
+ observe(incarnation.tag);
+ observe(incarnation.textStamp);
+ for (const alias of Object.values(incarnation.aliases)) observe(alias.textStamp);
+ }
+ for (const stamp of Object.values(record.tombstones)) observe(stamp);
+ }
+ for (const suppression of Object.values(state.suppressed)) observe(suppression.stamp);
+ // 原样返回无原型字典 —— 展开成 `{...vector}` 会把 Object.prototype 装回去,而
+ // nodeId 是可以长成 `__proto__` / `constructor` 的(`isCanonicalHlc` 只要求它非空
+ // 且不含 '.'),那样包含性比较会读到原型链上的值。JSON 序列化不受影响。
+ return vector;
+}
+
+/**
+ * `a` 是否已经见过 `b` 的全部事件(逐节点 ≥)。
+ *
+ * 互不包含(并发)时两边都返回 false —— 调用方必须为这种情况准备一条独立的决策,
+ * 不能默认"那就选 a"。
+ */
+export function versionVectorDominates(
+ a: Readonly<Record<string, string>>,
+ b: Readonly<Record<string, string>>,
+): boolean {
+ for (const [nodeId, stamp] of Object.entries(b)) {
+ const mine = a[nodeId];
+ if (mine === undefined || compareHlc(mine, stamp) < 0) return false;
+ }
+ return true;
+}
+
+/** 状态里最大的 HLC,用于收到远端状态后抬高本地时钟(见 `observeHlc`)。 */
+export function findMaxHlc(state: VoiceDictionarySyncState): HlcTimestamp | null {
+ let max: HlcTimestamp | null = null;
+ const observe = (stamp: HlcTimestamp | undefined): void => {
+ if (!stamp) return;
+ max = max === null ? stamp : maxHlc(max, stamp);
+ };
+ for (const record of Object.values(state.records)) {
+ for (const incarnation of Object.values(record.incarnations)) {
+ observe(incarnation.tag);
+ observe(incarnation.textStamp);
+ for (const alias of Object.values(incarnation.aliases)) observe(alias.textStamp);
+ }
+ for (const stamp of Object.values(record.tombstones)) observe(stamp);
+ }
+ for (const suppression of Object.values(state.suppressed)) observe(suppression.stamp);
+ return max;
+}
diff --git a/packages/voice-input-core/src/dictionary-sync/mutate.ts b/packages/voice-input-core/src/dictionary-sync/mutate.ts
new file mode 100644
index 0000000000..4c017a1fe4
--- /dev/null
+++ b/packages/voice-input-core/src/dictionary-sync/mutate.ts
@@ -0,0 +1,734 @@
+/**
+ * 本地变更原语:把「用户/学习器做了什么」翻译成对 CRDT 状态的一次操作。
+ *
+ * 全部是纯函数,返回新状态与新时钟,由调用方在写盘成功后再提交 —— 时钟一旦
+ * 前进就不能回退(回退会让此后产出的时间戳与已广播出去的产生冲突)。
+ *
+ * ## 计数只在这里增长
+ *
+ * 词典频次的唯一增长入口是本模块:每个真实事件让**本节点自己那一桶** +1。合并
+ * 永远不产生新计数(逐节点取 max),物化永远不产生新计数(只读求和)。所以频次
+ * 恒等于真实事件数,与同步了多少次、以什么拓扑同步无关。
+ */
+
+import { HLC_PREFIX_LENGTH, tickHlc, type HlcClock, type HlcTimestamp } from './hlc';
+import { MATERIALIZED_ID_PREFIX, materializeDictionary, pickDisplayText } from './materialize';
+import { dictionaryTermKey, normalizeDictionaryTermText } from './text';
+import {
+ copyDictionaryMap,
+ createDictionaryMap,
+ hasDictionaryKey,
+ listLiveIncarnations,
+ readCounterTotal,
+ withDictionaryKey,
+ type DictionaryIncarnation,
+ type DictionaryRecord,
+ type DictionaryStage,
+ type DictionaryTermSource,
+ type SyncAliasState,
+ type VoiceDictionarySyncState,
+} from './types';
+
+export interface MutationResult {
+ state: VoiceDictionarySyncState;
+ clock: HlcClock;
+ /** 本次操作是否真的改变了状态;false 时调用方可以跳过写盘与广播。 */
+ changed: boolean;
+}
+
+export interface LearningEventInput {
+ /** 词条原文(未归一化亦可)。 */
+ text: string;
+ /** 本次观察到的误识别写法。 */
+ aliases?: string[];
+ /** 目标阶段:攒证据用 'candidate',晋升或已是正式词条用 'entry'。 */
+ stage: DictionaryStage;
+ nowMs: number;
+}
+
+/**
+ * 记录一次自动学习事件。
+ *
+ * 对齐 desktop `applyVoiceInputDictionaryLearningActions` 的语义:
+ * - 已存在(有存活化身)→ 在其中一个化身上 +1,顺带按 stage 提级;
+ * - 不存在 → 新建化身,计数从 1 起;
+ * - 被抑制的词不会被自动学习重新建出来(但已存在的化身照常 +1 —— 抑制只在
+ * 物化阶段压制显示,这样「A 删除」与「B 并发学习」并发时删除意图不被绕过)。
+ *
+ * 晋升不需要特判:候选阶段攒下的计数就挂在同一个化身上,晋升事件 +1 之后总数
+ * 自然等于 desktop 单机路径的 `evidenceCount + 1`。
+ */
+export function recordLearningEvent(
+ state: VoiceDictionarySyncState,
+ clock: HlcClock,
+ input: LearningEventInput,
+): MutationResult {
+ const text = normalizeDictionaryTermText(input.text);
+ const key = dictionaryTermKey(text);
+ if (!key) return { state, clock, changed: false };
+
+ const record = state.records[key];
+ const live = record ? listLiveIncarnations(record) : [];
+ // 用户删除过这条自动词条:既不重新建出来,也不给残留的自动化身继续记证据。
+ // 后者看起来无害(物化阶段本来就会被抑制压住),但每次学习都会改状态 → 触发
+ // 写盘与同步广播,而且计数一直涨,是纯粹的浪费。用户手动把词加回来之后
+ // (存在 manual 存活化身)才恢复正常学习。
+ if (hasDictionaryKey(state.suppressed, key) && !live.some((item) => item.source === 'manual')) {
+ return { state, clock, changed: false };
+ }
+
+ const aliasTexts = normalizeAliasTexts(input.aliases, key);
+ const ticked = tickHlc(clock, input.nowMs);
+
+ if (live.length === 0) {
+ return {
+ state: putRecord(state, key, {
+ incarnations: {
+ [ticked.stamp]: createIncarnation({
+ tag: ticked.stamp,
+ text,
+ source: 'automatic',
+ stage: input.stage,
+ nodeId: clock.nodeId,
+ aliasTexts,
+ nowMs: input.nowMs,
+ }),
+ },
+ tombstones: record?.tombstones ?? {},
+ }),
+ clock: ticked.clock,
+ changed: true,
+ };
+ }
+
+ // 确定性地落在同一个化身上(存活化身按 tag 升序,取第一个),避免每次学习都
+ // 新建化身让状态无限膨胀。落在哪个化身上不影响总数:计数按节点分桶,不同设备
+ // 各记各的桶,合并后求和仍是真实事件总数。
+ const target = live[0];
+ return {
+ state: putRecord(state, key, {
+ ...record!,
+ incarnations: {
+ ...copyDictionaryMap(record!.incarnations),
+ [target.tag]: bumpIncarnation(target, {
+ nodeId: clock.nodeId,
+ stage: input.stage,
+ aliasTexts,
+ stamp: ticked.stamp,
+ nowMs: input.nowMs,
+ }),
+ },
+ }),
+ clock: ticked.clock,
+ changed: true,
+ };
+}
+
+export interface SeedTermInput {
+ /**
+ * 允许在「只剩墓碑」的键上重建化身。默认 true(降级回收语义)。
+ * sidecar 恢复认领必须显式传 false —— 见 seedTerm 内的说明。
+ */
+ allowTombstonedRevival?: boolean;
+ text: string;
+ source: DictionaryTermSource;
+ stage: DictionaryStage;
+ /** 已积累的证据次数(来自被认领的词典文件),至少按 1 计。 */
+ count: number;
+ /**
+ * 已积累的别名(误识别写法)及其次数。
+ *
+ * 别名是词典纠错能力的主体 —— 「web coding → Vibe Coding」这类映射全靠它。
+ * 认领时不带上,存量用户升级后纠错能力就凭空退化了,而且下一次物化写回文件
+ * 就永久丢失。
+ */
+ aliases?: ReadonlyArray<{ text: string; count?: number }>;
+ nowMs: number;
+}
+
+/**
+ * 以既有频次「种下」一个词条 —— 只用于把一份状态之外的词典认领进来。
+ *
+ * 与 {@link recordLearningEvent} 的区别是它一次写入 N 次证据,而不是 +1。这个能力
+ * 很危险,所以有一道硬约束:**只在该词条完全不存在于状态里时才生效**(连墓碑都
+ * 没有)。已经存在的词条一律不碰 —— 否则合并进来的远端计数会被文件里的数字覆盖
+ * 或重复记账,那正是词典频次膨胀的经典成因。
+ */
+/**
+ * 把某个词的存活化身提升为正式词条,不动计数。
+ *
+ * stage 是 entry-wins 单调寄存器,提升只会前进不会回退。降级期间老客户端把候选词
+ * 转正时会用到:那个键从没进过 `lastMaterializedKeys`,而状态里已有存活的候选化身,
+ * `seedTerm` 会因此判定「已存在」而放过 —— 不补这一步,转正就在下次物化时被写回候选。
+ */
+export function promoteTermToEntry(
+ state: VoiceDictionarySyncState,
+ clock: HlcClock,
+ input: { termKey: string; nowMs: number },
+): MutationResult {
+ const record = state.records[input.termKey];
+ if (!record) return { state, clock, changed: false };
+ const live = listLiveIncarnations(record);
+ if (live.length === 0 || live.every((item) => item.stage === 'entry')) {
+ return { state, clock, changed: false };
+ }
+
+ const incarnations = copyDictionaryMap(record.incarnations);
+ for (const incarnation of live) {
+ if (incarnation.stage === 'entry') continue;
+ incarnations[incarnation.tag] = { ...incarnation, stage: 'entry', updatedAt: input.nowMs };
+ }
+ return {
+ state: putRecord(state, input.termKey, { ...record, incarnations }),
+ clock,
+ changed: true,
+ };
+}
+
+export function seedTerm(
+ state: VoiceDictionarySyncState,
+ clock: HlcClock,
+ input: SeedTermInput,
+): MutationResult {
+ const text = normalizeDictionaryTermText(input.text);
+ const key = dictionaryTermKey(text);
+ if (!key) return { state, clock, changed: false };
+ // 判据是「有没有存活化身」,不是「记录键在不在」。一个被删过又被旧版本重新加
+ // 回来的词,记录里只剩墓碑 —— 按键存在就跳过的话,回收永远认领不了它,那条词
+ // 在升级后就凭空消失了。新化身自带新 tag,旧墓碑覆盖不到它。
+ const existing = state.records[key];
+ if (existing && listLiveIncarnations(existing).length > 0) {
+ return { state, clock, changed: false };
+ }
+ // sidecar 丢失后的恢复认领必须尊重对端墓碑:本机没有身份历史,新化身自带新 tag,
+ // 对端那条删除盖不住它 —— 用户在另一台电脑删掉的词会在合并后复活。降级回收则相反,
+ // 那时投影是老客户端刚写下的新证据,越过墓碑重建才是对的。
+ if (existing && input.allowTombstonedRevival === false) {
+ return { state, clock, changed: false };
+ }
+ if (input.source === 'automatic' && hasDictionaryKey(state.suppressed, key)) {
+ return { state, clock, changed: false };
+ }
+
+ const ticked = tickHlc(clock, input.nowMs);
+ const count = Math.max(1, Math.floor(input.count));
+ const incarnation = createIncarnation({
+ tag: ticked.stamp,
+ text,
+ source: input.source,
+ stage: input.stage,
+ nodeId: clock.nodeId,
+ aliasTexts: [],
+ nowMs: input.nowMs,
+ });
+
+ // 别名按各自既有次数种下(同样只在首次认领时发生,不会重复记账)。
+ const aliases = createDictionaryMap<SyncAliasState>();
+ for (const alias of input.aliases ?? []) {
+ const aliasText = normalizeDictionaryTermText(alias?.text);
+ const aliasKey = dictionaryTermKey(aliasText);
+ if (!aliasKey || aliasKey === key || hasDictionaryKey(aliases, aliasKey)) continue;
+ aliases[aliasKey] = {
+ text: aliasText,
+ textStamp: ticked.stamp,
+ counters: withDictionaryKey(null, clock.nodeId, Math.max(1, Math.floor(alias?.count ?? 1))),
+ lastSeenAt: input.nowMs,
+ };
+ }
+
+ const incarnations = createDictionaryMap<DictionaryIncarnation>();
+ incarnations[ticked.stamp] = {
+ ...incarnation,
+ counters: withDictionaryKey(null, clock.nodeId, count),
+ aliases,
+ };
+ return {
+ state: putRecord(state, key, {
+ incarnations: { ...copyDictionaryMap(existing?.incarnations), ...incarnations },
+ // 墓碑必须留着:它们对应的是旧化身,丢掉会让那些化身在别的设备上复活。
+ tombstones: copyDictionaryMap(existing?.tombstones),
+ }),
+ clock: ticked.clock,
+ changed: true,
+ };
+}
+
+export interface ManualEntryInput {
+ text: string;
+ nowMs: number;
+}
+
+/**
+ * 手动添加词条(设置页输入或 CSV 导入的单条)。
+ *
+ * 手动添加不受抑制集合限制 —— 用户显式要它回来。
+ *
+ * ## 为什么总是新建化身,而不是原地改已有化身
+ *
+ * 「A 上删除」与「B 上手动添加同一个词」并发时,用户在两台设备上表达了相反的
+ * 意图,没有先后可言。这里选 **add-wins**:显式添加胜出。词典多留一个词的代价,
+ * 远小于用户明确添加的词莫名消失。
+ *
+ * 原地改已有化身做不到这一点 —— A 的墓碑按 tag 覆盖,会把 B 改过的那个化身一起
+ * 带走,添加就白做了。新建化身带来全新的 tag,任何并发删除都覆盖不到它。
+ *
+ * 只有「这条词已经是 manual 正式词条」时才是真正的空操作(用户在 UI 上其实什么
+ * 都没改变),此时不新建化身,并发删除照常生效。判定只看合并主键,不比较原文
+ * 大小写 —— 设置页有独立的「编辑词条」入口负责改写法,重复添加不承担这个职责。
+ */
+export function addManualEntry(
+ state: VoiceDictionarySyncState,
+ clock: HlcClock,
+ input: ManualEntryInput,
+): MutationResult {
+ const text = normalizeDictionaryTermText(input.text);
+ const key = dictionaryTermKey(text);
+ if (!key) return { state, clock, changed: false };
+
+ const record = state.records[key];
+ const live = record ? listLiveIncarnations(record) : [];
+ const noop = live.some((item) => item.source === 'manual' && item.stage === 'entry');
+ if (noop) return { state, clock, changed: false };
+
+ const ticked = tickHlc(clock, input.nowMs);
+ return {
+ state: putRecord(state, key, {
+ incarnations: {
+ ...copyDictionaryMap(record?.incarnations),
+ [ticked.stamp]: createIncarnation({
+ tag: ticked.stamp,
+ text,
+ source: 'manual',
+ stage: 'entry',
+ nodeId: clock.nodeId,
+ aliasTexts: [],
+ nowMs: input.nowMs,
+ }),
+ },
+ tombstones: record?.tombstones ?? {},
+ }),
+ clock: ticked.clock,
+ changed: true,
+ };
+}
+
+export interface DeleteTermsInput {
+ /** 归一化主键;调用方拿到的若是词条 id,先翻译成主键再传进来。 */
+ termKeys: ReadonlyArray<string>;
+ nowMs: number;
+ /**
+ * 删除自动词条时是否写入抑制集合。默认 true(用户主动删除的语义)。
+ * 改名内部调用传 false —— 用户是改写法而不是拒绝这个词,抑制会误伤新写法。
+ */
+ suppressAutomatic?: boolean;
+}
+
+/**
+ * 删除词条(observed-remove)。
+ *
+ * 对「本机当前看得见的那些化身」记墓碑,而不是对主键记墓碑:这样之后重新添加
+ * 同名词会产生新化身,不会被这次删除的墓碑压住;同时被删化身上的计数一并失效,
+ * 离线设备带着旧计数回来也复活不了。
+ *
+ * 删的若是自动词条,同时写入抑制集合,阻止后台学习把它一路加回来 —— 与 desktop
+ * `deleteVoiceInputDictionaryEntriesFromSettings` 的单机语义一致。手动词条不写
+ * 抑制:之后自动学习可以合法地重新学出来。
+ */
+export function deleteTerms(
+ state: VoiceDictionarySyncState,
+ clock: HlcClock,
+ input: DeleteTermsInput,
+): MutationResult {
+ let nextState = state;
+ let nextClock = clock;
+ let changed = false;
+
+ for (const rawKey of input.termKeys) {
+ const key = dictionaryTermKey(rawKey);
+ const record = key ? nextState.records[key] : undefined;
+ if (!record) continue;
+ const live = listLiveIncarnations(record);
+ if (live.length === 0) continue;
+
+ const ticked = tickHlc(nextClock, input.nowMs);
+ nextClock = ticked.clock;
+
+ const tombstones: Record<HlcTimestamp, HlcTimestamp> = copyDictionaryMap(record.tombstones);
+ for (const incarnation of live) tombstones[incarnation.tag] = ticked.stamp;
+
+ const isAutomatic = !live.some((item) => item.source === 'manual');
+ nextState = putRecord(nextState, key, { ...record, tombstones });
+ if (input.suppressAutomatic !== false && isAutomatic && !hasDictionaryKey(nextState.suppressed, key)) {
+ nextState = {
+ ...nextState,
+ suppressed: withDictionaryKey(nextState.suppressed, key, {
+ // 抑制列表展示的文本与词条列表用同一套 LWW 规则,避免两处显示不一致。
+ text: pickDisplayText(live),
+ stamp: ticked.stamp,
+ }),
+ };
+ }
+ changed = true;
+ }
+
+ return { state: nextState, clock: nextClock, changed };
+}
+
+export interface RenameTermInput {
+ /** 被改写的词条主键。 */
+ termKey: string;
+ /** 新写法。 */
+ nextText: string;
+ nowMs: number;
+}
+
+/**
+ * 改写词条(设置页的「编辑词条」入口)。
+ *
+ * 分两种情况:
+ * - 只改写法(归一化主键不变,例如 litellm → LiteLLM):在存活化身上更新展示文本,
+ * 并把来源提升为 manual,频次与别名原样保留;
+ * - 改成了另一个词(主键变了):等价于「删掉旧词 + 添加新词」。此时**不写抑制**——
+ * 用户是在改名,不是拒绝这个词,否则新写法若日后被自动学习到会被自己的抑制挡住。
+ */
+/**
+ * 搬移化身时用的确定性 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,
+ input: RenameTermInput,
+): MutationResult {
+ const fromKey = dictionaryTermKey(input.termKey);
+ const nextText = normalizeDictionaryTermText(input.nextText);
+ const toKey = dictionaryTermKey(nextText);
+ if (!fromKey || !toKey) return { state, clock, changed: false };
+
+ const record = state.records[fromKey];
+ const live = record ? listLiveIncarnations(record) : [];
+ if (live.length === 0) return { state, clock, changed: false };
+
+ if (fromKey !== toKey) {
+ // 改名 = 把积累的证据整体**搬**到新键下,而不是「删旧 + 按聚合值新建」。
+ //
+ // 频次是排序权重、别名是纠错能力的主体,不搬过去等于用户纠正一个学错的写法就
+ // 把这个词学到的东西全丢了。但搬的方式很关键:早先是把跨化身求和出来的总频次
+ // 塞进一个全新化身。两台已收敛的电脑各自把同一个词改成同一个新名时,双方都会
+ // 算出同样的总数、各自造一个新化身;合并后两个化身都存活,物化把它们相加 ——
+ // 频次 5 的词变成 10,而其间没有发生任何一次学习。
+ //
+ // 现在把原化身连同它按节点分桶的计数一起搬过去,新 tag 由「原 tag + 目标键」
+ // 确定性派生:两台电脑搬出来的是**同一个**化身(tag 相同、计数相同),合并时
+ // 天然去重,搬多少次都不会涨。
+ //
+ // 不直接复用原 tag,是因为原键上刚给这个 tag 打了墓碑 —— 改回原名时(A→B→A)
+ // 搬回去的化身会被自己那条旧墓碑当场盖住,词条凭空消失。派生保证每次落地的
+ // tag 都是新的,同时仍然可去重。
+ const ticked = tickHlc(clock, input.nowMs);
+ const moved = createDictionaryMap<DictionaryIncarnation>();
+ for (const incarnation of live) {
+ const movedTag = deriveMoveTag(incarnation.tag, toKey);
+ moved[movedTag] = {
+ ...incarnation,
+ tag: movedTag,
+ text: nextText,
+ textStamp: ticked.stamp,
+ source: 'manual',
+ stage: 'entry',
+ updatedAt: input.nowMs,
+ };
+ }
+
+ // 原键打墓碑。墓碑是记录内部的,不会波及新键下同 tag 的化身。
+ const removed = deleteTerms(state, ticked.clock, {
+ termKeys: [fromKey],
+ nowMs: input.nowMs,
+ suppressAutomatic: false,
+ });
+
+ // 目标键已有词条时,搬过去的化身与它并存 —— 那是两批各自独立的证据,相加才对。
+ const target = removed.state.records[toKey];
+ return {
+ state: putRecord(removed.state, toKey, {
+ incarnations: { ...copyDictionaryMap(target?.incarnations), ...moved },
+ tombstones: copyDictionaryMap(target?.tombstones),
+ }),
+ clock: removed.clock,
+ changed: true,
+ };
+ }
+
+ if (live.every((item) => item.text === nextText && item.source === 'manual')) {
+ return { state, clock, changed: false };
+ }
+
+ const ticked = tickHlc(clock, input.nowMs);
+ const incarnations: Record<HlcTimestamp, DictionaryIncarnation> = copyDictionaryMap(record!.incarnations);
+ for (const incarnation of live) {
+ incarnations[incarnation.tag] = {
+ ...incarnation,
+ text: nextText,
+ textStamp: ticked.stamp,
+ source: 'manual',
+ updatedAt: Math.max(incarnation.updatedAt, input.nowMs),
+ };
+ }
+ return {
+ state: putRecord(state, fromKey, { ...record!, incarnations }),
+ clock: ticked.clock,
+ changed: true,
+ };
+}
+
+/**
+ * 把词条 id 翻译回合并主键。UI 只持有 id,删除入口需要这一步。
+ *
+ * 本模块物化出的 id 由主键确定性派生,直接反解即可;查不到前缀时回退到物化列表
+ * 查找,兼容接线迁移窗口里仍带着旧本地 id 的词条。
+ */
+export function termKeyFromMaterializedId(
+ state: VoiceDictionarySyncState,
+ entryId: string,
+ limits?: Parameters<typeof materializeDictionary>[1],
+): string | null {
+ const trimmed = entryId.trim();
+ if (!trimmed) return null;
+ if (trimmed.startsWith(MATERIALIZED_ID_PREFIX)) {
+ const key = trimmed.slice(MATERIALIZED_ID_PREFIX.length);
+ return hasDictionaryKey(state.records, key) ? key : null;
+ }
+ const match = materializeDictionary(state, limits).entries.find((entry) => entry.id === trimmed);
+ return match ? dictionaryTermKey(match.text) : null;
+}
+
+export interface GcOptions {
+ nowMs: number;
+ /** 墓碑保留时长。 */
+ ttlMs: number;
+}
+
+/** 墓碑默认保留 180 天。 */
+export const DEFAULT_TOMBSTONE_TTL_MS = 180 * 24 * 60 * 60 * 1000;
+
+/**
+ * 自动候选的**权威状态**硬上限。
+ *
+ * 物化只暴露前 200 条候选,但状态里存的是全部 —— 被挤出展示的那些既看不见也删不掉,
+ * 自动学习跑得久一点就单调增长下去,直到整份状态超过 relay 单帧上限,此后每一次
+ * 同步广播都被丢弃(而且不会有任何报错)。
+ *
+ * 上限定得远高于展示上限:正常用户碰不到,只有异常增长才会触发,尽量少动用户数据。
+ */
+export const MAX_AUTOMATIC_CANDIDATE_RECORDS = 2_000;
+
+/**
+ * 裁掉超出硬上限的最弱自动候选(打墓碑,不写抑制)。
+ *
+ * 只动**自动学习的候选**:手动词条是用户的显式意图,正式词条已经被用户看见并接受,
+ * 两者都不在裁剪范围内。不写抑制集合是关键 —— 抑制是永久的,而这些词只是暂时没
+ * 挤进来,日后再被学到应该能正常回来。
+ *
+ * 裁剪会生成墓碑并同步出去,所以判据必须确定性:证据数升序、并列时按主键。两台
+ * 设备各自裁剪出的集合可能不同,合并后是删除的并集 —— 候选是学习的中间态,重新
+ * 学到就会回来,这个代价可以接受;放任状态无界增长则会让同步彻底停摆。
+ */
+export function pruneWeakAutomaticCandidates(
+ state: VoiceDictionarySyncState,
+ clock: HlcClock,
+ options: { maxRecords?: number; nowMs: number },
+): MutationResult {
+ const limit = Math.max(0, options.maxRecords ?? MAX_AUTOMATIC_CANDIDATE_RECORDS);
+ const candidates: Array<{ key: string; weight: number }> = [];
+ for (const [key, record] of Object.entries(state.records)) {
+ const live = listLiveIncarnations(record);
+ if (live.length === 0) continue;
+ // 只要还有任何一个化身是正式词条或手动来源,这个词就不参与裁剪。
+ if (live.some((item) => item.stage === 'entry' || item.source === 'manual')) continue;
+ candidates.push({
+ key,
+ weight: live.reduce((sum, item) => sum + readCounterTotal(item.counters), 0),
+ });
+ }
+ if (candidates.length <= limit) return { state, clock, changed: false };
+
+ const doomed = candidates
+ .sort((a, b) => a.weight - b.weight || (a.key < b.key ? -1 : 1))
+ .slice(0, candidates.length - limit)
+ .map((item) => item.key);
+
+ // suppressAutomatic: false —— 这是容量裁剪,不是「用户不想要这个词」。
+ return deleteTerms(state, clock, {
+ termKeys: doomed,
+ nowMs: options.nowMs,
+ suppressAutomatic: false,
+ });
+}
+
+/**
+ * 回收过期墓碑。
+ *
+ * **必须连同被它覆盖的化身一起删掉** —— 只删墓碑会让化身立刻复活,是这类实现最
+ * 常见的自伤。
+ *
+ * 已知边界:回收之后,一台离线时长超过 TTL 的设备重新上线,理论上能把它手里的
+ * 旧化身带回来。自动词条有抑制集合兜底(抑制不过期),所以真正能复活的只剩
+ * 「手动词条 + 设备离线超过 TTL」这一种组合。
+ */
+export function gcTombstones(
+ state: VoiceDictionarySyncState,
+ options: GcOptions,
+): VoiceDictionarySyncState {
+ const threshold = options.nowMs - options.ttlMs;
+ let changed = false;
+ // 用户文本作键 —— 必须无原型,否则 GC 后给 `__proto__` 赋值会走原型 setter,
+ // 那条合法词条会被静默丢掉,而且这个丢失还会被持久化并同步出去。
+ const records: Record<string, DictionaryRecord> = createDictionaryMap<DictionaryRecord>();
+
+ 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);
+ 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 (Object.keys(incarnations).length > 0 || Object.keys(tombstones).length > 0) {
+ records[key] = { incarnations, tombstones };
+ }
+ }
+
+ 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,
+ record: DictionaryRecord,
+): VoiceDictionarySyncState {
+ return { ...state, records: withDictionaryKey(state.records, key, record) };
+}
+
+function createIncarnation(input: {
+ tag: HlcTimestamp;
+ text: string;
+ source: DictionaryTermSource;
+ stage: DictionaryStage;
+ nodeId: string;
+ aliasTexts: ReadonlyArray<string>;
+ nowMs: number;
+}): DictionaryIncarnation {
+ return {
+ tag: input.tag,
+ text: input.text,
+ textStamp: input.tag,
+ source: input.source,
+ stage: input.stage,
+ counters: { [input.nodeId]: 1 },
+ aliases: buildAliases({}, input.aliasTexts, input.nodeId, input.tag, input.nowMs),
+ createdAt: input.nowMs,
+ updatedAt: input.nowMs,
+ };
+}
+
+function bumpIncarnation(
+ incarnation: DictionaryIncarnation,
+ input: {
+ nodeId: string;
+ stage: DictionaryStage;
+ aliasTexts: ReadonlyArray<string>;
+ stamp: HlcTimestamp;
+ nowMs: number;
+ },
+): DictionaryIncarnation {
+ return {
+ ...incarnation,
+ stage: incarnation.stage === 'entry' || input.stage === 'entry' ? 'entry' : 'candidate',
+ counters: {
+ ...copyDictionaryMap(incarnation.counters),
+ [input.nodeId]: (incarnation.counters[input.nodeId] ?? 0) + 1,
+ },
+ aliases: buildAliases(incarnation.aliases, input.aliasTexts, input.nodeId, input.stamp, input.nowMs),
+ updatedAt: Math.max(incarnation.updatedAt, input.nowMs),
+ };
+}
+
+function buildAliases(
+ current: Record<string, SyncAliasState>,
+ aliasTexts: ReadonlyArray<string>,
+ nodeId: string,
+ stamp: HlcTimestamp,
+ nowMs: number,
+): Record<string, SyncAliasState> {
+ if (aliasTexts.length === 0) return current;
+ const next: Record<string, SyncAliasState> = copyDictionaryMap(current);
+ for (const aliasText of aliasTexts) {
+ const aliasKey = dictionaryTermKey(aliasText);
+ if (!aliasKey) continue;
+ const existing = next[aliasKey];
+ next[aliasKey] = existing
+ ? {
+ text: aliasText,
+ textStamp: stamp,
+ counters: { ...existing.counters, [nodeId]: (existing.counters[nodeId] ?? 0) + 1 },
+ lastSeenAt: Math.max(existing.lastSeenAt, nowMs),
+ }
+ : {
+ text: aliasText,
+ textStamp: stamp,
+ counters: { [nodeId]: 1 },
+ lastSeenAt: nowMs,
+ };
+ }
+ return next;
+}
+
+function normalizeAliasTexts(aliases: ReadonlyArray<string> | undefined, termKey: string): string[] {
+ if (!aliases || aliases.length === 0) return [];
+ const seen = new Set<string>();
+ const result: string[] = [];
+ for (const raw of aliases) {
+ const text = normalizeDictionaryTermText(raw);
+ const key = dictionaryTermKey(text);
+ // 别名等于词条本身没有意义(desktop 学习路径同样会把它过滤掉)。
+ if (!key || key === termKey || seen.has(key)) continue;
+ seen.add(key);
+ result.push(text);
+ }
+ return result;
+}
diff --git a/packages/voice-input-core/src/dictionary-sync/reconcile.ts b/packages/voice-input-core/src/dictionary-sync/reconcile.ts
new file mode 100644
index 0000000000..7153ff5de5
--- /dev/null
+++ b/packages/voice-input-core/src/dictionary-sync/reconcile.ts
@@ -0,0 +1,218 @@
+/**
+ * 降级回收:把「本机词典文件在 CRDT 之外被改过」这件事收回同步状态。
+ *
+ * 只有一种情况会触发 —— 用户装了旧版本客户端,旧版本直接读写词典文件、完全不知道
+ * 同步状态的存在。升级回来之后,这份改动必须被认领,否则用户在旧版本里加的词会在
+ * 下一次物化时被覆盖掉。
+ *
+ * ## 这条路径为什么必须小心
+ *
+ * 「比对文件与状态、把差异当成本地新增」正是最容易把词典搞成指数膨胀的写法:每次
+ * 物化都会把合并进来的远端计数写进文件,如果它再被当成本地增量记一遍,同步一轮翻
+ * 一倍。防线有三条:
+ *
+ * 1. **日常路径根本不走这里**。运行期的一切变更都直接调 mutate 原语写状态,文件只是
+ * 状态的投影。本函数只在启动时发现投影对不上时跑一次。
+ * 2. **只认领存在性,不认领频次**。降级期间涨的频次一律丢弃,以状态为准。频次是可
+ * 重新积累的软信息,而错认频次是膨胀的直接来源 —— 两害相权,丢弃更安全。
+ * 3. **删除判定基于上次物化写出去的主键集合**,而不是「状态里有、文件里没有」。被
+ * 上限挤出物化的词条本来就不在文件里,拿状态直接比会把它们全部误判成用户删除。
+ */
+
+import { tickHlc, type HlcClock } from './hlc';
+import { deleteTerms, promoteTermToEntry, seedTerm, type MutationResult } from './mutate';
+import { dictionaryTermKey, normalizeDictionaryTermText } from './text';
+import {
+ hasDictionaryKey,
+ withDictionaryKey,
+ type DictionaryTermSource,
+ type VoiceDictionarySyncState,
+} from './types';
+
+export interface LocalDictionarySnapshot {
+ entries: ReadonlyArray<{
+ text: string;
+ source: DictionaryTermSource;
+ frequency?: number;
+ aliases?: ReadonlyArray<{ text: string; count?: number }>;
+ }>;
+ suppressedTexts: ReadonlyArray<string>;
+ /**
+ * 候选词(还在攒证据、用户不可见的中间态)。只认领新增,不认领删除 —— 候选词
+ * 没有「上次物化」的基准可比,而丢一个候选词只会让它重新攒证据,代价极小。
+ */
+ candidates?: ReadonlyArray<{
+ text: string;
+ evidenceCount?: number;
+ aliases?: ReadonlyArray<{ text: string; count?: number }>;
+ }>;
+}
+
+export interface ReconcileInput {
+ /** 当前词典文件里的内容(可能被旧版本改过)。 */
+ snapshot: LocalDictionarySnapshot;
+ /** 上一次由本模块物化写进该文件的词条主键集合。 */
+ lastMaterializedKeys: ReadonlyArray<string>;
+ /**
+ * 是否允许在「只剩墓碑」的键上重建词条。默认 true。
+ *
+ * 降级回收要 true:投影是老客户端刚写下的新证据。sidecar 丢失后的恢复认领要
+ * false —— 本机没有身份历史,越过墓碑重建会让别的设备上删掉的词复活。
+ */
+ allowTombstonedRevival?: boolean;
+ nowMs: number;
+}
+
+export function reconcileFromLocalSnapshot(
+ state: VoiceDictionarySyncState,
+ clock: HlcClock,
+ input: ReconcileInput,
+): MutationResult {
+ let nextState = state;
+ let nextClock = clock;
+ let changed = false;
+
+ // 1. 抑制集合直接并集。旧版本删自动词条时会往文件里写抑制文本,这是比「猜哪条被
+ // 删了」更可靠的信号,而且抑制是只增集合,并集不会丢信息。
+ for (const rawText of input.snapshot.suppressedTexts ?? []) {
+ const text = normalizeDictionaryTermText(rawText);
+ const key = dictionaryTermKey(text);
+ if (!key || hasDictionaryKey(nextState.suppressed, key)) continue;
+ const result = deleteTerms(nextState, nextClock, {
+ termKeys: [key],
+ nowMs: input.nowMs,
+ suppressAutomatic: true,
+ });
+ nextState = result.state;
+ nextClock = result.clock;
+ // 该词可能压根不在状态里(旧版本删掉后状态里也没有),deleteTerms 不会写抑制,
+ // 这里补上,保证抑制意图不丢。
+ if (!hasDictionaryKey(nextState.suppressed, key)) {
+ const stamped = addSuppression(nextState, nextClock, key, text, input.nowMs);
+ nextState = stamped.state;
+ nextClock = stamped.clock;
+ }
+ changed = true;
+ }
+
+ const currentByKey = new Map<
+ string,
+ {
+ text: string;
+ source: DictionaryTermSource;
+ frequency: number;
+ aliases: ReadonlyArray<{ text: string; count?: number }>;
+ }
+ >();
+ for (const entry of input.snapshot.entries) {
+ const text = normalizeDictionaryTermText(entry.text);
+ const key = dictionaryTermKey(text);
+ if (!key) continue;
+ currentByKey.set(key, {
+ text,
+ source: entry.source === 'manual' ? 'manual' : 'automatic',
+ frequency: readCount(entry.frequency),
+ aliases: entry.aliases ?? [],
+ });
+ }
+
+ const previousKeys = new Set(
+ input.lastMaterializedKeys.map((key) => dictionaryTermKey(key)).filter(Boolean),
+ );
+
+ // 2. 文件里有、上次没物化出去过 → 旧版本期间新增的词条(首次迁移时是全部词条),
+ // 按它自己的来源认领。
+ //
+ // **频次只在这条路径上认领**,而且 seedTerm 只对状态里完全不存在的词条生效:
+ // 首次迁移时状态是空的,文件里的频次不可能包含任何远端计数,原样接管是安全的,
+ // 而丢掉它会把用户长期积累的排序权重清零。已存在的词条一律不碰频次 —— 那时
+ // 文件里的数字可能已经含有合并进来的远端计数,认领就是重复记账。
+ for (const [key, entry] of currentByKey) {
+ if (previousKeys.has(key)) continue;
+ const result = seedTerm(nextState, nextClock, {
+ text: entry.text,
+ source: entry.source,
+ stage: 'entry',
+ count: entry.frequency,
+ aliases: entry.aliases,
+ nowMs: input.nowMs,
+ allowTombstonedRevival: input.allowTombstonedRevival ?? true,
+ });
+ if (!result.changed) {
+ // 该词条已经在状态里了(典型情形:sidecar 的 lastMaterializedKeys 丢失或损坏,
+ // 于是所有词条都被当成「新增」)。存在性本来就已满足,这里必须什么都不做 ——
+ // 早先的写法在这里补记一次学习事件,那会让每次启动都给全部词条 +1,反复重启
+ // 就是一条缓慢但持续的膨胀曲线。
+ //
+ // 唯一的例外是阶段:状态里还是候选、而文件里已经是正式词条,说明老客户端在
+ // 降级期间把它转正了。只提升阶段,不碰计数 —— 不补这一步,这次转正会在下次
+ // 物化时被写回候选,用户在降级期间做的分类白做。
+ const promoted = promoteTermToEntry(nextState, nextClock, { termKey: key, nowMs: input.nowMs });
+ if (promoted.changed) {
+ nextState = promoted.state;
+ nextClock = promoted.clock;
+ changed = true;
+ }
+ continue;
+ }
+ nextState = result.state;
+ nextClock = result.clock;
+ changed = true;
+ }
+
+ // 3. 候选词只认领新增:状态里已经有这个词(不论什么阶段)就跳过,避免把同一条
+ // 候选反复记成新证据。
+ for (const candidate of input.snapshot.candidates ?? []) {
+ const text = normalizeDictionaryTermText(candidate.text);
+ const key = dictionaryTermKey(text);
+ if (!key || hasDictionaryKey(nextState.records, key) || currentByKey.has(key)) continue;
+ const result = seedTerm(nextState, nextClock, {
+ text,
+ source: 'automatic',
+ stage: 'candidate',
+ count: readCount(candidate.evidenceCount),
+ aliases: candidate.aliases,
+ nowMs: input.nowMs,
+ });
+ nextState = result.state;
+ nextClock = result.clock;
+ changed = changed || result.changed;
+ }
+
+ // 4. 上次物化出去过、现在文件里没有 → 旧版本期间被删掉了。抑制已在第 1 步按文件
+ // 的抑制列表处理过,这里不再重复写抑制,避免把「旧版本删手动词条」误升级成抑制。
+ const removedKeys = [...previousKeys].filter((key) => !currentByKey.has(key));
+ if (removedKeys.length > 0) {
+ const result = deleteTerms(nextState, nextClock, {
+ termKeys: removedKeys,
+ nowMs: input.nowMs,
+ suppressAutomatic: false,
+ });
+ nextState = result.state;
+ nextClock = result.clock;
+ changed = changed || result.changed;
+ }
+
+ return { state: nextState, clock: nextClock, changed };
+}
+
+function readCount(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 1;
+}
+
+function addSuppression(
+ state: VoiceDictionarySyncState,
+ clock: HlcClock,
+ key: string,
+ text: string,
+ nowMs: number,
+): { state: VoiceDictionarySyncState; clock: HlcClock } {
+ const ticked = tickHlc(clock, nowMs);
+ return {
+ state: {
+ ...state,
+ suppressed: withDictionaryKey(state.suppressed, key, { text, stamp: ticked.stamp }),
+ },
+ clock: ticked.clock,
+ };
+}
diff --git a/packages/voice-input-core/src/dictionary-sync/text.ts b/packages/voice-input-core/src/dictionary-sync/text.ts
new file mode 100644
index 0000000000..515b7f4ba3
--- /dev/null
+++ b/packages/voice-input-core/src/dictionary-sync/text.ts
@@ -0,0 +1,38 @@
+/**
+ * 词条文本归一化与主键。
+ *
+ * 与 desktop `apps/desktop/src/shared/voiceInputData.ts` 的
+ * `normalizeVoiceInputDictionaryEntryText` / `dictionaryTextKey` 行为逐字一致 ——
+ * 同步合并的主键必须和本地学习路径的查找键是同一个键,否则同一个词在两条路径
+ * 下会被认成两个词。desktop 侧在同步接线时改为复用本模块,消除漂移可能。
+ *
+ * 主键取小写归一化文本(而不是词条 id):id 是各设备本地生成的,两台设备各自学
+ * 到同一个词会得到不同 id,拿 id 当同步主键会让同一个词永远合并不到一起。
+ */
+
+/** 单条词条文本上限,与 desktop MAX_VOICE_INPUT_DICTIONARY_ENTRY_CHARS 一致。 */
+export const MAX_DICTIONARY_TERM_CHARS = 120;
+
+export function normalizeDictionaryTermText(value: unknown): string {
+ if (typeof value !== 'string') return '';
+ return value
+ .replace(/\r\n?/g, '\n')
+ .split('\n')
+ .map((line) => line.replace(/\s+/g, ' ').trim())
+ .filter(Boolean)
+ .join(' ')
+ .slice(0, MAX_DICTIONARY_TERM_CHARS)
+ .trim();
+}
+
+/**
+ * 合并主键。空字符串表示该文本不可用作词条。
+ *
+ * **必须用 locale 无关的 `toLowerCase()`**,不能用 `toLocaleLowerCase()`:后者跟随
+ * 设备系统语言,土耳其语 locale 下 `I` 折叠成 `ı`(无点)而英语 locale 折叠成 `i`。
+ * 这个值是 CRDT 记录键和物化 id —— 同一个词在两台不同语言设置的电脑上会落到两条
+ * 互不相干的记录,永远收敛不了。跨设备一致性优先于个别语言的大小写直觉。
+ */
+export function dictionaryTermKey(text: unknown): string {
+ return normalizeDictionaryTermText(text).toLowerCase();
+}
diff --git a/packages/voice-input-core/src/dictionary-sync/types.ts b/packages/voice-input-core/src/dictionary-sync/types.ts
new file mode 100644
index 0000000000..805c92c1c3
--- /dev/null
+++ b/packages/voice-input-core/src/dictionary-sync/types.ts
@@ -0,0 +1,275 @@
+/**
+ * 语音词典多设备同步的 CRDT 状态模型。
+ *
+ * ## 为什么是这个形状
+ *
+ * 设备之间没有中心裁决者,relay 也不暂存离线消息(目标不在线直接失败),所以同步
+ * 必须满足两件事:
+ *
+ * 1. **状态式合并**:每次交换整份状态,`mergeSyncStates` 幂等、可交换、可结合。
+ * 丢帧、重复投递、乱序、任意轮数都不影响最终一致 —— 这次没送到,下次上线再
+ * 合一次就收敛,不需要可靠投递、ack 或重传。
+ * 2. **计数不能靠相加**:两台设备各学同一个词 3 次,正确结果是 6;但如果合并规则
+ * 是「相加」,A 和 B 同步一轮各得 6,再同步一轮各得 12,词典会随同步次数指数
+ * 膨胀。因此频次不存总数,存 {@link GCounter}:按节点分桶记录各自的累计事件数,
+ * **合并逐节点取 max**(不是相加),显示值才是求和。
+ *
+ * ## 化身(incarnation)
+ *
+ * 删除必须能跨设备传播,又不能误杀「删掉之后用户重新添加的同名词」。裸墓碑
+ * (记下 textKey 就算删)做不到这一点:重新添加的词会被旧墓碑一直压着。
+ *
+ * 所以每个词条由若干**化身**组成,每个化身有全网唯一 tag(创建时的 HLC),而
+ * **频次、别名、阶段都挂在化身上,不挂在词条上**。删除 = 对「删除者当时看得见的
+ * 那些化身 tag」记墓碑(observed-remove)。于是:
+ *
+ * - 删除会连同那些化身的计数一起带走,离线设备回来后不会把旧计数复活;
+ * - 重新添加产生新 tag,任何旧墓碑都覆盖不到它,天然是一条干净的新词条;
+ * - 「删除」与「并发重新添加」并发时 add-wins,用户新表达的意图胜出。
+ *
+ * 词条可见 ⇔ 至少有一个化身没有被墓碑覆盖;显示频次 = **只对存活化身**求和。
+ */
+
+import type { HlcTimestamp } from './hlc';
+import { isCanonicalHlc } from './hlc';
+
+/** 状态结构版本;不兼容改动 +1,收到更高版本的状态整份忽略而不是猜着合并。 */
+export const VOICE_DICTIONARY_SYNC_VERSION = 1;
+
+/**
+ * 按节点分桶的增长计数器。key = 产生事件的节点 id,value = 该节点的累计事件数。
+ *
+ * 合并 = 逐 key 取 max(幂等);读取 = 所有 value 求和。
+ * 只有事件的产生者才会递增自己那一桶,所以「同一个事件被合并进来很多次」不会
+ * 让计数增长 —— 这是词典频次不会随同步次数膨胀的根本原因。
+ */
+export type GCounter = Record<string, number>;
+
+/** 词条所处阶段。candidate 是攒证据阶段,entry 是已进入词典。单调:只能升不能降。 */
+export type DictionaryStage = 'candidate' | 'entry';
+
+/** 词条来源。单调:automatic → manual 单向,用户手动确认过的词不会退回自动。 */
+export type DictionaryTermSource = 'manual' | 'automatic';
+
+/** 别名(误识别写法)在单个化身内的状态。 */
+export interface SyncAliasState {
+ /** 展示用原文;LWW,由 {@link textStamp} 定序。 */
+ text: string;
+ textStamp: HlcTimestamp;
+ /** 该别名被观察到的次数,按节点分桶。 */
+ counters: GCounter;
+ /** 最近一次观察到的墙钟毫秒;合并取 max,仅用于展示排序。 */
+ lastSeenAt: number;
+}
+
+/**
+ * 词条的一个化身。tag 全网唯一,创建后不可变;其余字段各自按自己的 CRDT 规则合并。
+ */
+export interface DictionaryIncarnation {
+ /** 创建时的 HLC,同时是这个化身的全局唯一 id。 */
+ tag: HlcTimestamp;
+ /** 展示用原文(保留大小写);LWW,由 {@link textStamp} 定序。 */
+ text: string;
+ textStamp: HlcTimestamp;
+ /** manual-wins 单调寄存器。 */
+ source: DictionaryTermSource;
+ /** entry-wins 单调寄存器。 */
+ stage: DictionaryStage;
+ /** 本化身的频次证据,按节点分桶。 */
+ counters: GCounter;
+ /** 别名表,key = 别名的归一化主键。 */
+ aliases: Record<string, SyncAliasState>;
+ /** 展示用时间;合并分别取 min / max。时钟回拨只影响展示排序,不影响正确性。 */
+ createdAt: number;
+ updatedAt: number;
+}
+
+/**
+ * 一个词(按归一化文本主键)的全部化身与墓碑。
+ *
+ * 墓碑按化身 tag 记录,value 是删除操作的 HLC(用于 TTL 回收与确定性合并)。
+ */
+export interface DictionaryRecord {
+ incarnations: Record<HlcTimestamp, DictionaryIncarnation>;
+ tombstones: Record<HlcTimestamp, HlcTimestamp>;
+}
+
+/**
+ * 「不要再自动学习这个词」的抑制集合。
+ *
+ * 用户删掉一条 automatic 词条时写入,阻止后台学习把它一路加回来 —— 这是 desktop
+ * 现有的单机语义(`deleteVoiceInputDictionaryEntriesFromSettings`),同步只是把它
+ * 扩展到全网。手动词条的删除**不写这里**,同样与现有单机语义一致:之后自动学习
+ * 可以合法地重新学出来。
+ *
+ * 当前产品没有「解除抑制」入口,所以这里是只增集合(G-Set),value 记首次抑制的
+ * HLC(合并取 min,保证确定性)。将来若要支持解除,需要升级为 OR-Set。
+ */
+export interface DictionarySuppression {
+ text: string;
+ stamp: HlcTimestamp;
+}
+
+/** 一份完整的可交换状态。JSON 可序列化:直接落盘、直接进 device-link push 帧。 */
+export interface VoiceDictionarySyncState {
+ version: typeof VOICE_DICTIONARY_SYNC_VERSION;
+ /** key = 归一化词条主键。 */
+ records: Record<string, DictionaryRecord>;
+ /** key = 归一化词条主键。 */
+ suppressed: Record<string, DictionarySuppression>;
+}
+
+/**
+ * 建一个没有原型的字典对象。
+ *
+ * 词条主键直接来自用户输入,而 `constructor`、`toString`、`__proto__`、`valueOf`
+ * 都是完全合法的技术术语。用普通 `{}` 的话 `'constructor' in records` 恒为真、
+ * `records['toString']` 会取到继承来的函数 —— 于是这些词会被当成"已存在"而静默
+ * 丢弃,或者把一个函数喂给只认记录结构的代码。所有以用户文本为键的对象一律用
+ * 这个工厂建。
+ */
+export function createDictionaryMap<T>(): Record<string, T> {
+ return Object.create(null) as Record<string, T>;
+}
+
+/**
+ * 复制成无原型字典。
+ *
+ * **不要用 `{ ...map }`**:对象字面量自带 `Object.prototype`,复制出来的东西再被
+ * 别处按 `map[key]` 读取时,`__proto__` 这类键会命中原型上的访问器,拿到的不是
+ * 词条而是原型对象本身(而且它 truthy,会一路蒙混到崩溃点才炸)。
+ */
+export function copyDictionaryMap<T>(map: Record<string, T> | undefined | null): Record<string, T> {
+ const next = createDictionaryMap<T>();
+ if (!map) return next;
+ for (const key of Object.keys(map)) next[key] = map[key];
+ return next;
+}
+
+/** 在无原型副本上写一个键,等价于安全版的 `{ ...map, [key]: value }`。 */
+export function withDictionaryKey<T>(
+ map: Record<string, T> | undefined | null,
+ key: string,
+ value: T,
+): Record<string, T> {
+ const next = copyDictionaryMap(map);
+ next[key] = value;
+ return next;
+}
+
+/** 自有属性检查。绝不用 `in`:它会命中原型链上的同名成员。 */
+export function hasDictionaryKey(map: object, key: string): boolean {
+ return Object.prototype.hasOwnProperty.call(map, key);
+}
+
+export function createEmptySyncState(): VoiceDictionarySyncState {
+ return {
+ version: VOICE_DICTIONARY_SYNC_VERSION,
+ records: createDictionaryMap(),
+ suppressed: createDictionaryMap(),
+ };
+}
+
+/**
+ * 深度校验一份来自隧道的状态。
+ *
+ * 只校验顶层是不够的:一个 incarnation 少了 `counters`、或者 aliases 里塞了字符串,
+ * 都能通过顶层检查并被持久化,然后在物化时才抛 —— 而且这份中毒的 sidecar 每次重启
+ * 都会被重新接受,词典修改和同步会一直坏下去,直到有人手工删文件。宁可在入口拒收
+ * 整帧。
+ */
+export function isValidSyncState(raw: unknown): raw is VoiceDictionarySyncState {
+ if (!isPlainRecord(raw)) return false;
+ const candidate = raw as Partial<VoiceDictionarySyncState>;
+ if (candidate.version !== VOICE_DICTIONARY_SYNC_VERSION) return false;
+ if (!isPlainRecord(candidate.records) || !isPlainRecord(candidate.suppressed)) return false;
+
+ for (const record of Object.values(candidate.records)) {
+ if (!isPlainRecord(record)) return false;
+ const { incarnations, tombstones } = record as Partial<DictionaryRecord>;
+ if (!isPlainRecord(incarnations) || !isPlainRecord(tombstones)) return false;
+ // 墓碑的键是被覆盖的化身 tag,值是删除时刻的时间戳 —— 两者都参与定序与 TTL,
+ // 都必须是规范 HLC。
+ for (const [tag, value] of Object.entries(tombstones)) {
+ if (!isCanonicalHlc(tag) || !isCanonicalHlc(value)) return false;
+ }
+ for (const [tag, incarnation] of Object.entries(incarnations)) {
+ if (!isCanonicalHlc(tag)) return false;
+ if (!isValidIncarnation(incarnation)) return false;
+ // 键必须与化身自称的 tag 一致:不一致时墓碑按键匹配、比较按 tag 走,
+ // 同一个化身会在两套判断下表现不同。
+ if ((incarnation as Partial<DictionaryIncarnation>).tag !== tag) return false;
+ }
+ }
+
+ for (const suppression of Object.values(candidate.suppressed)) {
+ if (!isPlainRecord(suppression)) return false;
+ const { text, stamp } = suppression as Partial<DictionarySuppression>;
+ if (typeof text !== 'string' || !isCanonicalHlc(stamp)) return false;
+ }
+ return true;
+}
+
+function isValidIncarnation(raw: unknown): boolean {
+ if (!isPlainRecord(raw)) return false;
+ const value = raw as Partial<DictionaryIncarnation>;
+ if (!isCanonicalHlc(value.tag) || typeof value.text !== 'string') return false;
+ if (!isCanonicalHlc(value.textStamp)) return false;
+ if (value.source !== 'manual' && value.source !== 'automatic') return false;
+ if (value.stage !== 'entry' && value.stage !== 'candidate') return false;
+ // 必须是有限值:`NaN` / `Infinity` 的 typeof 也是 'number',放进来之后物化阶段的
+ // `Math.min` / `Math.max` 会把它传播到整条词条的时间戳上,排序与展示随之失稳,
+ // 而且这份中毒状态是持久化并继续同步出去的。
+ if (!isValidTimestamp(value.createdAt) || !isValidTimestamp(value.updatedAt)) return false;
+ if (!isValidCounter(value.counters)) return false;
+ if (!isPlainRecord(value.aliases)) return false;
+ for (const alias of Object.values(value.aliases)) {
+ if (!isPlainRecord(alias)) return false;
+ const aliasValue = alias as Partial<SyncAliasState>;
+ if (typeof aliasValue.text !== 'string' || !isCanonicalHlc(aliasValue.textStamp)) return false;
+ if (!isValidTimestamp(aliasValue.lastSeenAt)) return false;
+ if (!isValidCounter(aliasValue.counters)) return false;
+ }
+ return true;
+}
+
+/**
+ * 计数桶。
+ *
+ * 语义是「事件累计次数」,所以只接受非负安全整数。放行负数或小数的话,展示读数会被
+ * `Math.floor` 悄悄改写 —— 症状出现在离入口很远的地方,而真正的原因(某一帧带了坏
+ * 计数)已经无从追溯;况且负计数还能让合并的逐节点 max 表现出反直觉的结果。
+ */
+function isValidCounter(raw: unknown): boolean {
+ if (!isPlainRecord(raw)) return false;
+ for (const value of Object.values(raw)) {
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) return false;
+ }
+ return true;
+}
+
+/** 毫秒时间戳:有限、非负。 */
+function isValidTimestamp(value: unknown): boolean {
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
+}
+
+/** 普通对象(排除 null 与数组 —— 两者的 typeof 都是 'object')。 */
+function isPlainRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+/** 存活化身 = 没有被墓碑覆盖的化身。词条的一切对外读数都只看这些。 */
+export function listLiveIncarnations(record: DictionaryRecord): DictionaryIncarnation[] {
+ return Object.values(record.incarnations)
+ .filter((incarnation) => !hasDictionaryKey(record.tombstones, incarnation.tag))
+ .sort((a, b) => (a.tag < b.tag ? -1 : a.tag > b.tag ? 1 : 0));
+}
+
+/** 计数器读数:所有节点分桶求和。 */
+export function readCounterTotal(counters: GCounter): number {
+ let total = 0;
+ for (const value of Object.values(counters)) {
+ if (Number.isFinite(value) && value > 0) total += Math.floor(value);
+ }
+ return total;
+}
diff --git a/packages/voice-input-core/src/index.ts b/packages/voice-input-core/src/index.ts
index 1783a79aa2..702d1468e7 100644
--- a/packages/voice-input-core/src/index.ts
+++ b/packages/voice-input-core/src/index.ts
@@ -5,4 +5,5 @@ export * from './VoiceTimelineLogger';
export * from './DictationRefiner';
export * from './DictationExternalEditInspector';
export * from './DictationDictionaryAdvisor';
+export * from './dictionary-sync';
export * from './streamingJson';