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): 补齐缓存断档并修正长任务历史分页

Dashd86b76f47d4a
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewOutline.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewOutline.test.ts
index bb12570429..32ab761004 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewOutline.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewOutline.test.ts
@@ -25,6 +25,21 @@ function stamp(content: string) {
}
describe('SQLite history outline', () => {
+ // 2026-10-25: repeated SDK bookkeeping exhausted the 8 MiB scan before
+ // a long child-agent range could reach its header. This is an outline only;
+ // grouping metadata and unknown fields must survive, full hydration is unchanged.
+ it('excludes repeated SDK bookkeeping from outlined rows while retaining grouping metadata', () => {
+ const agentMeta = { parentUuid: 'agent', model: 'model', delivery: 'steer',
+ turnCompleted: true, turnUsageDetails: { totalTokens: 12 }, unknown: 'keep',
+ uuid: 'sdk-row', sdkSessionId: 'sdk-session', requestId: 'request',
+ replyToClientId: 'reply', usage: { details: 'x'.repeat(20000) } };
+ const source = { id: '1', clientId: '1', role: 'thinking', content: '', createdAt: '', agentMeta };
+ const projected = withHistoryArtifacts(source);
+ expect(projected.agentMeta).toEqual({ parentUuid: 'agent', model: 'model', delivery: 'steer',
+ turnCompleted: true, turnUsageDetails: { totalTokens: 12 }, unknown: 'keep' });
+ expect(source.agentMeta).toBe(agentMeta);
+ expect(source.agentMeta.usage.details).toHaveLength(20000);
+ });
it('stamps a body with a short fact that changes when it is rewritten in place', () => {
const summary = JSON.stringify('build summary');
const full = JSON.stringify(`build summary\n${'full log line\n'.repeat(50000)}`);
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
index cd29d9306c..a6f2febecf 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import { throwIpcError } from '../../../utils/ipcValidate';
import { createHistoryViewReader } from '../historyViewReader';
+import { withHistoryArtifacts } from '../historyViewOutline';
import { historyViewLeaves, projectHistoryView, type HistoryMessageSource, type HistoryViewItem } from '@cindy/maker-shared/message-window';
function row(n: number, role = 'thinking'): HistoryMessageSource {
return { id: String(n), clientId: `c${n}`, rowid: n, role, content: 'body '.repeat(200), createdAt: new Date(1700000000000 + n).toISOString() };
@@ -20,6 +21,49 @@ function reader(source: HistoryMessageSource[]) {
return { list, api: createHistoryViewReader({ list, anchor, running: () => false }) };
}
describe('host history view', () => {
+ it('reaches a long run through compact outlines and keeps SDK metadata in hydrated details', async () => {
+ const source = [row(0, 'user'), ...Array.from({ length: 1100 }, (_, i) => ({
+ ...row(i + 1), content: 'thinking', agentMeta: { uuid: `sdk-${i}`, usage: { details: 'x'.repeat(9000) } },
+ })), { ...row(1101, 'assistant'), agentMeta: { turnCompleted: true } }];
+ const base = reader(source);
+ const outlined = reader(source.map(withHistoryArtifacts));
+ const api = createHistoryViewReader({ list: base.list, outline: outlined.list,
+ hydrate: async (_sid, ids) => source.filter(r => ids.includes(r.id)),
+ anchor: async (_sid, id, outline) => {
+ const found = source.find(r => r.id === id)!;
+ return outline ? withHistoryArtifacts(found) : found;
+ }, running: () => false });
+ const page = await api.page('s', undefined, true);
+ expect(page.hasMore).toBe(false);
+ expect(page.items.map(item => item.type)).toEqual(['messages', 'work', 'messages']);
+ const work = page.items[1];
+ if (work.type !== 'work') throw new Error('missing work');
+ const details = await api.details('s', work.summary);
+ expect(details.messages[0].agentMeta).toEqual(source[1].agentMeta);
+ expect(details.hasMore).toBe(true);
+ });
+ // 2026-10-25: ordinary simulator plugin calls cost one page item each although
+ // Mobile folds them. Exercise real paging and details, not just the classifier.
+ it('pages settled plugin work by visible groups and retains every call in details', async () => {
+ const source: HistoryMessageSource[] = [row(0, 'user')];
+ for (let n = 1; n <= 80; n++) {
+ source.push({ ...row(n * 2 - 1, 'tool_use'), content: {
+ toolName: 'mcp:cindy:ghost_call', toolUseId: `t${n}`, input: { ghost_id: 'simulator', tool: 'tap' },
+ } }, { ...row(n * 2, 'tool_result'), toolUseId: `t${n}`, content: 'ok' });
+ }
+ source.push({ ...row(161, 'assistant'), content: 'Done', agentMeta: { turnCompleted: true } });
+ const base = reader(source);
+ const api = createHistoryViewReader({ list: base.list, outline: base.list,
+ hydrate: async (_sid, ids) => source.filter(r => ids.includes(r.id)),
+ anchor: async (_sid, id) => source.find(r => r.id === id)!, running: () => false });
+ const page = await api.page('s', undefined, true);
+ expect(page.items.map(item => item.type)).toEqual(['messages', 'work', 'messages']);
+ expect(page.hasMore).toBe(false);
+ const work = page.items[1];
+ if (work.type !== 'work') throw new Error('missing work');
+ expect((await api.details('s', work.summary)).messages.map(r => r.id))
+ .toEqual(source.slice(1, -1).map(r => r.id));
+ });
it('paginates visible items across a long hidden run without splitting or sending its bodies', async () => {
const source = [row(0, 'user'), ...Array.from({ length: 600 }, (_, i) => row(i + 1)), row(601, 'assistant')];
const { api, list } = reader(source);
diff --git a/apps/desktop/src/main/localDb/ipc/historyViewOutline.ts b/apps/desktop/src/main/localDb/ipc/historyViewOutline.ts
index c5a5bbf84e..6693b148a7 100644
--- a/apps/desktop/src/main/localDb/ipc/historyViewOutline.ts
+++ b/apps/desktop/src/main/localDb/ipc/historyViewOutline.ts
@@ -119,6 +119,14 @@ export function historyOutlineContentStamp(): SQL<string> {
/** File content/patches never cross the outline query; commands yield only paths on the wire. */
export function withHistoryArtifacts<T extends HistoryMessageSource>(row: T): T & Pick<HistoryMessageSource, 'historyArtifacts'> {
+ // SDK routing/usage bookkeeping is repeated on thousands of hidden child rows.
+ // It has no grouping meaning, but used to exhaust the scan's byte budget before
+ // reaching their Agent header. Full bodies and metadata still come from hydrate.
+ if (row.agentMeta) {
+ const { uuid: _uuid, sdkSessionId: _sdkSessionId, requestId: _requestId,
+ replyToClientId: _replyToClientId, usage: _usage, ...agentMeta } = row.agentMeta as Record<string, unknown>;
+ row = { ...row, agentMeta };
+ }
if (row.role !== 'tool_use') return row;
const tool = parseMessageToolUse(row);
const descriptor = describeToolUse(tool.toolName, tool.input);
diff --git a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
index 08c847c255..e2366d6ef0 100644
--- a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
@@ -439,6 +439,38 @@ describe('冷缓存 hydrate', () => {
}
});
+ it('fills the missed-page gap before writing a refreshed mirror', async () => {
+ const s = sid();
+ const rows = Array.from({ length: 8 }, (_, i) => ({
+ ...dbMessage(s, String(i + 1), String(i + 1), `2026-10-11T00:00:0${i + 1}.000Z`), role: 'user' as const,
+ }));
+ const historyView = encodeRemoteHistory({ items: projectHistoryView(rows.slice(0, 3), false),
+ details: new Map(), expanded: new Set(), ready: true, loading: false, error: null, nextCursor: null, hasMore: false });
+ getMessages.mockResolvedValueOnce({ messages: [], invalidation: 0, ownerToken: cachedOwnerToken, accountCounter: 0, historyView } as CachedRead);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [
+ { id: s, status: 'active', updatedAt: rows[7].createdAt },
+ ] as never);
+ let finish!: () => void;
+ invoke.mockImplementationOnce((async () => ({ version: 1,
+ items: projectHistoryView(rows.slice(6), false), hasMore: true, nextCursor: '7',
+ })) as unknown as Parameters<typeof invoke.mockImplementationOnce>[0]);
+ invoke.mockImplementationOnce((async (_device: string, channel: string, args: unknown[]) => {
+ expect(channel).toBe('local-db:messages:view');
+ expect(args).toEqual([s, { lazyDetails: true, before: '7' }]);
+ await new Promise<void>(resolve => { finish = resolve; });
+ return { version: 1, items: projectHistoryView(rows.slice(2, 6), false), hasMore: true, nextCursor: '3' };
+ }) as unknown as Parameters<typeof invoke.mockImplementationOnce>[0]);
+ const pending = makerChatStore.prefetchRemoteHistories(DEVICE_ID);
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'), { interval: 1 });
+ expect(putMessages).not.toHaveBeenCalled();
+ finish();
+ await pending;
+ await vi.waitFor(() => expect(putMessages).toHaveBeenCalled());
+ const saved = decodeRemoteHistory(putMessages.mock.calls.at(-1)![6]!)!;
+ expect(saved.items.map(item => item.key)).toEqual(rows.map(row => row.clientId));
+ expect(saved.hasMore).toBe(false);
+ });
+
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 7a3fcbc975..0305abb374 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -44,7 +44,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, isHistoryCacheReceipt, historyCacheReceiptFollows, mergeHistoryPrefetchRequest, type HistoryCacheReceipt, type HistoryPrefetchRequest } from '@cindy/maker-shared/message-window';
+import { nextHistoryCacheReceipt, isHistoryCacheReceipt, historyCacheReceiptFollows, mergeHistoryPrefetchRequest, readContinuousHistoryPage, 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';
@@ -12001,20 +12001,25 @@ async function prefetchRemoteHistories(deviceId: string, sessionIds?: ReadonlySe
// Capture write authority before the read, like an open view does.
const write = remoteHistoryCacheWriter(deviceId, session.id);
const readReceipt = nextHistoryCacheReceipt();
- let page: HistoryViewPage<Message>;
+ const readPage = async (before?: string): Promise<HistoryViewPage<HistoryChatMessage> | null> => {
+ const page = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:messages:view',
+ [session.id, { lazyDetails: true, ...(before ? { before } : {}) }]) as HistoryViewPage<Message> | null;
+ return page && { ...page, items: mapHistoryViewMessages(page.items, (rows: Message[]) => mapServerMessages(rows).map((row) => ({
+ ...row, id: row.id ?? row.clientId, createdAt: row.createdAt ?? '',
+ }))) };
+ };
+ let page: HistoryViewPage<HistoryChatMessage> | null;
try {
- page = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:messages:view',
- [session.id, { lazyDetails: true }]) as HistoryViewPage<Message>;
+ page = await readPage();
+ if (page) page = await readContinuousHistoryPage(page, previous, readPage,
+ () => isCurrent(session.id) && token === sessionCacheInvalidationToken(session.id) && !getRemoteHistoryView(session.id));
} catch (error) {
// A Host without the history view serves tasks the old way; nothing to read ahead.
if (isHistoryViewUnavailable(error)) return;
throw error;
}
if (page == null || !isCurrent(session.id) || getRemoteHistoryView(session.id)) continue;
- const items = mapHistoryViewMessages(page.items, (rows: Message[]) => mapServerMessages(rows).map((row) => ({
- ...row, id: row.id ?? row.clientId, createdAt: row.createdAt ?? '',
- })));
- const snapshot = historySnapshotForCache({ ...page, items }, previous,
+ const snapshot = historySnapshotForCache(page, previous,
(candidate) => fitsRemoteHistoryCache(encodeRemoteHistory(candidate)));
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 3c51492774..92aaa99ab1 100644
--- a/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts
+++ b/apps/mobile/src/__tests__/remoteHistoryPrefetch.test.ts
@@ -43,6 +43,30 @@ afterEach(async () => {
});
describe('history read ahead after a list refresh', () => {
+ it.each([false, true])('fills a gap before replacing the offline reading window (failure=%s)', async (failure) => {
+ setMobileAuthOwner('user-1');
+ const rows: RemoteMessage[] = Array.from({ length: 8 }, (_, index) => ({ ...row(String(index + 1), index + 1), role: 'user' }));
+ const authority = historyDiskAuthority(DEVICE, 's');
+ const previous = snapshotOf(rows.slice(0, 3));
+ await writeHistoryDisk(authority, previous);
+ remoteSessionStore.setDeviceSessions(DEVICE, 'Mac', [session('s', rows[7].createdAt)]);
+ let finish!: () => void;
+ const reader = { readHistoryView: vi.fn(async (_id: string, before?: string) => {
+ if (!before) return { ...page(rows.slice(6)), hasMore: true, nextCursor: '7' };
+ await new Promise<void>(resolve => { finish = resolve; });
+ if (failure) throw new Error('temporary connection failure');
+ return { ...page(rows.slice(2, 6)), hasMore: true, nextCursor: '3' };
+ }) };
+ const pending = prefetchRemoteHistories(DEVICE, reader, () => true);
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'), { interval: 1 });
+ expect((await readHistoryDisk(authority))?.items).toEqual(previous.items);
+ finish();
+ await pending;
+ expect(reader.readHistoryView.mock.calls).toEqual([['s'], ['s', '7']]);
+ const cached = await readHistoryDisk(authority);
+ expect(cached?.items).toEqual(failure ? previous.items : page(rows).items);
+ expect(cached?.hasMore).toBe(false);
+ });
// A bounded reconnect read is not a superset of completion targets. Hold one
// real read pending, then enqueue both request kinds in either order.
it.each([false, true])('retains completion targets alongside a queued reconnect (recent first=%s)', async (recentFirst) => {
diff --git a/apps/mobile/src/session/remoteHistoryPrefetch.ts b/apps/mobile/src/session/remoteHistoryPrefetch.ts
index 5307ecbe02..791c110529 100644
--- a/apps/mobile/src/session/remoteHistoryPrefetch.ts
+++ b/apps/mobile/src/session/remoteHistoryPrefetch.ts
@@ -6,6 +6,7 @@ import {
selectHistoryPrefetchSessions,
mergeHistoryPrefetchRequest, type HistoryPrefetchRequest,
nextHistoryCacheReceipt,
+ readContinuousHistoryPage,
} from '@cindy/maker-shared/message-window';
import { isSharedTaskPeer } from '@cindy/device-link';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
@@ -73,12 +74,15 @@ export async function prefetchRemoteHistories(
let page;
try {
page = 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));
} catch (error) {
// A Host without the history view serves tasks the old way; nothing to read ahead.
if (isHistoryViewUnavailable(error)) return;
throw error;
}
- if (!isCurrent() || isRemoteHistoryViewMounted(deviceId, session.id)) continue;
+ if (!page || !isCurrent() || isRemoteHistoryViewMounted(deviceId, session.id)) continue;
const snapshot = historySnapshotForCache(page, previous, fitsHistoryDisk);
if (!snapshot || !await writeHistoryDisk(authority, { ...snapshot, readReceipt })) continue;
dropDetachedRemoteHistoryView(deviceId, session.id);
diff --git a/packages/maker-shared/src/__tests__/historyView.test.ts b/packages/maker-shared/src/__tests__/historyView.test.ts
index bc360b52d1..f7b1c5628a 100644
--- a/packages/maker-shared/src/__tests__/historyView.test.ts
+++ b/packages/maker-shared/src/__tests__/historyView.test.ts
@@ -9,6 +9,16 @@ function row(id: number, role: string, content: unknown): HistoryMessageSource {
}
describe('history reading projection', () => {
+ it.each(['pending', 'card', 'media', 'app'] as const)('keeps a plugin %s available outside deferred work', (kind) => {
+ const call = row(1, 'tool_use', { toolName: 'mcp__cindy__ghost_call', toolUseId: 'plugin', input: {} });
+ if (kind === 'app') call.agentMeta = { mcpApp: true };
+ const rows = [row(0, 'user', 'Work'), call];
+ if (kind !== 'pending') rows.push({ ...row(2, 'tool_result', kind === 'card'
+ ? JSON.stringify({ xdt_card_id: 'card' }) : kind === 'media' ? 'cindy-media://blobs/image.png' : 'ready'), toolUseId: 'plugin' });
+ const projected = projectHistoryView(rows, true, true);
+ expect(projected.flatMap(item => item.type === 'messages' ? item.messages : []).map(message => message.id))
+ .toContain('1');
+ });
it.each([false, true])('archives interrupted progress in recoverable history ranges (streaming=%s)', (streaming) => {
const rows = [row(0, 'user', 'Work'), row(1, 'assistant', 'Checking the build'),
row(2, 'thinking', 'detail'), row(3, 'error', { message: 'Usage limit reached' }),
@@ -245,17 +255,20 @@ describe('shared history view lifecycle', () => {
const completed = projectHistoryView([...rows, row(5, 'assistant', 'Done')], false);
expect(completed[0].key).not.toBe(running[0].key);
const replacement = overlap ? completed : projectHistoryView([row(9, 'user', 'Replaced')], false);
- const read = vi.fn(async () => ({ version: 1 as const, items: running, hasMore: true, nextCursor: 'latest' }));
+ const read = vi.fn(async (): Promise<HistoryViewPage<HistoryMessageSource>> => ({ version: 1 as const, items: running, hasMore: true, nextCursor: 'latest' }));
const view = new HistoryViewController({ page: read,
details: async () => ({ version: 1 as const, messages: [], hasMore: false, nextCursor: null }), expanded: async () => undefined });
await view.refresh();
read.mockResolvedValueOnce({ version: 1, items: prefix, hasMore: true, nextCursor: 'older' });
await view.refresh(true);
read.mockResolvedValueOnce({ version: 1, items: replacement, hasMore: true, nextCursor: 'new' });
+ // With no overlap, walk the authoritative older page before replacing the
+ // cache. A rewound/cleared source ends here and must not revive the old rows.
+ if (!overlap) read.mockResolvedValueOnce({ version: 1, items: [], hasMore: false, nextCursor: null });
await view.refresh();
expect(view.getSnapshot().items).toEqual(overlap ? [...prefix, ...completed] : replacement);
- expect(view.getSnapshot().nextCursor).toBe(overlap ? 'older' : 'new');
- expect(view.getSnapshot().hasMore).toBe(true);
+ expect(view.getSnapshot().nextCursor).toBe(overlap ? 'older' : null);
+ expect(view.getSnapshot().hasMore).toBe(overlap);
});
it.each(['success', 'failure', 'blur', 'unavailable'])('reads again after an ACK over an in-flight %s without changing expansion', async (outcome) => {
diff --git a/packages/maker-shared/src/__tests__/historyViewLoading.test.ts b/packages/maker-shared/src/__tests__/historyViewLoading.test.ts
index edcfca0e44..e66369fd4e 100644
--- a/packages/maker-shared/src/__tests__/historyViewLoading.test.ts
+++ b/packages/maker-shared/src/__tests__/historyViewLoading.test.ts
@@ -13,6 +13,37 @@ 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) => {
+ 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(),
+ }] })), hasMore, nextCursor: hasMore ? String(ids[0]) : null,
+ });
+ let finish!: (page: HistoryViewPage<HistoryMessageSource>) => void;
+ let fail!: (error: Error) => void;
+ const read = vi.fn().mockResolvedValueOnce(makePage([1, 2, 3], false))
+ .mockResolvedValueOnce(makePage([7, 8]))
+ .mockImplementationOnce(() => new Promise((resolve, reject) => { finish = resolve; fail = reject; }));
+ const view = new HistoryViewController<HistoryMessageSource>({ page: read, details: vi.fn(), expanded: vi.fn(async () => undefined) });
+ await view.refresh();
+ const visible: string[][] = [];
+ view.subscribe(() => visible.push(view.getSnapshot().items.map(item => item.key)));
+ const pending = view.refresh();
+ await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(3), { interval: 1 });
+ expect(view.getSnapshot().items.map(item => item.key)).toEqual(['1', '2', '3']);
+ if (outcome === 'blur') view.setActive(false);
+ 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'
+ ? ['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);
+ if (outcome === 'failure' || outcome === 'repeated-cursor') expect(view.getSnapshot().error).toBeTruthy();
+ });
// Desktop's push-driven repair asks these two questions to avoid a second page read
// per notice; an older-page read must not count as covering a latest-page notice.
it('reports when the latest page was last read and whether a latest read is in flight', async () => {
diff --git a/packages/maker-shared/src/historyView.ts b/packages/maker-shared/src/historyView.ts
index 13cd399a6b..f5c3e0bc69 100644
--- a/packages/maker-shared/src/historyView.ts
+++ b/packages/maker-shared/src/historyView.ts
@@ -138,18 +138,24 @@ export interface HistoryViewPage<TMessage extends HistoryMessageSource> {
hasMore: boolean;
}
+function historyPrefixBoundary<T extends HistoryMessageSource>(
+ page: HistoryViewPage<T>, previous: readonly HistoryViewItem<T>[],
+): number {
+ 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);
+ return previous.findIndex(item => item.key === first?.key
+ || (sourceId !== undefined && firstSourceId(item) === sourceId));
+}
+
/** 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));
+ const boundary = historyPrefixBoundary(page, previous.items);
// 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;
@@ -157,6 +163,32 @@ export function retainHistoryViewPrefix<T extends HistoryMessageSource>(
hasMore: previous.hasMore, nextCursor: previous.nextCursor };
}
+/** Fill a missed-page gap before replacing a cached reading window. Never join on time alone. */
+export async function readContinuousHistoryPage<T extends HistoryMessageSource>(
+ latest: HistoryViewPage<T>,
+ previous: { items: readonly HistoryViewItem<T>[]; hasMore: boolean; nextCursor: string | null } | null | undefined,
+ readOlder: (before: string) => Promise<HistoryViewPage<T> | null | undefined>,
+ isCurrent: () => boolean,
+): Promise<HistoryViewPage<T> | null> {
+ let page = latest;
+ const startedAt = (item: HistoryViewItem<T> | undefined) => item?.type === 'work'
+ ? item.summary.startedAtMs : Date.parse(item?.messages[0]?.createdAt ?? '');
+ 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])) {
+ const cursor = page.nextCursor;
+ if (!cursor || seen.has(cursor)) throw new Error('History page cursor did not advance');
+ seen.add(cursor);
+ const older = await readOlder(cursor);
+ if (!isCurrent()) return null;
+ if (!older) throw new Error('History page is unavailable while filling a gap');
+ const keys = new Set(page.items.map(item => item.key));
+ page = { ...older, items: [...older.items.filter(item => !keys.has(item.key)), ...page.items] };
+ }
+ return isCurrent() ? page : null;
+}
+
/**
* 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 4e5b6186cd..560f95967a 100644
--- a/packages/maker-shared/src/historyViewController.ts
+++ b/packages/maker-shared/src/historyViewController.ts
@@ -1,6 +1,6 @@
import {
nextHistoryCacheReceipt, type HistoryCacheReceipt,
- readHistoryWorkDetails, retainHistoryViewPrefix, isHistoryViewUnavailable, historyWorkSummaries, historyViewLeaves, type HistoryDetailPage, type HistoryMessageSource,
+ readHistoryWorkDetails, readContinuousHistoryPage, retainHistoryViewPrefix, isHistoryViewUnavailable, historyWorkSummaries, historyViewLeaves, type HistoryDetailPage, type HistoryMessageSource,
type HistoryViewItem, type HistoryViewPage, type HistoryWorkPatch, type HistoryWorkSummary,
} from './historyView.js';
@@ -210,7 +210,10 @@ 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;
- const retained = older ? page : retainHistoryViewPrefix(page, this.state);
+ const continuous = older ? page : await readContinuousHistoryPage(page, this.state,
+ (cursor) => this.transport.page(cursor), () => this.active && generation === this.generation);
+ if (!continuous) return;
+ const retained = older ? continuous : retainHistoryViewPrefix(continuous, this.state);
let items = retained.items;
if (older) {
const keys = new Set(items.map((item) => item.key));
diff --git a/packages/maker-shared/src/historyViewProjection.ts b/packages/maker-shared/src/historyViewProjection.ts
index 9708f0ebc4..a1905e6938 100644
--- a/packages/maker-shared/src/historyViewProjection.ts
+++ b/packages/maker-shared/src/historyViewProjection.ts
@@ -140,16 +140,20 @@ function projectHistorySourceView<T extends HistoryMessageSource>(
): HistoryViewItem<T>[] {
const names = new Map<string, string>();
const visibleResults = new Set<string>();
+ const settledTools = new Set<string>();
const nestedCalls = new Set<string>();
for (const row of rows) {
if (row.role === 'tool_use') {
const tool = parseMessageToolUse(row);
if (tool.toolUseId) names.set(tool.toolUseId, tool.toolName);
if (!preserveMixedSegments && tool.toolUseId && hasFileDelivery(row)) visibleResults.add(tool.toolUseId);
+ if (tool.toolUseId && (row.agentMeta as { mcpApp?: unknown } | null)?.mcpApp) visibleResults.add(tool.toolUseId);
if (tool.toolUseId && (row.agentMeta as { parentUuid?: unknown } | null)?.parentUuid) nestedCalls.add(tool.toolUseId);
}
- if (row.role === 'tool_result' && row.toolUseId && hasVisibleHistoryResult(row.content)) {
- visibleResults.add(row.toolUseId);
+ if (row.role === 'tool_result' && row.toolUseId) {
+ settledTools.add(row.toolUseId);
+ if (hasVisibleHistoryResult(row.content)
+ || (row.agentMeta as { mcpApp?: unknown } | null)?.mcpApp) visibleResults.add(row.toolUseId);
}
}
const source: SourceItem<T>[] = rows.map((row) => {
@@ -165,7 +169,12 @@ function projectHistorySourceView<T extends HistoryMessageSource>(
: !!thought?.text || !!thought?.durationMs || thought?.isRedacted === true);
const activity = !nested && (visibleThinking || (
(row.role === 'tool_use' || row.role === 'tool_result')
- && (isHistoryDetailTool(toolName ?? '') || (!preserveMixedSegments && ['Edit', 'Write', 'MultiEdit', 'edit', 'write'].includes(toolName ?? '')))
+ && (isHistoryDetailTool(toolName ?? '') || (!preserveMixedSegments && (
+ ['Edit', 'Write', 'MultiEdit', 'edit', 'write'].includes(toolName ?? '')
+ // Pending plugin calls may own an interaction. Once settled, ordinary
+ // results fold like other tools; media/cards remain source rows below.
+ || (!!toolId && settledTools.has(toolId) && /(?:^|:|__)ghost_call$/.test(toolName ?? ''))
+ )))
&& !(toolId && visibleResults.has(toolId))
));
const plainAssistant = !nested && row.role === 'assistant' && typeof row.content === 'string'