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): 保留后台刷新前已缓存的聊天历史 (#6128)

Dashd51754316e65
diff --git a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
index 4946d36749..74b3903c31 100644
--- a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
@@ -33,8 +33,8 @@ vi.mock('@/lib/sessionService', () => ({
}));
import { makerChatStore, getRemoteHistoryView } from '@/lib/makerChatStore';
-import { projectHistoryView } from '@cindy/maker-shared/message-window';
-import { encodeRemoteHistory } from '../../shared/remoteHistoryCache';
+import { projectHistoryView, type HistoryViewSnapshot } from '@cindy/maker-shared/message-window';
+import { decodeRemoteHistory, encodeRemoteHistory, fitsRemoteHistoryCache } from '../../shared/remoteHistoryCache';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import { listMessagesFor } from '@/lib/makerTransport';
import { collectSessionListSnapshot } from '@/features/device-link/refreshRemoteSessions';
@@ -326,6 +326,64 @@ describe('冷缓存 hydrate', () => {
}
});
+ it.each(['prefix', 'collapsed', 'latest'] 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');
+ const previous: HistoryViewSnapshot<Message> = {
+ items: projectHistoryView([old, anchor], false), details: new Map(), expanded: new Set(),
+ ready: true, loading: false, error: null, hasMore: false, nextCursor: null,
+ };
+ if (kind === 'collapsed') {
+ previous.items = [{ type: 'work', key: 'work', summary: {
+ key: 'work', firstMessageId: old.id, lastMessageId: old.id, revision: 'r1',
+ startedAtMs: Date.parse(old.createdAt), endedAtMs: Date.parse(old.createdAt),
+ messageCount: 1, toolCount: 1, isStreaming: false,
+ } }, ...projectHistoryView([anchor], false)];
+ previous.details = new Map([['work', { messages: [old], revision: 'r1', lastMessageId: old.id,
+ complete: true, loading: false, error: null }]]);
+ }
+ const historyView = encodeRemoteHistory(previous);
+ expect(fitsRemoteHistoryCache(historyView)).toBe(true);
+ getMessages.mockResolvedValue({ messages: [], invalidation: 0, ownerToken: cachedOwnerToken, accountCounter: 0, historyView } as CachedRead);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [
+ { id: s, status: 'active', updatedAt: '2026-10-11T00:00:09.000Z' },
+ ] 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,
+ })) as unknown as Parameters<typeof invoke.mockImplementationOnce>[0]);
+ try {
+ await makerChatStore.prefetchRemoteHistories(DEVICE_ID);
+ await flush(30);
+ expect(clearCache).not.toHaveBeenCalled();
+ if (kind === 'latest') {
+ expect(putMessages).not.toHaveBeenCalled();
+ invoke.mockImplementationOnce((async () => ({ version: 1,
+ items: projectHistoryView([anchor, { ...reply, content: 'small reply' }], false), hasMore: true, nextCursor: anchor.id,
+ })) as unknown as Parameters<typeof invoke.mockImplementationOnce>[0]);
+ await makerChatStore.prefetchRemoteHistories(DEVICE_ID);
+ await vi.waitFor(() => expect(putMessages).toHaveBeenCalled());
+ expect(invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view')).toHaveLength(2);
+ } else {
+ await vi.waitFor(() => expect(putMessages).toHaveBeenCalled());
+ const text = putMessages.mock.calls.at(-1)![6]!;
+ expect(fitsRemoteHistoryCache(text)).toBe(true);
+ const saved = decodeRemoteHistory(text)!;
+ expect(saved.items.at(-1)?.key).toBe(reply.clientId);
+ expect(saved.details.size).toBe(0);
+ expect(saved).toMatchObject(kind === 'prefix'
+ ? { hasMore: true, nextCursor: anchor.id } : { hasMore: false, nextCursor: null });
+ }
+ } finally {
+ getMessages.mockReset();
+ getMessages.mockImplementation(async (deviceId: string, sessionId: string) => ({
+ messages: cachedMessages.get(`${deviceId}::${sessionId}`) ?? [],
+ invalidation: cachedInvalidation, ownerToken: cachedOwnerToken, accountCounter: cachedAccountCounter,
+ }));
+ }
+ });
+
it('reads changed tasks ahead into the mirror after a refresh that may follow missed pushes', async () => {
const s = sid();
const old = dbMessage(s, 'old', 'cached reply', '2026-10-11T00:00:01.000Z');
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 4d331294e3..604b9b493a 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -10,6 +10,7 @@ import { readBotAuthorizationCard } from '../../shared/botAuthorization';
import { applyCindyMakeCardAttention } from './cindyMakeAttention';
import { confirmRemoteUsers, reserveRemoteUser } from './remoteUserHandoff';
import { readRemoteHistoryCache, remoteHistoryCacheWriter } from './remoteHistoryCache';
+import { encodeRemoteHistory, fitsRemoteHistoryCache } from '../../shared/remoteHistoryCache';
import { createPluginSecretPresentation, createPluginConnectionPresentation } from '../../shared/pluginOauth';
import { parsePluginConnectionInput, type InputHandoffSnapshot } from '@cindy/device-link';
/**
@@ -35,7 +36,7 @@ import { parsePluginConnectionInput, type InputHandoffSnapshot } from '@cindy/de
* - User-initiated stopSession (NOT called on session switch anymore)
*/
-import { HISTORY_WORK_PATCH_CHANNEL, HistoryViewController, isHistoryViewUnavailable, mapHistoryViewMessages, historyViewLeaves, historyWorkSummaries, historyPrefetchVersion, historySnapshotCovers, historySnapshotFromPage, selectHistoryPrefetchSessions, type HistoryViewPage, type HistoryDetailPage, type HistoryWorkPatch } from '@cindy/maker-shared/message-window';
+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 { SESSION_SYNC_CHANNEL } from '@cindy/device-link';
import { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from '@cindy/maker-shared/message-window';
@@ -11692,7 +11693,10 @@ async function prefetchRemoteHistories(deviceId: string): Promise<void> {
const items = mapHistoryViewMessages(page.items, (rows: Message[]) => mapServerMessages(rows).map((row) => ({
...row, id: row.id ?? row.clientId, createdAt: row.createdAt ?? '',
})));
- write(historySnapshotFromPage({ ...page, items }, previous));
+ const snapshot = historySnapshotForCache({ ...page, items }, previous,
+ (candidate) => fitsRemoteHistoryCache(encodeRemoteHistory(candidate)));
+ if (!snapshot) continue;
+ write(snapshot);
}
const version = historyPrefetchVersion(session);
if (version !== undefined) {
diff --git a/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts b/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts
index 7c08248462..8b07b6c2ab 100644
--- a/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts
+++ b/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { projectHistoryView, type HistoryViewPage, type HistoryViewSnapshot } from '@cindy/maker-shared/message-window';
+import { HistoryViewController, projectHistoryView, type HistoryViewPage, type HistoryViewSnapshot } from '@cindy/maker-shared/message-window';
import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
-import { clearHistoryDisk, historyDiskAuthority, readHistoryDisk, writeHistoryDisk } from '@/session/remoteHistoryDiskCache';
+import { clearHistoryDisk, fitsHistoryDisk, historyDiskAuthority, readHistoryDisk, writeHistoryDisk } from '@/session/remoteHistoryDiskCache';
import { prefetchRemoteHistories } from '@/session/remoteHistoryPrefetch';
import { clearRemoteHistoryViews, getRemoteHistoryView, mountRemoteHistoryView } from '@/session/remoteHistoryViews';
import { remoteSessionStore } from '@/session/remoteSessionStore';
@@ -43,6 +43,46 @@ afterEach(async () => {
});
describe('history read ahead after a list refresh', () => {
+ it.each(['prefix', 'collapsed', 'latest'] 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);
+ const previous = snapshotOf([old, anchor]);
+ if (kind === 'collapsed') {
+ previous.items = [{ type: 'work', key: 'work', summary: {
+ key: 'work', firstMessageId: old.id, lastMessageId: old.id, revision: 'r1',
+ startedAtMs: Date.parse(old.createdAt), endedAtMs: Date.parse(old.createdAt),
+ messageCount: 1, toolCount: 1, isStreaming: false,
+ } }, ...page([anchor]).items];
+ previous.details = new Map([['work', { messages: [old], revision: 'r1', lastMessageId: old.id,
+ complete: true, loading: false, error: null }]]);
+ }
+ 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 };
+ remoteSessionStore.setDeviceSessions(DEVICE, 'Mac', [session('s', reply.createdAt)]);
+ const reader = { readHistoryView: vi.fn(async () => latest) };
+ await prefetchRemoteHistories(DEVICE, reader, () => true);
+ const cached = await readHistoryDisk(authority);
+ expect(cached).not.toBeNull();
+ expect(fitsHistoryDisk(cached!)).toBe(true);
+ if (kind === 'latest') {
+ expect(cached?.items).toEqual(previous.items);
+ // Skipping an oversized latest page does not mark this activity version as cached.
+ reader.readHistoryView.mockResolvedValueOnce({ ...page([anchor, row('small', 9)]), hasMore: true, nextCursor: anchor.id });
+ await prefetchRemoteHistories(DEVICE, reader, () => true);
+ expect(reader.readHistoryView).toHaveBeenCalledTimes(2);
+ expect((await readHistoryDisk(authority))?.items.at(-1)?.key).toBe('small');
+ } 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');
+ }
+ });
+
it('fires on the first list and on a reconnect reseed, not on ordinary refreshes', () => {
const seen: string[] = [];
const off = remoteSessionStore.onSessionListRefreshAfterGap((deviceId) => seen.push(deviceId));
@@ -102,4 +142,27 @@ describe('history read ahead after a list refresh', () => {
release();
expect(reader.readHistoryView.mock.calls.map(([sessionId]) => sessionId)).toEqual(['other']);
});
+
+ it('restores previously read history offline after background read ahead saves a newer page', async () => {
+ setMobileAuthOwner('user-1');
+ const earlier: RemoteMessage = { ...row('u1', 1), role: 'user' };
+ const answer = row('a1', 2);
+ const latest: RemoteMessage = { ...row('u2', 3), role: 'user' };
+ const reply = row('a2', 9);
+ await writeHistoryDisk(historyDiskAuthority(DEVICE, 's'), snapshotOf([earlier, answer, latest]));
+ remoteSessionStore.setDeviceSessions(DEVICE, 'Mac', [session('s', reply.createdAt)]);
+ const reader = { readHistoryView: vi.fn(async () => ({
+ ...page([latest, reply]), hasMore: true, nextCursor: latest.id,
+ })) };
+ await prefetchRemoteHistories(DEVICE, reader, () => true);
+
+ const transport = { page: vi.fn(), details: vi.fn(), expanded: vi.fn() };
+ const offline = new HistoryViewController<RemoteMessage>(transport);
+ offline.setNetworkAvailable(false);
+ await offline.restoreCachedView(() => readHistoryDisk(historyDiskAuthority(DEVICE, 's')));
+ expect(offline.getSnapshot().items).toEqual(page([earlier, answer, latest, reply]).items);
+ expect(offline.getSnapshot()).toMatchObject({ hasMore: false, nextCursor: null });
+ expect(await offline.locate(earlier.clientId, earlier.createdAt)).toEqual(earlier);
+ expect(transport.page).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/mobile/src/session/remoteHistoryDiskCache.ts b/apps/mobile/src/session/remoteHistoryDiskCache.ts
index c183d7c6b1..dce083d030 100644
--- a/apps/mobile/src/session/remoteHistoryDiskCache.ts
+++ b/apps/mobile/src/session/remoteHistoryDiskCache.ts
@@ -65,9 +65,12 @@ export async function readHistoryDisk(authority: Authority): Promise<HistoryView
ready: true, loading: false, error: null };
} catch { return null; }
}
+export function fitsHistoryDisk(snapshot: HistoryViewSnapshot<RemoteMessage>): boolean {
+ return historyValueBytes([snapshot.items, snapshot.details, snapshot.expanded, snapshot.nextCursor], HISTORY_DISK_ITEM_BYTES - 1024) <= HISTORY_DISK_ITEM_BYTES - 1024;
+}
export async function writeHistoryDisk(authority: Authority, snapshot: HistoryViewSnapshot<RemoteMessage>): Promise<boolean> {
if (!authority.current() || !snapshot.ready || snapshot.loading || snapshot.error) return false;
- if (historyValueBytes([snapshot.items, snapshot.details, snapshot.expanded, snapshot.nextCursor], HISTORY_DISK_ITEM_BYTES - 1024) > HISTORY_DISK_ITEM_BYTES - 1024) return false;
+ if (!fitsHistoryDisk(snapshot)) return false;
try {
const messages = (rows: readonly RemoteMessage[]) => rows.map(row =>
row.agentMeta?.isStreaming === true || row.agentMeta?.streaming === true
diff --git a/apps/mobile/src/session/remoteHistoryPrefetch.ts b/apps/mobile/src/session/remoteHistoryPrefetch.ts
index 9147fade86..faead0ac00 100644
--- a/apps/mobile/src/session/remoteHistoryPrefetch.ts
+++ b/apps/mobile/src/session/remoteHistoryPrefetch.ts
@@ -1,13 +1,13 @@
import {
historyPrefetchVersion,
historySnapshotCovers,
- historySnapshotFromPage,
+ historySnapshotForCache,
isHistoryViewUnavailable,
selectHistoryPrefetchSessions,
} from '@cindy/maker-shared/message-window';
import { isSharedTaskPeer } from '@cindy/device-link';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
-import { historyDiskAuthority, readHistoryDisk, writeHistoryDisk } from './remoteHistoryDiskCache';
+import { fitsHistoryDisk, historyDiskAuthority, readHistoryDisk, writeHistoryDisk } from './remoteHistoryDiskCache';
import {
detachedRemoteHistorySnapshot,
dropDetachedRemoteHistoryView,
@@ -67,7 +67,8 @@ export async function prefetchRemoteHistories(
throw error;
}
if (!isCurrent() || isRemoteHistoryViewMounted(deviceId, session.id)) continue;
- if (!await writeHistoryDisk(authority, historySnapshotFromPage(page, previous))) continue;
+ const snapshot = historySnapshotForCache(page, previous, fitsHistoryDisk);
+ if (!snapshot || !await writeHistoryDisk(authority, snapshot)) continue;
dropDetachedRemoteHistoryView(deviceId, session.id);
}
const version = historyPrefetchVersion(session);
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 590bce4269..0e67809543 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -133,6 +133,12 @@ pnpm --filter mobile test:smoke
显示交接继续轮询或保留原始消息窗口;重新进入后沿用现有调度完成交接。旧电脑使用原始
消息窗口缓存;消息已经早于最近缓存窗口时正常交接,不在末尾留下旧的待发送气泡。
实现与回归见 `outboxHistoryCache.ts`、`outboxHistoryCache.test.ts`、`durableOutbox.test.ts`。
+- 首页预读最新历史页时,复用聊天页的连续边界判据,保留能够衔接的已读历史及其分页游标,
+ 不能直接把多页缓存缩成最新一页。已读工作详情只按内容版本是否有效保留,收起不等于
+ 删除缓存;离线重开仍可读取。无法证明连续、主机返回完整历史或明确回退时沿用原替换语义。
+ 后台预读写入前按平台现有容量检查:超限先省略收起详情,再退回最新页,必要时省略展开详情;
+ 退回最新页时同时恢复该页的分页游标。最新页本身仍超限则保留旧缓存,不标记预读成功。
+ 实现见共享 `historyViewPrefetch.ts`,回归见 `remoteHistoryPrefetch.test.ts`。
- 删除逐项尝试旧条目和文件,不依赖新增文件写入;任一后端失败不阻止另一后端清理,
单个文件失败也不阻止后续文件删除,全部尝试结束后统一报告失败。清理报错时可能仍有
无法删除的残留,不能视为清理成功。新登录或切换账号必须在持久化
diff --git a/packages/maker-shared/src/__tests__/historyViewPrefetch.test.ts b/packages/maker-shared/src/__tests__/historyViewPrefetch.test.ts
index 2c36b11776..7bd310cce3 100644
--- a/packages/maker-shared/src/__tests__/historyViewPrefetch.test.ts
+++ b/packages/maker-shared/src/__tests__/historyViewPrefetch.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { historyPrefetchVersion, historySnapshotCovers, historySnapshotFromPage, selectHistoryPrefetchSessions } from '../historyViewPrefetch.js';
+import { historyPrefetchVersion, historySnapshotCovers, historySnapshotForCache, historySnapshotFromPage, selectHistoryPrefetchSessions } from '../historyViewPrefetch.js';
import type { HistoryViewSnapshot } from '../historyViewController.js';
import type { HistoryMessageSource, HistoryViewItem, HistoryWorkSummary } from '../historyView.js';
@@ -12,6 +12,22 @@ const work = (key: string, revision: string, endedAtMs = 0): HistoryViewItem<His
const detail = (revision: string) => ({ messages: [], revision, lastMessageId: 'x', loading: false, complete: true, error: null });
describe('history read ahead', () => {
+ it('discards collapsed details before expanded ones and folds only if the latest page still cannot fit', () => {
+ const page = { version: 1 as const, items: [work('collapsed', 'r1'), work('expanded', 'r1')], hasMore: false, nextCursor: null };
+ const previous: HistoryViewSnapshot<HistoryMessageSource> = {
+ ...page, details: new Map([['collapsed', detail('r1')], ['expanded', detail('r1')]]),
+ expanded: new Set(['expanded']), loading: false, ready: true, error: null,
+ };
+ const expanded = historySnapshotForCache(page, previous, snapshot => snapshot.details.size <= 1)!;
+ expect([...expanded.details.keys()]).toEqual(['expanded']);
+ expect([...expanded.expanded]).toEqual(['expanded']);
+ const folded = historySnapshotForCache(page, previous, snapshot => snapshot.details.size === 0)!;
+ expect(folded.items).toEqual(page.items);
+ expect(folded.expanded.size).toBe(0);
+ expect(previous.details.size).toBe(2);
+ expect(previous.expanded.size).toBe(1);
+ });
+
it('reads only the newest changed tasks it has not read at their current version', () => {
const ms = (second: number) => Date.parse(`2026-10-11T00:00:0${second}Z`);
const sessions = [
@@ -54,4 +70,46 @@ describe('history read ahead', () => {
expect([...next.details.keys()]).toEqual(['same']);
expect(next).toMatchObject({ ready: true, loading: false, error: null, hasMore: true, nextCursor: 'older' });
});
+
+ it.each([true, false])('retains previously read pages and their pagination (hasMore=%s)', (hasMore) => {
+ const previous: HistoryViewSnapshot<HistoryMessageSource> = {
+ items: [work('earlier', 'r1'), work('latest', 'r1')],
+ details: new Map([['earlier', detail('r1')], ['latest', detail('r1')]]),
+ expanded: new Set(['earlier']), nextCursor: hasMore ? 'oldest' : null,
+ hasMore, loading: false, ready: true, error: null,
+ };
+ const next = historySnapshotFromPage({ version: 1,
+ items: [work('latest', 'r1'), work('new', 'r1')], hasMore: true, nextCursor: 'latest' }, previous);
+ expect(next.items.map(item => item.key)).toEqual(['earlier', 'latest', 'new']);
+ expect(next).toMatchObject({ hasMore, nextCursor: previous.nextCursor });
+ expect([...next.details.keys()]).toEqual(['earlier', 'latest']);
+ expect([...next.expanded]).toEqual(['earlier']);
+ });
+
+ it('keeps read details after collapse, but removes changed and absent ranges', () => {
+ const previous: HistoryViewSnapshot<HistoryMessageSource> = {
+ items: [work('same', 'r1'), work('changed', 'r1'), work('removed', 'r1')],
+ details: new Map(['same', 'changed', 'removed'].map(key => [key, detail('r1')])),
+ expanded: new Set(), nextCursor: null, hasMore: false, loading: false, ready: true, error: null,
+ };
+ const next = historySnapshotFromPage({ version: 1,
+ items: [work('same', 'r1'), work('changed', 'r2')], hasMore: false, nextCursor: null }, previous);
+ expect([...next.details.keys()]).toEqual(['same']);
+ expect(next.expanded.size).toBe(0);
+ });
+
+ it('does not join disconnected history or restore rows removed by an authoritative full page', () => {
+ const previous: HistoryViewSnapshot<HistoryMessageSource> = {
+ items: [work('earlier', 'r1'), work('latest', 'r1')], details: new Map(), expanded: new Set(),
+ nextCursor: 'oldest', hasMore: true, loading: false, ready: true, error: null,
+ };
+ for (const page of [
+ { version: 1 as const, items: [work('unrelated', 'r1'), work('latest', 'r1')], hasMore: true, nextCursor: 'gap' },
+ { version: 1 as const, items: [work('latest', 'r1')], hasMore: false, nextCursor: null },
+ ]) {
+ expect(historySnapshotFromPage(page, previous)).toMatchObject({
+ items: page.items, hasMore: page.hasMore, nextCursor: page.nextCursor,
+ });
+ }
+ });
});
diff --git a/packages/maker-shared/src/historyView.ts b/packages/maker-shared/src/historyView.ts
index 2793d5c594..d0d36f691c 100644
--- a/packages/maker-shared/src/historyView.ts
+++ b/packages/maker-shared/src/historyView.ts
@@ -118,6 +118,25 @@ export interface HistoryViewPage<TMessage extends HistoryMessageSource> {
hasMore: boolean;
}
+/** Keep already read pages only when the latest page proves a continuous source boundary. */
+export function retainHistoryViewPrefix<T extends HistoryMessageSource>(
+ page: HistoryViewPage<T>,
+ previous: { items: readonly HistoryViewItem<T>[]; hasMore: boolean; nextCursor: string | null } | null | undefined,
+): HistoryViewPage<T> {
+ if (!page.hasMore || !previous?.items.length) return page;
+ const firstSourceId = (item: HistoryViewItem<T> | undefined) => item?.type === 'work'
+ ? item.summary.firstMessageId : item?.messages[0]?.id;
+ const first = page.items[0];
+ const sourceId = firstSourceId(first);
+ const boundary = previous.items.findIndex(item => item.key === first?.key
+ || (sourceId !== undefined && firstSourceId(item) === sourceId));
+ // Completed groups can replace a running key while keeping its exact source start.
+ // A later overlap cannot prove continuity; a full page/rewind replaces the old view.
+ if (boundary <= 0) return page;
+ return { ...page, items: [...previous.items.slice(0, boundary), ...page.items],
+ hasMore: previous.hasMore, nextCursor: previous.nextCursor };
+}
+
/**
* Host → controller replacement of one running top-level work item. The Host sends it
* only when everything else on the latest page is unchanged since its last delivery to
diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.ts
index 50e3011cc2..4f0130c618 100644
--- a/packages/maker-shared/src/historyViewController.ts
+++ b/packages/maker-shared/src/historyViewController.ts
@@ -1,5 +1,5 @@
import {
- readHistoryWorkDetails, isHistoryViewUnavailable, historyWorkSummaries, historyViewLeaves, type HistoryDetailPage, type HistoryMessageSource,
+ readHistoryWorkDetails, retainHistoryViewPrefix, isHistoryViewUnavailable, historyWorkSummaries, historyViewLeaves, type HistoryDetailPage, type HistoryMessageSource,
type HistoryViewItem, type HistoryViewPage, type HistoryWorkPatch, type HistoryWorkSummary,
} from './historyView.js';
@@ -163,23 +163,12 @@ export class HistoryViewController<T extends HistoryMessageSource> {
const page = await this.transport.page(before);
if (page == null) throw new Error('[CHANNEL_NOT_ALLOWED] History view is unavailable');
if (!this.active || generation !== this.generation) return;
- let items = page.items;
+ const retained = older ? page : retainHistoryViewPrefix(page, this.state);
+ let items = retained.items;
if (older) {
const keys = new Set(items.map((item) => item.key));
items = [...items, ...this.state.items.filter((item) => !keys.has(item.key))];
- } else if (page.hasMore && this.state.items.length) {
- const firstSourceId = (item: HistoryViewItem<T> | undefined) => item?.type === 'work'
- ? item.summary.firstMessageId : item?.messages[0]?.id;
- const first = page.items[0];
- const sourceId = firstSourceId(first);
- const boundary = this.state.items.findIndex((item) => item.key === first?.key
- || (sourceId !== undefined && firstSourceId(item) === sourceId));
- // Completed outer groups can replace the running top-level key while
- // retaining its exact source start. Never infer a prefix from a later overlap.
- // Only retain a prefix with a proven overlap. Reset/rewind cannot leave an island.
- if (boundary > 0) items = [...this.state.items.slice(0, boundary), ...items];
}
- const retainedPrefix = !older && items.length > page.items.length;
// A background validation of the same page must not replace rendering
// identities. Applies to both Mobile and Desktop history consumers.
const previous = new Map(this.state.items.map((item) => [item.key, item]));
@@ -191,8 +180,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
&& items.every((item, index) => item === this.state.items[index]) ? this.state.items : items;
this.publish({ items: stableItems, ready: true, loading: false,
...(older ? {} : { stale: false }),
- hasMore: retainedPrefix ? this.state.hasMore : page.hasMore,
- nextCursor: retainedPrefix ? this.state.nextCursor : page.nextCursor });
+ hasMore: retained.hasMore, nextCursor: retained.nextCursor });
for (const summary of historyWorkSummaries(items)) {
if (this.state.expanded.has(summary.key)) void this.loadDetails(summary);
}
diff --git a/packages/maker-shared/src/historyViewPrefetch.ts b/packages/maker-shared/src/historyViewPrefetch.ts
index ed0d5c740d..259c7356cb 100644
--- a/packages/maker-shared/src/historyViewPrefetch.ts
+++ b/packages/maker-shared/src/historyViewPrefetch.ts
@@ -1,4 +1,4 @@
-import { historyWorkSummaries, type HistoryMessageSource, type HistoryViewPage } from './historyView.js';
+import { historyWorkSummaries, retainHistoryViewPrefix, type HistoryMessageSource, type HistoryViewPage } from './historyView.js';
import type { HistoryViewSnapshot, HistoryWorkDetailState } from './historyViewController.js';
import { historyViewEndMs } from './historyViewHandoff.js';
@@ -59,24 +59,48 @@ export function historySnapshotCovers<T extends HistoryMessageSource>(
}
/**
- * The latest page read ahead, in the shape a view restores from disk. Expanded work keeps its
- * cached body only while that range is unchanged; anything else opens folded.
+ * Read ahead uses the same continuous-prefix rule as an open view. Unchanged work keeps
+ * its cached body even after collapse; expansion is a display preference, not retention.
*/
export function historySnapshotFromPage<T extends HistoryMessageSource>(
page: HistoryViewPage<T>,
previous: HistoryViewSnapshot<T> | null | undefined,
): HistoryViewSnapshot<T> {
+ const retained = retainHistoryViewPrefix(page, previous);
const details = new Map<string, HistoryWorkDetailState<T>>();
const expanded = new Set<string>();
- for (const summary of historyWorkSummaries(page.items)) {
+ for (const summary of historyWorkSummaries(retained.items)) {
const detail = previous?.details.get(summary.key);
- if (!previous?.expanded.has(summary.key) || !detail?.complete || detail.loading || detail.error
+ if (!detail?.complete || detail.loading || detail.error
|| detail.revision !== summary.revision) continue;
details.set(summary.key, detail);
- expanded.add(summary.key);
+ if (previous?.expanded.has(summary.key)) expanded.add(summary.key);
}
return {
- items: page.items, details, expanded, nextCursor: page.nextCursor, hasMore: page.hasMore,
+ items: retained.items, details, expanded, nextCursor: retained.nextCursor, hasMore: retained.hasMore,
loading: false, ready: true, error: null,
};
}
+
+/** Fit read-ahead to the existing platform budget before invoking a cache writer. */
+export function historySnapshotForCache<T extends HistoryMessageSource>(
+ page: HistoryViewPage<T>,
+ previous: HistoryViewSnapshot<T> | null | undefined,
+ fits: (snapshot: HistoryViewSnapshot<T>) => boolean,
+): HistoryViewSnapshot<T> | null {
+ const merged = historySnapshotFromPage(page, previous);
+ if (fits(merged)) return merged;
+ const withoutCollapsed = (snapshot: HistoryViewSnapshot<T>): HistoryViewSnapshot<T> => ({
+ ...snapshot, details: new Map([...snapshot.details].filter(([key]) => snapshot.expanded.has(key))),
+ });
+ 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));
+ 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
+ // be recorded as successfully prefetched. The next normal refresh may try again.
+ return fits(folded) ? folded : null;
+}