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(chat): 收紧缓存覆盖顺序并保护实时正文

Dash999794f71eb2
diff --git a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
index c8bc066bdc..08c847c255 100644
--- a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
@@ -291,6 +291,39 @@ describe('冷缓存 hydrate', () => {
expect(makerChatStore.getSnapshot(s).messages.map(message => message.content)).toEqual(['earlier history', 'latest reply']);
});
+ // Unit: a live detail push wins even when an older disk receipt arrives later.
+ // The prior tests only mixed distinct IDs or two comparable cached receipts.
+ it.each([false, true])('keeps an unmarked live body when disk hydration is delayed (cached page=%s)', async (cachedPage) => {
+ const s = sid();
+ setDataOwnerGeneration('owner-a', 1);
+ registerRemote(s);
+ const live = dbMessage(s, 'reply', 'live body', '2026-10-11T00:00:01.000Z');
+ let release!: () => void;
+ if (cachedPage) getMessages.mockResolvedValueOnce({ messages: [], invalidation: cachedInvalidation,
+ ownerToken: cachedOwnerToken, accountCounter: cachedAccountCounter,
+ historyView: encodeRemoteHistory({ items: projectHistoryView([{ ...live, content: 'old page' }], false),
+ details: new Map(), expanded: new Set(), readReceipt: { run: 'old-run', order: 1 },
+ ready: true, loading: false, error: null, nextCursor: null, hasMore: false }) } as CachedRead);
+ getMessages.mockImplementationOnce(async () => {
+ await new Promise<void>(resolve => { release = resolve; });
+ return { messages: [{ ...live, content: 'old disk body', cacheReceipt: { run: 'old-run', order: 99 } }],
+ invalidation: cachedInvalidation, ownerToken: cachedOwnerToken, accountCounter: cachedAccountCounter };
+ });
+ let push!: Parameters<typeof window.electronAPI.deviceLink.onRemotePush>[0];
+ window.electronAPI.deviceLink.onRemotePush = vi.fn(callback => { push = callback; return () => {}; });
+ makerChatStore.initGlobalListeners();
+ remoteListPromise = new Promise<Message[]>(() => {});
+ if (cachedPage) remoteProjectsStore.markDeviceDisconnected(DEVICE_ID);
+ makerChatStore.ensureInitialMessages(s);
+ await flush(30);
+ if (cachedPage) expect(makerChatStore.getSnapshot(s).messages.map(message => message.content)).toEqual(['old page']);
+ push({ deviceId: DEVICE_ID, channel: 'local-db:messages:created', payload: { sessionId: s, message: live } });
+ expect(makerChatStore.getSnapshot(s).messages[0].cacheReceipt).toBeUndefined();
+ release();
+ await flush(30);
+ expect(makerChatStore.getSnapshot(s).messages.map(message => message.content)).toEqual(['live body']);
+ });
+
it.each([true, false])('shows list text while pending and only its owner persists receipts (owner=%s)', async (ownsRemoteListCache) => {
const s = sid();
setDataOwnerGeneration('owner-a', 1);
@@ -517,10 +550,10 @@ describe('冷缓存 hydrate', () => {
// A restart restores two caches: the structured page and a later durable list receipt.
// Neither resolution order may hide the newer body while the Host is offline.
- it.each([false, true])('restores a later disk receipt over the same row in old history (raw delayed=%s)', async (delayed) => {
+ it.each([[false, true], [true, true], [false, false], [true, false]])('restores disk receipts only in a comparable run (raw delayed=%s, same run=%s)', async (delayed, sameRun) => {
const s = sid();
const old = dbMessage(s, 'reply', 'old body', '2026-10-11T00:00:01.000Z');
- const latest = { ...old, content: 'latest body', cacheReceipt: { run: 'cached', order: 2 } };
+ const latest = { ...old, content: 'latest body', cacheReceipt: { run: sameRun ? 'cached' : 'other-old-run', order: 2 } };
const historyView = encodeRemoteHistory({ items: projectHistoryView([old], false), details: new Map(), expanded: new Set(),
readReceipt: { run: 'cached', order: 1 }, ready: true, loading: false, error: null, nextCursor: null, hasMore: false });
let reads = 0;
@@ -533,9 +566,9 @@ describe('冷缓存 hydrate', () => {
remoteProjectsStore.markDeviceDisconnected(DEVICE_ID);
makerChatStore.ensureInitialMessages(s);
await flush(60);
- expect(makerChatStore.getSnapshot(s).messages.map(row => row.content)).toEqual(['latest body']);
+ expect(makerChatStore.getSnapshot(s).messages.map(row => row.content)).toEqual([sameRun ? 'latest body' : 'old body']);
getRemoteHistoryView(s)?.setActive(true);
- expect(makerChatStore.getSnapshot(s).messages.map(row => row.content)).toEqual(['latest body']);
+ expect(makerChatStore.getSnapshot(s).messages.map(row => row.content)).toEqual([sameRun ? 'latest body' : 'old body']);
expect(invoke).not.toHaveBeenCalled();
makerChatStore.purgeSession(s);
getMessages.mockImplementation(async (deviceId, sessionId) => ({
diff --git a/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
index 23f9db5241..812491618f 100644
--- a/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
+++ b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
@@ -348,7 +348,7 @@ describe('reusable auxiliary window chrome', () => {
it('restores right-sidebar tab bodies only after the visible window has fresh context', async () => {
render(<SidebarWindowLayout />);
- expect(mocks.initGlobalListeners).toHaveBeenCalledWith({ ownsRemoteAuthRetry: false });
+ expect(mocks.initGlobalListeners).toHaveBeenCalledWith({ ownsRemoteAuthRetry: false, ownsRemoteListCache: false });
expect(mocks.sidebarShellVisible).toBe(false);
await act(async () => mocks.sidebarVisibilityListener?.({ visible: true }));
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index de58bf60f6..007d603952 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -40,7 +40,7 @@ import { parsePluginConnectionInput, type InputHandoffSnapshot } from '@cindy/de
import { HISTORY_WORK_PATCH_CHANNEL, HistoryViewController, isHistoryViewUnavailable, mapHistoryViewMessages, historyViewLeaves, historyWorkSummaries, historyPrefetchVersion, historySnapshotCovers, historySnapshotForCache, selectHistoryPrefetchSessions, type HistoryViewPage, type HistoryDetailPage, type HistoryWorkPatch } from '@cindy/maker-shared/message-window';
import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
-import { nextHistoryCacheReceipt, historyCacheReceiptFollows, mergeHistoryPrefetchRequest, type HistoryCacheReceipt, type HistoryPrefetchRequest } from '@cindy/maker-shared/message-window';
+import { nextHistoryCacheReceipt, isHistoryCacheReceipt, historyCacheReceiptFollows, mergeHistoryPrefetchRequest, type HistoryCacheReceipt, type HistoryPrefetchRequest } from '@cindy/maker-shared/message-window';
import { SESSION_SYNC_CHANNEL } from '@cindy/device-link';
import { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from '@cindy/maker-shared/message-window';
import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';
@@ -8753,6 +8753,11 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
clearRemoteOptimisticSend(sessionId, mapped.clientId);
const current = getOrCreateState(sessionId);
const existing = current.messages.find((candidate) => candidate.clientId === mapped.clientId);
+ if (existing?.cacheHydrated || existing?.cacheReceipt) {
+ // This is a live body now; it must not inherit the replaced cache's order or provenance.
+ mapped.cacheHydrated = false;
+ mapped.cacheReceipt = message.cacheReceipt;
+ }
if (mapped.systemCardType?.startsWith('cindy-make')) {
// A late update to an older preparation card must not replace the current result.
const existingIndex = existing ? current.messages.indexOf(existing) : -1;
@@ -11491,7 +11496,7 @@ function hydrateRemoteMessagesFromCache(sessionId: string): void {
const current = new Map(s.messages.map(message => [message.clientId, message]));
const newerReceipts = new Set(mapped.filter(message => {
const existing = current.get(message.clientId);
- return !existing?.isStreaming
+ return !existing?.isStreaming && isHistoryCacheReceipt(existing?.cacheReceipt)
&& historyCacheReceiptFollows(message.cacheReceipt, history?.readReceipt, history?.stale)
&& historyCacheReceiptFollows(message.cacheReceipt, existing?.cacheReceipt);
}).map(message => message.clientId));
@@ -11701,9 +11706,13 @@ function createRemoteHistoryView(sessionId: string) {
}
const available = historyViewLeaves(snapshot.items).flatMap((item) => item.type === 'messages' ? item.messages : []);
for (const detail of snapshot.details.values()) available.push(...detail.messages);
+ // Restored page rows are cached too. Keep their read order when borrowing them
+ // into the raw store, so a delayed disk receipt is comparable without treating live rows as old.
+ const borrowed = deviceId && snapshot.stale ? available.map(message => ({ ...message,
+ cacheHydrated: true as const, cacheReceipt: snapshot.readReceipt })) : available;
setState(sessionId, (state) => ({ ...state, historyLoaded: true,
messages: confirmRemoteUsers(
- mergeMessages(available, state.messages.filter((message) => !message.cacheHydrated
+ mergeMessages(borrowed, state.messages.filter((message) => !message.cacheHydrated
|| historyCacheReceiptFollows(message.cacheReceipt, snapshot.readReceipt, snapshot.stale)), { addOnly: true }),
new Set(available.filter((message) => message.role === 'user').map((message) => message.clientId)),
),
diff --git a/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts b/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts
index bc97d2afb2..d26a19c703 100644
--- a/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts
+++ b/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts
@@ -48,7 +48,7 @@ describe('mobile history handoff', () => {
// including receipts restored from a previous app run.
it.each([false, true])('retires old receipts after a clock rollback (previous run=%s)', async (previousRun) => {
const clock = vi.spyOn(Date, 'now').mockReturnValue(50_000);
- const cachedRead = previousRun ? { run: 'previous-snapshot', order: 1 } : nextHistoryCacheReceipt();
+ const cachedRead = previousRun ? { run: 'previous-run', order: 1 } : nextHistoryCacheReceipt();
const receipt = previousRun ? { run: 'previous-run', order: 999_999 } : nextHistoryCacheReceipt();
const old = { ...row('answer'), content: 'cached body', cacheReceipt: receipt };
const view = new HistoryViewController<RemoteMessage>({
@@ -76,6 +76,28 @@ describe('mobile history handoff', () => {
} finally { view.setActive(false); clock.mockRestore(); }
});
+ // Unit: separately saved raw (run A) and authoritative page (run B), restored
+ // offline in run C. Only an actual C push may supersede B; A cannot be ordered after B.
+ it.each([false, true])('does not guess the order of two old runs (current push=%s)', async (currentPush) => {
+ const raw = { ...row('answer'), content: 'raw body',
+ cacheReceipt: currentPush ? nextHistoryCacheReceipt() : { run: 'run-A', order: 999_999 } };
+ const view = new HistoryViewController<RemoteMessage>({
+ page: async () => { throw new Error('offline'); },
+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }), expanded: async () => undefined,
+ });
+ view.setNetworkAvailable(false);
+ await view.restoreCachedView(async () => ({ items: projectHistoryView([{ ...row('answer'), content: 'authoritative B' }], false),
+ details: new Map(), expanded: new Set(), nextCursor: null, hasMore: false,
+ loading: false, ready: true, error: null, readReceipt: { run: 'run-B', order: 1 } }));
+ const snapshot = view.getSnapshot();
+ const state = createHandoff().reconcile(snapshot, [raw]);
+ expect(buildMobileHistoryRenderItems({ view, snapshot, messages: state.messages, staleTail: state.tail,
+ pendingHandoff: state.pending, streaming: false, sessionId: 's' })
+ .filter(item => item.type === 'message').map(item => item.message.body))
+ .toEqual([currentPush ? 'raw body' : 'authoritative B']);
+ view.setActive(false);
+ });
+
it('keeps the live tail below completed text when recovery history has not caught up to that tail', async () => {
const first = { ...row('A'), content: 'first paragraph' };
let live = { ...row('B', true), content: 'second paragraph', createdAt: first.createdAt };
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 8917b4402a..5179a280b1 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -171,7 +171,9 @@ raw store 中晚于画面末尾的普通用户/助手行接在其后显示,
两端缓存可选保存本地正文接收标记 `cacheReceipt` 与最新页读取起始标记 `readReceipt`:
旧历史中的同 ID 正文不能遮住读取开始后收到的新正文,后续权威读取可接管。缓存延迟写回
也保留期间收到的正文;删除、rewind 和账号隔离继续遵守既有作废屏障。标记使用运行期 ID
-及递增序号,不依赖墙钟;冷启动先复用旧运行期缓存,成功的权威读取接管并退役旧标记。
+及递增序号,不依赖墙钟;同运行期按序号比较,不同旧运行期之间无法证明顺序时保留历史画面。
+当前运行期的新推送可接管恢复的旧画面,成功的权威读取接管旧标记。桌面延迟恢复的磁盘行
+只覆盖有可比较且更早标记的同 ID 行,不覆盖无标记的实时正文。
标记不作为主机消息修订号,不改变网络协议或扩展流式订阅范围。
`messages:list` / `messages:view` 的 options 可选携带 `messageBodies: { version: 1, known }`,
diff --git a/packages/maker-shared/src/historyView.ts b/packages/maker-shared/src/historyView.ts
index f3dfd9bb85..13cd399a6b 100644
--- a/packages/maker-shared/src/historyView.ts
+++ b/packages/maker-shared/src/historyView.ts
@@ -17,11 +17,11 @@ export function isHistoryCacheReceipt(value: unknown): value is HistoryCacheRece
const receipt = value as HistoryCacheReceipt | null;
return !!receipt && typeof receipt.run === 'string' && Number.isSafeInteger(receipt.order) && receipt.order > 0;
}
-/** Restored snapshots may borrow other-run receipts; a successful fresh read retires them. */
+/** Only a current-run push can supersede a restored page from another run. */
export function historyCacheReceiptFollows(receipt: unknown, read: unknown, restored = false): boolean {
if (!isHistoryCacheReceipt(receipt)) return false;
if (!isHistoryCacheReceipt(read)) return true;
- return receipt.run === read.run ? receipt.order > read.order : restored && read.run !== cacheReceiptRun;
+ return receipt.run === read.run ? receipt.order > read.order : restored && receipt.run === cacheReceiptRun;
}
export function isHistoryViewUnavailable(error: unknown): boolean {