Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 修复语音词典首次加载为空
Dash010fd0a67cc7
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 65a18110e1..720dd643de 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -36,6 +36,7 @@ import {DeviceLinkError,INVOKE_TIMEOUT_OVERRIDES_MS,} from '@cindy/device-link';+import { DEVICE_LINK_VOICE_DICTIONARY_SNAPSHOT_CHANNEL } from '@cindy/maker-shared/device-link-contract';import * as authManager from '../authManager';import { getActiveDataOwnerPushStamp } from '../appSessionState.js';import { createLogger } from '../logger';@@ -84,6 +85,7 @@ import {import {clearControllerPlatforms,getControllerPlatform,+ isMobilePlatform,setControllerPlatform,} from './controllerPlatform';import {@@ -103,6 +105,7 @@ import {broadcastDictionaryNow,handleDesktopPeerOnline,handleIncomingDictionaryState,+ handleMobilePeerOnline,initVoiceDictionarySync,notifyLocalDictionaryChanged,shouldExchangeDictionaryWith,@@ -766,6 +769,16 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v) {handleDesktopPeerOnline(snap.deviceId);}+ // 手机只接收只读投影:push 不属于 relay 的 CONTROL_KINDS,因此不要求桌面+ // 打开「允许被控」。来源平台只用于体验分流,撤销状态仍是实际准入边界。+ if (+ wasOnline !== true &&+ snap.online &&+ isMobilePlatform(snap.platform) &&+ !isDeviceRevoked(snap.deviceId)+ ) {+ handleMobilePeerOnline(snap.deviceId);+ }});let updateRelaunchControllersBusy = false;@@ -885,6 +898,17 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v}),).map(([deviceId]) => deviceId),+ sendMobileSnapshot: (deviceId, payload) => {+ client?.sendPush(deviceId, DEVICE_LINK_VOICE_DICTIONARY_SNAPSHOT_CHANNEL, payload);+ },+ listOnlineMobileDevices: () =>+ [...presenceOnlineByDevice.entries()]+ .filter(([deviceId, online]) =>+ online &&+ isMobilePlatform(getControllerPlatform(deviceId)) &&+ !isDeviceRevoked(deviceId),+ )+ .map(([deviceId]) => deviceId),});initContactsDeviceSync({getSelfDeviceId: () => client?.getSelfDeviceId() ?? null,diff --git a/apps/desktop/src/main/voice-input/__tests__/dictionarySyncDriver.test.ts b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncDriver.test.tsindex 80bce7a53a..ea8c71ae94 100644--- a/apps/desktop/src/main/voice-input/__tests__/dictionarySyncDriver.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncDriver.test.ts@@ -3,8 +3,9 @@** 这一层不碰合并语义(那在 voice-input-core 里),只回答三个问题:什么时候发、* 发给谁、收到什么才处理。盯住的边界:- * - 用户关掉开关后必须彻底静默(既不发也不合并);- * - 只发给桌面 —— 手机在后台收不到 push,给它发是纯浪费;+ * - 关掉同步开关后,桌面 CRDT 通道彻底静默(既不发也不合并);+ * - 手机只读投影不受「允许被控」限制;开关关闭时只在手机上线或开关切换时+ * 推一次空投影清缓存,本地学习/编辑不再持续推空表;* - 认不出的帧结构直接忽略,坏帧不能污染本机词典。*/@@ -32,21 +33,23 @@ vi.mock('../VoiceInputDataStore.js', () => ({const syncState = { version: 1 as const, records: {}, suppressed: {} };/** 让个别用例把状态换成超大对象,验证帧上限把关。 */const stateOverride: { value: unknown } = { value: null };+const defaultMaterializedEntry = {+ id: 'dict-sync-cindy',+ text: 'Cindy',+ source: 'manual' as const,+ frequency: 2,+ aliases: [{ text: 'sindy', count: 1, lastSeenAt: 5 }],+ createdAt: 1,+ updatedAt: 2,+};+const materialized = {+ entries: [defaultMaterializedEntry],+};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,- },- ],+ entries: materialized.entries,candidates: [],suppressedTexts: [],}),@@ -54,28 +57,38 @@ vi.mock('../VoiceDictionarySyncStore.js', () => ({}));const {+ broadcastDictionaryNow,handleDesktopPeerOnline,handleIncomingDictionaryState,+ handleMobilePeerOnline,initVoiceDictionarySync,isDesktopPlatform,+ notifyLocalDictionaryChanged,readDictionaryProjectionForMobile,shouldExchangeDictionaryWith,stopVoiceDictionarySync,} = await import('../dictionarySyncDriver.js');const sendState = vi.fn();+const sendMobileSnapshot = vi.fn();const onlineDesktops: string[] = [];+const onlineMobiles: string[] = [];beforeEach(() => {syncEnabled.value = true;sendState.mockClear();+ sendMobileSnapshot.mockClear();mergeRemoteDictionaryState.mockClear();mergeRemoteDictionaryState.mockReturnValue(true);onlineDesktops.length = 0;+ onlineMobiles.length = 0;stateOverride.value = null;+ materialized.entries = [defaultMaterializedEntry];initVoiceDictionarySync({sendState: (deviceId, payload) => sendState(deviceId, payload),listOnlineDesktopDevices: () => [...onlineDesktops],+ sendMobileSnapshot: (deviceId, payload) => sendMobileSnapshot(deviceId, payload),+ listOnlineMobileDevices: () => [...onlineMobiles],});});@@ -148,6 +161,54 @@ describe('出站', () => {handleIncomingDictionaryState('peer-1', { frameVersion: 1, state: syncState });expect(() => handleDesktopPeerOnline('peer-2')).not.toThrow();});++ it('手机上线时主动推只读快照,不依赖远程控制开关', () => {+ handleMobilePeerOnline('phone-1');+ expect(sendMobileSnapshot).toHaveBeenCalledWith('phone-1', {+ ok: true,+ entries: [+ { text: 'Cindy', frequency: 2, aliases: [{ text: 'sindy', count: 1 }] },+ ],+ });+ });++ it('同步关闭时仍推空投影给手机,让旧缓存及时清空', () => {+ syncEnabled.value = false;+ handleMobilePeerOnline('phone-1');+ expect(sendMobileSnapshot).toHaveBeenCalledWith('phone-1', { ok: true, entries: [] });+ });++ it('立即广播会同时刷新所有在线手机', () => {+ onlineMobiles.push('phone-1', 'phone-2');+ broadcastDictionaryNow();+ expect(sendMobileSnapshot).toHaveBeenCalledTimes(2);+ });++ it('同步关闭后本地变更不再向手机推空投影', () => {+ syncEnabled.value = false;+ onlineMobiles.push('phone-1');+ notifyLocalDictionaryChanged();+ expect(sendMobileSnapshot).not.toHaveBeenCalled();+ expect(sendState).not.toHaveBeenCalled();+ });++ it('手机快照超过单帧上限时不发送', () => {+ materialized.entries = Array.from({ length: 1_000 }, (_, index) => ({+ id: `term-${index}`,+ text: '词'.repeat(80),+ source: 'manual' as const,+ frequency: 1,+ aliases: Array.from({ length: 8 }, () => ({+ text: '别'.repeat(120),+ count: 1,+ lastSeenAt: 1,+ })),+ createdAt: 1,+ updatedAt: 1,+ }));+ handleMobilePeerOnline('phone-1');+ expect(sendMobileSnapshot).not.toHaveBeenCalled();+ });});describe('入站', () => {diff --git a/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts b/apps/desktop/src/main/voice-input/dictionarySyncDriver.tsindex 83052fb952..a47b78bcf2 100644--- a/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts+++ b/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts@@ -11,11 +11,12 @@* 交换的是整份 CRDT 状态,合并幂等且可交换,这次没送到,下次任一触发时机再送一次* 就收敛。为此触发点铺了三层:对端上线、本地变更(去抖)、以及长周期兜底。*- * 手机不参与这条通道:移动端在后台不维持 WebSocket,收不到 push。它改用- * `device-link:voice:dictionary:get` 主动向在线桌面拉一份只读快照。+ * 手机不参与 CRDT 通道:移动端在后台不维持 WebSocket,不持有可写副本。手机上线和+ * 桌面词典变化时,桌面改推一份只读全量快照;原有 invoke 拉取保留给旧版兼容兜底。*/import { MAX_FRAME_BYTES } from '@cindy/device-link';+import type { MobileVoiceDictionarySnapshotResult } from '@cindy/maker-shared/device-link-contract';import { buildStateVersionVector, type VoiceDictionarySyncState } from '@cindy/voice-input-core';import { createLogger } from '../logger.js';@@ -63,6 +64,10 @@ export interface DictionarySyncTransport {sendState(deviceId: string, payload: DictionarySyncFramePayload): void;/** 当前在线的同账号**桌面**设备。 */listOnlineDesktopDevices(): string[];+ /** 给手机发送只读全量快照(push 不经过远程控制门禁)。 */+ sendMobileSnapshot(deviceId: string, payload: MobileVoiceDictionarySnapshotResult): void;+ /** 当前在线、未撤销的同账号手机。 */+ listOnlineMobileDevices(): string[];}let transport: DictionarySyncTransport | null = null;@@ -116,6 +121,11 @@ export function handleDesktopPeerOnline(deviceId: string): void {sendStateTo(deviceId, 'peer-online', { requestReply: true });}+/** 手机上线时立即推送一次只读全量快照,不要求桌面打开「允许被控」。 */+export function handleMobilePeerOnline(deviceId: string): void {+ sendMobileSnapshotTo(deviceId, 'mobile-online');+}+/*** 立即广播一次当前状态,不走去抖。*@@ -127,17 +137,22 @@ export function broadcastDictionaryNow(): void {clearTimeout(debounceTimer);debounceTimer = null;}+ // 手机是只读消费者:开关刚切换时也要立即收到当前投影(关闭时为空表)。+ broadcastMobileSnapshots('sync-setting-changed');// 索取回发:本机可能在关闭同步期间落后了,而对端不会主动告诉我们。broadcastToAllPeers('sync-enabled', { requestReply: true });}/** 本地词典变更:去抖后广播。连续学习事件不会打出一连串帧。 */export function notifyLocalDictionaryChanged(): void {+ // 开关关闭后桌面 CRDT 与手机投影都保持静默。空投影只在开关切换或手机上线时+ // 推一次,用来清旧缓存;本地学习/编辑若继续推空表,只会制造无效流量和重绘。if (!isSyncEnabled()) return;if (debounceTimer) clearTimeout(debounceTimer);debounceTimer = setTimeout(() => {debounceTimer = null;broadcastToAllPeers('local-change');+ broadcastMobileSnapshots('local-change');}, BROADCAST_DEBOUNCE_MS);debounceTimer.unref?.();}@@ -197,6 +212,49 @@ export function readDictionaryProjectionForMobile(): {return Object.keys(vector).length > 0 ? { entries, stateVector: vector } : { entries };}+function broadcastMobileSnapshots(reason: string): void {+ if (!transport) return;+ const peers = transport.listOnlineMobileDevices();+ if (peers.length === 0) return;+ const payload = buildMobileSnapshot();+ if (!payload) return;+ for (const deviceId of peers) sendMobileSnapshotTo(deviceId, reason, payload);+}++function sendMobileSnapshotTo(+ deviceId: string,+ reason: string,+ payload?: MobileVoiceDictionarySnapshotResult | null,+): void {+ if (!transport) return;+ const snapshot = payload === undefined ? buildMobileSnapshot() : payload;+ if (!snapshot) return;+ try {+ transport.sendMobileSnapshot(deviceId, snapshot);+ } catch (error) {+ // push 是尽力而为的全量状态镜像;下次上线、变更或主动 invoke 会补齐。+ log.warn(`mobile dictionary snapshot push failed (${reason}) to ${deviceId.slice(0, 8)}`, {+ error: error instanceof Error ? error.message : String(error),+ });+ }+}++function buildMobileSnapshot(): MobileVoiceDictionarySnapshotResult | null {+ const payload: MobileVoiceDictionarySnapshotResult = {+ ok: true,+ ...readDictionaryProjectionForMobile(),+ };+ const bytes = Buffer.byteLength(JSON.stringify(payload), 'utf8');+ if (bytes <= MAX_STATE_FRAME_BYTES) return payload;+ // 与桌面 CRDT 同一条上限:超限帧会被 relay 拒绝。这里不另造分片协议,+ // 手机保留上次缓存,词典缩小后下一次上线/变更再推。+ log.error(+ `mobile dictionary snapshot is too large to push (${bytes} bytes > ${MAX_STATE_FRAME_BYTES}); `+ + 'phones will keep their last cache until the dictionary shrinks',+ );+ return null;+}+function broadcastToAllPeers(reason: string, options?: { requestReply?: boolean }): void {if (!isSyncEnabled() || !transport) return;const peers = transport.listOnlineDesktopDevices();@@ -260,5 +318,6 @@ export const __testing = {clearTimeout(debounceTimer);debounceTimer = null;broadcastToAllPeers('test-flush');+ broadcastMobileSnapshots('test-flush');},};diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsxindex 978ebf722a..edde25cf8c 100644--- a/apps/mobile/app/settings.tsx+++ b/apps/mobile/app/settings.tsx@@ -70,6 +70,7 @@ import {hydrateMobileVoiceDictionary,readCachedMobileVoiceDictionarySnapshot,refreshMobileVoiceDictionary,+ subscribeMobileVoiceDictionaryCache,} from '@/session/mobileVoiceDictionaryCache';import {buildMobileVoiceDictionaryEntryViews,@@ -736,14 +737,34 @@ export default function SettingsScreen() {});}, [desktopDevices, deviceLink]);+ // 页面打开后再由 effect 读取缓存和刷新。设备清单本身是异步 REST 请求,不能只+ // 捕获点击瞬间的 desktopDevices=[],否则清单稍后到达时历史缓存永远不会 hydrate。const openVoiceDictionary = useCallback(() => {setDictionaryScreenOpen(true);- // 进页面先把盘上缓存读进内存(离线也有内容可看),再拉一次最新的。+ }, []);++ useEffect(() => {+ if (!dictionaryScreenOpen || desktopDevices.length === 0) return;+ let cancelled = false;+ // 进页面先把盘上缓存读进内存(离线也有内容可看),再拉一次最新的。这个 effect+ // 同时依赖 desktopDevices,因此设备清单在页面打开后才到达时也会走同一条路径。void Promise.all(desktopDevices.map((host) => hydrateMobileVoiceDictionary(host.deviceId)))- .then(() => setDictionaryRevision((value) => value + 1))+ .then(() => {+ if (!cancelled) setDictionaryRevision((value) => value + 1);+ }).catch(() => undefined);refreshVoiceDictionary();- }, [desktopDevices, refreshVoiceDictionary]);+ return () => {+ cancelled = true;+ };+ }, [desktopDevices, dictionaryScreenOpen, refreshVoiceDictionary]);++ useEffect(() => {+ if (!dictionaryScreenOpen) return;+ return subscribeMobileVoiceDictionaryCache(() => {+ setDictionaryRevision((value) => value + 1);+ });+ }, [dictionaryScreenOpen]);// dictionaryRevision 只作为依赖存在:缓存是模块级的,刷新完成后靠它触发重算。const dictionaryEntries = useMemo(diff --git a/apps/mobile/src/__tests__/mobileSettings.test.ts b/apps/mobile/src/__tests__/mobileSettings.test.tsindex e1ac4879a3..ef977f18a8 100644--- a/apps/mobile/src/__tests__/mobileSettings.test.ts+++ b/apps/mobile/src/__tests__/mobileSettings.test.ts@@ -179,6 +179,24 @@ describe('mobile settings overview', () => {expect(source).not.toContain('clearManualName');});+ it('hydrates the voice dictionary after the async desktop list arrives', () => {+ const source = readTextLf(resolve(process.cwd(), 'app/settings.tsx'), 'utf8');+ const dictionaryEffectIndex = source.indexOf(+ 'if (!dictionaryScreenOpen || desktopDevices.length === 0) return;',+ );+ const dictionaryOpenIndex = source.indexOf('const openVoiceDictionary = useCallback(() => {');+ const hydrateIndex = source.indexOf(+ 'Promise.all(desktopDevices.map((host) => hydrateMobileVoiceDictionary(host.deviceId)))',+ dictionaryEffectIndex,+ );++ expect(dictionaryEffectIndex).toBeGreaterThan(-1);+ expect(dictionaryOpenIndex).toBeGreaterThan(-1);+ expect(hydrateIndex).toBeGreaterThan(dictionaryEffectIndex);+ expect(source).toContain('[desktopDevices, dictionaryScreenOpen, refreshVoiceDictionary]');+ expect(source).toContain('subscribeMobileVoiceDictionaryCache(() => {');+ });+it('always shows privacy policy + user agreement (regional links via legalLinks) above the cn-only App filing number', () => {const source = readTextLf(resolve(process.cwd(), 'app/settings.tsx'), 'utf8');const filingCardIndex = source.indexOf("<SettingsGroup title={t('settings.legal.sectionTitle')}>");diff --git a/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts b/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.tsindex 56a7bcfaab..02986a0427 100644--- a/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts+++ b/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts@@ -28,12 +28,14 @@ vi.mock('@/session/mobileVoiceHistoryStore', () => ({const {__resetMobileVoiceDictionaryCacheForTests,+ applyMobileVoiceDictionarySnapshot,setMobileVoiceDictionaryAccountScope,clearAllMobileVoiceDictionaryCaches,hydrateMobileVoiceDictionary,readCachedMobileVoiceDictionary,readCachedMobileVoiceDictionarySnapshot,refreshMobileVoiceDictionary,+ subscribeMobileVoiceDictionaryCache,} = await import('@/session/mobileVoiceDictionaryCache');const HOST = 'desktop-1';@@ -45,6 +47,20 @@ beforeEach(() => {});describe('mobileVoiceDictionaryCache', () => {+ it('接收桌面主动推送的快照后立即可读并落盘', async () => {+ await applyMobileVoiceDictionarySnapshot(HOST, {+ ok: true,+ entries: [{ text: '推送词', frequency: 4 }],+ });++ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([+ { text: '推送词', frequency: 4, aliases: [] },+ ]);+ __resetMobileVoiceDictionaryCacheForTests();+ await hydrateMobileVoiceDictionary(HOST);+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('推送词');+ });+it('拉取成功后缓存并落盘,重启后能恢复', async () => {await refreshMobileVoiceDictionary(HOST, async () => ({ok: true,@@ -198,6 +214,35 @@ describe('mobileVoiceDictionaryCache', () => {});describe('账号分区', () => {+ it('不把 v1 未分区缓存导入当前账号,只删除遗留键', async () => {+ setMobileVoiceDictionaryAccountScope('user-a');+ storage.set(+ 'xdt.mobileVoiceDictionary.v1.desktop-1',+ JSON.stringify({+ entries: [{ text: '旧版离线词', frequency: 2 }],+ fetchedAt: 123,+ }),+ );++ await hydrateMobileVoiceDictionary(HOST);++ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);+ expect(storage.has('xdt.mobileVoiceDictionary.v2.user-a.desktop-1')).toBe(false);+ expect(storage.has('xdt.mobileVoiceDictionary.v1.desktop-1')).toBe(false);+ });++ it('匿名分区也不接管 v1 未分区缓存,并清掉遗留键', async () => {+ storage.set(+ 'xdt.mobileVoiceDictionary.v1.desktop-1',+ JSON.stringify({ entries: [{ text: '不能泄漏' }], fetchedAt: 123 }),+ );++ await hydrateMobileVoiceDictionary(HOST);++ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);+ expect(storage.has('xdt.mobileVoiceDictionary.v1.desktop-1')).toBe(false);+ });+it('切换账号后读不到上一个账号的快照 —— 即使清理没删干净', async () => {setMobileVoiceDictionaryAccountScope('user-a');await refreshMobileVoiceDictionary(HOST, async () => ({@@ -353,4 +398,52 @@ describe('版本向量的入站校验', () => {await hydrateMobileVoiceDictionary(HOST);expect(readCachedMobileVoiceDictionarySnapshot(HOST).stateVector).toEqual({ 'node-a': STAMP_A });});++ it('后到的旧快照不能覆盖已有的更新状态', async () => {+ const newer = '0000000rt0.0000.node-a';+ await applyMobileVoiceDictionarySnapshot(HOST, {+ ok: true,+ entries: [{ text: '新词' }],+ stateVector: { 'node-a': newer },+ });+ await applyMobileVoiceDictionarySnapshot(HOST, {+ ok: true,+ entries: [{ text: '旧词' }],+ stateVector: { 'node-a': STAMP_A },+ });+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('新词');+ });++ it('无版本向量的空投影可以清空已有缓存', async () => {+ await applyMobileVoiceDictionarySnapshot(HOST, {+ ok: true,+ entries: [{ text: '旧词' }],+ stateVector: { 'node-a': STAMP_A },+ });+ await applyMobileVoiceDictionarySnapshot(HOST, {+ ok: true,+ entries: [],+ });+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);+ });+});++describe('缓存订阅隔离', () => {+ it('订阅者抛错不打断落盘', async () => {+ const unsubscribe = subscribeMobileVoiceDictionaryCache(() => {+ throw new Error('subscriber failed');+ });+ try {+ await expect(applyMobileVoiceDictionarySnapshot(HOST, {+ ok: true,+ entries: [{ text: '推送词', frequency: 1 }],+ })).resolves.toBeUndefined();+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('推送词');+ __resetMobileVoiceDictionaryCacheForTests();+ await hydrateMobileVoiceDictionary(HOST);+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('推送词');+ } finally {+ unsubscribe();+ }+ });});diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsxindex 9ab940f82a..f161e041df 100644--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx@@ -63,7 +63,11 @@ import {} from '@/session/scheduleIndex';import { isTransientRemoteError } from '@/device-link/remoteRetry';import { createRnWebSocket } from '@/device-link/rnWebSocket';-import type { MobileGoalStatusPayload } from '@cindy/maker-shared/device-link-contract';+import {+ DEVICE_LINK_VOICE_DICTIONARY_SNAPSHOT_CHANNEL,+ type MobileGoalStatusPayload,+ type MobileVoiceDictionarySnapshotResult,+} from '@cindy/maker-shared/device-link-contract';import {DeviceLinkTopicRegistry,markHeldRemoteTopicsSubscribed,@@ -72,6 +76,7 @@ import {topicsMissingRemoteAck,} from '@/device-link/topicRegistry';import { remoteSessionStore } from '@/session/remoteSessionStore';+import { applyMobileVoiceDictionarySnapshot } from '@/session/mobileVoiceDictionaryCache';import { revokedDevicesStore } from '@/device-link/revokedDevicesStore';import {acquireDeviceSendSlot,@@ -1163,6 +1168,15 @@ export function routeFrame(env: Envelope, handlers: {dispatchFileBrowserWatchEvent(push.payload);return;}+ if (push.channel === DEVICE_LINK_VOICE_DICTIONARY_SNAPSHOT_CHANNEL) {+ // 只读全量快照由桌面主动推送,不经过 remoteControlEnabled 控制门禁。+ // env.src 是 relay 写入的来源设备,缓存按它分片,不能信任 payload 自报 host。+ void applyMobileVoiceDictionarySnapshot(+ env.src,+ push.payload as MobileVoiceDictionarySnapshotResult,+ );+ return;+ }remoteSessionStore.applyRemotePush(env.src, push.channel, push.payload);}diff --git a/apps/mobile/src/session/mobileVoiceDictionaryCache.ts b/apps/mobile/src/session/mobileVoiceDictionaryCache.tsindex 6920f135e7..fc9e7a860d 100644--- a/apps/mobile/src/session/mobileVoiceDictionaryCache.ts+++ b/apps/mobile/src/session/mobileVoiceDictionaryCache.ts@@ -17,6 +17,7 @@import AsyncStorage from '@react-native-async-storage/async-storage';import { hlcNodeId, isCanonicalHlc } from '@cindy/voice-input-core';import { listMobileVoiceHistoryHosts } from '@/session/mobileVoiceHistoryStore';+import { isFresherMobileVoiceDictionarySnapshot } from '@/session/mobileVoiceDictionaryView';import type {MobileVoiceCredentialSyncDictionaryEntry,MobileVoiceDictionarySnapshotResult,@@ -71,6 +72,7 @@ type CachedDictionary = {};const memoryCache = new Map<string, CachedDictionary>();+const cacheListeners = new Set<() => void>();/*** 在途请求。键带账号分区 —— 只按 host 去重的话,账号切走之后新账号的刷新会拿到* 上一个账号那个还挂着的请求并一直等它,而那个请求的结果按代际检查又必然被丢弃:@@ -116,6 +118,12 @@ export function readCachedMobileVoiceDictionarySnapshot(hostDeviceId: string): {};}+/** 订阅缓存内容变化;设置页靠它接收桌面主动推送到达后的即时重绘。 */+export function subscribeMobileVoiceDictionaryCache(listener: () => void): () => void {+ cacheListeners.add(listener);+ return () => cacheListeners.delete(listener);+}+/** 从盘上恢复缓存(App 启动或首次用到该 host 时调用一次)。 */export async function hydrateMobileVoiceDictionary(hostDeviceId: string): Promise<void> {const host = normalizeHostDeviceId(hostDeviceId);@@ -125,7 +133,11 @@ export async function hydrateMobileVoiceDictionary(hostDeviceId: string): Promisconst epoch = cacheEpoch;const scope = accountScope;try {- const raw = await AsyncStorage.getItem(storageKeyForHost(host, scope));+ const currentKey = storageKeyForHost(host, scope);+ const raw = await AsyncStorage.getItem(currentKey);+ // v1 键不带账号。任何已登录账号都无法证明这份遗留快照属于自己,导入就是+ // 跨账号泄漏。只删不迁,词典由桌面 push / 主动拉取重建。+ await AsyncStorage.removeItem(legacyStorageKeyForHost(host)).catch(() => undefined);if (!raw) return;if (epoch !== cacheEpoch) return;const parsed = JSON.parse(raw) as Partial<CachedDictionary>;@@ -177,36 +189,7 @@ export async function refreshMobileVoiceDictionary(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);- }+ await storeSnapshot(host, result, epoch, scope);} catch {// 桌面离线、老被控端不识别该 channel、隧道抖动 —— 一律沿用现有缓存。} finally {@@ -217,6 +200,77 @@ export async function refreshMobileVoiceDictionary(return task;}+/**+ * 接收桌面主动推送的只读快照。+ *+ * push 不属于 relay 的远程控制调用,因此桌面关闭「允许被控」时手机仍能拿到词典。+ * 与主动拉取共用同一条校验、账号代际和落盘路径,避免形成第二份缓存语义。+ */+export async function applyMobileVoiceDictionarySnapshot(+ hostDeviceId: string,+ result: MobileVoiceDictionarySnapshotResult,+): Promise<void> {+ const host = normalizeHostDeviceId(hostDeviceId);+ if (!host) return;+ const epoch = cacheEpoch;+ const scope = accountScope;+ await storeSnapshot(host, result, epoch, scope);+}++async function storeSnapshot(+ host: string,+ result: MobileVoiceDictionarySnapshotResult,+ epoch: number,+ scope: string,+): Promise<void> {+ if (!result?.ok || epoch !== cacheEpoch) return;+ const next: CachedDictionary = {+ entries: normalizeEntries(result.entries),+ fetchedAt: Date.now(),+ stateVector: normalizeStateVector(result.stateVector),+ };+ const current = memoryCache.get(host);+ if (current && !shouldAcceptIncomingSnapshot(current, next)) return;+ memoryCache.set(host, next);+ for (const listener of cacheListeners) {+ try {+ listener();+ } catch {+ // 订阅者抛错不能打断落盘 / 索引登记,也不能变成未处理 rejection。+ }+ }+ // 顺序很关键:**先登记索引,再写快照**。两个写不是原子的,进程随时可能死在+ // 中间 —— 索引里多一条(快照还没写)只是清理时删一个不存在的 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);+ }+}++function shouldAcceptIncomingSnapshot(+ current: CachedDictionary,+ next: CachedDictionary,+): boolean {+ // 同步关闭的空投影没有版本向量,但是明确的清缓存指令。+ if (next.entries.length === 0 && next.stateVector === undefined) return true;+ return isFresherMobileVoiceDictionarySnapshot(next, current);+}+/*** 账号边界清理:退出登录 / 切换账号时抹掉所有词典缓存。*@@ -304,6 +358,7 @@ export function __resetMobileVoiceDictionaryCacheForTests(): void {cacheEpoch += 1;memoryCache.clear();inFlight.clear();+ cacheListeners.clear();}function normalizeEntries(raw: unknown): MobileVoiceCredentialSyncDictionaryEntry[] {diff --git a/apps/mobile/src/session/mobileVoiceDictionaryView.ts b/apps/mobile/src/session/mobileVoiceDictionaryView.tsindex 38a2ba59af..7dea1f06ac 100644--- a/apps/mobile/src/session/mobileVoiceDictionaryView.ts+++ b/apps/mobile/src/session/mobileVoiceDictionaryView.ts@@ -121,7 +121,7 @@ export interface MobileVoiceDictionarySnapshot {* 的快照)。两份都带时:一方包含另一方就选包含者;互不包含(真并发)时没有正确答案,* 退回按拉取时间取较新的。*/-function isFresherThan(+export function isFresherMobileVoiceDictionarySnapshot(candidate: MobileVoiceDictionarySnapshot,best: MobileVoiceDictionarySnapshot,): boolean {@@ -152,7 +152,7 @@ export function buildMobileVoiceDictionaryEntryViews(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;+ return !best || isFresherMobileVoiceDictionarySnapshot(snapshot, best) ? snapshot : best;}, null);if (!freshest) return [];diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 9c8181e3a8..0bc5e8b823 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -120,23 +120,18 @@ export const DL_VOICE_DICTIONARY_LEARNING_CHANNEL = 'device-link:voice:dictionar/*** 手机端拉取被控桌面的语音词典快照(只读)。*- * 桌面之间的词典靠 push 帧对等同步,但手机在后台不维持 WebSocket、收不到 push,- * 所以改为需要时主动拉一份。返回的是**只读投影**:词条文本 + 频次 + 别名,外加一个+ * 桌面之间的词典靠 push 帧对等同步,手机不参与 CRDT 合并而只接收桌面主动推送的+ * 只读投影;本 channel 保留作为旧版兼容和丢 push 时的主动刷新兜底。返回的是**只读投影**:+ * 词条文本 + 频次 + 别名,外加一个* 版本向量(`stateVector`)供手机判断多台电脑的快照谁包含谁。化身、墓碑、抑制项、* 时钟都不外泄 —— 手机不参与合并,不持有可写状态,避免移动端词典分叉。** 符合准入判据:不依赖 event.sender、无本机 UI 副作用、词典真相在被控端。*- * ## 已知限制:与电脑之间的同步不一致- *- * invoke 属于 relay 的 CONTROL_KINDS,转发前会校验目标的 remoteControlEnabled;- * 而电脑之间的词典同步走 push,不受该开关限制。结果是同一个功能有两套前提:用户- * 开了「词典同步」后电脑之间就通了,手机却还要额外打开「允许同账号设备控制本机」- * ——那个开关的语义是「允许别人操作我」,和「读一份词典」并不对应,用户撞上时基本- * 猜不到该去开什么。- *- * 后续可改为推送:桌面在 presence 看到手机上线时主动 push 只读投影,零配置且与- * 电脑之间同一条通道;本 channel 保留作为手机主动刷新的兜底。+ * invoke 仍属于 relay 的 CONTROL_KINDS,转发前会校验目标的 remoteControlEnabled;+ * 因此新版本优先使用独立的只读 push 快照通道,即使桌面关闭「允许被控」也能查看词典。+ * 本 channel 保留用于旧版桌面兼容和 push 丢失后的主动刷新,不能把 REMOTE_DISABLED+ * 当成“真的没有词条”。*/export const DL_VOICE_DICTIONARY_GET_CHANNEL = 'device-link:voice:dictionary:get';diff --git a/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts b/packages/maker-shared/src/__tests__/deviceLinkContract.test.tsindex 724b889ab9..be85ed96a5 100644--- a/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts+++ b/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts@@ -3,6 +3,7 @@ import {DEVICE_LINK_MEDIA_FETCH_CHANNEL,DEVICE_LINK_VOICE_CREDENTIAL_SYNC_CHANNEL,DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL,+ DEVICE_LINK_VOICE_DICTIONARY_SNAPSHOT_CHANNEL,DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL,MOBILE_REMOTE_INVOKE_CHANNELS,connectionIssueHint,@@ -29,6 +30,9 @@ describe('device-link shared contract', () => {expect(DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL).toBe('device-link:voice:transcribe');expect(DEVICE_LINK_VOICE_CREDENTIAL_SYNC_CHANNEL).toBe('device-link:voice:credential-sync');expect(DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL).toBe('device-link:voice:dictionary-learning');+ expect(DEVICE_LINK_VOICE_DICTIONARY_SNAPSHOT_CHANNEL).toBe(+ 'device-link:voice:dictionary:snapshot',+ );expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('maker:send');expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('maker:switch-session-agent');expect(MOBILE_REMOTE_INVOKE_CHANNELS).toContain('maker:get-session-agent-switch-intent');diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.tsindex 89cf014a83..857ed272f0 100644--- a/packages/maker-shared/src/deviceLinkContract.ts+++ b/packages/maker-shared/src/deviceLinkContract.ts@@ -10,6 +10,9 @@ export const DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL = 'device-link:voice:transcribexport 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';+/** 桌面主动推给手机的只读词典快照;push 不受 remoteControlEnabled 控制门禁。 */+export const DEVICE_LINK_VOICE_DICTIONARY_SNAPSHOT_CHANNEL =+ 'device-link:voice:dictionary:snapshot';export type MobileVoiceCredentialSyncAsr = {provider: string;