Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(mobile): 词典快照落盘串行化,关闭同步立刻推空表

Dash371241b9ea42
diff --git a/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts b/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts
index e741a8cb68..b913a7b467 100644
--- a/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts
+++ b/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts
@@ -102,6 +102,9 @@ export class VoiceInputDataStore {
const syncJustEnabled = isRecord(patch)
&& patch.dictionarySyncEnabled === true
&& current.settings.dictionarySyncEnabled === false;
+ const syncJustDisabled = isRecord(patch)
+ && patch.dictionarySyncEnabled === false
+ && current.settings.dictionarySyncEnabled === true;
// 词典三件套的真相在同步状态里,不接受整份覆盖 —— 那会绕过 CRDT,让本地写入
// 在下一次物化时被静默丢掉。词典变更一律走下面的语义化入口。
const nextSettings = normalizeVoiceInputSettings({
@@ -112,9 +115,9 @@ export class VoiceInputDataStore {
...current,
settings: nextSettings,
});
- // 刚打开同步开关:对端可能早已在线,既没有 presence 事件也没有词典变更,
- // 不主动推一次就要等到兜底心跳才收敛。
- if (syncJustEnabled) notifyDictionaryChanged({ immediate: true });
+ // 开关刚切到开或关:对端可能早已在线,既没有 presence 事件也没有词典变更。
+ // 打开时立刻推当前投影;关闭时立刻推空表,清掉已经在线的手机缓存。
+ if (syncJustEnabled || syncJustDisabled) notifyDictionaryChanged({ immediate: true });
return cloneSettings(nextSettings);
}
@@ -615,7 +618,7 @@ export const voiceInputDataStore = new VoiceInputDataStore();
const dictionaryChangedListeners = new Set<DictionaryChangedListener>();
/**
- * `immediate` = 这次变更希望立刻广播,不要走去抖(用户刚打开同步开关)。
+ * `immediate` = 这次变更希望立刻广播,不要走去抖(用户刚打开或关闭同步开关)。
*/
export type DictionaryChangedListener = (options?: { immediate?: boolean }) => void;
diff --git a/apps/desktop/src/main/voice-input/__tests__/VoiceInputDataStore.test.ts b/apps/desktop/src/main/voice-input/__tests__/VoiceInputDataStore.test.ts
index 86e5827ab5..9e87429fae 100644
--- a/apps/desktop/src/main/voice-input/__tests__/VoiceInputDataStore.test.ts
+++ b/apps/desktop/src/main/voice-input/__tests__/VoiceInputDataStore.test.ts
@@ -33,6 +33,7 @@ vi.mock('../../logger.js', () => ({
}));
import {
+ onVoiceInputDictionaryChanged,
registerVoiceInputDataStoreIpc,
voiceInputDataStore,
VoiceInputDataStore,
@@ -53,6 +54,21 @@ describe('VoiceInputDataStore persistence', () => {
vi.restoreAllMocks();
});
+ it('关闭同步开关也会立刻广播,让在线手机清掉旧词典', () => {
+ const store = new VoiceInputDataStore();
+ const listener = vi.fn();
+ const unsubscribe = onVoiceInputDictionaryChanged(listener);
+ try {
+ store.updateSettings({ dictionarySyncEnabled: false });
+ expect(listener).toHaveBeenCalledWith({ immediate: true });
+ listener.mockClear();
+ store.updateSettings({ dictionarySyncEnabled: true });
+ expect(listener).toHaveBeenCalledWith({ immediate: true });
+ } finally {
+ unsubscribe();
+ }
+ });
+
it('writes the candidate before committing state and broadcasting it', () => {
const store = new VoiceInputDataStore();
diff --git a/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts b/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts
index 7b90c48493..179a180ebb 100644
--- a/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts
+++ b/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts
@@ -10,10 +10,29 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { MobileVoiceDictionarySnapshotResult } from '@cindy/maker-shared/device-link-contract';
const storage = new Map<string, string>();
+const persistGate = {
+ delaySnapshotWrites: false,
+ waiters: [] as Array<() => void>,
+};
+
+function releaseSnapshotWrites(): void {
+ const waiters = persistGate.waiters.splice(0);
+ for (const release of waiters) release();
+}
+
vi.mock('@react-native-async-storage/async-storage', () => ({
default: {
getItem: async (key: string) => storage.get(key) ?? null,
setItem: async (key: string, value: string) => {
+ if (
+ persistGate.delaySnapshotWrites
+ && key.includes('mobileVoiceDictionary.v2.')
+ && !key.endsWith('.hosts')
+ ) {
+ await new Promise<void>((resolve) => {
+ persistGate.waiters.push(resolve);
+ });
+ }
storage.set(key, value);
},
removeItem: async (key: string) => {
@@ -42,6 +61,8 @@ const HOST = 'desktop-1';
beforeEach(() => {
storage.clear();
+ persistGate.delaySnapshotWrites = false;
+ releaseSnapshotWrites();
__resetMobileVoiceDictionaryCacheForTests();
setMobileVoiceDictionaryAccountScope('');
});
@@ -443,6 +464,31 @@ describe('版本向量的入站校验', () => {
expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);
});
+ it('并发落盘时较旧写入不能覆盖磁盘上的新快照', async () => {
+ persistGate.delaySnapshotWrites = true;
+ const older = applyMobileVoiceDictionarySnapshot(HOST, {
+ ok: true,
+ entries: [{ text: '旧词' }],
+ stateVector: { 'node-a': STAMP_A },
+ emittedAt: 1_000,
+ });
+ await Promise.resolve();
+ const newer = applyMobileVoiceDictionarySnapshot(HOST, {
+ ok: true,
+ entries: [{ text: '新词' }],
+ stateVector: { 'node-a': STAMP_A },
+ emittedAt: 2_000,
+ });
+ await Promise.resolve();
+ persistGate.delaySnapshotWrites = false;
+ releaseSnapshotWrites();
+ await Promise.all([older, newer]);
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('新词');
+ __resetMobileVoiceDictionaryCacheForTests();
+ await hydrateMobileVoiceDictionary(HOST);
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('新词');
+ });
+
it('更早发出的词表不能盖掉已清空的同一代投影', async () => {
await applyMobileVoiceDictionarySnapshot(HOST, {
ok: true,
diff --git a/apps/mobile/src/session/mobileVoiceDictionaryCache.ts b/apps/mobile/src/session/mobileVoiceDictionaryCache.ts
index 359afd62e8..a03e9006e9 100644
--- a/apps/mobile/src/session/mobileVoiceDictionaryCache.ts
+++ b/apps/mobile/src/session/mobileVoiceDictionaryCache.ts
@@ -245,27 +245,7 @@ async function storeSnapshot(
// 订阅者抛错不能打断落盘 / 索引登记,也不能变成未处理 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);
- }
+ await persistAcceptedSnapshot(host, next, epoch, scope);
}
function shouldAcceptIncomingSnapshot(
@@ -349,6 +329,40 @@ async function readHostIndex(): Promise<{ hosts: string[]; readable: boolean }>
*/
let hostIndexQueue: Promise<void> = Promise.resolve();
+let persistQueue: Promise<void> = Promise.resolve();
+
+function persistAcceptedSnapshot(
+ host: string,
+ next: CachedDictionary,
+ epoch: number,
+ scope: string,
+): Promise<void> {
+ persistQueue = persistQueue
+ .catch(() => undefined)
+ .then(async () => {
+ // 内存里已经换成更新的对象,这份就不要再落盘。
+ if (epoch !== cacheEpoch || memoryCache.get(host) !== next) return;
+ // 顺序很关键:**先登记索引,再写快照**。两个写不是原子的,进程随时可能死在
+ // 中间 —— 索引里多一条(快照还没写)只是清理时删一个不存在的 key,无害;
+ // 反过来快照落了盘而索引没登记,登出就枚举不到它,下个账号用同一台电脑会
+ // hydrate 到上个账号的词典。宁可多登记,不可漏登记。
+ try {
+ await addHostToIndex(host);
+ } catch {
+ return;
+ }
+ if (epoch !== cacheEpoch || memoryCache.get(host) !== next) 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);
+ }
+ });
+ return persistQueue;
+}
+
function addHostToIndex(hostDeviceId: string): Promise<void> {
hostIndexQueue = hostIndexQueue
.catch(() => undefined)
@@ -365,6 +379,7 @@ export function __resetMobileVoiceDictionaryCacheForTests(): void {
memoryCache.clear();
inFlight.clear();
cacheListeners.clear();
+ persistQueue = Promise.resolve();
}
function normalizeEntries(raw: unknown): MobileVoiceCredentialSyncDictionaryEntry[] {