From 91e428bfe482bac7ba5d599a7ecf71c770de5342 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 1 Nov 2026 05:45:54 +0000 Subject: [PATCH 1/5] fix(native-chat): keep a Claude reply visible when a Stop hook sends Claude back Claude writes a blocking Stop hook's reason as an injected user turn, which both Claude decoders dropped. The settled-turn fold then took the post-hook continuation as the turn's only answer and folded the real reply away. Both decoders now turn that feedback into a 'Stop hook feedback' row, and the fold keeps the prose before each such row as an answer too. --- .../__fixtures__/claude-hook-outcomes.jsonl | 4 ++ src/main/claude/claude-message-journaling.ts | 24 +++++++ src/main/claude/claude-stop-hook-feedback.ts | 17 +++++ ...ured-journal-restore-turn-grouping.test.ts | 3 +- .../hook-outcome-rows.test.ts | 34 ++++++++-- ...ipt-line-decoders-claude-stop-hook.test.ts | 65 +++++++++++++++++++ .../transcript-line-decoders-claude.ts | 15 +++++ src/shared/agent-session-hook-outcome.ts | 20 ++++-- .../transcript/native-chat-turn-fold.test.ts | 15 +++-- .../transcript/native-chat-turn-fold.ts | 36 +++++++--- 10 files changed, 209 insertions(+), 24 deletions(-) create mode 100644 src/main/claude/claude-stop-hook-feedback.ts create mode 100644 src/main/native-chat/transcript-line-decoders-claude-stop-hook.test.ts diff --git a/src/main/claude/__fixtures__/claude-hook-outcomes.jsonl b/src/main/claude/__fixtures__/claude-hook-outcomes.jsonl index d837a109a2dd..671768af9e13 100644 --- a/src/main/claude/__fixtures__/claude-hook-outcomes.jsonl +++ b/src/main/claude/__fixtures__/claude-hook-outcomes.jsonl @@ -1,2 +1,6 @@ {"case": "blocked-prompt", "frame": {"type": "system", "subtype": "informational", "content": "UserPromptSubmit operation blocked by hook:\n[/tmp/hook-capture/repo/block.sh]: Deploys are frozen\n\n\nOriginal prompt: BLOCKME please say hi", "level": "warning", "prevent_continuation": true, "prompt_submit_outcome": {"kind": "blocked_by_hook", "prompt_kept": false, "reason": "Deploys are frozen"}, "uuid": "00000000-0000-4000-8000-000000000001", "session_id": "00000000-0000-4000-8000-000000000002"}} {"case": "blocked-prompt", "frame": {"type": "result", "subtype": "success", "is_error": false, "num_turns": 0, "result": "UserPromptSubmit operation blocked by hook:\n[/tmp/hook-capture/repo/block.sh]: Deploys are frozen\n\n\nOriginal prompt: BLOCKME please say hi", "stop_reason": null, "session_id": "00000000-0000-4000-8000-000000000002", "uuid": "00000000-0000-4000-8000-000000000003", "duration_ms": 33, "duration_api_ms": 0}} +{"case": "stop-hook-sent-back", "frame": {"type": "assistant", "message": {"id": "msg_10", "type": "message", "role": "assistant", "model": "claude-haiku-5-5", "content": [{"type": "text", "text": "Grass is green."}], "stop_reason": null, "usage": {"input_tokens": 6, "output_tokens": 10}}, "parent_tool_use_id": null, "session_id": "00000000-0000-4000-8000-000000000002", "uuid": "00000000-0000-4000-8000-000000000010"}} +{"case": "stop-hook-sent-back", "frame": {"type": "user", "message": {"role": "user", "content": [{"type": "text", "text": "Stop hook feedback:\nVerify your statement with evidence before finishing."}]}, "parent_tool_use_id": null, "timestamp": "2026-11-01T05:34:54.630Z", "isSynthetic": true, "session_id": "00000000-0000-4000-8000-000000000002", "uuid": "00000000-0000-4000-8000-000000000011"}} +{"case": "stop-hook-sent-back", "frame": {"type": "assistant", "message": {"id": "msg_12", "type": "message", "role": "assistant", "model": "claude-haiku-5-5", "content": [{"type": "text", "text": "I checked: grass is green."}], "stop_reason": null, "usage": {"input_tokens": 6, "output_tokens": 10}}, "parent_tool_use_id": null, "session_id": "00000000-0000-4000-8000-000000000002", "uuid": "00000000-0000-4000-8000-000000000012"}} +{"case": "stop-hook-sent-back", "frame": {"type": "result", "subtype": "success", "is_error": false, "num_turns": 3, "result": "I checked: grass is green.", "stop_reason": "end_turn", "duration_ms": 12518, "duration_api_ms": 13517, "session_id": "00000000-0000-4000-8000-000000000002", "uuid": "00000000-0000-4000-8000-000000000013"}} diff --git a/src/main/claude/claude-message-journaling.ts b/src/main/claude/claude-message-journaling.ts index 4878ac48a23e..ad2101bc94f3 100644 --- a/src/main/claude/claude-message-journaling.ts +++ b/src/main/claude/claude-message-journaling.ts @@ -6,6 +6,7 @@ import type { ClaudeBackgroundTaskRows } from './claude-background-task-rows' import type { ClaudeToolOriginRegistry } from './claude-tool-origin-registry' import { claudeRecord, + claudeText, claudeMessageBody, claudeMessageIdentity, claudeOutputEnvelope, @@ -14,8 +15,10 @@ import { claudeToolResults, claudeToolUses, readClaudeMessageEnvelope, + type ClaudeMessageEnvelope, type ClaudeToolUse } from './structured/journal/claude-structured-item-translation' +import { claudeStopHookFeedbackRow } from './claude-stop-hook-feedback' import { appendUnmodeledContent, type ClaudeProviderFrameFallback @@ -125,6 +128,15 @@ export function journalClaudeMessage( } changed = true } + const stopHookFeedback = rootStopHookFeedbackRow(envelope) + if (stopHookFeedback) { + ctx.turn.ensureOpen(message, source, observedAt) + ctx.sink.appendItem(identity, stopHookFeedback, { + ...stamp(identity, stopHookFeedback), + lifecycle: true + }) + changed = true + } for (const tool of claudeToolUses(outputEnvelope)) { ctx.turn.ensureOpen(message, source, observedAt) ctx.tools.set(tool.id, tool) @@ -195,3 +207,15 @@ export function journalClaudeMessage( } return true } + +// Submitted-message filtering drops injected text, so read the hook's reason from the raw envelope. +function rootStopHookFeedbackRow(envelope: ClaudeMessageEnvelope) { + const [part] = envelope.content + const text = claudeText(claudeRecord(part)?.text) + return envelope.isInjectedUserTurn && + envelope.parentToolUseId === null && + envelope.content.length === 1 && + text + ? claudeStopHookFeedbackRow(text) + : null +} diff --git a/src/main/claude/claude-stop-hook-feedback.ts b/src/main/claude/claude-stop-hook-feedback.ts new file mode 100644 index 000000000000..2a73152954db --- /dev/null +++ b/src/main/claude/claude-stop-hook-feedback.ts @@ -0,0 +1,17 @@ +import { hookOutcomeRowBody } from '../../shared/agent-session-hook-outcome' +import type { AgentJournalPlainStatusItem } from '../../shared/agent-session-journal-types' + +// Claude injects a blocking Stop hook's reason as a meta user turn; exit-2 hooks prefix it with their command. +const STOP_HOOK_FEEDBACK = /^Stop hook feedback:\n/ + +/** The row for Claude's injected Stop-hook feedback text, or null for any other text. */ +export function claudeStopHookFeedbackRow(text: string): AgentJournalPlainStatusItem | null { + if (!STOP_HOOK_FEEDBACK.test(text)) { + return null + } + const reasons = text + .replace(STOP_HOOK_FEEDBACK, '') + .split('\n') + .map((line) => line.replace(/^\[[^\]\n]+\]: /, '')) + return hookOutcomeRowBody('sent-back', [reasons.join('\n')]) +} diff --git a/src/main/codex/codex-structured-journal-restore-turn-grouping.test.ts b/src/main/codex/codex-structured-journal-restore-turn-grouping.test.ts index 3c3112883c5c..ac508e43a264 100644 --- a/src/main/codex/codex-structured-journal-restore-turn-grouping.test.ts +++ b/src/main/codex/codex-structured-journal-restore-turn-grouping.test.ts @@ -97,7 +97,8 @@ describe('grouping a Codex thread restored from full history', () => { draws: true, outlivesTurn: false, reportsFailure: false, - explainsTurn: false + explainsTurn: false, + sendsBack: false })), settledTurnKeys: new Set(bars.settledTurns.keys()), expandedTurnKeys: new Set() diff --git a/src/main/native-chat/agent-session-wire/hook-outcome-rows.test.ts b/src/main/native-chat/agent-session-wire/hook-outcome-rows.test.ts index fcf6d22f743a..b6229661ffb6 100644 --- a/src/main/native-chat/agent-session-wire/hook-outcome-rows.test.ts +++ b/src/main/native-chat/agent-session-wire/hook-outcome-rows.test.ts @@ -61,7 +61,7 @@ async function captured(agent: 'codex' | 'claude', scenario: string): Promise return lines.map((line) => JSON.parse(line)).filter((line) => line.case === scenario) } -function settledRows(items: readonly AgentJournalRenderItem[]) { +function visibleRows(items: readonly AgentJournalRenderItem[]) { expect(withNativeChatCutTurnNotices(items, { agentName: 'Agent' })).toBe(items) const messages = projectStructuredItemsToNativeChat(items) const turnKeys = nativeChatRowTurnKeys(messages) @@ -70,9 +70,11 @@ function settledRows(items: readonly AgentJournalRenderItem[]) { settledTurnKeys: new Set(turnKeys.flatMap((key) => (key ? [key] : []))), expandedTurnKeys: new Set() }) - return messages.flatMap((message, index) => - message.role === 'system' && !foldedRows.has(index) ? message.blocks : [] - ) + return messages.filter((_, index) => !foldedRows.has(index)) +} + +function settledRows(items: readonly AgentJournalRenderItem[]) { + return visibleRows(items).flatMap((message) => (message.role === 'system' ? message.blocks : [])) } async function blockedChat( @@ -211,3 +213,27 @@ describe('a prompt hook that blocked the message', () => { expect(settledRows(items)).toEqual([row(`Blocked by hook: ${QA_POLICY}`)]) }) }) + +describe('a Stop hook that sent Claude back', () => { + it('keeps the reply before the hook row once the turn settles', async () => { + const frames = await captured('claude', 'stop-hook-sent-back') + const { items } = await blockedChat(CLAUDE_CHAT, (rig) => { + const lane = createClaudeJournalTranslator({ sink: rig.eventSink, fallbackIdPrefix: '1' }) + for (const { frame } of frames) { + lane.handle({ type: 'message', sessionId: 's', message: frame }) + } + }) + expect(visibleRows(items).map((message) => [message.role, message.blocks[0]])).toEqual([ + ['user', GO[0]], + ['assistant', { type: 'text', text: 'Grass is green.' }], + [ + 'system', + expect.objectContaining({ + tone: 'warning', + text: 'Stop hook feedback: Verify your statement with evidence before finishing.' + }) + ], + ['assistant', { type: 'text', text: 'I checked: grass is green.' }] + ]) + }) +}) diff --git a/src/main/native-chat/transcript-line-decoders-claude-stop-hook.test.ts b/src/main/native-chat/transcript-line-decoders-claude-stop-hook.test.ts new file mode 100644 index 000000000000..733baa0602be --- /dev/null +++ b/src/main/native-chat/transcript-line-decoders-claude-stop-hook.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import { nativeChatRowTurnKeys } from '../../shared/native-chat/transcript/native-chat-turn-grouping' +import { + nativeChatTurnFold, + nativeChatTurnFoldRow +} from '../../shared/native-chat/transcript/native-chat-turn-fold' +import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' + +// Text rows of a Claude Code 2.1.316 turn whose Stop hook blocked once. +function stopHookTurn(feedback: string): string[] { + return [ + { type: 'user', uuid: 'prompt', message: { role: 'user', content: 'Say: the sky is blue' } }, + { + type: 'assistant', + uuid: 'reply', + message: { role: 'assistant', content: [{ type: 'text', text: 'The sky is blue.' }] } + }, + { + type: 'user', + uuid: 'feedback', + isMeta: true, + message: { role: 'user', content: `Stop hook feedback:\n${feedback}` } + }, + { + type: 'assistant', + uuid: 'continuation', + message: { role: 'assistant', content: [{ type: 'text', text: 'Evidence: I checked.' }] } + } + ].map((record) => JSON.stringify({ timestamp: '2026-11-01T05:33:22.035Z', ...record })) +} + +describe('a Claude turn its Stop hook sent back', () => { + it.each([ + ['a JSON block decision', 'Verify your statement with evidence.'], + ['an exit-2 hook', '[/tmp/hook.sh]: Verify your statement with evidence.\n'] + ])('keeps the reply and the hook row visible once settled (%s)', (_, feedback) => { + const messages = stopHookTurn(feedback).flatMap( + (line) => decodeClaudeTranscriptLine(line, 'fallback') ?? [] + ) + const turnKeys = nativeChatRowTurnKeys(messages) + const { foldedRows } = nativeChatTurnFold({ + rows: messages.map((message, index) => + nativeChatTurnFoldRow(message, turnKeys[index], false) + ), + settledTurnKeys: new Set(['prompt']), + expandedTurnKeys: new Set() + }) + expect( + messages.flatMap((message, index) => + foldedRows.has(index) ? [] : [[message.role, message.blocks[0]]] + ) + ).toEqual([ + ['user', { type: 'text', text: 'Say: the sky is blue' }], + ['assistant', { type: 'text', text: 'The sky is blue.' }], + [ + 'system', + expect.objectContaining({ + text: 'Stop hook feedback: Verify your statement with evidence.', + tone: 'warning' + }) + ], + ['assistant', { type: 'text', text: 'Evidence: I checked.' }] + ]) + }) +}) diff --git a/src/main/native-chat/transcript-line-decoders-claude.ts b/src/main/native-chat/transcript-line-decoders-claude.ts index 12b1a2d8ed14..fa52f1c778dc 100644 --- a/src/main/native-chat/transcript-line-decoders-claude.ts +++ b/src/main/native-chat/transcript-line-decoders-claude.ts @@ -16,6 +16,8 @@ import { claudeContentBlocks } from './transcript-record-blocks' import { unwrapClaudePastedContentBlock } from '../../shared/claude-pasted-content' import { unwrapClaudeBashInputBlock } from '../../shared/claude-bash-input' import { claudeInterruptedMessageId } from './transcript-turn-markers' +import { claudeStopHookFeedbackRow } from '../claude/claude-stop-hook-feedback' +import { structuredAgentSessionStatusBlock } from '../../shared/structured-agent-session-status-block' const MAX_EDIT_PATCH_HUNKS = 40 const MAX_EDIT_PATCH_HUNK_LINES = 400 @@ -106,6 +108,10 @@ export function decodeClaudeTranscriptLine( const isInjectedUserTurn = role === 'user' && (record.isMeta === true || record.isSynthetic === true || record.isCompactSummary === true) + const stopHookFeedback = isInjectedUserTurn ? claudeStopHookFeedbackMessage(decodedBlocks) : null + if (stopHookFeedback) { + return { id: recordMessageId, timestamp, source: 'transcript', ...stopHookFeedback, ...parent } + } // Keep image-source companions despite isMeta: prompt base64 has no path and cannot render attachments. const blocks = isInjectedUserTurn ? isImageSourceRecord(decodedBlocks) @@ -153,6 +159,15 @@ function claudeQueuedPromptAsUserRecord( return { ...record, type: 'user', message: { role: 'user', content: prompt } } } +function claudeStopHookFeedbackMessage( + blocks: NativeChatBlock[] +): Pick | null { + const [block] = blocks + const row = + blocks.length === 1 && block?.type === 'text' ? claudeStopHookFeedbackRow(block.text) : null + return row ? { role: 'system', blocks: [structuredAgentSessionStatusBlock(row)] } : null +} + // Mixed prose/markers are injected turns, never image-source companions. function isImageSourceRecord(blocks: NativeChatBlock[]): boolean { return ( diff --git a/src/shared/agent-session-hook-outcome.ts b/src/shared/agent-session-hook-outcome.ts index 36e8e99fab41..70db5e69b9b3 100644 --- a/src/shared/agent-session-hook-outcome.ts +++ b/src/shared/agent-session-hook-outcome.ts @@ -1,20 +1,32 @@ -// Keep blocked/stopped prompt hooks as visible rows using the hook's reason, consistently across agents. +// Keep hook outcomes as visible rows using the hook's reason, consistently across agents. import type { AgentJournalPlainStatusItem } from './agent-session/journal/agent-session-journal-types' import { AGENT_SESSION_TURN_NOTICE_PRESENTATION } from './agent-session-turn-notice' -export type AgentSessionHookOutcome = 'blocked' | 'stopped' +/** A Stop hook sent the agent back to work, so the reply before this row was an answer. */ +export const AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION = 'hook-sent-back' + +export type AgentSessionHookOutcome = 'blocked' | 'stopped' | 'sent-back' + +const HOOK_OUTCOME_HEADERS: Record = { + blocked: 'Blocked by hook', + stopped: 'Hook stopped', + 'sent-back': 'Stop hook feedback' +} export function hookOutcomeRowBody( outcome: AgentSessionHookOutcome, details: readonly string[] ): AgentJournalPlainStatusItem { - const header = outcome === 'blocked' ? 'Blocked by hook' : 'Hook stopped' + const header = HOOK_OUTCOME_HEADERS[outcome] const lines = details.map((detail) => detail.trim()).filter((detail) => detail.length > 0) return { kind: 'status', tone: 'warning', - presentation: AGENT_SESSION_TURN_NOTICE_PRESENTATION, + presentation: + outcome === 'sent-back' + ? AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION + : AGENT_SESSION_TURN_NOTICE_PRESENTATION, text: lines.length === 0 ? `${header}.` diff --git a/src/shared/native-chat/transcript/native-chat-turn-fold.test.ts b/src/shared/native-chat/transcript/native-chat-turn-fold.test.ts index a5155cb50dc6..a707f5ede552 100644 --- a/src/shared/native-chat/transcript/native-chat-turn-fold.test.ts +++ b/src/shared/native-chat/transcript/native-chat-turn-fold.test.ts @@ -14,6 +14,7 @@ function row(overrides: Partial = {}): NativeChatTurnFold outlivesTurn: false, reportsFailure: false, explainsTurn: false, + sendsBack: false, ...overrides } } @@ -35,32 +36,32 @@ const NONE = new Set() describe('nativeChatTurnAnswerRows', () => { it('names the last assistant row that renders prose, not the first', () => { - expect(nativeChatTurnAnswerRows(TURN).get('turn-1')).toBe(4) + expect([...nativeChatTurnAnswerRows(TURN)]).toEqual([4]) }) it('ignores rows that render no prose, so a trailing tool run is not the answer', () => { const rows = [row({ role: 'user' }), row(), row({ rendersProse: false })] - expect(nativeChatTurnAnswerRows(rows).get('turn-1')).toBe(1) + expect([...nativeChatTurnAnswerRows(rows)]).toEqual([1]) }) it('ignores reasoning and system rows, which are never the agent answering', () => { const rows = [row({ role: 'user' }), row(), row({ role: 'reasoning' }), row({ role: 'system' })] - expect(nativeChatTurnAnswerRows(rows).get('turn-1')).toBe(1) + expect([...nativeChatTurnAnswerRows(rows)]).toEqual([1]) }) it('names a failure report as the answer when nothing the agent said comes after it', () => { const rows = [row({ role: 'user' }), row(), FAILURE] - expect(nativeChatTurnAnswerRows(rows).get('turn-1')).toBe(2) + expect([...nativeChatTurnAnswerRows(rows)]).toEqual([2]) }) it('names the later prose as the answer when the agent recovered from a failure', () => { const rows = [row({ role: 'user' }), FAILURE, row()] - expect(nativeChatTurnAnswerRows(rows).get('turn-1')).toBe(2) + expect([...nativeChatTurnAnswerRows(rows)]).toEqual([2]) }) it('reports no answer for a turn that only ran tools', () => { const rows = [row({ role: 'user' }), row({ rendersProse: false })] - expect(nativeChatTurnAnswerRows(rows).has('turn-1')).toBe(false) + expect(nativeChatTurnAnswerRows(rows).size).toBe(0) }) }) @@ -215,6 +216,6 @@ describe('nativeChatTurnFold', () => { expandedTurnKeys: NONE }) expect([...foldedRows]).toEqual([1]) - expect(nativeChatTurnAnswerRows(rows).get('turn-1')).toBe(3) + expect([...nativeChatTurnAnswerRows(rows)]).toEqual([3]) }) }) diff --git a/src/shared/native-chat/transcript/native-chat-turn-fold.ts b/src/shared/native-chat/transcript/native-chat-turn-fold.ts index 4293934cf898..e7f5450b0b84 100644 --- a/src/shared/native-chat/transcript/native-chat-turn-fold.ts +++ b/src/shared/native-chat/transcript/native-chat-turn-fold.ts @@ -1,7 +1,8 @@ -// Derive settled-turn answers from the last assistant prose or system failure; the journal has no answer marker. +// Derive settled-turn answers from the last assistant prose or system failure, plus the prose a Stop hook sent back; the journal has no answer marker. // Earlier work/recovered errors fold behind that answer, while failed turns end visibly on their error. import { AGENT_SESSION_COMPACTION_SKIPPED_PRESENTATION } from '../../agent-session/agent-session-compaction' +import { AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION } from '../../agent-session-hook-outcome' import { AGENT_SESSION_ORCA_STOP_PRESENTATION } from '../../agent-session/lifecycle/agent-session-orca-stop' import { AGENT_SESSION_TURN_NOTICE_PRESENTATION } from '../../agent-session-turn-notice' import { nativeChatRowRendersContent } from './native-chat-row-content' @@ -29,6 +30,8 @@ export type NativeChatTurnFoldRow = { reportsFailure: boolean /** Compaction/interruption/turn notices remain visible; hiding them leaves only generic turn status. */ explainsTurn: boolean + /** A Stop hook sent the agent back after it answered, so the prose before this row is an answer too. */ + sendsBack: boolean } /** How the fold reads a transcript row, with the same derivation the row renders from. */ @@ -64,7 +67,12 @@ export function nativeChatTurnFoldRow( (block.presentation === 'compaction' || block.presentation === AGENT_SESSION_COMPACTION_SKIPPED_PRESENTATION || block.presentation === AGENT_SESSION_ORCA_STOP_PRESENTATION || - block.presentation === AGENT_SESSION_TURN_NOTICE_PRESENTATION) + block.presentation === AGENT_SESSION_TURN_NOTICE_PRESENTATION || + block.presentation === AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION) + ), + sendsBack: message.blocks.some( + (block) => + block.type === 'text' && block.presentation === AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION ) } } @@ -81,19 +89,31 @@ export const NATIVE_CHAT_EMPTY_TURN_FOLD: NativeChatTurnFold = { foldableTurnKeys: new Set() } -/** Last assistant prose/system failure per turn; no answer means fold all work. */ +/** Last assistant prose/system failure per turn and before each send-back; no answer means fold all work. */ export function nativeChatTurnAnswerRows( rows: readonly NativeChatTurnFoldRow[] -): ReadonlyMap { - const answers = new Map() +): ReadonlySet { + const answers = new Set() + const latest = new Map() for (const [index, row] of rows.entries()) { + if (row.turnKey === undefined) { + continue + } + const answer = latest.get(row.turnKey) + if (row.sendsBack && answer !== undefined) { + answers.add(answer) + latest.delete(row.turnKey) + } const isCandidate = row.rendersProse && (row.role === 'assistant' || (row.role === 'system' && row.reportsFailure)) - if (row.turnKey !== undefined && isCandidate) { - answers.set(row.turnKey, index) + if (isCandidate) { + latest.set(row.turnKey, index) } } + for (const index of latest.values()) { + answers.add(index) + } return answers } @@ -124,7 +144,7 @@ export function nativeChatTurnFold({ continue } // No-prose turns fold wholly behind the status anchor instead of leaving every command expanded. - if (index === answers.get(turnKey)) { + if (answers.has(index)) { continue } foldableTurnKeys.add(turnKey) From 1ebc859675a34e21fefa7ec202a873543614600b Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:13:46 +0000 Subject: [PATCH 2/5] fix(native-chat): keep the Stop hook row when catching up a Claude chat transcript --- src/main/claude/claude-message-journaling.ts | 18 ++--------- src/main/claude/claude-stop-hook-feedback.ts | 19 +++++++++++ .../claude/claude-transcript-catch-up.test.ts | 32 +++++++++++++++++++ .../claude/claude-transcript-import-plan.ts | 11 +++---- 4 files changed, 58 insertions(+), 22 deletions(-) diff --git a/src/main/claude/claude-message-journaling.ts b/src/main/claude/claude-message-journaling.ts index ad2101bc94f3..b5c080bff703 100644 --- a/src/main/claude/claude-message-journaling.ts +++ b/src/main/claude/claude-message-journaling.ts @@ -6,7 +6,6 @@ import type { ClaudeBackgroundTaskRows } from './claude-background-task-rows' import type { ClaudeToolOriginRegistry } from './claude-tool-origin-registry' import { claudeRecord, - claudeText, claudeMessageBody, claudeMessageIdentity, claudeOutputEnvelope, @@ -15,10 +14,9 @@ import { claudeToolResults, claudeToolUses, readClaudeMessageEnvelope, - type ClaudeMessageEnvelope, type ClaudeToolUse } from './structured/journal/claude-structured-item-translation' -import { claudeStopHookFeedbackRow } from './claude-stop-hook-feedback' +import { claudeEnvelopeStopHookFeedbackRow } from './claude-stop-hook-feedback' import { appendUnmodeledContent, type ClaudeProviderFrameFallback @@ -128,7 +126,7 @@ export function journalClaudeMessage( } changed = true } - const stopHookFeedback = rootStopHookFeedbackRow(envelope) + const stopHookFeedback = claudeEnvelopeStopHookFeedbackRow(envelope) if (stopHookFeedback) { ctx.turn.ensureOpen(message, source, observedAt) ctx.sink.appendItem(identity, stopHookFeedback, { @@ -207,15 +205,3 @@ export function journalClaudeMessage( } return true } - -// Submitted-message filtering drops injected text, so read the hook's reason from the raw envelope. -function rootStopHookFeedbackRow(envelope: ClaudeMessageEnvelope) { - const [part] = envelope.content - const text = claudeText(claudeRecord(part)?.text) - return envelope.isInjectedUserTurn && - envelope.parentToolUseId === null && - envelope.content.length === 1 && - text - ? claudeStopHookFeedbackRow(text) - : null -} diff --git a/src/main/claude/claude-stop-hook-feedback.ts b/src/main/claude/claude-stop-hook-feedback.ts index 2a73152954db..d2fe442938d5 100644 --- a/src/main/claude/claude-stop-hook-feedback.ts +++ b/src/main/claude/claude-stop-hook-feedback.ts @@ -1,5 +1,10 @@ import { hookOutcomeRowBody } from '../../shared/agent-session-hook-outcome' import type { AgentJournalPlainStatusItem } from '../../shared/agent-session-journal-types' +import { + claudeRecord, + claudeText, + type ClaudeMessageEnvelope +} from './claude-structured-item-translation' // Claude injects a blocking Stop hook's reason as a meta user turn; exit-2 hooks prefix it with their command. const STOP_HOOK_FEEDBACK = /^Stop hook feedback:\n/ @@ -15,3 +20,17 @@ export function claudeStopHookFeedbackRow(text: string): AgentJournalPlainStatus .map((line) => line.replace(/^\[[^\]\n]+\]: /, '')) return hookOutcomeRowBody('sent-back', [reasons.join('\n')]) } + +/** The same row from a root-agent envelope; it continues the turn, so importers must not treat it as a prompt. */ +export function claudeEnvelopeStopHookFeedbackRow( + envelope: ClaudeMessageEnvelope +): AgentJournalPlainStatusItem | null { + const [part] = envelope.content + const text = claudeText(claudeRecord(part)?.text) + return envelope.isInjectedUserTurn && + envelope.parentToolUseId === null && + envelope.content.length === 1 && + text + ? claudeStopHookFeedbackRow(text) + : null +} diff --git a/src/main/claude/claude-transcript-catch-up.test.ts b/src/main/claude/claude-transcript-catch-up.test.ts index 09123710ba17..7410173947da 100644 --- a/src/main/claude/claude-transcript-catch-up.test.ts +++ b/src/main/claude/claude-transcript-catch-up.test.ts @@ -466,6 +466,38 @@ describe('Claude chat catch-up', () => { expect(c.warn).not.toHaveBeenCalled() }) + it('keeps an outside Stop hook row inside the turn it sent back', async () => { + const c = await chat() + await c.live() + await c.write([ + ...chatTurn, + prompt('p2', 'a1', 'ask 2', 3), + reply('a2', 'p2', 'msg_b', { type: 'text', text: 'answer 2' }, 4), + { + ...prompt('h2', 'a2', 'Stop hook feedback:\n[/hook.sh]: Cite evidence.\n', 5), + isMeta: true + }, + reply('a3', 'h2', 'msg_c', { type: 'text', text: 'evidence' }, 6), + ...bookkeeping + ]) + await c.open('a1') + expect(c.rows()).toEqual([ + 'user:ask 1', + 'assistant:answer 1', + '(continued-outside)', + 'user:ask 2', + 'assistant:answer 2', + '(hook-sent-back)', + 'assistant:evidence' + ]) + const scopes = c.journal + .snapshot() + .items.filter((item) => item.body.kind !== 'turn') + .slice(-3) + .map((item) => JSON.stringify(item.turnScope)) + expect(new Set(scopes).size).toBe(1) + }) + it('imports a later outside batch from the retained leaf without reusing its old divider', async () => { const c = await chat() await c.live() diff --git a/src/main/claude/claude-transcript-import-plan.ts b/src/main/claude/claude-transcript-import-plan.ts index 754f2058c89e..73fe4e40b819 100644 --- a/src/main/claude/claude-transcript-import-plan.ts +++ b/src/main/claude/claude-transcript-import-plan.ts @@ -34,12 +34,14 @@ import { claudeText, claudeThinkingIdentity, claudeToolIdentity, + claudeToolResults, claudeToolUses, readClaudeMessageEnvelope } from './structured/journal/claude-structured-item-translation' import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' import { createClaudeTranscriptItemReader } from './claude-transcript-item-reader' import { idleClaudeJournalTurn } from './claude-session-state-turn-over' +import { claudeEnvelopeStopHookFeedbackRow } from './claude-stop-hook-feedback' /** An isolated projection of final source items, compared with saved historical content. */ export function createClaudeTranscriptImportPlan(input: { @@ -189,17 +191,14 @@ export function createClaudeTranscriptImportPlan(input: { for (const tool of claudeToolUses(envelope)) { matchSource([claudeToolIdentity(envelope.sessionId, tool.id)]) } - for (const part of envelope.content) { - const result = claudeRecord(part) - const toolUseId = result?.type === 'tool_result' ? claudeText(result.tool_use_id) : null - if (toolUseId) { - matchSource([claudeToolIdentity(envelope.sessionId, toolUseId)]) - } + for (const result of claudeToolResults(envelope)) { + matchSource([claudeToolIdentity(envelope.sessionId, result.toolUseId)]) } } const prompt = queued || (envelope?.role === 'user' && + !claudeEnvelopeStopHookFeedbackRow(envelope) && envelope.content.some((part) => claudeRecord(part)?.type !== 'tool_result')) const decoded = prompt ? decodeClaudeTranscriptLine(JSON.stringify(row), `${input.providerSessionId}:${uuid}`) From ca3aac3436550a9df4c49afd664c12a0ec54123f Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:06:09 +0000 Subject: [PATCH 3/5] refactor(native-chat): one row table for hook outcomes --- src/main/claude/claude-stop-hook-feedback.ts | 7 ++----- src/shared/agent-session-hook-outcome.ts | 21 ++++++++++---------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/src/main/claude/claude-stop-hook-feedback.ts b/src/main/claude/claude-stop-hook-feedback.ts index d2fe442938d5..fa90084be188 100644 --- a/src/main/claude/claude-stop-hook-feedback.ts +++ b/src/main/claude/claude-stop-hook-feedback.ts @@ -14,11 +14,8 @@ export function claudeStopHookFeedbackRow(text: string): AgentJournalPlainStatus if (!STOP_HOOK_FEEDBACK.test(text)) { return null } - const reasons = text - .replace(STOP_HOOK_FEEDBACK, '') - .split('\n') - .map((line) => line.replace(/^\[[^\]\n]+\]: /, '')) - return hookOutcomeRowBody('sent-back', [reasons.join('\n')]) + const reason = text.replace(STOP_HOOK_FEEDBACK, '').replace(/^\[[^\]\n]+\]: /gm, '') + return hookOutcomeRowBody('sent-back', [reason]) } /** The same row from a root-agent envelope; it continues the turn, so importers must not treat it as a prompt. */ diff --git a/src/shared/agent-session-hook-outcome.ts b/src/shared/agent-session-hook-outcome.ts index 70db5e69b9b3..b7610d3ed45e 100644 --- a/src/shared/agent-session-hook-outcome.ts +++ b/src/shared/agent-session-hook-outcome.ts @@ -8,25 +8,26 @@ export const AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION = 'hook-sent-back' export type AgentSessionHookOutcome = 'blocked' | 'stopped' | 'sent-back' -const HOOK_OUTCOME_HEADERS: Record = { - blocked: 'Blocked by hook', - stopped: 'Hook stopped', - 'sent-back': 'Stop hook feedback' -} +const HOOK_OUTCOME_ROWS: Record = + { + blocked: { header: 'Blocked by hook', presentation: AGENT_SESSION_TURN_NOTICE_PRESENTATION }, + stopped: { header: 'Hook stopped', presentation: AGENT_SESSION_TURN_NOTICE_PRESENTATION }, + 'sent-back': { + header: 'Stop hook feedback', + presentation: AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION + } + } export function hookOutcomeRowBody( outcome: AgentSessionHookOutcome, details: readonly string[] ): AgentJournalPlainStatusItem { - const header = HOOK_OUTCOME_HEADERS[outcome] + const { header, presentation } = HOOK_OUTCOME_ROWS[outcome] const lines = details.map((detail) => detail.trim()).filter((detail) => detail.length > 0) return { kind: 'status', tone: 'warning', - presentation: - outcome === 'sent-back' - ? AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION - : AGENT_SESSION_TURN_NOTICE_PRESENTATION, + presentation, text: lines.length === 0 ? `${header}.` From 167b35a07e5fa918c582d3e5701f74e830387525 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:15:44 +0000 Subject: [PATCH 4/5] fix(native-chat): import journal types from their new home --- src/main/claude/claude-stop-hook-feedback.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/claude/claude-stop-hook-feedback.ts b/src/main/claude/claude-stop-hook-feedback.ts index fa90084be188..40b8ead222ff 100644 --- a/src/main/claude/claude-stop-hook-feedback.ts +++ b/src/main/claude/claude-stop-hook-feedback.ts @@ -1,5 +1,5 @@ import { hookOutcomeRowBody } from '../../shared/agent-session-hook-outcome' -import type { AgentJournalPlainStatusItem } from '../../shared/agent-session-journal-types' +import type { AgentJournalPlainStatusItem } from '../../shared/agent-session/journal/agent-session-journal-types' import { claudeRecord, claudeText, From 5c98f168122672ae0e155b5bbc53054c90c9a7d9 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:41:16 +0000 Subject: [PATCH 5/5] fix(native-chat): import moved translation and status-block modules from their new homes --- src/main/claude/claude-stop-hook-feedback.ts | 2 +- src/main/native-chat/transcript-line-decoders-claude.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/claude/claude-stop-hook-feedback.ts b/src/main/claude/claude-stop-hook-feedback.ts index 40b8ead222ff..25fd12426c5f 100644 --- a/src/main/claude/claude-stop-hook-feedback.ts +++ b/src/main/claude/claude-stop-hook-feedback.ts @@ -4,7 +4,7 @@ import { claudeRecord, claudeText, type ClaudeMessageEnvelope -} from './claude-structured-item-translation' +} from './structured/journal/claude-structured-item-translation' // Claude injects a blocking Stop hook's reason as a meta user turn; exit-2 hooks prefix it with their command. const STOP_HOOK_FEEDBACK = /^Stop hook feedback:\n/ diff --git a/src/main/native-chat/transcript-line-decoders-claude.ts b/src/main/native-chat/transcript-line-decoders-claude.ts index fa52f1c778dc..8dc8ad2c9b9b 100644 --- a/src/main/native-chat/transcript-line-decoders-claude.ts +++ b/src/main/native-chat/transcript-line-decoders-claude.ts @@ -17,7 +17,7 @@ import { unwrapClaudePastedContentBlock } from '../../shared/claude-pasted-conte import { unwrapClaudeBashInputBlock } from '../../shared/claude-bash-input' import { claudeInterruptedMessageId } from './transcript-turn-markers' import { claudeStopHookFeedbackRow } from '../claude/claude-stop-hook-feedback' -import { structuredAgentSessionStatusBlock } from '../../shared/structured-agent-session-status-block' +import { structuredAgentSessionStatusBlock } from '../../shared/agent-session/view/structured-agent-session-status-block' const MAX_EDIT_PATCH_HUNKS = 40 const MAX_EDIT_PATCH_HUNK_LINES = 400