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
This commit is contained in:
Kelvin Amoaba
2026-11-16 03:18:07 +00:00
committed by GitHub
parent 1f72e79911
commit 20366fa992
14 changed files with 268 additions and 31 deletions
@@ -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) {
@@ -26,6 +26,17 @@ export function isClaudeInjectedUserMessage(frame: Record<string, unknown>): boo
)
}
/** A delivered task notification: Claude resuming on its own, a turn no prompt opened. */
export function isClaudeTaskNotificationTurnStart(frame: Record<string, unknown>): 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<string, unknown>
@@ -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))
}
}
@@ -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: '<task-notification>',
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<string, unknown>
@@ -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:
'<task-notification>\n<task-id>t1</task-id>\n<tool-use-id>toolu_1</tool-use-id>\n<status>completed</status>\n<summary>Agent "Survey" finished</summary>\n<result>Done.</result>\n</task-notification>'
}
},
{
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: '<task-notification>\n<task-id>t1</task-id>\n</task-notification>'
},
{ 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' }]
})
})
})
+6 -2
View File
@@ -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') {
@@ -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
@@ -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: [] }
}
+2 -1
View File
@@ -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') {
@@ -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) {
@@ -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)
@@ -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<NativeChatMessage, 'role' | 'blocks'>
): boolean {
return message.role === 'system' && message.blocks.some(isNativeChatProviderTurnStartBlock)
}
@@ -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<Row extends NativeChatTurnRow>(
messages: readonly Row[],
turnKeysByItemId?: ReadonlyMap<string, string> | 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(
@@ -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<string>
}
type NativeChatTurnMember = Pick<NativeChatMessage, 'id' | 'role' | 'unsent' | 'journalPosition'>
/** 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
}
}