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): 被打断的长轮次按两端渲染口径折叠,手机上翻不再只拉长「已工作」 (#5798)

Dashc5af1dfe42d6
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 1dfb65899e..5bbec0edfa 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/historyViewReader.test.ts
@@ -56,6 +56,26 @@ describe('host history view', () => {
expect(seen.sort((a, b) => Number(a) - Number(b))).toEqual(source.map((message) => message.id));
});
+ it('keeps an interrupted turn folded when its cost-stamped answer starts the newer page', async () => {
+ let n = 0;
+ const say = (content: string, agentMeta?: object) => ({ ...row(n++, 'assistant'), content, ...(agentMeta ? { agentMeta } : {}) });
+ const source: HistoryMessageSource[] = [row(n++, 'user')];
+ for (let i = 0; i < 30; i++) source.push(say(`Still building ${i}`), row(n++));
+ source.push({ ...row(n++, 'user'), agentMeta: { delivery: 'steer' } }, row(n++));
+ const answer = say('Checking CI', { turnCompleted: false, turnCost: { amount: 5, currency: 'USD' } });
+ source.push(answer, row(n++));
+ for (let i = 0; i < 9; i++) source.push(row(n++, 'user'), say('Done', { turnCompleted: true }));
+ const { api } = reader(source);
+ const latest = await api.page('s');
+ expect(latest.items).toHaveLength(20);
+ expect(latest.nextCursor).toBe(answer.id);
+ const older = await api.page('s', latest.nextCursor!);
+ // One fold for the whole run before the steer, instead of a page of progress lines.
+ expect(older.items.map((item) => item.type === 'work' ? 'work' : item.messages[0].role))
+ .toEqual(['user', 'work', 'user', 'work']);
+ expect(older.hasMore).toBe(false);
+ });
+
it('recovers every in-flight block and automatically continues across their byte boundary', async () => {
const stored = [row(0, 'user')];
const live = [1, 2].map((n) => ({ ...row(n), id: `history-live:c${n}`, content: 'x'.repeat(200000) }));
diff --git a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
index cdb30bdf6f..3e5ff3df53 100644
--- a/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
+++ b/apps/desktop/src/main/localDb/ipc/historyViewReader.ts
@@ -4,7 +4,7 @@ import { isDeliveryProseText } from '@cindy/maker-shared/message-render';
import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';
import {
HISTORY_VIEW_PAGE_BYTES, HISTORY_VIEW_PAGE_ITEMS, HISTORY_DETAIL_PAGE_BYTES,
- HISTORY_WORK_LINE_LIMIT, projectHistoryView, projectHistoryWorkLines, historySubagentScopes, mapHistoryViewMessages, historyWorkSummaries,
+ HISTORY_WORK_LINE_LIMIT, completesHistoryTurn, projectHistoryView, projectHistoryWorkLines, historySubagentScopes, mapHistoryViewMessages, historyWorkSummaries,
type HistoryMessageSource, type HistoryWorkLine, type HistoryViewItem, type HistoryViewPage, type HistoryDetailPage, type HistoryWorkReference,
} from '@cindy/maker-shared/message-window';
@@ -125,8 +125,9 @@ export function createHistoryViewReader<T extends HistoryMessageSource>(deps: Hi
// A page may start at a sealed answer. Keep that answer as right-hand
// context when reading the preceding page, or an older progress seal
// would become the "last answer" and escape its completed work group.
- const context = beforeAnchor?.role === 'assistant'
- && (beforeAnchor.agentMeta as { turnCompleted?: unknown } | null)?.turnCompleted === true
+ // Uses the projection's seal, so a cost-stamped interrupted answer still
+ // closes its turn when it is the first item of the newer page.
+ const context = beforeAnchor?.role === 'assistant' && completesHistoryTurn(beforeAnchor)
? beforeAnchor : undefined;
const projected = projectHistoryView(
[...raw.slice(boundary), ...live, ...(context ? [context] : [])],
diff --git a/packages/maker-shared/src/__tests__/historyView.test.ts b/packages/maker-shared/src/__tests__/historyView.test.ts
index ab49b03589..eb88c87513 100644
--- a/packages/maker-shared/src/__tests__/historyView.test.ts
+++ b/packages/maker-shared/src/__tests__/historyView.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import { projectHistoryView } from '../historyViewProjection.js';
import { CONTINUE_AFTER_ERROR_PROMPT } from '../syntheticTrigger.js';
-import { historyWorkSummaries, isHistoryViewUnavailable, readHistoryWorkDetails, type HistoryMessageSource } from '../historyView.js';
+import { historyViewLeaves, historyWorkSummaries, isHistoryViewUnavailable, readHistoryWorkDetails, type HistoryMessageSource } from '../historyView.js';
function row(id: number, role: string, content: unknown): HistoryMessageSource {
return { id: String(id), clientId: `c${id}`, role, content,
@@ -87,6 +87,35 @@ describe('history reading projection', () => {
expect(projectHistoryView(rows, true).filter((item) => item.type === 'work')
.map((item) => item.summary.isStreaming)).toEqual([false, true]);
});
+
+ // Pages count projected items; clients fold progress before a cost-stamped
+ // interrupted answer, so each progress line must not cost a page item.
+ it.each([
+ { turnCompleted: false, turnCost: { amount: 539.3, currency: 'USD' } },
+ { userTurnCostUsd: 0.4 },
+ { turnUsageDetails: { totalTokens: 12 } },
+ ])('folds progress before an answer that carries end-of-turn cost or usage (%j)', (meta) => {
+ const rows = [row(0, 'user', 'Work'), row(1, 'assistant', 'Still building'), row(2, 'thinking', 'wait'),
+ row(3, 'assistant', 'Still building'), row(4, 'thinking', 'wait'),
+ { ...row(5, 'user', 'Is it fine?'), agentMeta: { delivery: 'steer' } },
+ { ...row(6, 'assistant', 'Checking CI'), agentMeta: { assistantPhase: 'commentary', ...meta } },
+ row(7, 'thinking', 'check'), row(8, 'user', 'Next')];
+ const projected = projectHistoryView(rows, false, true);
+ expect(projected.map((item) => item.type === 'work' ? `work:${item.summary.firstMessageId}` : item.messages[0].id))
+ .toEqual(['0', 'work:1', '5', '6', 'work:7', '8']);
+ expect(projected[1]).toMatchObject({ summary: { lastMessageId: '4' } });
+ });
+
+ // Mobile does not seal on usage without tokens; it regroups the delivered rows itself.
+ it('still delivers every progress line when only a token-less usage record seals the turn', () => {
+ const rows = [row(0, 'user', 'Work'), row(1, 'assistant', 'Still building'), row(2, 'thinking', 'wait'),
+ { ...row(3, 'assistant', 'Checking'), agentMeta: { turnUsageDetails: { totalTokens: 0, turnDurationMs: 900 } } },
+ row(4, 'user', 'Next')];
+ const projected = projectHistoryView(rows, false, true);
+ expect(projected[1]).toMatchObject({ type: 'work', children: [{ type: 'messages', messages: [{ id: '1' }] }, { type: 'work' }] });
+ expect(historyViewLeaves(projected).flatMap((item) => item.type === 'messages' ? item.messages.map((message) => message.id) : []))
+ .toEqual(['0', '1', '3', '4']);
+ });
});
describe('automatic process detail reading', () => {
diff --git a/packages/maker-shared/src/historyViewProjection.ts b/packages/maker-shared/src/historyViewProjection.ts
index f9076db87d..9708f0ebc4 100644
--- a/packages/maker-shared/src/historyViewProjection.ts
+++ b/packages/maker-shared/src/historyViewProjection.ts
@@ -45,6 +45,27 @@ export function hasVisibleHistoryResult(content: unknown): boolean {
} catch { return false; }
}
+/**
+ * The renderers' turn-end signal (desktop `isCompletedAssistantMessage`, mobile
+ * `remoteMessageCompletesTurn`): cost and usage are stamped only when a turn ends,
+ * including an interrupted one whose `turnCompleted` is false. Pages count the
+ * items this projection folds, so a narrower seal here leaves every progress line
+ * of a long interrupted turn as its own page item while clients fold them all.
+ * The two renderers differ on usage without tokens (desktop seals, mobile does not);
+ * this takes the union. Folding only regroups: every visible row is still delivered
+ * and clients regroup it themselves, so an extra seal merely yields a larger page.
+ */
+export function completesHistoryTurn(row: HistoryMessageSource): boolean {
+ const meta = row.agentMeta as Record<string, unknown> | null | undefined;
+ if (!meta) return false;
+ const positive = (value: unknown) => typeof value === 'number' && Number.isFinite(value) && value > 0;
+ const money = (value: unknown) => positive((value as { amount?: unknown } | null)?.amount);
+ return meta.turnCompleted === true
+ || money(meta.userTurnCost) || money(meta.turnCost)
+ || positive(meta.userTurnCostUsd) || positive(meta.turnCostUsd)
+ || (typeof meta.turnUsageDetails === 'object' && meta.turnUsageDetails !== null);
+}
+
function hasFileDelivery(row: HistoryMessageSource): boolean {
if (row.role !== 'tool_use') return false;
const tool = parseMessageToolUse(row);
@@ -240,8 +261,7 @@ function projectHistorySourceView<T extends HistoryMessageSource>(
isContinuationBoundary: (item) => item.type === 'source' && isContinuationMessage(item.row),
isAnswer: (item) => item.type === 'source' && item.row.role === 'assistant'
&& typeof item.row.content === 'string' && !!item.row.content.trim(),
- isSealedAnswer: (item) => item.type === 'source'
- && (item.row.agentMeta as Record<string, unknown> | null)?.turnCompleted === true,
+ isSealedAnswer: (item) => item.type === 'source' && completesHistoryTurn(item.row),
isCompactBoundary: (item) => item.type === 'source' && item.row.role === 'system',
isActivity: (item): item is SourceItem<T> => item.type === 'source' && item.activity,
isArchivable: (item): item is SourceItem<T> => item.type === 'source' && item.archivable,
diff --git a/packages/maker-shared/src/messageWindow.ts b/packages/maker-shared/src/messageWindow.ts
index 30f985d4f2..86d3ad16dd 100644
--- a/packages/maker-shared/src/messageWindow.ts
+++ b/packages/maker-shared/src/messageWindow.ts
@@ -1,7 +1,7 @@
export { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from './remoteTextStream.js';
export * from './historyView.js';
export * from './historyWorkLines.js';
-export { projectHistoryView, historySubagentScopes, isHistoryDetailTool, hasVisibleHistoryResult } from './historyViewProjection.js';
+export { projectHistoryView, historySubagentScopes, isHistoryDetailTool, hasVisibleHistoryResult, completesHistoryTurn } from './historyViewProjection.js';
export * from './historyViewController.js';
export { renderHistoryView } from './historyViewRender.js';
export { HistoryViewHandoff } from './historyViewHandoff.js';