diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-tail.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-tail.ts index 923e3cd5bca..adc0bc0f0df 100644 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-tail.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-tail.ts @@ -15,10 +15,11 @@ import { withMobileNativeChatHarness } from './mobile-native-chat-projection-sources' import { - buildMobileNativeChatUnit, - groupMobileNativeChatUnitMembers, - type Unit -} from './mobile-native-chat-projection-units' + buildNativeChatFoldUnit, + groupNativeChatFoldUnitMembers, + type NativeChatFoldUnit as Unit +} from '../../../../../src/shared/native-chat/transcript/native-chat-fold-units' +import { finishMobileNativeChatMessages } from '../mobile-native-chat-render-data' // A tail harness row that is its own image unit and no roster member leaves every earlier unit as it was. function staysInTail(harness: NativeChatMessage): boolean { @@ -109,9 +110,15 @@ export function projectMobileNativeChatTail( rescan.push(...newRows) // Orphan names depend on every earlier id, so a re-projected unit with orphans takes the full pass. const rebuilt: Unit[] = [] - for (const members of groupMobileNativeChatUnitMembers(rescan, kinds)) { + for (const members of groupNativeChatFoldUnitMembers(rescan, kinds)) { const held = previous.units.findLast((unit) => unit.sources[0]!.id === members[0]!.id) - const unit = buildMobileNativeChatUnit(members, NO_IDS, kinds, held) + const unit = buildNativeChatFoldUnit( + members, + NO_IDS, + kinds, + held, + finishMobileNativeChatMessages + ) if (unit !== held && unit.orphans.length > 0) { return null } diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-units.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-units.ts deleted file mode 100644 index 51ac45b648d..00000000000 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-units.ts +++ /dev/null @@ -1,135 +0,0 @@ -import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' -import { - foldToolMessages, - type NativeChatToolFoldKind -} from '../../../../../src/shared/native-chat/tools/native-chat-tool-fold' -import { - orphanRowId, - type NativeChatOrphanOrigin -} from '../../../../../src/shared/native-chat/tools/native-chat-folded-tool-results' -import { finishMobileNativeChatMessages } from '../mobile-native-chat-render-data' - -export type Unit = { - sources: readonly NativeChatMessage[] - rows: NativeChatMessage[] - orphans: readonly NativeChatOrphanOrigin[] -} - -export function groupMobileNativeChatUnitMembers( - grouped: readonly NativeChatMessage[], - kinds: ReadonlyMap -): NativeChatMessage[][] { - const members: NativeChatMessage[][] = [] - let active = false - for (const source of grouped) { - const kind = kinds.get(source)! - if (active && (kind === 'tool' || kind === 'sidecar' || kind === 'pass')) { - members.at(-1)!.push(source) - } else { - members.push([source]) - active = source.role === 'assistant' && kind !== 'orphan' - } - } - return members -} - -export function buildMobileNativeChatUnit( - sources: readonly NativeChatMessage[], - ids: ReadonlySet, - kinds: ReadonlyMap, - before: Unit | undefined -): Unit { - if ( - before && - before.sources.length === sources.length && - before.sources.every((source, index) => source === sources[index]) - ) { - return before - } - const substituted = before && substituteProse(before, sources, kinds) - const orphans: NativeChatOrphanOrigin[] = [] - const rows = - substituted ?? - finishMobileNativeChatMessages( - foldToolMessages(sources, ids, kinds, (origin) => orphans.push(origin)) - ) - return { sources, rows, orphans: substituted ? before!.orphans : orphans } -} - -export function buildMobileNativeChatUnits( - grouped: readonly NativeChatMessage[], - kinds: ReadonlyMap, - previous?: { units: readonly Unit[] } -): Unit[] { - const ids = new Set(grouped.map((row) => row.id)) - const oldUnits = new Map(previous?.units.map((unit) => [unit.sources[0]!.id, unit])) - const units = groupMobileNativeChatUnitMembers(grouped, kinds).map((sources) => - buildMobileNativeChatUnit(sources, ids, kinds, oldUnits.get(sources[0]!.id)) - ) - const allocated = new Set(ids) - const occurrences = new Map() - return units.map((unit) => { - const renamed = new Map() - const orphans = unit.orphans.map((origin) => { - const id = orphanRowId(origin.sourceId, allocated, occurrences) - allocated.add(id) - if (id === origin.row.id) { - return origin - } - const row = { ...origin.row, id } - renamed.set(origin.row, row) - return { ...origin, row } - }) - return renamed.size === 0 - ? unit - : { - ...unit, - orphans, - rows: unit.rows.map((row) => renamed.get(row) ?? row) - } - }) -} - -function substituteProse( - before: Unit, - sources: readonly NativeChatMessage[], - kinds: ReadonlyMap -): NativeChatMessage[] | null { - if (before.sources.length !== sources.length) { - return null - } - const changed = sources.flatMap((source, index) => - source === before.sources[index] ? [] : [index] - ) - if (changed.length !== 1 || changed[0] !== 0) { - return null - } - const old = before.sources[0]!, - next = sources[0]! - if ( - old.role !== next.role || - (next.role !== 'assistant' && next.role !== 'reasoning') || - old.unpairedToolResults || - next.unpairedToolResults || - !old.blocks.every((block) => block.type === 'text' && !block.providerFrame) || - !next.blocks.every((block) => block.type === 'text' && !block.providerFrame) - ) { - return null - } - const target = before.rows.find((row) => row.id === old.id && row.role === old.role) - if (!target || !old.blocks.every((block, index) => block === target.blocks[index])) { - return null - } - const contribution = sources - .slice(1) - .findLast( - (source) => - source.journalPosition && (kinds.get(source) === 'tool' || kinds.get(source) === 'sidecar') - ) - const replacement: NativeChatMessage = { - ...next, - blocks: [...next.blocks, ...target.blocks.slice(old.blocks.length)], - ...(contribution ? { foldedJournalPosition: contribution.journalPosition } : {}) - } - return before.rows.map((row) => (row === target ? replacement : row)) -} diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts index d393b28d89a..e7b598ab6c2 100644 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts @@ -9,13 +9,19 @@ import { nativeChatImageTranscriptUnits, normalizeImageTranscriptUnit } from '../../../../../src/shared/native-chat/transcript/native-chat-image-transcript-markers' -import { foldMobileNativeChatMessages } from '../mobile-native-chat-render-data' +import { + finishMobileNativeChatMessages, + foldMobileNativeChatMessages +} from '../mobile-native-chat-render-data' import { prepareMobileNativeChatSources, type MobileNativeChatProjectionSource } from './mobile-native-chat-projection-sources' import { projectMobileNativeChatTail } from './mobile-native-chat-projection-tail' -import { buildMobileNativeChatUnits, type Unit } from './mobile-native-chat-projection-units' +import { + buildNativeChatFoldUnits, + type NativeChatFoldUnit as Unit +} from '../../../../../src/shared/native-chat/transcript/native-chat-fold-units' type ImageUnit = { sources: readonly NativeChatMessage[]; rows: NativeChatMessage[] } export type MobileNativeChatProjection = { @@ -75,7 +81,12 @@ export function projectMobileNativeChatMessages( const kinds = new Map( grouped.map((source) => [source, previous?.kinds.get(source) ?? nativeChatToolFoldKind(source)]) ) - const units = buildMobileNativeChatUnits(grouped, kinds, previous) + const units = buildNativeChatFoldUnits( + grouped, + kinds, + new Map(previous?.units.map((unit) => [unit.sources[0]!.id, unit])), + finishMobileNativeChatMessages + ) const unchanged = previous && units.length === previous.units.length && diff --git a/mobile/src/session/use-mobile-structured-transcript.ts b/mobile/src/session/use-mobile-structured-transcript.ts index f4fa032ca3c..4d1e1745023 100644 --- a/mobile/src/session/use-mobile-structured-transcript.ts +++ b/mobile/src/session/use-mobile-structured-transcript.ts @@ -5,7 +5,8 @@ import { latestAgentSessionContextClearSequence } from '../../../src/shared/agent-session/agent-session-context-clear' import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' -import { projectStructuredAgentSessionMessages } from '../../../src/shared/agent-session/view/structured-agent-session-message-projection' +import type { StructuredAgentSessionOptimisticMessage } from '../../../src/shared/agent-session/view/structured-agent-session-message-projection' +import { createStructuredAgentSessionMessageProjection } from '../../../src/shared/agent-session/view/structured-agent-session-message-stream' import { tuiAgentDisplayName } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names' import { withNativeChatCutTurnNotices } from '../../../src/shared/native-chat/transcript/native-chat-cut-turn-notice' import { omitNativeChatThreadGoalRows } from '../../../src/shared/native-chat/transcript/native-chat-thread-goal-rows' @@ -22,7 +23,7 @@ const mobileStructuredTranscript = createStructuredQuestionProjection( export function useMobileStructuredTranscript( agent: string | null, state: Pick, - optimistic: Parameters[1], + optimistic: readonly StructuredAgentSessionOptimisticMessage[], sessionKey: string ) { const [clearSent, setClearSent] = useState<{ @@ -61,24 +62,22 @@ export function useMobileStructuredTranscript( }), [agent, floor, state.items] ) + const projectMessages = useMemo( + () => createStructuredAgentSessionMessageProjection(mobileStructuredTranscript.messages), + [] + ) + const questionTranscript = useMemo(() => mobileStructuredTranscript.stream(), []) const messages = useMemo( () => // The goal strip on the composer shows goal state, as on desktop. - omitNativeChatThreadGoalRows( - projectStructuredAgentSessionMessages( - transcriptItems, - optimistic, - state.submissions, - mobileStructuredTranscript.messages - ) - ), - [transcriptItems, optimistic, state.submissions] + omitNativeChatThreadGoalRows(projectMessages(transcriptItems, optimistic, state.submissions)), + [transcriptItems, optimistic, state.submissions, projectMessages] ) return { clearing, onClearSent, transcriptItems, messages, - receipts: mobileStructuredTranscript.transcript(transcriptItems).receipts + receipts: questionTranscript(transcriptItems).receipts } } diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx index b8714c4e801..13599631a53 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx @@ -124,10 +124,10 @@ export function NativeChatMessageList({ runtimeContext?: RuntimeFileOperationArgs | null }): React.JSX.Element { const t = useTranslate() + const questionTranscript = useMemo(() => desktopStructuredTranscript.stream(), []) const receipts = useMemo( - () => - journalItems ? desktopStructuredTranscript.transcript(journalItems).receipts : new Map(), - [journalItems] + () => (journalItems ? questionTranscript(journalItems).receipts : new Map()), + [journalItems, questionTranscript] ) const scrollRef = useRef(null) const contentRef = useRef(null) diff --git a/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-projection.ts b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-projection.ts index 138ab05320c..2c69315490c 100644 --- a/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-projection.ts +++ b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-projection.ts @@ -4,27 +4,31 @@ import { type NativeChatSubagentRow, type NativeChatTranscriptProjection } from '../../../../../../shared/native-chat/transcript/native-chat-transcript-projection' -import type { NativeChatTurnJournal } from '../../../../../../shared/native-chat/transcript/native-chat-turn-membership' +import { + hostStatesTurnScopes, + type NativeChatTurnJournal +} from '../../../../../../shared/native-chat/transcript/native-chat-turn-membership' import { compareNativeChatDisplayMessages as compareMessages, + nativeChatDisplaySortRank, orderNativeChatDisplayMessages as orderMessages } from '../../../../../../shared/native-chat/transcript/native-chat-message-order' - -function sameMessage(left: NativeChatMessage, right: NativeChatMessage): boolean { - // Most rows retain input identity; only folded assistant runs need field comparison. - if (left === right) { - return true - } - const keys = Object.keys(left) as (keyof NativeChatMessage)[] - return ( - keys.length === Object.keys(right).length && - keys.every( - (key) => Object.hasOwn(right, key) && (key === 'blocks' || left[key] === right[key]) - ) && - left.blocks.length === right.blocks.length && - left.blocks.every((block, index) => block === right.blocks[index]) - ) -} +import { buildNativeChatFoldUnits } from '../../../../../../shared/native-chat/transcript/native-chat-fold-units' +import { + nativeChatToolFoldKind, + type NativeChatToolFoldKind +} from '../../../../../../shared/native-chat/tools/native-chat-tool-fold' +import { foldSubagentItems } from '../../../../../../shared/native-chat/transcript/native-chat-subagent-items' +import { stripNoiseMessages } from '../../../../../../shared/native-chat/native-chat-noise' +import { agentJournalItemSubagentId } from '../../../../../../shared/agent-session/journal/agent-session-journal-producer' +import { reuseUnits } from './native-chat-message-list-reuse' +import { subagentTurnKeys } from './native-chat-message-list-turns' +import { + settleUnit, + unitStarts, + type NativeChatListScope, + type NativeChatListState +} from './native-chat-message-list-units' function sameRows( left: readonly T[] | undefined, @@ -41,195 +45,137 @@ function sameRows( const sameSubagentRow = (a: NativeChatSubagentRow, b: NativeChatSubagentRow): boolean => a.message === b.message && a.turnKey === b.turnKey -function plainAssistant(message: NativeChatMessage): boolean { - return ( - message.role === 'assistant' && - message.agentId === undefined && - message.blocks.every((block) => block.type === 'text' && !block.providerFrame) +function projectFully( + messages: readonly NativeChatMessage[], + journal: NativeChatTurnJournal | null | undefined, + previous: NativeChatListState | null +): NativeChatListState { + const ids = new Set(messages.map((message) => message.id)) + if (ids.size !== messages.length) { + // Units are keyed by source id; duplicate ids take the plain fold and leave nothing to reuse. + return { + input: messages, + ids, + journal, + projection: retainIdentity( + projectNativeChatTranscript(messages, compareMessages, journal, orderMessages), + previous?.projection + ), + scopes: [], + place: new Map(), + kinds: new Map(), + turnKeys: null, + ordered: false + } + } + const held = new Map( + previous?.scopes.flatMap((scope) => scope.units.map((unit) => [unit.sources[0]!.id, unit])) ) + const kinds = new Map() + const place = new Map() + const scopes: NativeChatListScope[] = [] + const agentRows = new Map() + let ordered = false + const order = (rows: readonly NativeChatMessage[]) => { + const sorted = orderMessages(rows) + ordered = sorted.every( + (row, index) => + row === rows[index] && row.journalPosition && nativeChatDisplaySortRank(row) === 0 + ) + return sorted + } + const projectScope = (rows: readonly NativeChatMessage[]): NativeChatMessage[] => { + const grouped = foldSubagentItems(rows) + for (const source of grouped) { + kinds.set(source, previous?.kinds.get(source) ?? nativeChatToolFoldKind(source)) + } + const ids = new Set(grouped.map((row) => row.id)) + const units = buildNativeChatFoldUnits(grouped, kinds, held, stripNoiseMessages, ids).map( + (unit) => settleUnit(unit, held.get(unit.sources[0]!.id)) + ) + const agentId = rows[0] ? agentJournalItemSubagentId(rows[0]) : null + const offset = agentId === null ? 0 : (agentRows.get(agentId) ?? 0) + const scope = scopes.length + for (const [index, unit] of units.entries()) { + for (const source of unit.sources) { + place.set(source, { scope, unit: index }) + } + } + const starts = unitStarts(units) + const projected = units.flatMap((unit) => unit.rows) + if (agentId !== null) { + agentRows.set(agentId, offset + projected.length) + } + scopes.push({ agentId, offset, ids, units, starts }) + return projected + } + const projected = projectNativeChatTranscript( + messages, + compareMessages, + journal, + order, + projectScope + ) + for (const scope of scopes) { + const first = + scope.agentId !== null && scope.units.some((unit) => unit.rows.length > 0) + ? projected.subagentRows.get(scope.agentId)?.[scope.offset] + : undefined + if (first) { + scope.turn = { key: first.turnKey } + } + } + return { + input: messages, + ids, + journal, + projection: retainIdentity(projected, previous?.projection), + scopes, + place, + kinds, + turnKeys: + journal && hostStatesTurnScopes(journal.items) + ? projected.subagentRows.size > 0 + ? subagentTurnKeys(projected.subagentRows, journal.items) + : new Map() + : null, + ordered + } } -function sameTextPlacement(before: NativeChatMessage, next: NativeChatMessage): boolean { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Runtime keys are used only for equality, including any extra message fields. - const keys = Object.keys(before) as (keyof NativeChatMessage)[] - return ( - keys.length === Object.keys(next).length && - keys.every((key) => { - if (!Object.hasOwn(next, key)) { - return false - } - if (key === 'blocks') { - return true - } - if (key === 'journalPosition') { - return ( - before.journalPosition?.sequence === next.journalPosition?.sequence && - before.journalPosition?.index === next.journalPosition?.index - ) - } - // Journal creation position, rather than a revised provider clock, orders these rows. - return key === 'timestamp' && before.journalPosition && next.journalPosition - ? true - : before[key] === next[key] - }) - ) -} - -function reuseConversation( - messages: NativeChatMessage[], - before: NativeChatMessage[] | null, - previous: NativeChatTranscriptProjection, - byId: ReadonlyMap, - indexes: ReadonlyMap, - rawIds: ReadonlySet -): { - conversation: NativeChatMessage[] - changes: { index: number; message: NativeChatMessage; source: NativeChatMessage | null }[] -} | null { - if (!before || messages.length < before.length || previous.subagentRows.size > 0) { - return null +function retainIdentity( + projected: NativeChatTranscriptProjection, + previous: NativeChatTranscriptProjection | undefined +): NativeChatTranscriptProjection { + if (!previous) { + return projected } - const changes: { index: number; message: NativeChatMessage; source: NativeChatMessage | null }[] = - [] - for (let index = 0; index < before.length; index += 1) { - const prior = before[index]! - const message = messages[index]! - if (prior === message) { - continue - } - const projectedIndex = indexes.get(prior) - // Folded rows can own later tools: only a directly drawn prose row is independent. - if ( - projectedIndex === undefined || - !plainAssistant(prior) || - !plainAssistant(message) || - !sameTextPlacement(prior, message) - ) { - return null - } - changes.push({ index: projectedIndex, message, source: prior }) + const subagentRows = new Map() + for (const [agentId, rows] of projected.subagentRows) { + const prior = previous.subagentRows.get(agentId) + subagentRows.set(agentId, prior && sameRows(prior, rows, sameSubagentRow) ? prior : rows) } - const appended = messages.slice(before.length) - if (appended.length > 0) { - let last: NativeChatMessage | undefined - for (const message of before) { - if (!message.journalPosition || message.pendingSend || message.queued) { - return null - } - if (!last || compareMessages(last, message) < 0) { - last = message - } - } - const addedIds = new Set() - for (const message of appended) { - if ( - !plainAssistant(message) || - !message.journalPosition || - message.pendingSend || - message.queued || - rawIds.has(message.id) || - byId.has(message.id) || - addedIds.has(message.id) || - (last && compareMessages(last, message) > 0) - ) { - return null - } - addedIds.add(message.id) - last = message - } + const sameConversation = sameRows(previous.conversation, projected.conversation, Object.is) + const sameSubagents = + subagentRows.size === previous.subagentRows.size && + Array.from(subagentRows).every(([agentId, rows]) => previous.subagentRows.get(agentId) === rows) + if (sameConversation && sameSubagents) { + return previous } - if (changes.length === 0 && appended.length === 0) { - return { conversation: previous.conversation, changes } + return { + conversation: sameConversation ? previous.conversation : projected.conversation, + subagentRows: sameSubagents ? previous.subagentRows : subagentRows } - const conversation = previous.conversation.slice() - for (const { index, message } of changes) { - conversation[index] = message - } - for (const message of appended) { - changes.push({ index: conversation.length, message, source: null }) - conversation.push(message) - } - return { conversation, changes } } export function createNativeChatMessageListProjection(): ( messages: NativeChatMessage[], journal?: NativeChatTurnJournal | null ) => NativeChatTranscriptProjection { - let previous: NativeChatTranscriptProjection = { conversation: [], subagentRows: new Map() } - let byId = new Map() - let input: NativeChatMessage[] | null = null - let indexes: Map | null = null - let rawIds: Set | null = null + let state: NativeChatListState | null = null return (messages, journal) => { - const reused = - indexes && rawIds ? reuseConversation(messages, input, previous, byId, indexes, rawIds) : null - const appendedStart = input?.length ?? 0 - input = messages - if (reused) { - if (reused.conversation !== previous.conversation) { - // Reuse the index for content-only revisions; append changes only its new suffix. - for (const { index, message, source } of reused.changes) { - byId.set(message.id, message) - if (source) { - indexes!.delete(source) - } - indexes!.set(message, index) - } - for (let index = appendedStart; index < messages.length; index += 1) { - rawIds!.add(messages[index]!.id) - } - previous = { ...previous, conversation: reused.conversation } - } - return previous - } - const projected = projectNativeChatTranscript(messages, compareMessages, journal, orderMessages) - // Folding clones historical tool runs even when every contributing block is unchanged. - const settle = (message: NativeChatMessage): NativeChatMessage => { - const prior = byId.get(message.id) - return prior && sameMessage(prior, message) ? prior : message - } - const conversation = projected.conversation.map(settle) - const subagentRows = new Map() - for (const [agentId, rows] of projected.subagentRows) { - const settled = rows.map((row) => ({ ...row, message: settle(row.message) })) - const prior = previous.subagentRows.get(agentId) - subagentRows.set( - agentId, - prior && sameRows(prior, settled, sameSubagentRow) ? prior : settled - ) - } - const sameConversation = sameRows(previous.conversation, conversation, Object.is) - const sameSubagents = - subagentRows.size === previous.subagentRows.size && - Array.from(subagentRows).every( - ([agentId, rows]) => previous.subagentRows.get(agentId) === rows - ) - const independent = subagentRows.size === 0 - rawIds = independent ? new Set(messages.map((message) => message.id)) : null - // Settlement can restore raw identity after a fold; only canonical output proves provenance. - indexes = - rawIds?.size === messages.length - ? new Map(projected.conversation.map((message, index) => [message, index])) - : null - if (indexes?.size !== projected.conversation.length) { - indexes = null - } - if (sameConversation && sameSubagents) { - return previous - } - previous = { - conversation: sameConversation ? previous.conversation : conversation, - subagentRows: sameSubagents ? previous.subagentRows : subagentRows - } - byId = new Map( - [ - ...conversation, - ...Array.from(subagentRows.values()) - .flat() - .map((row) => row.message) - ].map((message) => [message.id, message]) - ) - return previous + state = + (state && reuseUnits(state, messages, journal)) ?? projectFully(messages, journal, state) + return state.projection } } diff --git a/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-reuse.ts b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-reuse.ts new file mode 100644 index 00000000000..efe782103a3 --- /dev/null +++ b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-reuse.ts @@ -0,0 +1,279 @@ +import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import { + sameNativeChatRowPlacement, + type NativeChatSubagentRow +} from '../../../../../../shared/native-chat/transcript/native-chat-transcript-projection' +import type { NativeChatTurnJournal } from '../../../../../../shared/native-chat/transcript/native-chat-turn-membership' +import { + compareNativeChatDisplayMessages as compareMessages, + nativeChatDisplaySortRank +} from '../../../../../../shared/native-chat/transcript/native-chat-message-order' +import { + buildNativeChatFoldUnit, + groupNativeChatFoldUnitMembers, + type NativeChatFoldUnit +} from '../../../../../../shared/native-chat/transcript/native-chat-fold-units' +import { nativeChatToolFoldKind } from '../../../../../../shared/native-chat/tools/native-chat-tool-fold' +import { isOrphanRowId } from '../../../../../../shared/native-chat/tools/native-chat-folded-tool-results' +import { subagentItemBlock } from '../../../../../../shared/native-chat/transcript/native-chat-subagent-items' +import { stripNoiseMessages } from '../../../../../../shared/native-chat/native-chat-noise' +import { agentJournalItemSubagentId } from '../../../../../../shared/agent-session/journal/agent-session-journal-producer' +import { appendedSubagentTurnKey, appendedTurnNeutralItems } from './native-chat-message-list-turns' +import { + settleUnit, + unitStarts, + type NativeChatListScope, + type NativeChatListState +} from './native-chat-message-list-units' + +/** Revised rows re-fold only their unit, and conversation appends only the last unit onward; else null. */ +export function reuseUnits( + state: NativeChatListState, + messages: readonly NativeChatMessage[], + journal: NativeChatTurnJournal | null | undefined +): NativeChatListState | null { + const before = state.input + const subagents = state.projection.subagentRows.size > 0 + // Revisions keep every ordering field, so only appends need input already in display order. + if (messages.length < before.length || (!state.ordered && messages.length !== before.length)) { + return null + } + // Subagent rows keep their turns only while no earlier turn input changed. + let appendedItems = subagents ? appendedTurnNeutralItems(state.journal, journal) : null + // Only explicit turn scopes prove an appended row leaves earlier rows' turns alone. + if (subagents && (!appendedItems || (messages.length > before.length && !state.turnKeys))) { + return null + } + const changed: [NativeChatMessage, NativeChatMessage][] = [] + for (let index = 0; index < before.length; index += 1) { + const prior = before[index]! + const message = messages[index]! + if (prior === message) { + continue + } + if ( + prior.id !== message.id || + !sameNativeChatRowPlacement(prior, message) || + subagentItemBlock(prior) !== null || + subagentItemBlock(message) !== null || + // A conversation user row opens the turns subagent rows are grouped by. + (subagents && message.role === 'user') || + state.kinds.get(prior) !== nativeChatToolFoldKind(message) + ) { + return null + } + changed.push([prior, message]) + } + const appended = messages.slice(before.length) + const appendedIds = new Set() + const appendedTurns = new Map() + let last = before.at(-1) + for (const message of appended) { + if (agentJournalItemSubagentId(message) !== null) { + appendedItems ??= appendedTurnNeutralItems(state.journal, journal) + const turn = + appendedItems && + state.turnKeys && + appendedSubagentTurnKey(message, appendedItems, state.turnKeys) + if (!turn) { + return null + } + appendedTurns.set(message, turn.turnKey) + } + if ( + !message.journalPosition || + nativeChatDisplaySortRank(message) !== 0 || + subagentItemBlock(message) !== null || + // A raw id shaped like a detached result's renames every later orphan. + isOrphanRowId(message.id) || + state.ids.has(message.id) || + appendedIds.has(message.id) || + (last && compareMessages(last, message) >= 0) + ) { + return null + } + appendedIds.add(message.id) + last = message + } + const scopes = state.scopes.slice() + const edit = (index: number): NativeChatListScope => { + if (scopes[index] === state.scopes[index]) { + scopes[index] = { ...scopes[index]!, units: scopes[index]!.units.slice() } + } + return scopes[index]! + } + let conversation = state.projection.conversation + const copiedRows = new Map() + const agentRowsFor = (agentId: string): NativeChatSubagentRow[] => { + let rows = copiedRows.get(agentId) + if (!rows) { + rows = state.projection.subagentRows.get(agentId)?.slice() ?? [] + copiedRows.set(agentId, rows) + } + return rows + } + // Several revisions in one unit re-fold it once. + const revisedUnits = new Map< + string, + { scope: number; unit: number; swaps: Map } + >() + for (const [prior, message] of changed) { + const at = state.place.get(prior) + if (!at) { + return null + } + const key = `${at.scope}:${at.unit}` + const entry = revisedUnits.get(key) ?? { ...at, swaps: new Map() } + entry.swaps.set(prior, message) + revisedUnits.set(key, entry) + } + for (const { scope: scopeIndex, unit: unitIndex, swaps } of revisedUnits.values()) { + const scope = edit(scopeIndex) + const unit = scope.units[unitIndex]! + // A refused reuse projects in full with fresh maps, so recording sources as we go is safe. + for (const [prior, message] of swaps) { + state.kinds.set(message, state.kinds.get(prior)!) + } + const rebuilt = settleUnit( + buildNativeChatFoldUnit( + unit.sources.map((source) => swaps.get(source) ?? source), + scope.ids, + state.kinds, + unit, + stripNoiseMessages + ), + unit + ) + // Detached result ids are allocated across units, so only a full pass may change them. + if ( + unit.orphans.length > 0 || + rebuilt.orphans.length > 0 || + rebuilt.rows.length !== unit.rows.length + ) { + return null + } + scope.units[unitIndex] = rebuilt + for (const [prior, message] of swaps) { + state.kinds.delete(prior) + state.place.delete(prior) + state.place.set(message, { scope: scopeIndex, unit: unitIndex }) + } + if (rebuilt.rows.every((row, index) => row === unit.rows[index])) { + continue + } + const start = scope.offset + scope.starts[unitIndex]! + if (scope.agentId === null) { + conversation = + conversation === state.projection.conversation ? conversation.slice() : conversation + conversation.splice(start, rebuilt.rows.length, ...rebuilt.rows) + } else { + const rows = agentRowsFor(scope.agentId) + for (const [offset, row] of rebuilt.rows.entries()) { + rows[start + offset] = { message: row, turnKey: rows[start + offset]!.turnKey } + } + } + } + // Each scope's appended rows re-fold from its last unit; a subagent row in a new turn opens a new chunk. + const appendTo = (index: number, added: readonly NativeChatMessage[]): boolean => { + const scope = edit(index) + for (const message of added) { + state.kinds.set(message, nativeChatToolFoldKind(message)) + state.ids.add(message.id) + scope.ids.add(message.id) + } + const from = Math.max(0, scope.units.length - 1) + const head = scope.units[from] + const units: NativeChatFoldUnit[] = [] + for (const members of groupNativeChatFoldUnitMembers( + [...(head?.sources ?? []), ...added], + state.kinds + )) { + const held = members[0] === head?.sources[0] ? head : undefined + const unit = settleUnit( + buildNativeChatFoldUnit(members, scope.ids, state.kinds, held, stripNoiseMessages), + held + ) + if (unit.orphans.length > 0 || (held && held.orphans.length > 0)) { + return false + } + unit.sources.forEach((source) => + state.place.set(source, { scope: index, unit: from + units.length }) + ) + units.push(unit) + } + const start = scope.starts[from] ?? 0 + scope.units.splice(from, scope.units.length - from, ...units) + scope.starts = [ + ...scope.starts.slice(0, from), + ...unitStarts(units).map((offset) => start + offset) + ] + const rows = units.flatMap((unit) => unit.rows) + if (scope.agentId === null) { + conversation = [...conversation.slice(0, start), ...rows] + return true + } + const agentRows = agentRowsFor(scope.agentId) + const turnKey = scope.turn?.key + agentRows.splice( + scope.offset + start, + agentRows.length, + ...rows.map((message) => ({ message, turnKey })) + ) + return true + } + const own = appended.filter((message) => !appendedTurns.has(message)) + if (own.length > 0 && !appendTo(0, own)) { + return null + } + // Per subagent, consecutive rows of one turn extend its last chunk or open the next. + const runs: { agentId: string; turnKey: string | undefined; rows: NativeChatMessage[] }[] = [] + const lastRun = new Map() + for (const [message, turnKey] of appendedTurns) { + const agentId = agentJournalItemSubagentId(message)! + const run = lastRun.get(agentId) + if (run && run.turnKey === turnKey) { + run.rows.push(message) + } else { + const next = { agentId, turnKey, rows: [message] } + runs.push(next) + lastRun.set(agentId, next) + } + } + const lastScope = new Map() + if (runs.length > 0) { + scopes.forEach((scope, index) => scope.agentId !== null && lastScope.set(scope.agentId, index)) + } + for (const { agentId, turnKey, rows } of runs) { + const tail = lastScope.get(agentId) ?? -1 + let index = tail + if (tail === -1 || !scopes[tail]!.turn || scopes[tail]!.turn!.key !== turnKey) { + if (tail !== -1 && !scopes[tail]!.turn) { + return null + } + index = scopes.length + lastScope.set(agentId, index) + scopes.push({ + agentId, + offset: agentRowsFor(agentId).length, + ids: new Set(), + units: [], + starts: [], + turn: { key: turnKey } + }) + } + if (!appendTo(index, rows)) { + return null + } + } + const projection = + conversation === state.projection.conversation && copiedRows.size === 0 + ? state.projection + : { + conversation, + subagentRows: + copiedRows.size === 0 + ? state.projection.subagentRows + : new Map([...state.projection.subagentRows, ...copiedRows]) + } + return { ...state, input: messages, journal, projection, scopes } +} diff --git a/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-turns.ts b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-turns.ts new file mode 100644 index 00000000000..b3c25bf7684 --- /dev/null +++ b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-turns.ts @@ -0,0 +1,99 @@ +import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import type { NativeChatSubagentRow } from '../../../../../../shared/native-chat/transcript/native-chat-transcript-projection' +import type { NativeChatTurnJournal } from '../../../../../../shared/native-chat/transcript/native-chat-turn-membership' +import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' +import { compareAgentJournalItems } from '../../../../../../shared/agent-session/journal/agent-session-journal-position' +import { readAgentJournalTurn } from '../../../../../../shared/agent-session/lifecycle/agent-session-turn-record' + +// Subagent rows are grouped by the parent turn they belong to; these checks prove that grouping still holds. + +/** User rows and turn records anchor turns; neither may change for earlier rows to keep their turn. */ +function opensOrRecordsTurn(item: AgentJournalRenderItem): boolean { + return ( + (item.body.kind === 'message' && item.body.role === 'user') || + readAgentJournalTurn(item.body) !== null + ) +} + +function turnItemId(item: AgentJournalRenderItem): string | undefined { + return item.turnScope?.kind === 'turn' ? item.turnScope.turnItemId : undefined +} + +/** The journal items appended since `before`, by id, when every turn input of the earlier items is unchanged; + * null when a turn input changed. Turn keys read user rows, turn records, scopes, submissions and the latest turn. */ +export function appendedTurnNeutralItems( + before: NativeChatTurnJournal | null | undefined, + after: NativeChatTurnJournal | null | undefined +): ReadonlyMap | null { + if (!before || !after) { + return before === after ? new Map() : null + } + if ( + before.submissions !== after.submissions || + before.working !== after.working || + JSON.stringify(before.latestTurn) !== JSON.stringify(after.latestTurn) || + after.items.length < before.items.length + ) { + return null + } + for (const [index, item] of before.items.entries()) { + const next = after.items[index]! + if ( + item !== next && + (item.itemId !== next.itemId || + item.agentId !== next.agentId || + compareAgentJournalItems(item, next) !== 0 || + item.turnScope?.kind !== next.turnScope?.kind || + turnItemId(item) !== turnItemId(next) || + opensOrRecordsTurn(item) || + opensOrRecordsTurn(next)) + ) { + return null + } + } + const appended = new Map() + for (const item of after.items.slice(before.items.length)) { + if (opensOrRecordsTurn(item)) { + return null + } + appended.set(item.itemId, item) + } + return appended +} + +/** Each journal turn's key as drawn on its subagent rows, for a host that states turn scopes. */ +export function subagentTurnKeys( + subagentRows: ReadonlyMap, + items: readonly AgentJournalRenderItem[] +): Map { + const byId = new Map(items.map((item) => [item.itemId, item])) + const keys = new Map() + for (const rows of subagentRows.values()) { + for (const { message, turnKey } of rows) { + const turn = byId.get(message.id) + const id = turn && turnItemId(turn) + if (id !== undefined) { + keys.set(id, turnKey) + } + } + } + return keys +} + +/** An appended subagent row's turn key, read from an earlier row of the same turn; undefined when unknown. */ +export function appendedSubagentTurnKey( + message: NativeChatMessage, + appendedItems: ReadonlyMap, + turnKeys: ReadonlyMap +): { turnKey: string | undefined } | undefined { + const item = appendedItems.get(message.id) + if (!item) { + return undefined + } + const id = turnItemId(item) + if (id === undefined) { + // Unscoped or unknown-scope rows own no turn. + return { turnKey: undefined } + } + return turnKeys.has(id) ? { turnKey: turnKeys.get(id) } : undefined +} diff --git a/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-units.ts b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-units.ts new file mode 100644 index 00000000000..2f027dcbb7a --- /dev/null +++ b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-units.ts @@ -0,0 +1,70 @@ +import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import type { NativeChatTranscriptProjection } from '../../../../../../shared/native-chat/transcript/native-chat-transcript-projection' +import type { NativeChatTurnJournal } from '../../../../../../shared/native-chat/transcript/native-chat-turn-membership' +import type { NativeChatFoldUnit } from '../../../../../../shared/native-chat/transcript/native-chat-fold-units' +import type { NativeChatToolFoldKind } from '../../../../../../shared/native-chat/tools/native-chat-tool-fold' + +function sameMessage(left: NativeChatMessage, right: NativeChatMessage): boolean { + // Most rows retain input identity; only folded assistant runs need field comparison. + if (left === right) { + return true + } + const keys = Object.keys(left) as (keyof NativeChatMessage)[] + return ( + keys.length === Object.keys(right).length && + keys.every( + (key) => Object.hasOwn(right, key) && (key === 'blocks' || left[key] === right[key]) + ) && + left.blocks.length === right.blocks.length && + left.blocks.every((block, index) => block === right.blocks[index]) + ) +} + +/** Folding clones a run's head even when every contributing block is unchanged. */ +export function settleUnit(unit: NativeChatFoldUnit, before: NativeChatFoldUnit | undefined) { + if (!before || unit === before) { + return unit + } + const prior = new Map(before.rows.map((row) => [row.id, row])) + const rows = unit.rows.map((row) => { + const held = prior.get(row.id) + return held && sameMessage(held, row) ? held : row + }) + return rows.every((row, index) => row === unit.rows[index]) ? unit : { ...unit, rows } +} + +/** The conversation, or one subagent's rows within one parent turn, folded by units. */ +export type NativeChatListScope = { + agentId: string | null + /** Where the scope's rows start in its agent's subagent rows; 0 for the conversation. */ + offset: number + ids: Set + units: NativeChatFoldUnit[] + /** Each unit's first row within the scope's rows. */ + starts: number[] + /** A subagent chunk's parent turn, when its rows show it. */ + turn?: { key: string | undefined } +} + +export type NativeChatListState = { + input: readonly NativeChatMessage[] + ids: Set + journal: NativeChatTurnJournal | null | undefined + projection: NativeChatTranscriptProjection + scopes: NativeChatListScope[] + place: Map + kinds: Map + /** Subagent rows' turn keys by journal turn, when the host states turn scopes. */ + turnKeys: Map | null + /** Input arrived in display order, every row journal-placed and ordinarily ranked, so appends can follow it. */ + ordered: boolean +} + +export function unitStarts(units: readonly NativeChatFoldUnit[]): number[] { + let start = 0 + return units.map((unit) => { + const at = start + start += unit.rows.length + return at + }) +} diff --git a/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.ts b/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.ts index 7f8df5ab365..8a3f93ddae4 100644 --- a/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.ts +++ b/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.ts @@ -6,6 +6,7 @@ import { type StructuredAgentSessionOptimisticMessage, projectStructuredAgentSessionMessages as projectMessages } from '../../../../../../shared/agent-session/view/structured-agent-session-message-projection' +import { createStructuredAgentSessionMessageProjection } from '../../../../../../shared/agent-session/view/structured-agent-session-message-stream' import { createStructuredQuestionProjection } from '../../../../../../shared/structured-agent-question-projection' import { projectStructuredAgentStartItem } from '../../../../../../shared/structured-agent-start-projection' @@ -21,3 +22,8 @@ export function projectStructuredAgentSessionMessages( ) { return projectMessages(items, optimistic, submissions, desktopStructuredTranscript.messages) } + +/** One mounted chat's messages across journal commits. */ +export function createDesktopStructuredAgentSessionMessageProjection() { + return createStructuredAgentSessionMessageProjection(desktopStructuredTranscript.messages) +} diff --git a/src/renderer/src/components/native-chat/conversation/projection/use-structured-agent-session-messages.ts b/src/renderer/src/components/native-chat/conversation/projection/use-structured-agent-session-messages.ts index 8557e630ce3..f8a95ea3f76 100644 --- a/src/renderer/src/components/native-chat/conversation/projection/use-structured-agent-session-messages.ts +++ b/src/renderer/src/components/native-chat/conversation/projection/use-structured-agent-session-messages.ts @@ -4,15 +4,16 @@ import type { AgentJournalSubmission } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' import type { StructuredAgentSessionOptimisticMessage } from '../../../../../../shared/agent-session/view/structured-agent-session-message-projection' -import { projectStructuredAgentSessionMessages } from './structured-agent-session-message-projection' +import { createDesktopStructuredAgentSessionMessageProjection } from './structured-agent-session-message-projection' export function useStructuredAgentSessionMessages( items: readonly AgentJournalRenderItem[], optimistic: readonly StructuredAgentSessionOptimisticMessage[], submissions: readonly AgentJournalSubmission[] ) { + const project = useMemo(() => createDesktopStructuredAgentSessionMessageProjection(), []) return useMemo( - () => projectStructuredAgentSessionMessages(items, optimistic, submissions), - [items, optimistic, submissions] + () => project(items, optimistic, submissions), + [items, optimistic, submissions, project] ) } diff --git a/src/shared/agent-session/structured-agent-session-reducer.ts b/src/shared/agent-session/structured-agent-session-reducer.ts index e3042fdf9c3..5a3f29f83b8 100644 --- a/src/shared/agent-session/structured-agent-session-reducer.ts +++ b/src/shared/agent-session/structured-agent-session-reducer.ts @@ -33,6 +33,7 @@ import type { AgentSessionRefusalReference } from './failures/agent-session-wire import { backgroundTaskStatesEqual } from './agent-session-background-task-state-equality' import { admitAgentSessionBackgroundTaskState } from './agent-session-background-task-state-admission' import { + LIVE_TRIM_SLACK_OWN_ITEMS, MAX_RETAINED_ITEMS, MAX_RETAINED_OWN_ITEMS, mergeSubmissions, @@ -275,7 +276,12 @@ export function reduceStructuredAgentSession( // Retained items already fit the limits, which only grow, so an unchanged journal skips the scan. const items = journalUnchanged ? merged - : trimRetainedItems(merged, state.retainedOwnItemLimit, state.retainedItemCap) + : trimRetainedItems( + merged, + state.retainedOwnItemLimit, + state.retainedItemCap, + LIVE_TRIM_SLACK_OWN_ITEMS + ) const outsideWindow = [ ...(liveItems.length < event.batch.items.length ? event.batch.items.filter((item) => !liveItems.includes(item)) diff --git a/src/shared/agent-session/view/structured-agent-session-history-state.ts b/src/shared/agent-session/view/structured-agent-session-history-state.ts index 4267fa7f11a..8ac8290a698 100644 --- a/src/shared/agent-session/view/structured-agent-session-history-state.ts +++ b/src/shared/agent-session/view/structured-agent-session-history-state.ts @@ -59,10 +59,14 @@ export function replacePage( } export function mergeItems( - current: readonly AgentJournalRenderItem[], + current: AgentJournalRenderItem[], incoming: readonly AgentJournalRenderItem[], removedIds: readonly string[] ): AgentJournalRenderItem[] { + const upserted = removedIds.length === 0 ? upsertItems(current, incoming) : null + if (upserted) { + return upserted + } const removed = new Set(removedIds) const byId = new Map( current.filter((item) => !removed.has(item.itemId)).map((item) => [item.itemId, item]) @@ -76,6 +80,49 @@ export function mergeItems( return [...byId.values()].sort(compareAgentJournalItems) } +/** Streamed revisions replace their row in place and new rows append past the tail, keeping every other row's + * position; anything that would move a row returns null for the full merge. */ +function upsertItems( + current: AgentJournalRenderItem[], + incoming: readonly AgentJournalRenderItem[] +): AgentJournalRenderItem[] | null { + if (incoming.length === 0) { + return current + } + // One pass copies the rows and finds every incoming id's row. + const rowOf = new Map(incoming.map((item) => [item.itemId, -1])) + const next: AgentJournalRenderItem[] = [] + for (const row of current) { + if (rowOf.has(row.itemId)) { + rowOf.set(row.itemId, next.length) + } + next.push(row) + } + let changed = false + for (const item of incoming) { + const index = rowOf.get(item.itemId)! + const prior = next[index] + if (prior && item.revision < prior.revision) { + continue + } + const tail = next.at(-1) + if ( + prior + ? compareAgentJournalItems(prior, item) !== 0 + : tail && compareAgentJournalItems(tail, item) >= 0 + ) { + return null + } + if (prior) { + next[index] = item + } else { + rowOf.set(item.itemId, next.push(item) - 1) + } + changed = true + } + return changed ? next : current +} + /** Keep the contiguous loaded suffix: an older revision retains its sequence and would move the paging anchor past a hole. * Leave it for paging unless the window already covers the whole journal, where revival below the head cannot skip rows. */ export function liveItemsWithinWindow( diff --git a/src/shared/agent-session/view/structured-agent-session-item-retention.test.ts b/src/shared/agent-session/view/structured-agent-session-item-retention.test.ts index 1410290db87..a41c0429aa6 100644 --- a/src/shared/agent-session/view/structured-agent-session-item-retention.test.ts +++ b/src/shared/agent-session/view/structured-agent-session-item-retention.test.ts @@ -90,4 +90,32 @@ describe('structured agent session item retention', () => { expect(oldestStructuredAgentSessionCursor(older)?.sequence).toBe(50) expect(older.hasOlder).toBe(false) }) + it('lets a live chat run 128 rows past its window before trimming back to it', () => { + let state = hydrate(Array.from({ length: 1024 }, (_, index) => item(index + 1))) + const append = (sequence: number) => { + state = reduceStructuredAgentSession(state, { + type: 'event', + event: { + type: 'batch', + sessionId: 'session-a', + batch: { + cursor: { epoch: 'epoch-a', sequence }, + items: [item(sequence)], + removedItemIds: [], + submissions: [] + } + } + }) + } + for (let sequence = 1025; sequence <= 1152; sequence += 1) { + append(sequence) + } + expect(state.items).toHaveLength(1152) + expect(state.items[0]?.sequence).toBe(1) + + append(1153) + expect(state.items).toHaveLength(1024) + expect(state.items[0]?.sequence).toBe(130) + expect(state.hasOlder).toBe(true) + }) }) diff --git a/src/shared/agent-session/view/structured-agent-session-item-retention.ts b/src/shared/agent-session/view/structured-agent-session-item-retention.ts index 017577a96c8..751a7e23474 100644 --- a/src/shared/agent-session/view/structured-agent-session-item-retention.ts +++ b/src/shared/agent-session/view/structured-agent-session-item-retention.ts @@ -14,13 +14,29 @@ export function ownItemCount(items: readonly AgentJournalRenderItem[]): number { return items.reduce((count, item) => (isRootAgentJournalItem(item) ? count + 1 : count), 0) } +// Live commits trim only past the limits by this margin, so most appends keep every row's position for incremental projection. +export const LIVE_TRIM_SLACK_OWN_ITEMS = 128 + /** Trim only through an own row; paged-in child rows at the head survive until an own row pushes them out. */ export function trimRetainedItems( items: AgentJournalRenderItem[], ownLimit: number, - cap: number + cap: number, + slack = 0 ): AgentJournalRenderItem[] { - let start = Math.max(0, items.length - cap) + if (slack > 0 && retainedStart(items, ownLimit + slack, cap + 4 * slack) === 0) { + return items + } + const start = retainedStart(items, ownLimit, cap) + return start === 0 ? items : items.slice(start) +} + +function retainedStart( + items: readonly AgentJournalRenderItem[], + ownLimit: number, + cap: number +): number { + const start = Math.max(0, items.length - cap) let own = 0 for (let index = items.length - 1; index >= start; index -= 1) { if (!isRootAgentJournalItem(items[index])) { @@ -28,11 +44,10 @@ export function trimRetainedItems( } own += 1 if (own > ownLimit) { - start = index + 1 - break + return index + 1 } } - return start === 0 ? items : items.slice(start) + return start } const MAX_RETAINED_SUBMISSIONS = 256 diff --git a/src/shared/agent-session/view/structured-agent-session-message-projection.ts b/src/shared/agent-session/view/structured-agent-session-message-projection.ts index 4aeb243af71..60931d822ca 100644 --- a/src/shared/agent-session/view/structured-agent-session-message-projection.ts +++ b/src/shared/agent-session/view/structured-agent-session-message-projection.ts @@ -98,6 +98,27 @@ export function projectStructuredAgentSessionMessages( submissions: readonly AgentJournalSubmission[], projectItems = projectStructuredItemsToNativeChat ): NativeChatMessage[] { + return projectStructuredAgentSessionMessageRows(items, optimistic, submissions, projectItems) + .output +} + +export type StructuredAgentSessionItemProjector = ( + items: readonly AgentJournalRenderItem[] +) => NativeChatMessage[] + +export type StructuredAgentSessionMessageRows = { + output: NativeChatMessage[] + /** Rows before the held cards and optimistic echoes. */ + conversationEnd: number + hasStoppedSends: boolean +} + +export function projectStructuredAgentSessionMessageRows( + items: readonly AgentJournalRenderItem[], + optimistic: readonly StructuredAgentSessionOptimisticMessage[], + submissions: readonly AgentJournalSubmission[], + projectItems: StructuredAgentSessionItemProjector +): StructuredAgentSessionMessageRows { // Keep stopped-before-start sends in conversation history; queued handoffs stay in their cards. const stoppedBeforeStart = new Map( submissions @@ -182,14 +203,16 @@ export function projectStructuredAgentSessionMessages( : collapseProviderRetryRuns(delivered) const conversation = shownStopped.size > 0 ? withStopRowsAfterStoppedSends(ordered, shownStopped) : ordered - return [ - // Merge unsent rows at journal positions after stop grouping so each run retains one stop notice. - ...(unsentItems.length > 0 + // Merge unsent rows at journal positions after stop grouping so each run retains one stop notice. + const placed = + unsentItems.length > 0 ? withRowsAtJournalPlaces( conversation, projectItems(unsentItems).map((message) => ({ ...message, unsent: true as const })) ) - : conversation), + : conversation + const output = [ + ...placed, // Held cards follow the conversation outside its runs. ...held, // Host rows supersede client echoes under either client or provider IDs. @@ -227,6 +250,11 @@ export function projectStructuredAgentSessionMessages( } }) ] + return { + output, + conversationEnd: placed.length, + hasStoppedSends: stoppedBeforeStart.size > 0 + } } /** Merge placed rows in journal order so clients rendering the list directly need no sort. */ diff --git a/src/shared/agent-session/view/structured-agent-session-message-stream.ts b/src/shared/agent-session/view/structured-agent-session-message-stream.ts new file mode 100644 index 00000000000..eadedacb111 --- /dev/null +++ b/src/shared/agent-session/view/structured-agent-session-message-stream.ts @@ -0,0 +1,195 @@ +import type { + AgentJournalRenderItem, + AgentJournalSubmission +} from '../journal/agent-session-journal-types' +import { compareAgentJournalItems } from '../journal/agent-session-journal-position' +import { agentJournalSubmissionKey } from '../journal/agent-session-journal-item-key' +import { + isAgentSessionContextClear, + isNativeChatContextClear +} from '../agent-session-context-clear' +import { isNativeChatProviderRetryRow } from '../../native-chat/native-chat-provider-retry-runs' +import { + compareNativeChatTranscriptMessages, + sameNativeChatRowPlacement +} from '../../native-chat/transcript/native-chat-transcript-projection' +import type { NativeChatMessage } from '../../native-chat/native-chat-types' +import { + isQuestionNeutralAgentJournalItem, + sameQuestionTurnBoundary +} from '../../structured-agent-question-projection' +import { projectStructuredItemsToNativeChat } from './structured-agent-session-projection' +import { + projectStructuredAgentSessionMessageRows, + type StructuredAgentSessionItemProjector, + type StructuredAgentSessionMessageRows, + type StructuredAgentSessionOptimisticMessage +} from './structured-agent-session-message-projection' + +// Streamed commits mostly revise or append rows; re-deriving only those keeps a long chat's commit cost off its history. + +/** Whether a revision or append of this item can change only its own row. */ +function drawsOnlyItsOwnRow(item: AgentJournalRenderItem): boolean { + return ( + isQuestionNeutralAgentJournalItem(item) && + !isAgentSessionContextClear(item.body) && + !(item.body.kind === 'message' && item.body.command) + ) +} + +function independentRow(row: NativeChatMessage | undefined): boolean { + return row === undefined || (!isNativeChatProviderRetryRow(row) && !isNativeChatContextClear(row)) +} + +type MessageStream = StructuredAgentSessionMessageRows & { + items: readonly AgentJournalRenderItem[] + optimistic: readonly StructuredAgentSessionOptimisticMessage[] + submissions: readonly AgentJournalSubmission[] + /** Conversation row index by id, for rows drawn undecorated from one item. */ + rowAt: Map + submissionIds: ReadonlySet + optimisticIds: ReadonlySet +} + +function withRowIndex( + projection: StructuredAgentSessionMessageRows, + items: readonly AgentJournalRenderItem[], + optimistic: readonly StructuredAgentSessionOptimisticMessage[], + submissions: readonly AgentJournalSubmission[] +): MessageStream { + const rowAt = new Map() + for (let index = 0; index < projection.conversationEnd; index += 1) { + rowAt.set(projection.output[index]!.id, index) + } + return { + ...projection, + items, + optimistic, + submissions, + rowAt, + submissionIds: new Set( + submissions.map((submission) => agentJournalSubmissionKey(submission.clientMessageId)) + ), + optimisticIds: new Set( + optimistic.map((entry) => agentJournalSubmissionKey(entry.clientMessageId)) + ) + } +} + +/** Revised rows replace their own; appended rows join the conversation before held cards and echoes. */ +function reuseMessages( + previous: MessageStream, + items: readonly AgentJournalRenderItem[], + projectItems: StructuredAgentSessionItemProjector +): MessageStream | null { + if (previous.hasStoppedSends || items.length < previous.items.length) { + return null + } + let output: NativeChatMessage[] | null = null + for (let index = 0; index < previous.items.length; index += 1) { + const before = previous.items[index]! + const item = items[index]! + if (before === item) { + continue + } + if ( + !drawsOnlyItsOwnRow(before) || + !drawsOnlyItsOwnRow(item) || + !sameQuestionTurnBoundary(before, item) || + compareAgentJournalItems(before, item) !== 0 + ) { + return null + } + const [old] = projectItems([before]) + const [row] = projectItems([item]) + if (!old || !row) { + if (old || row) { + return null + } + continue + } + const at = previous.rowAt.get(old.id) + if ( + at === undefined || + previous.output[at] !== old || + !independentRow(old) || + !independentRow(row) || + !sameNativeChatRowPlacement(old, row) + ) { + return null + } + ;(output ??= previous.output.slice())[at] = row + } + const appended = items.slice(previous.items.length) + if (appended.length === 0) { + return output ? { ...previous, items, output } : { ...previous, items } + } + if ( + appended.some( + (item) => + !drawsOnlyItsOwnRow(item) || + previous.submissionIds.has(item.itemId) || + previous.optimisticIds.has(item.itemId) + ) + ) { + return null + } + const rows = projectItems(appended) + let last = previous.output[previous.conversationEnd - 1] + for (const row of rows) { + if ( + !independentRow(row) || + !row.journalPosition || + previous.rowAt.has(row.id) || + previous.submissionIds.has(row.id) || + previous.optimisticIds.has(row.id) || + (last && compareNativeChatTranscriptMessages(last, row) >= 0) + ) { + return null + } + last = row + } + const base = output ?? previous.output + for (const [offset, row] of rows.entries()) { + previous.rowAt.set(row.id, previous.conversationEnd + offset) + } + return { + ...previous, + items, + output: [ + ...base.slice(0, previous.conversationEnd), + ...rows, + ...base.slice(previous.conversationEnd) + ], + conversationEnd: previous.conversationEnd + rows.length + } +} + +/** One consumer's messages across commits: re-derive only revised or appended items when nothing else can + * change, else project in full. */ +export function createStructuredAgentSessionMessageProjection( + projectItems: StructuredAgentSessionItemProjector = projectStructuredItemsToNativeChat +) { + let previous: MessageStream | null = null + return ( + items: readonly AgentJournalRenderItem[], + optimistic: readonly StructuredAgentSessionOptimisticMessage[], + submissions: readonly AgentJournalSubmission[] + ): NativeChatMessage[] => { + const reused = + previous?.optimistic === optimistic && previous.submissions === submissions + ? previous.items === items + ? previous + : reuseMessages(previous, items, projectItems) + : null + previous = + reused ?? + withRowIndex( + projectStructuredAgentSessionMessageRows(items, optimistic, submissions, projectItems), + items, + optimistic, + submissions + ) + return previous.output + } +} diff --git a/src/shared/native-chat/native-chat-provider-retry-runs.ts b/src/shared/native-chat/native-chat-provider-retry-runs.ts index fc496f44b2b..deb63ccae8a 100644 --- a/src/shared/native-chat/native-chat-provider-retry-runs.ts +++ b/src/shared/native-chat/native-chat-provider-retry-runs.ts @@ -4,7 +4,7 @@ import { agentJournalItemSubagentId } from '../agent-session/journal/agent-sessi import type { NativeChatMessage } from './native-chat-types' import { isNativeChatContextClear } from '../agent-session/agent-session-context-clear' -function isProviderRetryRow(message: NativeChatMessage): boolean { +export function isNativeChatProviderRetryRow(message: NativeChatMessage): boolean { const block = message.blocks.length === 1 ? message.blocks[0] : undefined return ( message.role === 'system' && @@ -17,7 +17,7 @@ function isProviderRetryRow(message: NativeChatMessage): boolean { export function collapseProviderRetryRuns( messages: readonly NativeChatMessage[] ): readonly NativeChatMessage[] { - if (!messages.some(isProviderRetryRow)) { + if (!messages.some(isNativeChatProviderRetryRow)) { return messages } // Each agent's open run, as the index of its latest row in `drawn`. @@ -27,7 +27,7 @@ export function collapseProviderRetryRuns( if (isNativeChatContextClear(message)) { openRuns.clear() } - if (!isProviderRetryRow(message)) { + if (!isNativeChatProviderRetryRow(message)) { if (openRuns.size > 0) { openRuns.delete(agentJournalItemSubagentId(message)) } diff --git a/src/shared/native-chat/transcript/native-chat-fold-units.ts b/src/shared/native-chat/transcript/native-chat-fold-units.ts new file mode 100644 index 00000000000..032850e0e15 --- /dev/null +++ b/src/shared/native-chat/transcript/native-chat-fold-units.ts @@ -0,0 +1,223 @@ +import type { NativeChatBlock, NativeChatMessage } from '../native-chat-types' +import { foldToolMessages, type NativeChatToolFoldKind } from '../tools/native-chat-tool-fold' +import { orphanRowId, type NativeChatOrphanOrigin } from '../tools/native-chat-folded-tool-results' + +/** An assistant row with the tool rows it absorbs, or one standalone row; each surface finishes its own rows. */ +export type NativeChatFoldUnit = { + sources: readonly NativeChatMessage[] + rows: NativeChatMessage[] + orphans: readonly NativeChatOrphanOrigin[] +} + +export type NativeChatFoldUnitFinish = (rows: NativeChatMessage[]) => NativeChatMessage[] + +export function groupNativeChatFoldUnitMembers( + grouped: readonly NativeChatMessage[], + kinds: ReadonlyMap +): NativeChatMessage[][] { + const members: NativeChatMessage[][] = [] + let active = false + for (const source of grouped) { + const kind = kinds.get(source)! + if (active && (kind === 'tool' || kind === 'sidecar' || kind === 'pass')) { + members.at(-1)!.push(source) + } else { + members.push([source]) + active = source.role === 'assistant' && kind !== 'orphan' + } + } + return members +} + +export function buildNativeChatFoldUnit( + sources: readonly NativeChatMessage[], + ids: ReadonlySet, + kinds: ReadonlyMap, + before: NativeChatFoldUnit | undefined, + finish: NativeChatFoldUnitFinish +): NativeChatFoldUnit { + if ( + before && + before.sources.length === sources.length && + before.sources.every((source, index) => source === sources[index]) + ) { + return before + } + // A detached result moves blocks out of its run and can drop an emptied head, so those units re-fold. + const substituted = + before && + !before.rows.some((row) => row.unpairedToolResults) && + (substituteProse(before, sources, kinds) ?? substituteTool(before, sources, kinds)) + if (substituted) { + return { sources, rows: finish(substituted), orphans: before!.orphans } + } + const orphans: NativeChatOrphanOrigin[] = [] + const rows = finish(foldToolMessages(sources, ids, kinds, (origin) => orphans.push(origin))) + return { sources, rows, orphans } +} + +export function buildNativeChatFoldUnits( + grouped: readonly NativeChatMessage[], + kinds: ReadonlyMap, + previous: ReadonlyMap, + finish: NativeChatFoldUnitFinish, + ids: ReadonlySet = new Set(grouped.map((row) => row.id)) +): NativeChatFoldUnit[] { + const units = groupNativeChatFoldUnitMembers(grouped, kinds).map((sources) => + buildNativeChatFoldUnit(sources, ids, kinds, previous.get(sources[0]!.id), finish) + ) + if (units.every((unit) => unit.orphans.length === 0)) { + return units + } + const allocated = new Set(ids) + const occurrences = new Map() + return units.map((unit) => { + const renamed = new Map() + const orphans = unit.orphans.map((origin) => { + const id = orphanRowId(origin.sourceId, allocated, occurrences) + allocated.add(id) + if (id === origin.row.id) { + return origin + } + const row = { ...origin.row, id } + renamed.set(origin.row, row) + return { ...origin, row } + }) + return renamed.size === 0 + ? unit + : { + ...unit, + orphans, + rows: unit.rows.map((row) => renamed.get(row) ?? row) + } + }) +} + +/** The one source index that differs, or null when none or several do. */ +function onlyChangedSource( + before: NativeChatFoldUnit, + sources: readonly NativeChatMessage[] +): number | null { + if (before.sources.length !== sources.length) { + return null + } + let changed: number | null = null + for (let index = 0; index < sources.length; index += 1) { + if (sources[index] !== before.sources[index]) { + if (changed !== null) { + return null + } + changed = index + } + } + return changed +} + +function substituteProse( + before: NativeChatFoldUnit, + sources: readonly NativeChatMessage[], + kinds: ReadonlyMap +): NativeChatMessage[] | null { + if (onlyChangedSource(before, sources) !== 0) { + return null + } + const old = before.sources[0]!, + next = sources[0]! + if ( + old.role !== next.role || + (next.role !== 'assistant' && next.role !== 'reasoning') || + old.unpairedToolResults || + next.unpairedToolResults || + !old.blocks.every((block) => block.type === 'text' && !block.providerFrame) || + !next.blocks.every((block) => block.type === 'text' && !block.providerFrame) + ) { + return null + } + const target = before.rows.find((row) => row.id === old.id && row.role === old.role) + if (!target || !old.blocks.every((block, index) => block === target.blocks[index])) { + return null + } + const contribution = sources + .slice(1) + .findLast( + (source) => + source.journalPosition && (kinds.get(source) === 'tool' || kinds.get(source) === 'sidecar') + ) + const replacement: NativeChatMessage = { + ...next, + blocks: [...next.blocks, ...target.blocks.slice(old.blocks.length)], + ...(contribution ? { foldedJournalPosition: contribution.journalPosition } : {}) + } + return before.rows.map((row) => (row === target ? replacement : row)) +} + +/** Pairing reads only tool block order, types and call ids. */ +function sameToolShape( + left: readonly NativeChatBlock[], + right: readonly NativeChatBlock[] +): boolean { + return ( + left.length === right.length && + left.every((block, index) => { + const other = right[index] + return ( + (block.type === 'tool-call' || block.type === 'tool-result') && + (other?.type === 'tool-call' || other?.type === 'tool-result') && + other.type === block.type && + other.callId === block.callId + ) + }) + ) +} + +/** A streamed tool row in a wide run splices its blocks into the folded row instead of re-folding every call. */ +function substituteTool( + before: NativeChatFoldUnit, + sources: readonly NativeChatMessage[], + kinds: ReadonlyMap +): NativeChatMessage[] | null { + const changed = onlyChangedSource(before, sources) + if (!changed || before.orphans.length > 0) { + return null + } + const old = before.sources[changed]!, + next = sources[changed]! + if ( + kinds.get(old) !== 'tool' || + kinds.get(next) !== 'tool' || + !sameToolShape(old.blocks, next.blocks) || + old.journalPosition?.sequence !== next.journalPosition?.sequence || + old.journalPosition?.index !== next.journalPosition?.index + ) { + return null + } + const head = before.sources[0]! + const target = before.rows.find((row) => row.id === head.id && row.role === 'assistant') + if (!target) { + return null + } + // Fold order: the head's blocks, then each tool member's blocks and each sidecar member's results. + let offset = head.blocks.length + for (let index = 1; index < changed; index += 1) { + const member = before.sources[index]! + const kind = kinds.get(member) + offset += + kind === 'tool' + ? member.blocks.length + : kind === 'sidecar' + ? member.blocks.filter((block) => block.type === 'tool-result').length + : 0 + } + if (!old.blocks.every((block, index) => target.blocks[offset + index] === block)) { + return null + } + const replacement: NativeChatMessage = { + ...target, + blocks: [ + ...target.blocks.slice(0, offset), + ...next.blocks, + ...target.blocks.slice(offset + old.blocks.length) + ] + } + return before.rows.map((row) => (row === target ? replacement : row)) +} diff --git a/src/shared/native-chat/transcript/native-chat-message-order.ts b/src/shared/native-chat/transcript/native-chat-message-order.ts index b36af014649..093d621ba1d 100644 --- a/src/shared/native-chat/transcript/native-chat-message-order.ts +++ b/src/shared/native-chat/transcript/native-chat-message-order.ts @@ -7,7 +7,7 @@ import { } from './native-chat-transcript-projection' // Clocks cannot order a null-timestamp preview against a client send or a remote transcript. -function messageSortRank(message: NativeChatMessage): number { +export function nativeChatDisplaySortRank(message: NativeChatMessage): number { if (message.queued || message.pendingSend === 'queued') { return 3 } @@ -28,8 +28,8 @@ export function compareNativeChatDisplayMessages( a: NativeChatMessage, b: NativeChatMessage ): number { - const rank = messageSortRank(a) - const difference = rank - messageSortRank(b) + const rank = nativeChatDisplaySortRank(a) + const difference = rank - nativeChatDisplaySortRank(b) return difference || (rank === 0 ? compareNativeChatTranscriptMessages(a, b) : 0) } @@ -38,7 +38,7 @@ export function orderNativeChatDisplayEntries( messageOf: (entry: T) => NativeChatMessage ): T[] { return [0, 1, 2, 3].flatMap((rank) => { - const tier = entries.filter((entry) => messageSortRank(messageOf(entry)) === rank) + const tier = entries.filter((entry) => nativeChatDisplaySortRank(messageOf(entry)) === rank) return rank === 0 ? orderNativeChatTranscriptEntries(tier, messageOf) : tier }) } diff --git a/src/shared/native-chat/transcript/native-chat-transcript-projection.ts b/src/shared/native-chat/transcript/native-chat-transcript-projection.ts index a27b75bc979..3eb2fa414d2 100644 --- a/src/shared/native-chat/transcript/native-chat-transcript-projection.ts +++ b/src/shared/native-chat/transcript/native-chat-transcript-projection.ts @@ -61,6 +61,36 @@ export function compareNativeChatTranscriptMessages( type NativeChatMessageCompare = (a: NativeChatMessage, b: NativeChatMessage) => number +/** Every field but the blocks agrees, so a revision keeps its place and attribution among the other rows. */ +export function sameNativeChatRowPlacement( + before: NativeChatMessage, + next: NativeChatMessage +): boolean { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Runtime keys are used only for equality, including any extra message fields. + const keys = Object.keys(before) as (keyof NativeChatMessage)[] + return ( + keys.length === Object.keys(next).length && + keys.every((key) => { + if (!Object.hasOwn(next, key)) { + return false + } + if (key === 'blocks') { + return true + } + if (key === 'journalPosition') { + return ( + before.journalPosition?.sequence === next.journalPosition?.sequence && + before.journalPosition?.index === next.journalPosition?.index + ) + } + // Journal creation position, rather than a revised provider clock, orders these rows. + return key === 'timestamp' && before.journalPosition && next.journalPosition + ? true + : before[key] === next[key] + }) + ) +} + /** One of a subagent's rows, with the conversation turn it happened during. */ export type NativeChatSubagentRow = { message: NativeChatMessage @@ -131,7 +161,9 @@ export function projectNativeChatTranscript( compare: NativeChatMessageCompare = compareNativeChatTranscriptMessages, journal?: NativeChatTurnJournal | null, order = (rows: readonly NativeChatMessage[]) => - orderNativeChatTranscriptEntries(rows, (row) => row, compare) + orderNativeChatTranscriptEntries(rows, (row) => row, compare), + /** Folds one scope: the conversation, or one subagent's rows within one parent turn. */ + projectScope: (rows: readonly NativeChatMessage[]) => NativeChatMessage[] = projectRows ): NativeChatTranscriptProjection { const sorted = order(messages) const own: NativeChatMessage[] = [] @@ -149,7 +181,7 @@ export function projectNativeChatTranscript( } } } - const conversation = projectRows(own) + const conversation = projectScope(own) if (byAgent.size === 0) { return { conversation, subagentRows: NO_SUBAGENT_ROWS } } @@ -168,7 +200,7 @@ export function projectNativeChatTranscript( let chunk: NativeChatMessage[] = [] let chunkTurn: string | undefined const flush = (): void => { - for (const message of projectRows(chunk)) { + for (const message of projectScope(chunk)) { projected.push({ message, turnKey: chunkTurn }) } chunk = [] diff --git a/src/shared/structured-agent-question-projection.ts b/src/shared/structured-agent-question-projection.ts index 75f4d990ee5..e24966a0079 100644 --- a/src/shared/structured-agent-question-projection.ts +++ b/src/shared/structured-agent-question-projection.ts @@ -172,6 +172,102 @@ function projectQuestions( return { messages, receipts } } +/** Whether revising or appending this item leaves every other row's question grouping and receipts as they were. */ +export function isQuestionNeutralAgentJournalItem(item: AgentJournalRenderItem): boolean { + const { body } = item + return ( + body.kind !== 'question' && + body.kind !== 'approval' && + !(body.kind === 'tool-call' && isAskUserQuestionTool(body.name)) + ) +} + +/** Both revisions delimit question turns alike: a user row by its id, a turn record by its turnId. */ +export function sameQuestionTurnBoundary( + before: AgentJournalRenderItem, + after: AgentJournalRenderItem +): boolean { + return ( + before.itemId === after.itemId && + before.body.kind === after.body.kind && + (before.body.kind !== 'message' || + (after.body.kind === 'message' && before.body.role === after.body.role)) && + readAgentJournalTurn(before.body)?.turnId === readAgentJournalTurn(after.body)?.turnId + ) +} + +type QuestionTranscript = ReturnType +type QuestionStreamState = { + items: readonly AgentJournalRenderItem[] + projection: QuestionTranscript + /** Each item's row in `projection.messages`, or -1 when it draws none. */ + rowOf: number[] +} + +function questionRowIndexes( + items: readonly AgentJournalRenderItem[], + messages: readonly NativeChatMessage[], + project: (item: AgentJournalRenderItem) => Projection +): number[] { + let next = 0 + return items.map((item) => { + const message = project(item).message + return message !== null && messages[next] === message ? next++ : -1 + }) +} + +function reuseQuestions( + previous: QuestionStreamState, + items: readonly AgentJournalRenderItem[], + project: (item: AgentJournalRenderItem) => Projection +): QuestionStreamState | null { + if (items.length < previous.items.length) { + return null + } + let messages: NativeChatMessage[] | null = null + for (let index = 0; index < previous.items.length; index += 1) { + const before = previous.items[index]! + const item = items[index]! + if (before === item) { + continue + } + if ( + !isQuestionNeutralAgentJournalItem(before) || + !isQuestionNeutralAgentJournalItem(item) || + !sameQuestionTurnBoundary(before, item) + ) { + return null + } + const old = project(before).message + const next = project(item).message + const row = previous.rowOf[index]! + if ((old === null) !== (next === null) || (old && previous.projection.messages[row] !== old)) { + return null + } + if (next) { + ;(messages ??= previous.projection.messages.slice())[row] = next + } + } + let rowOf = previous.rowOf + for (let index = previous.items.length; index < items.length; index += 1) { + const item = items[index]! + if (!isQuestionNeutralAgentJournalItem(item)) { + return null + } + const message = project(item).message + messages ??= previous.projection.messages.slice() + rowOf = rowOf === previous.rowOf ? rowOf.slice() : rowOf + rowOf.push(message ? messages.push(message) - 1 : -1) + } + return { + items, + projection: messages + ? { messages, receipts: previous.projection.receipts } + : previous.projection, + rowOf + } +} + /** Each surface owns caches for the item interpretation it renders. */ export function createStructuredQuestionProjection( projectMessage: ItemProjector = projectStructuredItemToNativeChat @@ -190,8 +286,30 @@ export function createStructuredQuestionProjection( } return projection } + /** One consumer's transcript across commits: question-neutral revisions and appends reuse its rows and receipts. */ + const stream = () => { + let previous: QuestionStreamState | null = null + return (items: readonly AgentJournalRenderItem[]): QuestionTranscript => { + if (previous?.items === items) { + return previous.projection + } + const reused = previous && reuseQuestions(previous, items, project) + if (reused) { + previous = reused + } else { + const projection = transcript(items) + previous = { + items, + projection, + rowOf: questionRowIndexes(items, projection.messages, project) + } + } + return previous.projection + } + } return { transcript, + stream, messages: (items: readonly AgentJournalRenderItem[]) => transcript(items).messages } }