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): 词典快照按发出时间收敛,presence 不再反复拉取

Dash87d941b2581b
diff --git a/apps/desktop/src/main/voice-input/__tests__/dictionarySyncDriver.test.ts b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncDriver.test.ts
index ea8c71ae94..8ce41b57bb 100644
--- a/apps/desktop/src/main/voice-input/__tests__/dictionarySyncDriver.test.ts
+++ b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncDriver.test.ts
@@ -164,18 +164,22 @@ describe('出站', () => {
it('手机上线时主动推只读快照,不依赖远程控制开关', () => {
handleMobilePeerOnline('phone-1');
- expect(sendMobileSnapshot).toHaveBeenCalledWith('phone-1', {
+ expect(sendMobileSnapshot).toHaveBeenCalledWith('phone-1', expect.objectContaining({
ok: true,
entries: [
{ text: 'Cindy', frequency: 2, aliases: [{ text: 'sindy', count: 1 }] },
],
- });
+ }));
+ expect(sendMobileSnapshot.mock.calls[0][1].emittedAt).toEqual(expect.any(Number));
});
it('同步关闭时仍推空投影给手机,让旧缓存及时清空', () => {
syncEnabled.value = false;
handleMobilePeerOnline('phone-1');
- expect(sendMobileSnapshot).toHaveBeenCalledWith('phone-1', { ok: true, entries: [] });
+ expect(sendMobileSnapshot).toHaveBeenCalledWith(
+ 'phone-1',
+ expect.objectContaining({ ok: true, entries: [] }),
+ );
});
it('立即广播会同时刷新所有在线手机', () => {
@@ -292,7 +296,7 @@ describe('手机只读投影', () => {
expect(projection.entries).toEqual([
{ text: 'Cindy', frequency: 2, aliases: [{ text: 'sindy', count: 1 }] },
]);
- // 除了词条和版本向量,不该漏出节点 id、化身、墓碑等同步内部结构。
+ // 除了词条、发出时间和版本向量,不该漏出节点 id、化身、墓碑等同步内部结构。
expect(Object.keys(projection).sort()).toEqual(['entries']);
});
@@ -312,4 +316,16 @@ describe('手机只读投影', () => {
expect(versionVectorDominates(after, before!)).toBe(true);
expect(versionVectorDominates(before!, after)).toBe(false);
});
+
+ it('同步关闭的空投影仍带上当前版本向量,避免晚到的空表清掉更新快照', () => {
+ const first = addManualEntry(createEmptySyncState(), createHlcClock('node-a', 1_000), {
+ text: 'Cindy',
+ nowMs: 1_000,
+ });
+ stateOverride.value = first.state;
+ syncEnabled.value = false;
+ const projection = readDictionaryProjectionForMobile();
+ expect(projection.entries).toEqual([]);
+ expect(projection.stateVector && Object.keys(projection.stateVector)).toEqual(['node-a']);
+ });
});
diff --git a/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts b/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts
index a47b78bcf2..1084d578c8 100644
--- a/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts
+++ b/apps/desktop/src/main/voice-input/dictionarySyncDriver.ts
@@ -200,16 +200,21 @@ export function readDictionaryProjectionForMobile(): {
entries: Array<{ text: string; frequency: number; aliases: Array<{ text: string; count: number }> }>;
stateVector?: Record<string, string>;
} {
- if (!isSyncEnabled()) return { entries: [] };
+ // 版本向量对合并单调(逐节点取 max),所以「逐节点 ≥」等价于「已经见过对方的
+ // 全部事件」—— 这才是手机可以拿一份替代另一份的条件,而不是谁的时间戳大。
+ // 同步关闭时仍带上当前向量:空表是清缓存指令,但必须证明自己不比手机已有的
+ // 快照更旧,否则晚到的空投影会把更新的词表抹掉。
+ const vector = buildStateVersionVector(voiceDictionarySyncStore.getState());
+ const stateVector = Object.keys(vector).length > 0 ? vector : undefined;
+ if (!isSyncEnabled()) {
+ return stateVector ? { entries: [], stateVector } : { 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 };
+ return stateVector ? { entries, stateVector } : { entries };
}
function broadcastMobileSnapshots(reason: string): void {
@@ -242,6 +247,7 @@ function sendMobileSnapshotTo(
function buildMobileSnapshot(): MobileVoiceDictionarySnapshotResult | null {
const payload: MobileVoiceDictionarySnapshotResult = {
ok: true,
+ emittedAt: Date.now(),
...readDictionaryProjectionForMobile(),
};
const bytes = Buffer.byteLength(JSON.stringify(payload), 'utf8');
diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsx
index edde25cf8c..1c4bed081b 100644
--- a/apps/mobile/app/settings.tsx
+++ b/apps/mobile/app/settings.tsx
@@ -122,8 +122,7 @@ export default function SettingsScreen() {
const { locale, setLocale } = useLocale();
const windowDimensions = useWindowDimensions();
const safeAreaInsets = useSafeAreaInsets();
- const deviceLink = useDeviceLink();
- const { lastPresenceSnapshot, status } = deviceLink;
+ const { lastPresenceSnapshot, status, invoke } = useDeviceLink();
const [copiedRowId, setCopiedRowId] = useState<string | null>(null);
const [loggingOut, setLoggingOut] = useState(false);
const [accountDeletionAvailable, setAccountDeletionAvailable] =
@@ -723,7 +722,7 @@ export default function SettingsScreen() {
void Promise.all(
online.map((host) => refreshMobileVoiceDictionary(
host.deviceId,
- () => deviceLink.invoke<MobileVoiceDictionarySnapshotResult>(
+ () => invoke<MobileVoiceDictionarySnapshotResult>(
host.deviceId,
DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL,
[],
@@ -735,7 +734,7 @@ export default function SettingsScreen() {
// 缓存写在模块里,组件靠这个计数触发重渲染。
setDictionaryRevision((value) => value + 1);
});
- }, [desktopDevices, deviceLink]);
+ }, [desktopDevices, invoke]);
// 页面打开后再由 effect 读取缓存和刷新。设备清单本身是异步 REST 请求,不能只
// 捕获点击瞬间的 desktopDevices=[],否则清单稍后到达时历史缓存永远不会 hydrate。
diff --git a/apps/mobile/src/__tests__/mobileSettings.test.ts b/apps/mobile/src/__tests__/mobileSettings.test.ts
index ef977f18a8..b8d92ecd48 100644
--- a/apps/mobile/src/__tests__/mobileSettings.test.ts
+++ b/apps/mobile/src/__tests__/mobileSettings.test.ts
@@ -194,6 +194,8 @@ describe('mobile settings overview', () => {
expect(dictionaryOpenIndex).toBeGreaterThan(-1);
expect(hydrateIndex).toBeGreaterThan(dictionaryEffectIndex);
expect(source).toContain('[desktopDevices, dictionaryScreenOpen, refreshVoiceDictionary]');
+ expect(source).toContain('[desktopDevices, invoke]');
+ expect(source).not.toContain('[desktopDevices, deviceLink]');
expect(source).toContain('subscribeMobileVoiceDictionaryCache(() => {');
});
diff --git a/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts b/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts
index 02986a0427..7b90c48493 100644
--- a/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts
+++ b/apps/mobile/src/__tests__/mobileVoiceDictionaryCache.test.ts
@@ -414,15 +414,47 @@ describe('版本向量的入站校验', () => {
expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('新词');
});
- it('无版本向量的空投影可以清空已有缓存', async () => {
+ it('后到的无向量空投影不能清掉已有的更新快照', async () => {
+ await applyMobileVoiceDictionarySnapshot(HOST, {
+ ok: true,
+ entries: [{ text: '新词' }],
+ stateVector: { 'node-a': STAMP_A },
+ });
+ await applyMobileVoiceDictionarySnapshot(HOST, {
+ ok: true,
+ entries: [],
+ });
+ expect(readCachedMobileVoiceDictionary(HOST)[0].text).toBe('新词');
+ });
+
+ it('带同一代版本向量且更晚发出的空投影可以清空缓存', async () => {
await applyMobileVoiceDictionarySnapshot(HOST, {
ok: true,
entries: [{ text: '旧词' }],
stateVector: { 'node-a': STAMP_A },
+ emittedAt: 1_000,
+ });
+ await applyMobileVoiceDictionarySnapshot(HOST, {
+ ok: true,
+ entries: [],
+ stateVector: { 'node-a': STAMP_A },
+ emittedAt: 2_000,
});
+ expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);
+ });
+
+ it('更早发出的词表不能盖掉已清空的同一代投影', async () => {
await applyMobileVoiceDictionarySnapshot(HOST, {
ok: true,
entries: [],
+ stateVector: { 'node-a': STAMP_A },
+ emittedAt: 2_000,
+ });
+ await applyMobileVoiceDictionarySnapshot(HOST, {
+ ok: true,
+ entries: [{ text: '旧词' }],
+ stateVector: { 'node-a': STAMP_A },
+ emittedAt: 1_000,
});
expect(readCachedMobileVoiceDictionary(HOST)).toEqual([]);
});
diff --git a/apps/mobile/src/session/mobileVoiceDictionaryCache.ts b/apps/mobile/src/session/mobileVoiceDictionaryCache.ts
index fc9e7a860d..25776f7128 100644
--- a/apps/mobile/src/session/mobileVoiceDictionaryCache.ts
+++ b/apps/mobile/src/session/mobileVoiceDictionaryCache.ts
@@ -69,6 +69,8 @@ type CachedDictionary = {
fetchedAt: number;
/** 被控端上报的版本向量;老版本不带,此时只能退回按 fetchedAt 比较。 */
stateVector?: Record<string, string>;
+ /** 桌面生成投影的时间;有则优先于 fetchedAt 判断同一 host 的先后。 */
+ emittedAt?: number;
};
const memoryCache = new Map<string, CachedDictionary>();
@@ -109,12 +111,14 @@ export function readCachedMobileVoiceDictionarySnapshot(hostDeviceId: string): {
entries: MobileVoiceCredentialSyncDictionaryEntry[];
fetchedAt: number;
stateVector?: Record<string, string>;
+ emittedAt?: number;
} {
const cached = memoryCache.get(normalizeHostDeviceId(hostDeviceId));
return {
entries: cached?.entries ?? [],
fetchedAt: cached?.fetchedAt ?? 0,
stateVector: cached?.stateVector,
+ emittedAt: cached?.emittedAt,
};
}
@@ -145,6 +149,7 @@ export async function hydrateMobileVoiceDictionary(hostDeviceId: string): Promis
entries: normalizeEntries(parsed?.entries),
fetchedAt: typeof parsed?.fetchedAt === 'number' ? parsed.fetchedAt : 0,
stateVector: normalizeStateVector(parsed?.stateVector),
+ emittedAt: normalizeEmittedAt(parsed?.emittedAt),
};
// 开麦路径会并发跑 hydrate 与 refresh。磁盘读晚于网络响应返回时,不能用旧
// 快照盖掉刚拉到的新数据 —— 只在内存仍为空、或盘上确实更新时才写。
@@ -228,6 +233,7 @@ async function storeSnapshot(
entries: normalizeEntries(result.entries),
fetchedAt: Date.now(),
stateVector: normalizeStateVector(result.stateVector),
+ emittedAt: normalizeEmittedAt(result.emittedAt),
};
const current = memoryCache.get(host);
if (current && !shouldAcceptIncomingSnapshot(current, next)) return;
@@ -266,8 +272,10 @@ function shouldAcceptIncomingSnapshot(
current: CachedDictionary,
next: CachedDictionary,
): boolean {
- // 同步关闭的空投影没有版本向量,但是明确的清缓存指令。
- if (next.entries.length === 0 && next.stateVector === undefined) return true;
+ // 同一 host 只接受更新鲜的快照。新鲜度唯一判据是版本向量包含关系,
+ // 并列或都没有向量时才比到达时间。同步关闭的空投影必须自带当时的
+ // stateVector,才能清掉同一代缓存;无向量的空表不能覆盖已证明自己
+ // 更新的快照。
return isFresherMobileVoiceDictionarySnapshot(next, current);
}
@@ -391,6 +399,10 @@ function readPositiveInt(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 1;
}
+function normalizeEmittedAt(value: unknown): number | undefined {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : undefined;
+}
+
/**
* 归一化被控端上报的版本向量;形状不对一律当作「没有」,退回按拉取时间比较。
*
diff --git a/apps/mobile/src/session/mobileVoiceDictionaryView.ts b/apps/mobile/src/session/mobileVoiceDictionaryView.ts
index 7dea1f06ac..185015ae3f 100644
--- a/apps/mobile/src/session/mobileVoiceDictionaryView.ts
+++ b/apps/mobile/src/session/mobileVoiceDictionaryView.ts
@@ -92,6 +92,8 @@ export interface MobileVoiceDictionarySnapshot {
fetchedAt: number;
/** 被控端上报的版本向量 `{nodeId: 最大 HLC}`;老版本被控端没有。 */
stateVector?: Record<string, string>;
+ /** 桌面生成投影的时间;有则优先于 fetchedAt 做并列时的先后判断。 */
+ emittedAt?: number;
}
/**
@@ -129,10 +131,22 @@ export function isFresherMobileVoiceDictionarySnapshot(
const candidateDominates = dominates(candidate.stateVector, best.stateVector);
const bestDominates = dominates(best.stateVector, candidate.stateVector);
if (candidateDominates !== bestDominates) return candidateDominates;
- return candidate.fetchedAt > best.fetchedAt;
+ return isLaterSnapshot(candidate, best);
}
if (candidate.stateVector) return true;
if (best.stateVector) return false;
+ return isLaterSnapshot(candidate, best);
+}
+
+function isLaterSnapshot(
+ candidate: MobileVoiceDictionarySnapshot,
+ best: MobileVoiceDictionarySnapshot,
+): boolean {
+ if (candidate.emittedAt !== undefined && best.emittedAt !== undefined) {
+ return candidate.emittedAt > best.emittedAt;
+ }
+ if (candidate.emittedAt !== undefined) return true;
+ if (best.emittedAt !== undefined) return false;
return candidate.fetchedAt > best.fetchedAt;
}
diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.ts
index 857ed272f0..94ca61eeea 100644
--- a/packages/maker-shared/src/deviceLinkContract.ts
+++ b/packages/maker-shared/src/deviceLinkContract.ts
@@ -91,6 +91,12 @@ export type MobileVoiceDictionarySnapshotResult =
* 拿它当完整答案会漏词。老版本被控端不带这个字段,手机退回按到达时间比较。
*/
stateVector?: Record<string, string>;
+ /**
+ * 桌面生成这份投影的本地时间(unix ms)。同一台电脑、同一代版本向量里,
+ * 用它而不是手机到达时间判断谁先发出 —— 晚到的旧拉取不能盖掉先发出的新推送。
+ * 老版本被控端不带这个字段。
+ */
+ emittedAt?: number;
}
| {
ok: false;