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(history): 保留超限断档的最新缓存并跨越同时间边界

Dashfb712ef5cca1
diff --git a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
index e2366d6ef0..5f5e0a4320 100644
--- a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
@@ -381,7 +381,8 @@ describe('冷缓存 hydrate', () => {
}
});
- it.each(['prefix', 'collapsed', 'latest'] as const)('never clears the mirror when read ahead exceeds its budget (%s)', async (kind) => {
+ // Oversized gaps must fall back to the original page, not retain the entire gap.
+ it.each(['prefix', 'collapsed', 'latest', 'gap'] as const)('never clears the mirror when read ahead exceeds its budget (%s)', async (kind) => {
const s = sid();
const old = dbMessage(s, 'old', 'x'.repeat(400_000), '2026-10-11T00:00:01.000Z');
const anchor = dbMessage(s, 'anchor', 'anchor', '2026-10-11T00:00:02.000Z');
@@ -406,7 +407,12 @@ describe('冷缓存 hydrate', () => {
] as never);
const reply = dbMessage(s, 'new', 'y'.repeat(kind === 'latest' ? 600_000 : 180_000), '2026-10-11T00:00:09.000Z');
invoke.mockImplementationOnce((async () => ({ version: 1,
- items: projectHistoryView([anchor, reply], false), hasMore: true, nextCursor: anchor.id,
+ items: projectHistoryView(kind === 'gap' ? [reply] : [anchor, reply], false), hasMore: true,
+ nextCursor: kind === 'gap' ? reply.id : anchor.id,
+ })) as unknown as Parameters<typeof invoke.mockImplementationOnce>[0]);
+ if (kind === 'gap') invoke.mockImplementationOnce((async () => ({ version: 1,
+ items: projectHistoryView([anchor, dbMessage(s, 'gap', 'z'.repeat(600_000), '2026-10-11T00:00:05.000Z')], false),
+ hasMore: true, nextCursor: anchor.id,
})) as unknown as Parameters<typeof invoke.mockImplementationOnce>[0]);
try {
await makerChatStore.prefetchRemoteHistories(DEVICE_ID);
@@ -427,8 +433,13 @@ describe('冷缓存 hydrate', () => {
const saved = decodeRemoteHistory(text)!;
expect(saved.items.at(-1)?.key).toBe(reply.clientId);
expect(saved.details.size).toBe(0);
- expect(saved).toMatchObject(kind === 'prefix'
+ expect(saved).toMatchObject(kind === 'gap' ? { hasMore: true, nextCursor: reply.id } : kind === 'prefix'
? { hasMore: true, nextCursor: anchor.id } : { hasMore: false, nextCursor: null });
+ if (kind === 'gap') {
+ expect(saved.items.map(item => item.key)).toEqual([reply.clientId]);
+ await makerChatStore.prefetchRemoteHistories(DEVICE_ID);
+ expect(invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(2);
+ }
}
} finally {
getMessages.mockReset();
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 0305abb374..34f3ec21a7 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -12009,8 +12009,9 @@ async function prefetchRemoteHistories(deviceId: string, sessionIds?: ReadonlySe
}))) };
};
let page: HistoryViewPage<HistoryChatMessage> | null;
+ let latestPage: HistoryViewPage<HistoryChatMessage> | null;
try {
- page = await readPage();
+ page = latestPage = await readPage();
if (page) page = await readContinuousHistoryPage(page, previous, readPage,
() => isCurrent(session.id) && token === sessionCacheInvalidationToken(session.id) && !getRemoteHistoryView(session.id));
} catch (error) {
@@ -12020,7 +12021,7 @@ async function prefetchRemoteHistories(deviceId: string, sessionIds?: ReadonlySe
}
if (page == null || !isCurrent(session.id) || getRemoteHistoryView(session.id)) continue;
const snapshot = historySnapshotForCache(page, previous,
- (candidate) => fitsRemoteHistoryCache(encodeRemoteHistory(candidate)));
+ (candidate) => fitsRemoteHistoryCache(encodeRemoteHistory(candidate)), latestPage ?? page);
if (!snapshot) continue;
write({ ...snapshot, readReceipt });
}
diff --git a/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts b/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts
index 92aaa99ab1..ffa4895919 100644
--- a/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts
+++ b/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts
@@ -120,7 +120,8 @@ describe('history read ahead after a list refresh', () => {
} finally { off(); }
});
- it.each(['prefix', 'collapsed', 'latest'] as const)('handles an oversized %s without losing the offline cache', async (kind) => {
+ // A filled gap can exceed the cache even when its original latest page fits.
+ it.each(['prefix', 'collapsed', 'latest', 'gap'] as const)('handles an oversized %s without losing the offline cache', async (kind) => {
setMobileAuthOwner('user-1');
const old = row('old', 1, 'x'.repeat(1_250_000));
const anchor = row('anchor', 2);
@@ -137,9 +138,13 @@ describe('history read ahead after a list refresh', () => {
const authority = historyDiskAuthority(DEVICE, 's');
expect(await writeHistoryDisk(authority, previous)).toBe(true);
const reply = row('new', 9, 'y'.repeat(kind === 'latest' ? 1_500_000 : 200_000));
- const latest = { ...page([anchor, reply]), hasMore: true, nextCursor: anchor.id };
+ const latest = { ...page(kind === 'gap' ? [reply] : [anchor, reply]), hasMore: true,
+ nextCursor: kind === 'gap' ? reply.id : anchor.id };
remoteSessionStore.setDeviceSessions(DEVICE, 'Mac', [session('s', reply.createdAt)]);
const reader = { readHistoryView: vi.fn(async () => latest) };
+ if (kind === 'gap') reader.readHistoryView.mockResolvedValueOnce(latest).mockResolvedValueOnce({
+ ...page([anchor, row('gap', 5, 'z'.repeat(1_500_000))]), hasMore: true, nextCursor: anchor.id,
+ });
await prefetchRemoteHistories(DEVICE, reader, () => true);
const cached = await readHistoryDisk(authority);
expect(cached).not.toBeNull();
@@ -154,9 +159,13 @@ describe('history read ahead after a list refresh', () => {
} else {
expect(cached?.items.at(-1)?.key).toBe(reply.id);
expect(cached?.details.size).toBe(0);
- expect(cached).toMatchObject(kind === 'prefix'
- ? { hasMore: true, nextCursor: anchor.id } : { hasMore: false, nextCursor: null });
- expect(cached?.items[0].key).toBe(kind === 'prefix' ? latest.items[0].key : 'work');
+ expect(cached).toMatchObject(kind === 'prefix' || kind === 'gap'
+ ? { hasMore: true, nextCursor: latest.nextCursor } : { hasMore: false, nextCursor: null });
+ expect(cached?.items[0].key).toBe(kind === 'prefix' || kind === 'gap' ? latest.items[0].key : 'work');
+ if (kind === 'gap') {
+ await prefetchRemoteHistories(DEVICE, reader, () => true);
+ expect(reader.readHistoryView).toHaveBeenCalledTimes(2);
+ }
}
});
diff --git a/apps/mobile/src/session/remoteHistoryPrefetch.ts b/apps/mobile/src/session/remoteHistoryPrefetch.ts
index 791c110529..8f7e13f31a 100644
--- a/apps/mobile/src/session/remoteHistoryPrefetch.ts
+++ b/apps/mobile/src/session/remoteHistoryPrefetch.ts
@@ -72,8 +72,9 @@ export async function prefetchRemoteHistories(
if (!historySnapshotCovers(previous, session)) {
const readReceipt = nextHistoryCacheReceipt();
let page;
+ let latestPage;
try {
- page = await reader.readHistoryView(session.id);
+ page = latestPage = await reader.readHistoryView(session.id);
if (page) page = await readContinuousHistoryPage(page, previous,
(before) => reader.readHistoryView(session.id, before),
() => isCurrent() && authority.current() && !isRemoteHistoryViewMounted(deviceId, session.id));
@@ -83,7 +84,7 @@ export async function prefetchRemoteHistories(
throw error;
}
if (!page || !isCurrent() || isRemoteHistoryViewMounted(deviceId, session.id)) continue;
- const snapshot = historySnapshotForCache(page, previous, fitsHistoryDisk);
+ const snapshot = historySnapshotForCache(page, previous, fitsHistoryDisk, latestPage);
if (!snapshot || !await writeHistoryDisk(authority, { ...snapshot, readReceipt })) continue;
dropDetachedRemoteHistoryView(deviceId, session.id);
}
diff --git a/packages/maker-shared/src/__tests__/historyViewLoading.test.ts b/packages/maker-shared/src/__tests__/historyViewLoading.test.ts
index e66369fd4e..12eea54ffe 100644
--- a/packages/maker-shared/src/__tests__/historyViewLoading.test.ts
+++ b/packages/maker-shared/src/__tests__/historyViewLoading.test.ts
@@ -15,11 +15,12 @@ function fixture() {
describe('history read coverage', () => {
// A latest page can advance beyond the cached tail while the phone is away.
// The old overlap-only tests never exercised this gap (2026-10-25 shrink).
- it.each(['join', 'failure', 'blur', 'repeated-cursor'] as const)('keeps the cached reading window until a disconnected refresh settles (%s)', async (outcome) => {
+ // Equal timestamps still have distinct rowid order; time equality is not a boundary.
+ it.each(['join', 'same-time', 'failure', 'blur', 'repeated-cursor'] as const)('keeps the cached reading window until a disconnected refresh settles (%s)', async (outcome) => {
const makePage = (ids: number[], hasMore = true): HistoryViewPage<HistoryMessageSource> => ({
version: 1, items: ids.map(id => ({ type: 'messages', key: String(id), messages: [{
id: String(id), clientId: String(id), role: 'user', content: String(id),
- createdAt: new Date(1700000000000 + id * 1000).toISOString(),
+ createdAt: new Date(1700000000000 + (outcome === 'same-time' ? 0 : id * 1000)).toISOString(),
}] })), hasMore, nextCursor: hasMore ? String(ids[0]) : null,
});
let finish!: (page: HistoryViewPage<HistoryMessageSource>) => void;
@@ -38,7 +39,7 @@ describe('history read coverage', () => {
if (outcome === 'failure') fail(new Error('temporary read failure'));
else finish(outcome === 'repeated-cursor' ? makePage([7, 8]) : makePage([3, 4, 5, 6]));
await pending;
- expect(view.getSnapshot().items.map(item => item.key)).toEqual(outcome === 'join'
+ expect(view.getSnapshot().items.map(item => item.key)).toEqual(outcome === 'join' || outcome === 'same-time'
? ['1', '2', '3', '4', '5', '6', '7', '8'] : ['1', '2', '3']);
expect(visible.every(items => items[0] === '1')).toBe(true);
expect(view.getSnapshot().hasMore).toBe(false);
diff --git a/packages/maker-shared/src/historyView.ts b/packages/maker-shared/src/historyView.ts
index f5c3e0bc69..17e4cf009d 100644
--- a/packages/maker-shared/src/historyView.ts
+++ b/packages/maker-shared/src/historyView.ts
@@ -176,7 +176,8 @@ export async function readContinuousHistoryPage<T extends HistoryMessageSource>(
const seen = new Set<string>();
while (isCurrent() && previous?.items.length && page.hasMore
&& historyPrefixBoundary(page, previous.items) < 0
- && startedAt(page.items[0]) > startedAt(previous.items[0])) {
+ // Equal timestamps can still contain later rows in the Host's rowid order.
+ && startedAt(page.items[0]) >= startedAt(previous.items[0])) {
const cursor = page.nextCursor;
if (!cursor || seen.has(cursor)) throw new Error('History page cursor did not advance');
seen.add(cursor);
diff --git a/packages/maker-shared/src/historyViewPrefetch.ts b/packages/maker-shared/src/historyViewPrefetch.ts
index 60a9568fb3..1a14579b42 100644
--- a/packages/maker-shared/src/historyViewPrefetch.ts
+++ b/packages/maker-shared/src/historyViewPrefetch.ts
@@ -103,6 +103,7 @@ export function historySnapshotForCache<T extends HistoryMessageSource>(
page: HistoryViewPage<T>,
previous: HistoryViewSnapshot<T> | null | undefined,
fits: (snapshot: HistoryViewSnapshot<T>) => boolean,
+ latestPage: HistoryViewPage<T> = page,
): HistoryViewSnapshot<T> | null {
const merged = historySnapshotFromPage(page, previous);
if (fits(merged)) return merged;
@@ -111,9 +112,9 @@ export function historySnapshotForCache<T extends HistoryMessageSource>(
});
const expandedOnly = withoutCollapsed(merged);
if (fits(expandedOnly)) return expandedOnly;
- // Removing the prefix must also restore the latest page's cursor/hasMore, so the
- // omitted rows remain reachable online. Never slice rows out of a work range.
- const latest = withoutCollapsed(historySnapshotFromPage(page, previous ? { ...previous, items: [] } : null));
+ // A filled gap can itself exceed the cache. Restore the original latest page
+ // and its cursor, so omitted rows stay reachable online; never slice a work range.
+ const latest = withoutCollapsed(historySnapshotFromPage(latestPage, previous ? { ...previous, items: [] } : null));
if (fits(latest)) return latest;
const folded = { ...latest, details: new Map<string, HistoryWorkDetailState<T>>(), expanded: new Set<string>() };
// A latest page that cannot fit even folded must not clear the existing mirror or