From 20366fa992f5ee815308fde959dc729adcb533c1 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:18:07 +0000 Subject: [PATCH] fix(native-chat): show the reply before a background task hand-back in terminal chats (#42932) * fix(native-chat): keep the reply before a background task hand-back in terminal chats Claude's task-notification record opens a new turn, but the chat transcript decoder dropped it, so the hand-back reply joined the prompt's turn and the turn fold hid the reply before it. Chat reads now keep a wordless turn marker there, and journal-less turn grouping and timing start a turn at it. * fix(native-chat): keep tool results a task notification delivers mid-turn * fix(native-chat): draw only the bar for the turn marker on mobile, not every empty system row --- .../messages/MobileNativeChatMessage.tsx | 5 +- .../claude-internal-message-content.ts | 11 ++ .../transcripts/claude-transcript-prompt.ts | 10 +- .../transcript-line-decoders-claude.ts | 36 ++++- .../transcript-hand-back-turns.test.ts | 144 ++++++++++++++++++ src/main/native-chat/transcript-reader.ts | 8 +- .../native-chat/transcript-tail-reader.ts | 4 +- .../transcripts/worker-transcript-read.ts | 7 +- src/shared/native-chat/native-chat-noise.ts | 3 +- .../native-chat/native-chat-terminal-turn.ts | 11 +- .../row-content/native-chat-row-content.ts | 5 +- .../turns/native-chat-provider-turn-start.ts | 17 +++ .../turns/native-chat-turn-grouping.ts | 26 +++- .../turns/native-chat-turn-membership.ts | 12 +- 14 files changed, 268 insertions(+), 31 deletions(-) create mode 100644 src/main/native-chat/transcript-hand-back-turns.test.ts create mode 100644 src/shared/native-chat/transcript/turns/native-chat-provider-turn-start.ts diff --git a/mobile/src/session/native-chat/transcript/messages/MobileNativeChatMessage.tsx b/mobile/src/session/native-chat/transcript/messages/MobileNativeChatMessage.tsx index 6a2d8c514cd..254b94d083b 100644 --- a/mobile/src/session/native-chat/transcript/messages/MobileNativeChatMessage.tsx +++ b/mobile/src/session/native-chat/transcript/messages/MobileNativeChatMessage.tsx @@ -11,6 +11,7 @@ import { withoutSubagentGroupTwins } from '../../../../../../src/shared/native-chat/transcript/subagents/native-chat-subagent-summary' import { deriveNativeChatRowContent } from '../../../../../../src/shared/native-chat/transcript/row-content/native-chat-row-content' +import { isNativeChatProviderTurnStart } from '../../../../../../src/shared/native-chat/transcript/turns/native-chat-provider-turn-start' import { MobileNativeChatGroupedThought, MobileNativeChatReasoningRow @@ -203,8 +204,8 @@ function MobileNativeChatMessageImpl({ onToggleExpanded={turnKey && onToggleTurn ? () => onToggleTurn(turnKey) : undefined} /> ) : null - // Keep answered receipts visible even when their tool run folds away. - if (joinsWorkRun || (foldedAway && !receipt)) { + // Keep answered receipts visible even when their tool run folds away; a provider turn mark draws only its bar. + if (joinsWorkRun || (foldedAway && !receipt) || isNativeChatProviderTurnStart(message)) { return <>{statusRow} } if (receipt) { diff --git a/src/main/claude/structured/journal/claude-internal-message-content.ts b/src/main/claude/structured/journal/claude-internal-message-content.ts index 9a834efd669..6cee01c3533 100644 --- a/src/main/claude/structured/journal/claude-internal-message-content.ts +++ b/src/main/claude/structured/journal/claude-internal-message-content.ts @@ -26,6 +26,17 @@ export function isClaudeInjectedUserMessage(frame: Record): boo ) } +/** A delivered task notification: Claude resuming on its own, a turn no prompt opened. */ +export function isClaudeTaskNotificationTurnStart(frame: Record): boolean { + return ( + frame.type === 'user' && + asRecord(frame.origin)?.kind === 'task-notification' && + frame.isMeta !== true && + frame.isSynthetic !== true && + frame.isCompactSummary !== true + ) +} + /** Resume repair text is not conversation; semantic siblings still take their normal paths. */ export function claudeMessageWithoutSyntheticText( frame: Record diff --git a/src/main/claude/transcripts/claude-transcript-prompt.ts b/src/main/claude/transcripts/claude-transcript-prompt.ts index 492baa69221..90df70ac045 100644 --- a/src/main/claude/transcripts/claude-transcript-prompt.ts +++ b/src/main/claude/transcripts/claude-transcript-prompt.ts @@ -1,8 +1,8 @@ import { isClaudeToolResultContent } from '../../../shared/agent-hook-listener/providers/claude/transcripts/claude-tool-content' import { decodeClaudeTranscriptLine } from '../../native-chat/transcript-decoding/transcript-line-decoders-claude' import { claudeEnvelopeStopHookFeedbackRow } from '../structured/journal/claude-stop-hook-feedback' +import { isClaudeTaskNotificationTurnStart } from '../structured/journal/claude-internal-message-content' import { - claudeRecord, claudeOutputEnvelope, type ClaudeMessageEnvelope } from '../structured/journal/claude-structured-item-translation' @@ -30,13 +30,7 @@ export function claudeTranscriptPrompt( return { decoded, ignored: prompt && (!decoded || decoded.role === 'system'), - internalTurnStart: - candidate && - row.type === 'user' && - claudeRecord(row.origin)?.kind === 'task-notification' && - row.isMeta !== true && - row.isSynthetic !== true && - row.isCompactSummary !== true, + internalTurnStart: candidate && isClaudeTaskNotificationTurnStart(row), hasWork: Boolean(envelope && (claudeOutputEnvelope(envelope).content.length || feedback)) } } diff --git a/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude.ts b/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude.ts index 85c1609e7b3..fac0dbd32fb 100644 --- a/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude.ts +++ b/src/main/native-chat/transcript-decoding/transcript-line-decoders-claude.ts @@ -11,6 +11,7 @@ import { parseJsonObject } from '../../ai-vault/parsing/session-json-object' import { timestampMs } from '../../ai-vault/parsing/session-record-time' import { imageSourcePathFromText } from '../../../shared/native-chat/transcript/images/native-chat-image-transcript-markers' import { claudeContentBlocks } from './transcript-record-blocks' +import { isClaudeToolResultContent } from '../../../shared/agent-hook-listener/providers/claude/transcripts/claude-tool-content' import { isKnownRasterImageMimeType } from '../../../shared/file-preview/raster-image-preview-limits' import { unwrapClaudePastedContentBlock } from '../../../shared/agent-hook-listener/providers/claude/transcripts/claude-pasted-content' import { unwrapClaudeBashInputBlock } from '../../../shared/agent-hook-listener/providers/claude/transcripts/claude-bash-input' @@ -19,8 +20,10 @@ import { claudeStopHookFeedbackRow } from '../../claude/structured/journal/claud import { structuredAgentSessionStatusBlock } from '../../../shared/agent-session/view/structured-agent-session-status-block' import { claudeMessageWithoutSyntheticText, - isClaudeInjectedUserMessage + isClaudeInjectedUserMessage, + isClaudeTaskNotificationTurnStart } from '../../claude/structured/journal/claude-internal-message-content' +import { NATIVE_CHAT_PROVIDER_TURN_START_PRESENTATION } from '../../../shared/native-chat/transcript/turns/native-chat-provider-turn-start' const MAX_EDIT_PATCH_HUNKS = 40 const MAX_EDIT_PATCH_HUNK_LINES = 400 @@ -140,6 +143,37 @@ export function decodeClaudeTranscriptLine( } } +/** Chat reads keep where Claude resumed on its own, so journal-less turns split there as structured turns do. */ +export function decodeClaudeChatTranscriptLine( + line: string, + fallbackId: string +): NativeChatMessage | null { + const record = line.includes('task-notification') ? parseJsonObject(line) : null + const content = asRecord(record?.message)?.content + // One row per record: a notification that also settles a waiting call keeps its results instead. + if ( + !record || + !isClaudeTaskNotificationTurnStart(record) || + (Array.isArray(content) && content.some(isClaudeToolResultContent)) + ) { + return decodeClaudeTranscriptLine(line, fallbackId) + } + return { + id: extractString(record.uuid) ?? fallbackId, + role: 'system', + // Harness text: clients that predate the marker strip it as an injected turn. + blocks: [ + { + type: 'text', + text: '', + presentation: NATIVE_CHAT_PROVIDER_TURN_START_PRESENTATION + } + ], + timestamp: parseTimestamp(record.timestamp), + source: 'transcript' + } +} + /** Mid-turn human prompts exist only as queued_command attachments; decode them to reconcile local echoes. */ function claudeQueuedPromptAsUserRecord( record: Record diff --git a/src/main/native-chat/transcript-hand-back-turns.test.ts b/src/main/native-chat/transcript-hand-back-turns.test.ts new file mode 100644 index 00000000000..3a788fdb761 --- /dev/null +++ b/src/main/native-chat/transcript-hand-back-turns.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, it } from 'vitest' + +import { nativeChatLineDecoderForAgent } from './transcript-tail-reader' +import { projectNativeChatTranscriptMessages } from '../../shared/native-chat/transcript/native-chat-transcript-projection' +import { nativeChatTurnMembership } from '../../shared/native-chat/transcript/turns/native-chat-turn-membership' +import { nativeChatTranscriptSettledTurns } from '../../shared/native-chat/native-chat-terminal-turn' +import { + nativeChatTurnFold, + nativeChatTurnFoldRow +} from '../../shared/native-chat/transcript/folding/native-chat-turn-fold' + +// Claude Code 2.1.314 record shapes: a background Agent, reply A, then the task notification that opens reply B's turn. +const TRANSCRIPT = [ + { + type: 'user', + uuid: 'prompt', + origin: { kind: 'human' }, + timestamp: '2026-11-10T16:37:18.178Z', + message: { + role: 'user', + content: [{ type: 'text', text: 'Survey the repo in the background' }] + } + }, + { + type: 'assistant', + uuid: 'spawn', + parentUuid: 'prompt', + timestamp: '2026-11-10T16:37:56.536Z', + message: { + id: 'msg_1', + role: 'assistant', + stop_reason: 'tool_use', + content: [ + { + type: 'tool_use', + id: 'toolu_1', + name: 'Agent', + input: { description: 'Survey', prompt: 'Survey the repo', run_in_background: true } + } + ] + } + }, + { + type: 'user', + uuid: 'spawn-result', + parentUuid: 'spawn', + timestamp: '2026-11-10T16:37:56.647Z', + message: { + role: 'user', + content: [ + { + type: 'tool_result', + tool_use_id: 'toolu_1', + content: [{ type: 'text', text: 'Async agent launched successfully.' }] + } + ] + } + }, + { + type: 'assistant', + uuid: 'reply-a', + parentUuid: 'spawn-result', + timestamp: '2026-11-10T16:38:11.321Z', + message: { + id: 'msg_2', + role: 'assistant', + stop_reason: 'end_turn', + content: [{ type: 'text', text: 'I started a survey agent.' }] + } + }, + { + type: 'user', + uuid: 'hand-back', + parentUuid: 'reply-a', + promptId: 'prompt-2', + origin: { kind: 'task-notification', producer: 'session-task', runId: 'run-1' }, + timestamp: '2026-11-10T16:39:53.424Z', + message: { + role: 'user', + content: + '\nt1\ntoolu_1\ncompleted\nAgent "Survey" finished\nDone.\n' + } + }, + { + type: 'assistant', + uuid: 'reply-b', + parentUuid: 'hand-back', + timestamp: '2026-11-10T16:39:56.981Z', + message: { + id: 'msg_3', + role: 'assistant', + stop_reason: 'end_turn', + content: [{ type: 'text', text: 'The survey is back.' }] + } + } +] + +describe('Claude chat transcript with a background task hand-back', () => { + it('keeps the reply before the hand-back as its own turn’s answer', () => { + const decode = nativeChatLineDecoderForAgent('claude')! + const raw = TRANSCRIPT.flatMap( + (record, index) => decode(JSON.stringify(record), `line-${index}`) ?? [] + ) + const rows = projectNativeChatTranscriptMessages(raw) + const { turnKeys } = nativeChatTurnMembership(rows, null) + const settled = nativeChatTranscriptSettledTurns(raw) + const fold = nativeChatTurnFold({ + rows: rows.map((row, index) => nativeChatTurnFoldRow(row, turnKeys[index], false)), + settledTurnKeys: new Set(['prompt', 'hand-back']), + expandedTurnKeys: new Set() + }) + + expect(rows.map((row, index) => [row.id, turnKeys[index]])).toEqual([ + ['prompt', 'prompt'], + ['spawn', 'prompt'], + ['reply-a', 'prompt'], + ['hand-back', 'hand-back'], + ['reply-b', 'hand-back'] + ]) + expect([...fold.foldedRows].map((index) => rows[index]!.id)).toEqual(['spawn']) + expect(settled.get('prompt')?.workedSeconds).toBe(53) + }) + + it('keeps the tool result a notification delivers to a waiting call', () => { + const decode = nativeChatLineDecoderForAgent('claude')! + const mixed = { + ...TRANSCRIPT[4], + message: { + role: 'user', + content: [ + { + type: 'text', + text: '\nt1\n' + }, + { type: 'tool_result', tool_use_id: 'toolu_2', content: 'real result' } + ] + } + } + expect(decode(JSON.stringify(mixed), 'line-0')).toMatchObject({ + role: 'tool', + blocks: [{ type: 'tool-result', output: 'real result' }] + }) + }) +}) diff --git a/src/main/native-chat/transcript-reader.ts b/src/main/native-chat/transcript-reader.ts index efb401c12cb..af8ab32637e 100644 --- a/src/main/native-chat/transcript-reader.ts +++ b/src/main/native-chat/transcript-reader.ts @@ -10,7 +10,7 @@ import { errorMessage } from '../../shared/errors/error-message' import { resolveSessionFilePath, type ResolveSessionFileOptions } from './session-file-resolver' import { openTranscriptReadStream } from './transcript-filesystem/wsl-transcript-fs-access' import { wslTranscriptFsRefusal } from './transcript-filesystem/wsl-transcript-fs-error' -import { decodeClaudeTranscriptLine } from './transcript-decoding/transcript-line-decoders-claude' +import { decodeClaudeChatTranscriptLine } from './transcript-decoding/transcript-line-decoders-claude' import { decodeCodexTranscriptLine } from './transcript-decoding/transcript-line-decoders-codex' import { decodeGrokTranscriptLine } from './transcript-decoding/transcript-line-decoders-grok' import { decodeOmpTranscriptLine } from './transcript-decoding/transcript-line-decoders-omp' @@ -59,7 +59,11 @@ export async function readNativeChatTranscript( const transcriptAgent = resolveNativeChatTranscriptAgent(agent) if (transcriptAgent === 'claude') { return { - messages: await readTranscript(filePath, decodeClaudeTranscriptLine, options.sourceOrder) + messages: await readTranscript( + filePath, + decodeClaudeChatTranscriptLine, + options.sourceOrder + ) } } if (transcriptAgent === 'codex') { diff --git a/src/main/native-chat/transcript-tail-reader.ts b/src/main/native-chat/transcript-tail-reader.ts index e6f32d41d6c..c1a7fdaf030 100644 --- a/src/main/native-chat/transcript-tail-reader.ts +++ b/src/main/native-chat/transcript-tail-reader.ts @@ -7,7 +7,7 @@ import type { } from '../../shared/native-chat/native-chat-types' import { resolveNativeChatTranscriptAgent } from '../../shared/native-chat/native-chat-agent-support' import { resolveSessionFilePath, type ResolveSessionFileOptions } from './session-file-resolver' -import { decodeClaudeTranscriptLine } from './transcript-decoding/transcript-line-decoders-claude' +import { decodeClaudeChatTranscriptLine } from './transcript-decoding/transcript-line-decoders-claude' import { decodeCodexTranscriptLine } from './transcript-decoding/transcript-line-decoders-codex' import { decodeGrokTranscriptLine } from './transcript-decoding/transcript-line-decoders-grok' import { decodeOmpTranscriptLine } from './transcript-decoding/transcript-line-decoders-omp' @@ -38,7 +38,7 @@ export type NativeChatLineDecoder = (line: string, fallbackId: string) => Native export function nativeChatLineDecoderForAgent(agent: AgentType): NativeChatLineDecoder | null { const transcriptAgent = resolveNativeChatTranscriptAgent(agent) if (transcriptAgent === 'claude') { - return decodeClaudeTranscriptLine + return decodeClaudeChatTranscriptLine } if (transcriptAgent === 'codex') { return decodeCodexTranscriptLine diff --git a/src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.ts b/src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.ts index 962d0e4d760..741ae6b6b26 100644 --- a/src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.ts +++ b/src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.ts @@ -4,6 +4,7 @@ import { resolveNativeChatTranscriptAgent } from '../../../../../shared/native-c import type { OrchestrationWorkerReadFallbackReason } from '../../../../../shared/orchestration/workers/orchestration-worker-output' import { resolveSessionFilePath } from '../../../../native-chat/session-file-resolver' import { nativeChatLineDecoderForAgent } from '../../../../native-chat/transcript-tail-reader' +import { decodeClaudeTranscriptLine } from '../../../../native-chat/transcript-decoding/transcript-line-decoders-claude' import { boundWorkerTranscriptMessages, clampWorkerTranscriptLimit @@ -55,7 +56,11 @@ export async function readWorkerTranscript(args: { if (!transcriptAgent) { return { ok: false, reason: 'provider_unsupported', warnings: [] } } - const decode = nativeChatLineDecoderForAgent(args.agent) + // Workers read text; the chat's wordless turn markers have none to give. + const decode = + transcriptAgent === 'claude' + ? decodeClaudeTranscriptLine + : nativeChatLineDecoderForAgent(args.agent) if (!decode) { return { ok: false, reason: 'provider_unsupported', warnings: [] } } diff --git a/src/shared/native-chat/native-chat-noise.ts b/src/shared/native-chat/native-chat-noise.ts index 0a97e9383f8..ed5b413c1f3 100644 --- a/src/shared/native-chat/native-chat-noise.ts +++ b/src/shared/native-chat/native-chat-noise.ts @@ -1,5 +1,6 @@ import { isKnownHarnessInjectedUserTurnText } from '../harness-injected-user-turns' import { isTextBlock, type NativeChatMessage } from './native-chat-types' +import { isNativeChatProviderTurnStart } from './transcript/turns/native-chat-provider-turn-start' function messageText(message: NativeChatMessage): string { return message.blocks @@ -11,7 +12,7 @@ function messageText(message: NativeChatMessage): string { /** Harness-injected user/system turns are transport machinery, not conversation. */ export function isNoiseMessage(message: NativeChatMessage): boolean { - if (message.agentStart) { + if (message.agentStart || isNativeChatProviderTurnStart(message)) { return false } if (message.role !== 'user' && message.role !== 'system') { diff --git a/src/shared/native-chat/native-chat-terminal-turn.ts b/src/shared/native-chat/native-chat-terminal-turn.ts index 2c503fc4467..871d9e5a9f4 100644 --- a/src/shared/native-chat/native-chat-terminal-turn.ts +++ b/src/shared/native-chat/native-chat-terminal-turn.ts @@ -5,6 +5,7 @@ import type { NativeChatSettledTurns } from './transcript/turns/native-chat-turn-status' import { isNoiseMessage } from './native-chat-noise' +import { isNativeChatProviderTurnStart } from './transcript/turns/native-chat-provider-turn-start' import { shouldShowNativeChatWorking } from './native-chat-working-suppression' /** shown prompts have a card in this pane; unshown prompts require input in the agent’s terminal. */ @@ -78,9 +79,13 @@ export function nativeChatHookLatestTurnWorkedSeconds( return hookSilent ? null : undefined } +/** A prompt the transcript draws, or the host's mark that the agent resumed on its own. */ +function opensTerminalTurn(message: NativeChatMessage): boolean { + return message.role === 'user' ? !isNoiseMessage(message) : isNativeChatProviderTurnStart(message) +} + export function nativeChatLatestTurnId(messages: readonly NativeChatMessage[]): string | null { - const latest = messages.findLast((message) => message.role === 'user' && !isNoiseMessage(message)) - return latest?.id ?? null + return messages.findLast(opensTerminalTurn)?.id ?? null } /** Time finished turns within the transcript clock; ignore unrelated system rows and omit the latest or incomplete turn to preserve pane observations. */ @@ -91,7 +96,7 @@ export function nativeChatTranscriptSettledTurns( let turn: { id: string; startedAt: number | null; endedAt: number | null } | null = null for (const message of messages) { // A harness notice is user-role but draws no row, so it neither starts nor extends a turn. - if (message.role !== 'user' || isNoiseMessage(message)) { + if (!opensTerminalTurn(message)) { const agentRow = message.role === 'system' ? isInterruptedStatusMessage(message) : message.role !== 'user' if (turn && agentRow && message.timestamp != null) { diff --git a/src/shared/native-chat/transcript/row-content/native-chat-row-content.ts b/src/shared/native-chat/transcript/row-content/native-chat-row-content.ts index fc815d234a8..fa98cf26aec 100644 --- a/src/shared/native-chat/transcript/row-content/native-chat-row-content.ts +++ b/src/shared/native-chat/transcript/row-content/native-chat-row-content.ts @@ -6,6 +6,7 @@ import { withoutBackgroundTaskRows } from '../../input/task-lists/native-chat-background-task-row' import { isWordlessProviderFrameBlock } from '../../native-chat-provider-frame-summary' +import { isNativeChatProviderTurnStartBlock } from '../turns/native-chat-provider-turn-start' import { isReplacedSubagentGroupTwin, subagentGroupBlocks @@ -27,7 +28,9 @@ function readMarkdown(this: { prose: NativeChatBlock[] }): string { function derive(blocks: readonly NativeChatBlock[]) { const split = splitNativeChatBlocks( - blocks.filter((block) => !isWordlessProviderFrameBlock(block)) + blocks.filter( + (block) => !isWordlessProviderFrameBlock(block) && !isNativeChatProviderTurnStartBlock(block) + ) ) const groups = subagentGroupBlocks(split.prose) const tasks = backgroundTaskBlocks(split.prose) diff --git a/src/shared/native-chat/transcript/turns/native-chat-provider-turn-start.ts b/src/shared/native-chat/transcript/turns/native-chat-provider-turn-start.ts new file mode 100644 index 00000000000..96eb60f023d --- /dev/null +++ b/src/shared/native-chat/transcript/turns/native-chat-provider-turn-start.ts @@ -0,0 +1,17 @@ +import type { NativeChatBlock, NativeChatMessage } from '../../native-chat-types' + +/** Journal-less transcripts mark where the agent resumed on its own, such as a background task's hand-back. */ +export const NATIVE_CHAT_PROVIDER_TURN_START_PRESENTATION = 'provider-turn-start' + +export function isNativeChatProviderTurnStartBlock(block: NativeChatBlock): boolean { + return ( + block.type === 'text' && block.presentation === NATIVE_CHAT_PROVIDER_TURN_START_PRESENTATION + ) +} + +/** Opens a turn and draws nothing but that turn's bar. */ +export function isNativeChatProviderTurnStart( + message: Pick +): boolean { + return message.role === 'system' && message.blocks.some(isNativeChatProviderTurnStartBlock) +} diff --git a/src/shared/native-chat/transcript/turns/native-chat-turn-grouping.ts b/src/shared/native-chat/transcript/turns/native-chat-turn-grouping.ts index 881e70c787b..ae06c784625 100644 --- a/src/shared/native-chat/transcript/turns/native-chat-turn-grouping.ts +++ b/src/shared/native-chat/transcript/turns/native-chat-turn-grouping.ts @@ -2,10 +2,16 @@ import type { AgentJournalRenderItem } from '../../../agent-session/journal/agent-session-journal-types' import { readAgentJournalTurn } from '../../../agent-session/lifecycle/records/agent-session-turn-record' -import type { NativeChatRole } from '../../native-chat-types' +import type { NativeChatMessage, NativeChatRole } from '../../native-chat-types' +import { isNativeChatProviderTurnStart } from './native-chat-provider-turn-start' type NativeChatTurnRow = { id: string; role: NativeChatRole } +export type NativeChatTurnMember = Pick< + NativeChatMessage, + 'id' | 'role' | 'blocks' | 'unsent' | 'journalPosition' +> + /** Which rows can open a turn by themselves: in a conversation, its user rows. */ export type NativeChatOpensTurn = (message: NativeChatTurnRow) => boolean @@ -13,10 +19,10 @@ export const nativeChatUserRowOpensTurn: NativeChatOpensTurn = (message) => mess /** Host turn attribution wins over mid-turn send position. Unmapped rows use preceding-user grouping; * opensTurn restricts which unmapped rows can anchor turns in interleaved streams. */ -export function nativeChatRowTurnKeys( - messages: readonly NativeChatTurnRow[], +export function nativeChatRowTurnKeys( + messages: readonly Row[], turnKeysByItemId?: ReadonlyMap | null, - opensTurn: NativeChatOpensTurn = nativeChatUserRowOpensTurn + opensTurn: (message: Row) => boolean = nativeChatUserRowOpensTurn ): (string | undefined)[] { let currentTurnKey: string | undefined return messages.map((message) => { @@ -32,6 +38,18 @@ export function nativeChatRowTurnKeys( }) } +/** Without turn records, the host marks where the agent resumed on its own, and that opens a turn too. */ +export function nativeChatPositionalTurnKeys( + messages: readonly NativeChatTurnMember[], + opensTurn: NativeChatOpensTurn +): (string | undefined)[] { + return nativeChatRowTurnKeys( + messages, + null, + (message) => opensTurn(message) || isNativeChatProviderTurnStart(message) + ) +} + /** Legacy unscoped hosts assign rows between root records to that turn’s mapped opener. Openers key themselves; * steers inherit only after later turn content proves continuation, so fresh tail sends keep waiting. Rows before the first record remain unmapped. */ export function nativeChatJournalOrderTurnKeys( diff --git a/src/shared/native-chat/transcript/turns/native-chat-turn-membership.ts b/src/shared/native-chat/transcript/turns/native-chat-turn-membership.ts index 3d20162c9fe..e53de9e02fd 100644 --- a/src/shared/native-chat/transcript/turns/native-chat-turn-membership.ts +++ b/src/shared/native-chat/transcript/turns/native-chat-turn-membership.ts @@ -16,12 +16,14 @@ import type { import { readAgentJournalTurn } from '../../../agent-session/lifecycle/records/agent-session-turn-record' import { nativeChatJournalOrderTurnKeys, + nativeChatPositionalTurnKeys, nativeChatRowTurnKeys, nativeChatTurnDrawOrder, nativeChatUserRowOpensTurn, - type NativeChatOpensTurn + type NativeChatOpensTurn, + type NativeChatTurnMember } from './native-chat-turn-grouping' -import type { NativeChatMessage, NativeChatRole } from '../../native-chat-types' +import type { NativeChatRole } from '../../native-chat-types' import { dispatchWasWithdrawn } from '../../../agent-session/requests/structured-agent-session-dispatch-rejection' import { inSendOrder } from '../../native-chat-send-order' import { runningStructuredAgentSessionTurnScope } from '../../../agent-session/view/structured-agent-session-live-turn' @@ -235,8 +237,6 @@ export type NativeChatTurnMembership = { unresolvedRowIds?: ReadonlySet } -type NativeChatTurnMember = Pick - /** Anchoring/unscoped user entries key themselves; steers take their owning turn. Legacy hosts use journal-order keys. * opensTurn narrows anchors in interleaved streams; unsent messages belong to no turn and never become live. */ export function nativeChatTurnMembership( @@ -246,10 +246,10 @@ export function nativeChatTurnMembership( ): NativeChatTurnMembership { const opens: NativeChatOpensTurn = (message) => !isUnsent(message) && opensTurn(message) if (!journal) { - const turnKeys = withoutUnsent(messages, nativeChatRowTurnKeys(messages, null, opens)) + const turnKeys = withoutUnsent(messages, nativeChatPositionalTurnKeys(messages, opens)) return { turnKeys, - liveTurnKey: newestNativeChatUserTurnKey(messages, turnKeys), + liveTurnKey: turnKeys.findLast((turnKey) => turnKey !== undefined), drawOrder: null } }