Skip to content

The agent that grows with you

fix(desktop): preserve interim messages across history and tool boundaries (#107386)

Xipongb066034eaf69
diff --git a/agent/history_commentary.py b/agent/history_commentary.py
new file mode 100644
index 00000000000..578ddc00eba
--- /dev/null
+++ b/agent/history_commentary.py
@@ -0,0 +1,176 @@
+"""Display-only Codex commentary projection shared by REST and gateway history.
+
+Provider items and the stored reasoning string remain untouched for model replay.
+Only the projected fields may be used for public transcript text.
+"""
+
+import json
+from contextlib import contextmanager
+from typing import Any
+
+from agent.redact import redact_sensitive_text
+from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+from utils import is_truthy_value
+
+
+@contextmanager
+def _owning_home(home):
+ token = set_hermes_home_override(str(home)) if home is not None else None
+ try:
+ yield
+ finally:
+ if token is not None:
+ reset_hermes_home_override(token)
+
+
+def visible_commentary(text: str, *, strip_thinking=None) -> str:
+ """Use the same think stripping and secret redaction as live delivery."""
+ if strip_thinking is None:
+ from agent.agent_runtime_helpers import strip_think_blocks
+
+ strip_thinking = lambda value: strip_think_blocks(None, value)
+
+ visible = strip_thinking(text).strip()
+ return redact_sensitive_text(visible) if visible else visible
+
+
+def _phase_message_items(message: dict, phases: frozenset[str | None]) -> list[str]:
+ items = message.get("codex_message_items")
+ if isinstance(items, str):
+ try:
+ items = json.loads(items)
+ except (TypeError, ValueError):
+ return []
+ if not isinstance(items, list):
+ return []
+ result = []
+ for item in items:
+ if (
+ not isinstance(item, dict)
+ or item.get("type") != "message"
+ or item.get("role") != "assistant"
+ ):
+ continue
+ phase, content = item.get("phase"), item.get("content")
+ if phase is not None and not isinstance(phase, str):
+ continue
+ normalized_phase = phase.strip().lower() if isinstance(phase, str) else None
+ if normalized_phase not in phases or not isinstance(content, list):
+ continue
+ text = "".join(
+ part["text"]
+ for part in content
+ if isinstance(part, dict)
+ and part.get("type") == "output_text"
+ and isinstance(part.get("text"), str)
+ and part["text"].strip()
+ ).strip()
+ if text:
+ result.append(text)
+ return result
+
+
+def _commentary_items(message: dict) -> list[str]:
+ return _phase_message_items(message, frozenset({"commentary"}))
+
+
+def _final_items(message: dict) -> list[str]:
+ # Unphased assistant messages are normalized as final content too.
+ return _phase_message_items(message, frozenset({"final", "final_answer", None}))
+
+
+def _without_flattened_commentary(reasoning: str, commentary: list[str]) -> str:
+ """Omit exact whole-line public segments from a display copy, not source data.
+
+ Current normalization separates parts with two newlines; older rows may
+ have one. If a private segment happens to be identical, origin is ambiguous:
+ omit both occurrences rather than leaking the public text or choosing the
+ wrong one. Surrounding reasoning is retained in its original line style.
+ """
+ remaining = reasoning
+ for text in sorted(set(commentary), key=len, reverse=True):
+ search_from = 0
+ while (at := remaining.find(text, search_from)) >= 0:
+ end = at + len(text)
+ if (at == 0 or remaining[at - 1] == "\n") and (
+ end == len(remaining) or remaining[end] == "\n"
+ ):
+ before, after = remaining[:at], remaining[end:]
+ prefix, suffix = before.rstrip("\n"), after.lstrip("\n")
+ separator = (
+ "\n\n"
+ if before.endswith("\n\n") or after.startswith("\n\n")
+ else "\n"
+ )
+ remaining = prefix + (separator if prefix and suffix else "") + suffix
+ search_from = 0
+ else:
+ search_from = end
+ return remaining
+
+
+def _project_one(message: dict, *, enabled: bool) -> dict:
+ if message.get("role") != "assistant" or message.get("display_kind") == "hidden":
+ return message
+ raw = _commentary_items(message)
+ if not raw:
+ return message
+ projected = dict(message)
+ # A disabled profile must not recover raw sidecar text on the frontend.
+ projected["display_commentary"] = []
+ if enabled:
+ projected["display_commentary"] = [
+ part for text in raw if (part := visible_commentary(text))
+ ]
+ reasoning = (
+ message.get("reasoning")
+ or message.get("reasoning_content")
+ or message.get("reasoning_details")
+ or ""
+ )
+ if isinstance(reasoning, str):
+ projected["display_reasoning"] = _without_flattened_commentary(reasoning, raw)
+
+ # A nonempty canonical answer can also be filled by stream recovery after
+ # the provider sidecar was captured. Without a matching final item there
+ # is no way to distinguish "commentary + final" from a real final that
+ # merely starts with the same words. Never delete canonical answer bytes.
+ # Sanitize the display copy when it contains raw commentary and avoid
+ # duplicating a leading commentary item in a separate Desktop bubble.
+ content = message.get(
+ "display_content", message.get("content", message.get("text"))
+ )
+ if isinstance(content, str) and any(text in content for text in raw):
+ finals = _final_items(message)
+ if not (finals and content.strip() == "\n".join(finals)):
+ projected["display_content"] = visible_commentary(content)
+ if any(content.startswith(text) for text in raw):
+ projected["display_commentary"] = []
+ return projected
+
+
+def project_history_commentary(messages: list[dict], *, home: Any = None) -> list[dict]:
+ """Project a batch inside the owning profile's config and redaction scope."""
+ if not any(
+ isinstance(message, dict) and message.get("codex_message_items")
+ for message in messages
+ ):
+ return messages
+ with _owning_home(home):
+ from hermes_cli.config import load_config
+
+ try:
+ display = load_config().get("display") or {}
+ enabled = is_truthy_value(
+ display.get("show_commentary"), default=True
+ ) and is_truthy_value(
+ display.get("interim_assistant_messages"), default=True
+ )
+ except Exception:
+ enabled = False # unreadable policy must not publish raw provider items
+ return [
+ _project_one(message, enabled=enabled)
+ if isinstance(message, dict)
+ else message
+ for message in messages
+ ]
diff --git a/agent/stream_delivery.py b/agent/stream_delivery.py
index 13a8af8ebae..2d88432e649 100644
--- a/agent/stream_delivery.py
+++ b/agent/stream_delivery.py
@@ -10,7 +10,7 @@ from typing import Any, Dict, List
from agent.memory_manager import sanitize_context
from agent.message_content import flatten_message_text
-from agent.redact import redact_sensitive_text
+from agent.history_commentary import visible_commentary
# Same logger name as the origin module so log records / caplog filters are unchanged.
logger = logging.getLogger("run_agent")
@@ -135,8 +135,7 @@ class StreamDeliveryMixin:
def _visible_commentary(self, text: str) -> str:
"""Think-stripped, redacted commentary text ("" when nothing visible remains)."""
- visible = self._strip_think_blocks(text).strip()
- return redact_sensitive_text(visible) if visible else visible
+ return visible_commentary(text, strip_thinking=getattr(self, "_strip_think_blocks"))
def _extract_codex_interim_visible_text(self, assistant_msg: Dict[str, Any]) -> str:
"""All visible Codex commentary joined, for comparison/fallback."""
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/interim-history.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/interim-history.test.tsx
new file mode 100644
index 00000000000..24993107fb8
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/interim-history.test.tsx
@@ -0,0 +1,110 @@
+import type { GatewayEvent } from '@hermes/shared'
+import { act, cleanup } from '@testing-library/react'
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { chatMessageText, toChatMessages } from '@/lib/chat-messages'
+import type { SessionMessage } from '@/types/hermes'
+
+import { renderMessageStream } from './test-harness'
+
+const SID = 'interim-preservation'
+
+afterEach(cleanup)
+
+describe('intermediate assistant text survives Desktop lifecycle boundaries', () => {
+ it.each(['message.complete', 'message.interim'] as const)(
+ 'keeps pre-tool text when %s settles the next response',
+ async terminal => {
+ const stream = renderMessageStream(SID)
+
+ const emit = async (type: GatewayEvent['type'], payload: GatewayEvent['payload']) => {
+ await act(() => stream.handleEvent({ type, payload, session_id: SID }))
+ }
+
+ await emit('message.start', {})
+ await emit('message.delta', { text: 'Checking the files.', timestamp: 1 })
+ // Missing/disabled interim delivery must not make this older model response
+ // disposable when the later model response is finalized.
+ await emit('tool.start', { tool_id: 'call-1', name: 'terminal', args: { command: 'pwd' }, timestamp: 2 })
+ await emit('tool.complete', { tool_id: 'call-1', name: 'terminal', result: 'ok', timestamp: 3 })
+ await emit('message.delta', { text: 'Partial answer', timestamp: 4 })
+ await emit(terminal, { text: 'The result is ready.', timestamp: 5 })
+ const messages = stream.state().messages
+ const visible = messages.map(chatMessageText).join('\n')
+ expect(visible).toContain('Checking the files.')
+ expect(visible).toContain('The result is ready.')
+ expect(visible).not.toContain('Partial answer')
+ expect(messages.flatMap(message => message.parts).filter(part => part.type === 'tool-call')).toHaveLength(1)
+ expect(stream.state().busy).toBe(terminal === 'message.interim')
+ }
+ )
+
+ it.each(['rpc', 'rest'] as const)(
+ 'preserves the same public commentary on live → %s history projection',
+ async transport => {
+ const stream = renderMessageStream(SID)
+
+ const emit = async (type: GatewayEvent['type'], payload: GatewayEvent['payload']) => {
+ await act(() => stream.handleEvent({ type, payload, session_id: SID }))
+ }
+
+ await emit('message.start', {})
+ await emit('reasoning.delta', { text: 'Real reasoning.', timestamp: 1 })
+ await emit('message.interim', { text: 'I will inspect the files.', already_streamed: false, timestamp: 2 })
+ await emit('tool.start', { tool_id: 'call-1', name: 'terminal', args: { command: 'pwd' }, timestamp: 3 })
+ await emit('tool.complete', { tool_id: 'call-1', name: 'terminal', result: 'ok', timestamp: 4 })
+ await emit('message.delta', { text: 'All checks passed.', timestamp: 5 })
+ await emit('message.complete', { text: 'All checks passed.', timestamp: 6 })
+
+ const items = [
+ {
+ type: 'message',
+ role: 'assistant',
+ phase: 'commentary',
+ content: [{ type: 'output_text', text: 'I will inspect the files.' }]
+ }
+ ]
+
+ const rows: SessionMessage[] = [
+ {
+ role: 'assistant',
+ content: '',
+ timestamp: 1,
+ reasoning: 'Real reasoning.\n\nI will inspect the files.',
+ display_reasoning: 'Real reasoning.',
+ display_commentary: ['I will inspect the files.'],
+ codex_message_items: transport === 'rest' ? JSON.stringify(items) : items,
+ tool_calls: [
+ { id: 'call-1', type: 'function', function: { name: 'terminal', arguments: '{"command":"pwd"}' } }
+ ]
+ },
+ { role: 'tool', content: 'ok', tool_call_id: 'call-1', name: 'terminal', timestamp: 4 },
+ { role: 'assistant', content: 'All checks passed.', timestamp: 5 }
+ ]
+
+ const texts = (messages: ReturnType<typeof toChatMessages>) =>
+ messages
+ .flatMap(message => message.parts.flatMap(part => (part.type === 'text' ? [part.text.trim()] : [])))
+ .filter(Boolean)
+
+ const live = texts(stream.state().messages)
+ const restored = texts(toChatMessages(rows))
+ expect(live).toEqual(['I will inspect the files.', 'All checks passed.'])
+ expect(restored).toEqual(live)
+ expect(restored.join('')).not.toContain('Real reasoning.')
+
+ const restoredReasoning = toChatMessages(rows)
+ .flatMap(message => message.parts)
+ .filter(part => part.type === 'reasoning')
+ .map(part => part.text)
+
+ expect(restoredReasoning).toEqual(['Real reasoning.'])
+
+ expect(
+ toChatMessages(rows)
+ .flatMap(message => message.parts)
+ .filter(part => part.type === 'tool-call')
+ ).toHaveLength(1)
+ }
+ )
+})
diff --git a/apps/desktop/src/lib/chat-messages.codex-commentary-reprojection.test.ts b/apps/desktop/src/lib/chat-messages.codex-commentary-reprojection.test.ts
new file mode 100644
index 00000000000..ca17143370a
--- /dev/null
+++ b/apps/desktop/src/lib/chat-messages.codex-commentary-reprojection.test.ts
@@ -0,0 +1,251 @@
+import { describe, expect, it } from 'vitest'
+
+import { chatMessageText, toChatMessages } from '@/lib/chat-messages'
+import type { SessionMessage } from '@/types/hermes'
+
+describe('public Codex commentary after transcript hydration', () => {
+ it('keeps a tool-call preamble in assistant text, not the Thinking disclosure', () => {
+ // Real row shape: the Responses adapter persists a phase=commentary item
+ // alongside an empty content column and a reasoning blob containing both
+ // the genuine summary and the already-delivered public preamble.
+ const preamble = 'I will inspect the repository before changing code.'
+
+ const row: SessionMessage = {
+ id: 310,
+ role: 'assistant',
+ content: '',
+ reasoning: `**Checking workflow docs**\n\n${preamble}`,
+ display_reasoning: '**Checking workflow docs**',
+ display_commentary: [preamble],
+ tool_calls: [{ id: 'call-read', type: 'function', function: { name: 'read_file', arguments: '{}' } }],
+ codex_message_items: [
+ {
+ type: 'message',
+ role: 'assistant',
+ phase: 'commentary',
+ content: [{ type: 'output_text', text: preamble }]
+ }
+ ],
+ timestamp: 2
+ }
+
+ const [message] = toChatMessages([row])
+ const thoughts = message.parts.filter(part => part.type === 'reasoning')
+
+ expect(chatMessageText(message)).toBe(preamble)
+ expect(thoughts).toHaveLength(1)
+ expect(thoughts[0]).toMatchObject({ text: '**Checking workflow docs**' })
+ })
+
+ it('removes only exact commentary segments, preserving surrounding and incidental reasoning', () => {
+ const commentary = 'Inspect the files.\n\nThen run tests.'
+
+ const row: SessionMessage = {
+ id: 311,
+ role: 'assistant',
+ content: 'Final reply.',
+ reasoning: `Summary before.\n\n${commentary}\n\nSummary after.`,
+ display_reasoning: 'Summary before.\n\nSummary after.',
+ display_commentary: [commentary],
+ codex_message_items: [
+ {
+ type: 'message',
+ role: 'assistant',
+ phase: 'commentary',
+ content: [{ type: 'output_text', text: commentary }]
+ },
+ { type: 'message', role: 'assistant', phase: 'analysis', content: [{ type: 'output_text', text: 'Private.' }] }
+ ],
+ timestamp: 3
+ }
+
+ const [message] = toChatMessages([row])
+
+ expect(message.parts.filter(part => part.type === 'text').map(part => part.text)).toEqual([
+ commentary,
+ 'Final reply.'
+ ])
+ expect(message.parts.filter(part => part.type === 'reasoning').map(part => part.text)).toEqual([
+ 'Summary before.\n\nSummary after.'
+ ])
+
+ const incidental: SessionMessage = {
+ ...row,
+ reasoning: `Summary mentioning ${commentary} as an example.`,
+ display_reasoning: `Summary mentioning ${commentary} as an example.`
+ }
+
+ const [unchanged] = toChatMessages([incidental])
+
+ expect(unchanged.parts.filter(part => part.type === 'reasoning').map(part => part.text)).toEqual([
+ incidental.reasoning
+ ])
+ })
+
+ it('honors disabled interim commentary without suppressing a separate final reply', () => {
+ const commentary = 'I will inspect the files.'
+
+ const row: SessionMessage = {
+ id: 312,
+ role: 'assistant',
+ content: 'Here is the final result.',
+ reasoning: `Private summary.\n\n${commentary}`,
+ display_reasoning: 'Private summary.',
+ display_commentary: [],
+ codex_message_items: [
+ {
+ type: 'message',
+ role: 'assistant',
+ phase: 'commentary',
+ content: [{ type: 'output_text', text: commentary }]
+ }
+ ],
+ timestamp: 4
+ }
+
+ const [message] = toChatMessages([row])
+
+ expect(chatMessageText(message)).toBe('Here is the final result.')
+ expect(message.parts.filter(part => part.type === 'reasoning').map(part => part.text)).toEqual(['Private summary.'])
+ })
+
+ it('uses only backend-authorized display commentary, never raw replay items', () => {
+ const raw = 'My key is «redacted:sk-…». <think>private</think>'
+
+ const row: SessionMessage = {
+ id: 314,
+ role: 'assistant',
+ content: '',
+ reasoning: `Private summary.\n\n${raw}`,
+ display_reasoning: 'Private summary.',
+ display_commentary: ['My key is redacted.'],
+ codex_message_items: [
+ { type: 'message', role: 'assistant', phase: 'commentary', content: [{ type: 'output_text', text: raw }] }
+ ],
+ timestamp: 5
+ }
+
+ expect(chatMessageText(toChatMessages([row])[0])).toBe('My key is redacted.')
+ expect(
+ toChatMessages([row])[0]
+ .parts.filter(part => part.type === 'reasoning')
+ .map(part => part.text)
+ ).toEqual(['Private summary.'])
+ expect(chatMessageText(toChatMessages([{ ...row, display_commentary: undefined }])[0])).toBe('')
+ })
+
+ it('keeps a sanitized canonical answer intact when its sidecar origin is ambiguous', () => {
+ const raw = 'Checking. <think>hidden</think> key=' + 'sk-' + 'demo0123456789abcdef'
+
+ const row: SessionMessage = {
+ id: 315,
+ role: 'assistant',
+ content: `${raw}\n\nFinal result.`,
+ display_content: 'Checking. key=«redacted»\n\nFinal result.',
+ display_commentary: [],
+ reasoning: `Private.\n\n${raw}`,
+ display_reasoning: 'Private.',
+ codex_message_items: [
+ { type: 'message', role: 'assistant', phase: 'commentary', content: [{ type: 'output_text', text: raw }] }
+ ],
+ timestamp: 6
+ }
+
+ const [shown] = toChatMessages([row])
+ expect(shown.parts.filter(part => part.type === 'text').map(part => part.text)).toEqual([
+ 'Checking. key=«redacted»\n\nFinal result.'
+ ])
+ expect(shown.parts.filter(part => part.type === 'reasoning').map(part => part.text)).toEqual(['Private.'])
+ expect(chatMessageText(toChatMessages([{ ...row, display_commentary: [] }])[0])).toBe(
+ 'Checking. key=«redacted»\n\nFinal result.'
+ )
+ })
+
+ it('keeps an explicit empty display content authoritative over a stale final sidecar', () => {
+ const row: SessionMessage = {
+ id: 316,
+ role: 'assistant',
+ content: 'Working',
+ display_content: '',
+ display_commentary: [],
+ reasoning: 'Private.\n\nWorking',
+ display_reasoning: 'Private.',
+ codex_message_items: [
+ {
+ type: 'message',
+ role: 'assistant',
+ phase: 'commentary',
+ content: [{ type: 'output_text', text: 'Working' }]
+ },
+ {
+ type: 'message',
+ role: 'assistant',
+ phase: 'final',
+ content: [{ type: 'output_text', text: 'Stale sidecar final' }]
+ }
+ ],
+ timestamp: 7
+ }
+
+ expect(chatMessageText(toChatMessages([row])[0])).toBe('')
+ expect(
+ toChatMessages([row])[0]
+ .parts.filter(part => part.type === 'reasoning')
+ .map(part => part.text)
+ ).toEqual(['Private.'])
+ // Older backends without a display projection still use final sidecars.
+ expect(chatMessageText(toChatMessages([{ ...row, display_content: undefined }])[0])).toBe('Working')
+ })
+
+ it('keeps a final answer that starts with or equals the commentary text', () => {
+ for (const final of ['Checking. The answer is 42.', 'Checking.']) {
+ const row: SessionMessage = {
+ id: 317,
+ role: 'assistant',
+ content: final,
+ display_commentary: ['Checking.'],
+ display_reasoning: 'Private.',
+ codex_message_items: [
+ {
+ type: 'message',
+ role: 'assistant',
+ phase: 'commentary',
+ content: [{ type: 'output_text', text: 'Checking.' }]
+ },
+ { type: 'message', role: 'assistant', phase: 'final', content: [{ type: 'output_text', text: final }] }
+ ],
+ timestamp: 8
+ }
+
+ const shown = toChatMessages([row])[0]
+ .parts.filter(part => part.type === 'text')
+ .map(part => part.text)
+
+ expect(shown).toEqual(final === 'Checking.' ? [final] : ['Checking.', final])
+ expect(chatMessageText(toChatMessages([{ ...row, display_commentary: [] }])[0])).toBe(final)
+ }
+ })
+
+ it('uses each message owner’s display projection, not a foreground global setting', () => {
+ const row: SessionMessage = {
+ id: 313,
+ role: 'assistant',
+ content: '',
+ reasoning: 'Checking files.',
+ codex_message_items: [
+ {
+ type: 'message',
+ role: 'assistant',
+ phase: 'commentary',
+ content: [{ type: 'output_text', text: 'Checking files.' }]
+ }
+ ],
+ timestamp: 5
+ }
+
+ expect(chatMessageText(toChatMessages([{ ...row, display_commentary: [] }])[0])).toBe('')
+ expect(chatMessageText(toChatMessages([{ ...row, display_commentary: ['Checking files.'] }])[0])).toBe(
+ 'Checking files.'
+ )
+ })
+})
diff --git a/apps/desktop/src/lib/chat-messages.codex-json-sidecar.test.ts b/apps/desktop/src/lib/chat-messages.codex-json-sidecar.test.ts
index 984d193be12..88aeff32ae6 100644
--- a/apps/desktop/src/lib/chat-messages.codex-json-sidecar.test.ts
+++ b/apps/desktop/src/lib/chat-messages.codex-json-sidecar.test.ts
@@ -30,9 +30,16 @@ it('hydrates the SQLite JSON-text sidecar returned by REST like the decoded RPC
expect(toChatMessages([{ ...empty, codex_message_items: '{invalid' }])).toEqual([])
expect(toChatMessages([{ ...empty, display_kind: 'hidden', codex_message_items: JSON.stringify(items) }])).toEqual([])
- for (const phase of ['analysis', 'commentary']) {
- expect(toChatMessages([{ ...empty, codex_message_items: JSON.stringify([{ ...items[0], phase }]) }])).toEqual([])
- }
+ expect(
+ toChatMessages([{ ...empty, codex_message_items: JSON.stringify([{ ...items[0], phase: 'analysis' }]) }])
+ ).toEqual([])
+ const rawCommentary = JSON.stringify([{ ...items[0], phase: 'commentary' }])
+ expect(toChatMessages([{ ...empty, codex_message_items: rawCommentary }])).toEqual([])
+ expect(
+ chatMessageText(
+ toChatMessages([{ ...empty, codex_message_items: rawCommentary, display_commentary: ['Durable reply'] }])[0]
+ )
+ ).toBe('Durable reply')
expect(
chatMessageText(
diff --git a/apps/desktop/src/lib/chat-messages.codex-sidecar-hydration.test.ts b/apps/desktop/src/lib/chat-messages.codex-sidecar-hydration.test.ts
index 4429b6eab07..438d0797c6b 100644
--- a/apps/desktop/src/lib/chat-messages.codex-sidecar-hydration.test.ts
+++ b/apps/desktop/src/lib/chat-messages.codex-sidecar-hydration.test.ts
@@ -31,6 +31,7 @@ describe('#68321 assistant rows whose reply persisted only in codex_message_item
content: '',
reasoning: null,
reasoning_content: null,
+ display_commentary: ['Working through the approach...'],
codex_message_items: [
{
type: 'message',
@@ -66,8 +67,8 @@ describe('#68321 assistant rows whose reply persisted only in codex_message_item
expect(messages.map(m => m.role)).toEqual(['user', 'assistant', 'user'])
// The final-answer text is painted as the bubble's reply text...
expect(chatMessageText(messages[1])).toContain('Here is the full response you saw live.')
- // ...and commentary / analysis narration (reasoning channel on the backend) is not.
- expect(chatMessageText(messages[1])).not.toContain('Working through the approach...')
+ // ...and public commentary survives too, without promoting analysis.
+ expect(chatMessageText(messages[1])).toContain('Working through the approach...')
expect(chatMessageText(messages[1])).not.toContain('Scratchpad thoughts.')
})
})
diff --git a/apps/desktop/src/lib/chat-messages.interim-preservation.test.ts b/apps/desktop/src/lib/chat-messages.interim-preservation.test.ts
new file mode 100644
index 00000000000..e0f64e70f12
--- /dev/null
+++ b/apps/desktop/src/lib/chat-messages.interim-preservation.test.ts
@@ -0,0 +1,251 @@
+import { describe, expect, it } from 'vitest'
+
+import type { SessionMessage } from '@/types/hermes'
+
+import {
+ assistantTextPart,
+ type ChatMessagePart,
+ chatMessageText,
+ mergeFinalAssistantText,
+ reasoningPart,
+ toChatMessages,
+ upsertToolPart
+} from './chat-messages'
+
+const item = (phase: string, text: string) => ({
+ type: 'message',
+ role: 'assistant',
+ phase,
+ content: [{ type: 'output_text', text }]
+})
+
+const textParts = (parts: ChatMessagePart[]) => parts.flatMap(part => (part.type === 'text' ? [part.text] : []))
+
+const assistantText = (rows: SessionMessage[]) =>
+ toChatMessages(rows)
+ .filter(message => message.role === 'assistant')
+ .map(chatMessageText)
+ .join('\n')
+
+const withTool = (parts: ChatMessagePart[], id = 'call-1', timestamp = 2) =>
+ upsertToolPart(
+ parts,
+ { tool_id: id, name: 'terminal', args: { command: 'pwd' }, result: 'ok' },
+ 'complete',
+ timestamp
+ )
+
+describe('stored assistant commentary preservation', () => {
+ it.each(['rpc', 'rest'] as const)('restores commentary before the canonical reply through %s history', transport => {
+ const items = [
+ item('commentary', 'I will inspect the files.'),
+ item('analysis', 'Private analysis.'),
+ item('final_answer', 'Stale sidecar final.')
+ ]
+
+ const row: SessionMessage = {
+ role: 'assistant',
+ content: 'Canonical final.',
+ timestamp: 2,
+ reasoning: 'Real reasoning.',
+ display_commentary: ['I will inspect the files.'],
+ codex_message_items: transport === 'rest' ? JSON.stringify(items) : items
+ }
+
+ const [message] = toChatMessages([row])
+ expect(textParts(message.parts)).toEqual(['I will inspect the files.', 'Canonical final.'])
+ expect(chatMessageText(message)).not.toContain('Private analysis.')
+ expect(chatMessageText(message)).not.toContain('Stale sidecar final.')
+ expect(message.parts.filter(part => part.type === 'reasoning')).toEqual([reasoningPart('Real reasoning.', 2)])
+ })
+
+ it.each(['rpc', 'rest'] as const)('keeps a commentary-only assistant row through %s history', transport => {
+ const items = [item('commentary', 'Still checking.')]
+
+ const rows: SessionMessage[] = [
+ { role: 'user', content: 'Check it.', timestamp: 1 },
+ {
+ role: 'assistant',
+ content: '',
+ timestamp: 2,
+ display_commentary: ['Still checking.'],
+ codex_message_items: transport === 'rest' ? JSON.stringify(items) : items
+ },
+ { role: 'user', content: 'Continue.', timestamp: 3 }
+ ]
+
+ expect(toChatMessages(rows).map(message => message.role)).toEqual(['user', 'assistant', 'user'])
+ expect(assistantText(rows)).toBe('Still checking.')
+ })
+
+ it('keeps separate commentary items in order and joins only chunks of the same item', () => {
+ const first = item('commentary', 'First ')
+ first.content.push({ type: 'output_text', text: 'update.' })
+
+ const [message] = toChatMessages([
+ {
+ role: 'assistant',
+ content: '',
+ timestamp: 2,
+ display_commentary: ['First update.', 'Second update.'],
+ codex_message_items: [first, item('commentary', 'Second update.'), item('final_answer', 'Final answer.')]
+ }
+ ])
+
+ expect(textParts(message.parts)).toEqual(['First update.', 'Second update.', 'Final answer.'])
+ })
+
+ it('keeps backend-authorized commentary without exposing analysis', () => {
+ expect(
+ assistantText([
+ {
+ role: 'assistant',
+ content: '',
+ timestamp: 2,
+ display_commentary: ['Visible update.'],
+ codex_message_items: [
+ item(' Commentary ', 'Visible update.'),
+ item(' ANALYSIS ', 'Hidden analysis.'),
+ item('final_answer', 'Answer.')
+ ]
+ }
+ ])
+ ).toBe('Visible update.Answer.')
+ })
+
+ it('does not duplicate commentary also present in canonical content', () => {
+ const items = [item('commentary', 'First update.'), item('commentary', 'Second update.')]
+ expect(
+ assistantText([
+ {
+ role: 'assistant',
+ content: 'First update.\n\nSecond update.',
+ timestamp: 2,
+ display_commentary: ['First update.', 'Second update.'],
+ codex_message_items: items
+ }
+ ])
+ ).toBe('First update.\n\nSecond update.')
+ })
+
+ it('keeps canonical text authoritative when it equals one commentary item', () => {
+ expect(
+ assistantText([
+ {
+ role: 'assistant',
+ content: 'Same text.',
+ timestamp: 2,
+ display_commentary: ['Same text.'],
+ codex_message_items: [item('commentary', 'Same text.'), item('final_answer', 'Stale text.')]
+ }
+ ])
+ ).toBe('Same text.')
+ })
+
+ it('respects explicitly hidden and non-assistant rows', () => {
+ const codex_message_items = [item('commentary', 'Do not surface this.')]
+ expect(
+ toChatMessages([{ role: 'assistant', content: '', timestamp: 2, display_kind: 'hidden', codex_message_items }])
+ ).toEqual([])
+ expect(assistantText([{ role: 'user', content: 'User text.', timestamp: 2, codex_message_items }])).toBe('')
+ })
+
+ it.each(['{broken', 'null', '{}', '42'])(
+ 'ignores malformed sidecar %s without losing canonical content',
+ codex_message_items => {
+ expect(assistantText([{ role: 'assistant', content: 'Keep me.', timestamp: 2, codex_message_items }])).toBe(
+ 'Keep me.'
+ )
+ }
+ )
+
+ it('does not promote a reasoning-only row into an answer', () => {
+ const [message] = toChatMessages([{ role: 'assistant', content: '', timestamp: 2, reasoning: 'Only reasoning.' }])
+ expect(chatMessageText(message)).toBe('')
+ expect(message.parts).toEqual([reasoningPart('Only reasoning.', 2)])
+ })
+
+ it('never promotes raw sidecar commentary without backend authorization', () => {
+ expect(
+ assistantText([
+ {
+ role: 'assistant',
+ content: '',
+ timestamp: 2,
+ codex_message_items: JSON.stringify([
+ null,
+ 1,
+ [],
+ { ...item('commentary', 'Foreign text.'), role: 'user' },
+ { ...item('commentary', 'Wrong type.'), type: 'reasoning' },
+ { ...item('commentary', 'Bad content.'), content: 'not an array' },
+ { ...item('commentary', ''), content: [null, 1, [], { type: 'output_text', text: 42 }] },
+ item('commentary', 'Valid update.')
+ ])
+ }
+ ])
+ ).toBe('')
+ })
+})
+
+describe('authoritative final text is scoped to the latest tool-delimited response', () => {
+ it('does not erase commentary from before a tool when the interim frame is absent', () => {
+ const earlier = withTool([assistantTextPart('Checking the repository.', 1)])
+ const parts = [...earlier, assistantTextPart('Partial final', 3)]
+ const before = structuredClone(parts)
+ const result = mergeFinalAssistantText(parts, 'Final answer.', 4)
+ expect(textParts(result)).toEqual(['Checking the repository.', 'Final answer.'])
+ expect(result.slice(0, earlier.length)).toEqual(earlier)
+ expect(parts).toEqual(before)
+ })
+
+ it('keeps all earlier tool-delimited updates, not just the latest one', () => {
+ const first = withTool([assistantTextPart('First update.', 1)])
+ const second = withTool([...first, assistantTextPart('Second update.', 3)], 'call-2', 4)
+ const result = mergeFinalAssistantText([...second, assistantTextPart('Draft', 5)], 'Done.', 6)
+ expect(textParts(result)).toEqual(['First update.', 'Second update.', 'Done.'])
+ expect(result.filter(part => part.type === 'tool-call')).toHaveLength(2)
+ })
+
+ it('does not duplicate an exact cumulative final prefix while preserving the tool boundary', () => {
+ const parts = [...withTool([assistantTextPart('Earlier update.', 1)]), assistantTextPart('Partial', 3)]
+ const result = mergeFinalAssistantText(parts, 'Earlier update.Final answer.', 4)
+ expect(textParts(result)).toEqual(['Earlier update.', 'Final answer.'])
+ expect(result.findIndex(part => part.type === 'tool-call')).toBe(1)
+ })
+
+ it('keeps a longer earlier update when the final is only its short prefix', () => {
+ const parts = withTool([assistantTextPart('Done. The investigation details follow.', 1)])
+ expect(textParts(mergeFinalAssistantText(parts, 'Done.', 3))).toEqual([
+ 'Done. The investigation details follow.',
+ 'Done.'
+ ])
+ })
+
+ it('drops a later provisional draft when the cumulative final equals the earlier response exactly', () => {
+ const earlier = withTool([assistantTextPart('Earlier update.', 1)])
+ const parts = [...earlier, reasoningPart('Checking.', 3), assistantTextPart('Unfinished draft', 4)]
+
+ const result = mergeFinalAssistantText(parts, 'Earlier update.', 5)
+
+ expect(textParts(result)).toEqual(['Earlier update.'])
+ expect(result.slice(0, earlier.length)).toEqual(earlier)
+ expect(result.find(part => part.type === 'reasoning')?.text).toBe('Checking.')
+ })
+
+ it('still replaces provisional text within one response, even across reasoning parts', () => {
+ const parts = [
+ assistantTextPart('Wrong draft.', 1),
+ reasoningPart('Reconsidering.', 2),
+ assistantTextPart('Another draft.', 3)
+ ]
+
+ expect(textParts(mergeFinalAssistantText(parts, 'Correct final.', 4))).toEqual(['Correct final.'])
+ })
+
+ it('keeps a confirmed full stream and an empty terminal frame unchanged', () => {
+ const parts = [...withTool([assistantTextPart('Earlier.', 1)]), assistantTextPart('Final.', 3)]
+ expect(mergeFinalAssistantText(parts, 'Earlier.Final.', 4)).toBe(parts)
+ expect(mergeFinalAssistantText(parts, ' ', 4)).toBe(parts)
+ })
+})
diff --git a/apps/desktop/src/lib/chat-messages.test.ts b/apps/desktop/src/lib/chat-messages.test.ts
index d9c18c09234..6b2be68a385 100644
--- a/apps/desktop/src/lib/chat-messages.test.ts
+++ b/apps/desktop/src/lib/chat-messages.test.ts
@@ -1173,7 +1173,9 @@ describe('mergeFinalAssistantText', () => {
expect(result[0]).toMatchObject({ text: 'final answer', timestamp: 12.5, type: 'text' })
})
- it('removes all text parts and appends the final text', () => {
+ it('preserves pre-tool text and appends the later final response', () => {
+ // These deltas precede the tool call: they belong to an earlier model
+ // response, not to the provisional draft of the final being settled.
const parts = [
{ type: 'text' as const, text: 'streamed delta 1' },
{ type: 'text' as const, text: 'streamed delta 2' },
@@ -1182,8 +1184,11 @@ describe('mergeFinalAssistantText', () => {
const result = mergeFinalAssistantText(parts, 'final answer')
- expect(result.filter(p => p.type === 'text')).toHaveLength(1)
- expect(result.filter(p => p.type === 'text')[0]).toMatchObject({ text: 'final answer' })
+ expect(result.filter(p => p.type === 'text').map(p => p.text)).toEqual([
+ 'streamed delta 1',
+ 'streamed delta 2',
+ 'final answer'
+ ])
expect(result.some(p => p.type === 'tool-call')).toBe(true)
})
diff --git a/apps/desktop/src/lib/chat-messages/hydration.ts b/apps/desktop/src/lib/chat-messages/hydration.ts
index ecf79177ed0..31e886a2ca7 100644
--- a/apps/desktop/src/lib/chat-messages/hydration.ts
+++ b/apps/desktop/src/lib/chat-messages/hydration.ts
@@ -4,7 +4,14 @@ import { extractImageRefs } from '@/lib/embedded-images'
import { dedupeGeneratedImageEchoesInParts } from '@/lib/generated-images'
import type { MessageReaction, SessionMessage } from '@/types/hermes'
-import { assistantTextPart, chatMessageText, dedupeRepeatedTextInParts, reasoningPart, textPart } from './parts'
+import {
+ assistantTextPart,
+ chatMessageText,
+ dedupeRepeatedTextInParts,
+ reasoningPart,
+ renderMediaTags,
+ textPart
+} from './parts'
import {
applyStoredToolResult,
applyStoredToolResultToParts,
@@ -26,29 +33,32 @@ const DISCORD_TRIGGERING_NOTE_RE =
/(^|\n)\[Triggering message id: `[^`\n]*` — use as `message_id` for reply\/react\/pin via the discord tools\.\]\n*/
/**
- * Reply text from a Responses-API `codex_message_items` sidecar (#68321), for rows
- * whose `content` persisted empty. `commentary` / `analysis` items are mid-turn
- * narration the backend routes to the reasoning channel
- * (codex_responses_adapter `_OutputScan._message`); the remaining phases are the reply.
+ * Backend history projection authorizes/sanitizes public commentary before it
+ * reaches Desktop. Raw Responses sidecars are used only for final-answer fallback;
+ * phase=analysis and raw phase=commentary are never promoted to assistant text.
*/
-function codexMessageItemText(message: SessionMessage): string {
+function codexMessageItemText(message: SessionMessage): { commentary: string[]; reply: string } {
let items = message.codex_message_items
+ const commentary = Array.isArray(message.display_commentary)
+ ? message.display_commentary.filter((part): part is string => typeof part === 'string' && Boolean(part.trim()))
+ : []
+
+ const replies: string[] = []
+
// REST carries SQLite JSON text; RPC history carries the decoded list.
if (typeof items === 'string') {
try {
items = JSON.parse(items)
} catch {
- return ''
+ return { commentary, reply: '' }
}
}
if (!Array.isArray(items)) {
- return ''
+ return { commentary, reply: '' }
}
- const texts: string[] = []
-
for (const item of items) {
if (!item || typeof item !== 'object' || Array.isArray(item)) {
continue
@@ -60,37 +70,34 @@ function codexMessageItemText(message: SessionMessage): string {
continue
}
- if (record.phase === 'commentary' || record.phase === 'analysis') {
- continue
- }
-
- const content = record.content
+ const phase = typeof record.phase === 'string' ? record.phase.trim().toLowerCase() : ''
- if (!Array.isArray(content)) {
+ if (phase === 'analysis' || phase === 'commentary' || !Array.isArray(record.content)) {
continue
}
- for (const part of content) {
+ const chunks: string[] = []
+
+ for (const part of record.content) {
if (!part || typeof part !== 'object' || Array.isArray(part)) {
continue
}
const partRecord = part as Record<string, unknown>
- const partType = partRecord.type
- if (partType !== 'output_text' && partType !== 'text') {
- continue
+ if ((partRecord.type === 'output_text' || partRecord.type === 'text') && typeof partRecord.text === 'string') {
+ chunks.push(partRecord.text)
}
+ }
- const text = partRecord.text
+ const text = chunks.join('')
- if (typeof text === 'string' && text.length > 0) {
- texts.push(text)
- }
+ if (text) {
+ replies.push(text)
}
}
- return texts.join('')
+ return { commentary, reply: replies.join('') }
}
function displayContentForMessage(role: SessionMessage['role'], content: unknown): string {
@@ -368,31 +375,40 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
const sourceHasTools = Array.isArray(message.tool_calls) && message.tool_calls.length > 0
const durableComplete = sourceHasTools ? false : rowId !== undefined ? true : undefined
- const reasoning =
+ const codexText =
+ displayRole === 'assistant' && message.display_kind !== 'hidden' ? codexMessageItemText(message) : null
+
+ const commentary = codexText?.commentary ?? []
+
+ const rawReasoning =
message.reasoning ||
message.reasoning_content ||
(typeof message.reasoning_details === 'string' ? message.reasoning_details : '')
+ const reasoning = message.display_reasoning !== undefined ? message.display_reasoning : rawReasoning
+
if (reasoning && message.role === 'assistant') {
parts.push(reasoningPart(reasoning, message.timestamp))
}
- if (displayContent) {
- parts.push(
- displayRole === 'assistant'
- ? assistantTextPart(displayContent, message.timestamp)
- : textPart(displayContent, message.timestamp)
- )
- }
+ const reply = message.display_content !== undefined ? displayContent : displayContent || codexText?.reply
+ // Some providers also persist the joined commentary as canonical content.
+ // Keep that authoritative copy once, without treating unrelated final text
+ // as a reason to discard the earlier public messages.
+ const normalized = (value: string) => renderMediaTags(value).replace(/\s+/g, ' ').trim()
- // Reply text can live only in the sidecar alongside reasoning or tool parts.
- // Those parts are not a substitute for the answer; canonical content still wins.
- if (message.role === 'assistant' && message.display_kind !== 'hidden' && !displayContent) {
- const codexText = codexMessageItemText(message)
+ const commentaryIsReply = Boolean(
+ reply && commentary.length && normalized(commentary.join('\n\n')) === normalized(reply)
+ )
- if (codexText) {
- parts.push(assistantTextPart(codexText, message.timestamp))
- }
+ if (!commentaryIsReply) {
+ parts.push(...commentary.map(text => assistantTextPart(text, message.timestamp)))
+ }
+
+ if (reply) {
+ parts.push(
+ displayRole === 'assistant' ? assistantTextPart(reply, message.timestamp) : textPart(reply, message.timestamp)
+ )
}
if (message.role === 'assistant' && Array.isArray(message.tool_calls)) {
diff --git a/apps/desktop/src/lib/chat-messages/parts.ts b/apps/desktop/src/lib/chat-messages/parts.ts
index eedf425e5e6..144d7c53f7a 100644
--- a/apps/desktop/src/lib/chat-messages/parts.ts
+++ b/apps/desktop/src/lib/chat-messages/parts.ts
@@ -266,8 +266,10 @@ export function dedupeRepeatedTextInParts(parts: ChatMessagePart[]): ChatMessage
/**
* Merge the final assistant text into a message's parts.
*
- * - Removes all existing `text` parts (they were streamed deltas, now superseded
- * by the authoritative final response).
+ * - Preserves earlier tool-delimited responses: a missed interim frame must
+ * not make their public text disposable.
+ * - Replaces provisional text only in the latest response with its authoritative
+ * final text, retaining confirmed text/reasoning boundaries.
* - Keeps `reasoning` parts, but drops one that the final text fully covers
* (reasoning ⊆ final) — the final restates it. A short final ("Done.") must
* NOT swallow a longer reasoning block that merely starts with it (#61447).
@@ -300,14 +302,41 @@ export function mergeFinalAssistantText(
return parts
}
+ // A tool call is an explicit model-response boundary even when no
+ // message.interim frame sealed the earlier text into a separate bubble.
+ // Only the suffix after the last call belongs to this authoritative final.
+ const lastToolIndex = parts.findLastIndex(part => part.type === 'tool-call')
+
+ if (lastToolIndex >= 0) {
+ const earlier = parts.slice(0, lastToolIndex + 1)
+
+ const earlierText = earlier
+ .filter((part): part is Extract<ChatMessagePart, { type: 'text' }> => part.type === 'text')
+ .map(part => part.text)
+ .join('')
+
+ // Some terminal frames carry cumulative text. Strip only an exact prefix;
+ // fuzzy similarity is not proof that two assistant messages are the same.
+ const responseText =
+ earlierText && finalText.startsWith(earlierText) ? finalText.slice(earlierText.length) : finalText
+
+ const suffix = parts.slice(lastToolIndex + 1)
+
+ // A cumulative final can stop exactly at the pre-tool update. The suffix
+ // draft is still provisional; the ordinary empty-final path keeps drafts.
+ if (earlierText && finalText === earlierText) {
+ return [...earlier, ...suffix.filter(part => part.type !== 'text')]
+ }
+
+ return [...earlier, ...mergeFinalAssistantText(suffix, responseText, fallbackTimestamp)]
+ }
+
const previousText = parts.findLast(part => part.type === 'text')
const kept = parts.filter(part => {
if (part.type === 'text') {
- // Sealed text parts were already finalized into their own bubbles —
- // this filter only runs on the LAST streaming bubble, so there are no
- // sealed parts here. All text parts are streamed deltas that get
- // replaced by the authoritative final text.
+ // The tool-delimited prefix was retained above. This suffix is
+ // provisional text from the response being finalized.
return false
}
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index efc0cde6df6..6a91ec97de9 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -628,6 +628,10 @@ export interface SessionMessage {
content: unknown
/** Backend-projected user-visible content when a physical row also carries internal model scaffolding. */
display_content?: unknown
+ /** Sanitized, profile-authorized public commentary supplied by the history backend. Never recover this from raw replay. */
+ display_commentary?: string[]
+ /** Display-only reasoning after removing exact public commentary; stored reasoning remains unmodified. */
+ display_reasoning?: string
context?: unknown
name?: string
reasoning?: null | string
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.py
index 97a852b22a2..68d47f9cb70 100644
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@ -551,9 +551,20 @@ def _with_tool_call_labels(message: dict) -> dict:
return {**message, "tool_call_labels": labels} if labels else message
-def _project_for_display(messages: list) -> list:
+def _history_profile_home(profile):
+ if profile:
+ return _cron_profile_home(profile)[1]
+ # An omitted profile reads this process's DB (including custom HERMES_HOME),
+ # not necessarily the registered default profile used by cron routes.
+ from hermes_cli.config import get_hermes_home
+
+ return get_hermes_home()
+
+
+def _project_for_display(messages: list, *, home=None) -> list:
from agent.compaction_display import project_compaction_message_for_display
from agent.context_compressor import is_compaction_summary_message
+ from agent.history_commentary import project_history_commentary
from agent.turn_failure_copy import untyped_failed_turn_display_kind
projected_messages = []
@@ -579,7 +590,7 @@ def _project_for_display(messages: list) -> list:
projected["display_content"] = display_view.get("content")
projected.pop("display_kind", None)
projected_messages.append(projected)
- return projected_messages
+ return project_history_commentary(projected_messages, home=home)
@manage_router.get("/api/sessions/{session_id}/messages")
@@ -608,7 +619,8 @@ async def get_session_messages(
if result is None:
raise HTTPException(status_code=404, detail=_NOT_FOUND)
sid, _limit, messages = result
- projected_messages = _project_for_display(messages)
+ projected_messages = await asyncio.to_thread(
+ _project_for_display, messages, home=_history_profile_home(profile))
return {
"session_id": sid,
# The same stamp list rows carry, so the Desktop keys a page under the
@@ -676,7 +688,8 @@ async def get_session_messages_around(
return {"session_id": sid, "profile": owner, **page}
result = await asyncio.to_thread(_with_db, profile, _read, read_only=True)
- result["messages"] = _project_for_display(result["messages"])
+ result["messages"] = await asyncio.to_thread(
+ _project_for_display, result["messages"], home=_history_profile_home(profile))
return result
diff --git a/tests/hermes_cli/test_history_commentary_display.py b/tests/hermes_cli/test_history_commentary_display.py
new file mode 100644
index 00000000000..7bccd70440d
--- /dev/null
+++ b/tests/hermes_cli/test_history_commentary_display.py
@@ -0,0 +1,504 @@
+"""Public Codex commentary is a display projection, never a replay mutation."""
+
+from hermes_cli.web_routers.sessions import _project_for_display
+from tui_gateway.server import _history_to_messages
+from agent.history_commentary import visible_commentary
+from hermes_constants import get_hermes_home_override
+
+import asyncio
+import pytest
+
+
+def _row(text="I will inspect the files."):
+ return {
+ "role": "assistant",
+ "content": "",
+ "reasoning": f"Private summary.\n\n{text}",
+ "reasoning_content": f"Private summary.\n\n{text}",
+ "codex_message_items": [
+ {
+ "type": "message",
+ "role": "assistant",
+ "phase": "commentary",
+ "content": [{"type": "output_text", "text": text}],
+ },
+ {
+ "type": "message",
+ "role": "assistant",
+ "phase": "analysis",
+ "content": [{"type": "output_text", "text": "private analysis"}],
+ },
+ ],
+ "tool_calls": [
+ {
+ "id": "call-1",
+ "type": "function",
+ "function": {"name": "terminal", "arguments": "{}"},
+ }
+ ],
+ "timestamp": 1,
+ }
+
+
+def test_rest_history_separates_public_commentary_without_changing_source():
+ row = _row()
+ projected = _project_for_display([row])[0]
+
+ assert projected["display_commentary"] == ["I will inspect the files."]
+ assert projected["display_reasoning"] == "Private summary."
+ assert projected["codex_message_items"] == row["codex_message_items"]
+ assert projected["tool_calls"] == row["tool_calls"]
+ assert row["reasoning"] == "Private summary.\n\nI will inspect the files."
+
+
+def test_gateway_history_uses_same_display_projection():
+ row = _row()
+ projected = _history_to_messages([row])[0]
+
+ assert projected["display_commentary"] == ["I will inspect the files."]
+ assert projected["display_reasoning"] == "Private summary."
+ assert projected["codex_message_items"] == row["codex_message_items"]
+ assert row["reasoning"].endswith("I will inspect the files.")
+
+
+def test_history_applies_live_stripping_and_redaction_without_changing_raw_items(
+ monkeypatch,
+):
+ monkeypatch.setattr("agent.redact._redact_enabled", lambda: True)
+ raw = (
+ "Start. <think>private scratchpad</think> Key=" + "sk-" + "demo0123456789abcdef"
+ )
+ row = _row(raw)
+
+ for projected in (_project_for_display([row])[0], _history_to_messages([row])[0]):
+ assert projected["display_commentary"] == [visible_commentary(raw)]
+ assert "<think>" not in projected["display_commentary"][0]
+ assert "sk-demo0123456789abcdef" not in projected["display_commentary"][0]
+ assert projected["display_reasoning"] == "Private summary."
+ assert projected["codex_message_items"] == row["codex_message_items"]
+
+
+ "disabled",
+ [
+ {"show_commentary": False},
+ {"show_commentary": "false"},
+ {"interim_assistant_messages": False},
+ ],
+)
+def test_owner_profile_settings_apply_to_rest_and_rpc(monkeypatch, tmp_path, disabled):
+ from hermes_cli import config as config_mod
+
+ enabled_home, disabled_home = tmp_path / "enabled", tmp_path / "disabled"
+ observed = []
+
+ def config():
+ home = get_hermes_home_override()
+ observed.append(str(home))
+ return {"display": {} if str(home) == str(enabled_home) else disabled}
+
+ monkeypatch.setattr(config_mod, "load_config", config)
+ row = _row()
+ for adapter in (
+ lambda home: _project_for_display([row], home=home)[0],
+ lambda home: _history_to_messages([row], profile_home=home)[0],
+ ):
+ assert adapter(enabled_home)["display_commentary"] == [
+ "I will inspect the files."
+ ]
+ hidden = adapter(disabled_home)
+ assert hidden["display_commentary"] == []
+ assert hidden["display_reasoning"] == "Private summary."
+ assert hidden["reasoning"] == row["reasoning"]
+ assert adapter(enabled_home)["display_reasoning"] == "Private summary."
+ assert observed == [str(enabled_home), str(disabled_home), str(enabled_home)] * 2
+
+
+def test_rest_pages_bind_the_history_owner_for_messages_and_around(
+ monkeypatch, tmp_path
+):
+ from hermes_cli import config as config_mod
+ from hermes_cli.web_routers import sessions
+ import hermes_state_timeline
+
+ row = _row()
+ homes = {name: tmp_path / name for name in ("visible", "hidden")}
+ monkeypatch.setattr(
+ sessions, "_cron_profile_home", lambda profile: (profile, homes[profile])
+ )
+ monkeypatch.setattr(
+ config_mod,
+ "load_config",
+ lambda: {
+ "display": {
+ "show_commentary": str(get_hermes_home_override())
+ == str(homes["visible"])
+ }
+ },
+ )
+
+ class FakeDB:
+ def resolve_session_id(self, sid):
+ return sid
+
+ def resolve_resume_session_id(self, sid):
+ return sid
+
+ def get_messages(self, *args, **kwargs):
+ return [row]
+
+ monkeypatch.setattr(
+ sessions, "_with_db", lambda profile, fn, read_only: fn(FakeDB())
+ )
+ monkeypatch.setattr(sessions, "_timeline_session_id", lambda db, sid, owner: sid)
+ monkeypatch.setattr(
+ hermes_state_timeline,
+ "get_session_messages_around",
+ lambda *args, **kwargs: {"messages": [row], "pagination": {}},
+ )
+
+ async def exercise():
+ for profile, expected in (
+ ("visible", ["I will inspect the files."]),
+ ("hidden", []),
+ ):
+ page = await sessions.get_session_messages(
+ "sid",
+ profile=profile,
+ limit=120,
+ offset=0,
+ order="latest",
+ include_compacted=True,
+ )
+ around = await sessions.get_session_messages_around(
+ "sid", row_id=1, profile=profile, limit=120
+ )
+ assert page["messages"][0]["display_commentary"] == expected
+ assert around["messages"][0]["display_commentary"] == expected
+ assert page["profile"] == around["profile"] == profile
+
+ asyncio.run(exercise())
+
+
+def test_unscoped_rest_history_uses_custom_home_of_its_database(monkeypatch, tmp_path):
+ from hermes_cli import config as config_mod
+ from hermes_cli.web_routers import sessions
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ import hermes_state_timeline
+
+ custom, default = tmp_path / "custom", tmp_path / "default"
+ monkeypatch.setattr(
+ sessions, "_cron_profile_home", lambda profile: ("default", default)
+ )
+ monkeypatch.setattr(
+ config_mod,
+ "load_config",
+ lambda: {
+ "display": {
+ "show_commentary": str(get_hermes_home_override()) != str(custom)
+ }
+ },
+ )
+ row = _row()
+
+ class FakeDB:
+ def resolve_session_id(self, sid):
+ return sid
+
+ def resolve_resume_session_id(self, sid):
+ return sid
+
+ def get_messages(self, *args, **kwargs):
+ return [row]
+
+ monkeypatch.setattr(
+ sessions, "_with_db", lambda profile, fn, read_only: fn(FakeDB())
+ )
+ monkeypatch.setattr(sessions, "_timeline_session_id", lambda db, sid, owner: sid)
+ monkeypatch.setattr(
+ hermes_state_timeline,
+ "get_session_messages_around",
+ lambda *args, **kwargs: {"messages": [row], "pagination": {}},
+ )
+
+ async def exercise():
+ page = await sessions.get_session_messages(
+ "sid",
+ profile=None,
+ limit=120,
+ offset=0,
+ order="latest",
+ include_compacted=True,
+ )
+ around = await sessions.get_session_messages_around(
+ "sid",
+ row_id=1,
+ profile=None,
+ limit=120,
+ )
+ assert page["messages"][0]["display_commentary"] == []
+ assert around["messages"][0]["display_commentary"] == []
+
+ token = set_hermes_home_override(str(custom))
+ try:
+ asyncio.run(exercise())
+ finally:
+ reset_hermes_home_override(token)
+
+
+def test_cold_resume_uses_the_resumed_session_home(monkeypatch, tmp_path):
+ from hermes_cli import config as config_mod
+ from tui_gateway.server import _Resume
+
+ home = tmp_path / "disabled"
+ monkeypatch.setattr(
+ config_mod,
+ "load_config",
+ lambda: {
+ "display": {"show_commentary": str(get_hermes_home_override()) != str(home)}
+ },
+ )
+ resume = _Resume.__new__(_Resume)
+ resume.omit_messages = False
+ resume.profile_home = home
+
+ assert resume.messages([_row()])[0]["display_commentary"] == []
+
+
+def test_joined_canonical_commentary_uses_sanitized_display_copy(monkeypatch):
+ monkeypatch.setattr("agent.redact._redact_enabled", lambda: True)
+ raw = "Checking. Key=" + "sk-" + "demo0123456789abcdef"
+ row = _row(raw)
+ row["content"] = raw
+
+ visible = _project_for_display([row])[0]
+ assert visible["display_content"] == visible_commentary(raw)
+ assert visible["content"] == raw
+ assert visible["display_reasoning"] == "Private summary."
+
+ from agent.history_commentary import project_history_commentary
+ from hermes_cli import config as config_mod
+
+ monkeypatch.setattr(
+ config_mod, "load_config", lambda: {"display": {"show_commentary": False}}
+ )
+ hidden = project_history_commentary([row])[0]
+ assert hidden["display_content"] == visible_commentary(raw)
+ assert hidden["display_commentary"] == []
+
+
+def test_only_exact_delimiter_bounded_copy_is_removed():
+ row = _row("Same phrase")
+ row["reasoning"] = "Summary mentioning Same phrase as an incidental substring."
+ projected = _project_for_display([row])[0]
+ assert projected["display_reasoning"] == row["reasoning"]
+
+ row["reasoning"] = "Before.\n\nSame phrase\n\nAfter."
+ assert _project_for_display([row])[0]["display_reasoning"] == "Before.\n\nAfter."
+
+
+def test_foreign_and_malformed_items_are_not_public():
+ row = _row()
+ row["codex_message_items"][0]["role"] = "user"
+ assert "display_commentary" not in _project_for_display([row])[0]
+ row["codex_message_items"] = "{invalid JSON"
+ assert "display_commentary" not in _project_for_display([row])[0]
+
+
+def test_mixed_canonical_content_is_sanitized_without_truncating_possible_final(
+ monkeypatch,
+):
+ raw = "Checking. <think>hidden</think> key=" + "sk-" + "demo0123456789abcdef"
+ row = _row(raw)
+ row["content"] = raw + "\n\nFinal result."
+ monkeypatch.setattr("agent.redact._redact_enabled", lambda: True)
+
+ for projected in (_project_for_display([row])[0], _history_to_messages([row])[0]):
+ assert projected["display_commentary"] == []
+ assert projected["display_content"] == visible_commentary(row["content"])
+ assert raw not in projected["display_reasoning"]
+
+ from hermes_cli import config as config_mod
+
+ monkeypatch.setattr(
+ config_mod, "load_config", lambda: {"display": {"show_commentary": False}}
+ )
+ for projected in (_project_for_display([row])[0], _history_to_messages([row])[0]):
+ assert projected["display_commentary"] == []
+ assert projected["display_content"] == visible_commentary(row["content"])
+ assert row["content"].startswith(raw)
+
+
[email protected]("final", ["Checking. The answer is 42.", "Checking."])
+def test_stream_recovered_final_without_final_sidecar_is_authoritative(
+ monkeypatch, final
+):
+ from types import SimpleNamespace
+ from agent.turn_finalizer import _close_transcript_tail
+ from hermes_cli import config as config_mod
+
+ row = _row("Checking.")
+ agent = SimpleNamespace(_db_flush_scan_prefix=None)
+ _close_transcript_tail(agent, [row], final, False, True)
+ assert row["content"] == final
+ for visible in (True, False):
+ monkeypatch.setattr(
+ config_mod,
+ "load_config",
+ lambda visible=visible: {"display": {"show_commentary": visible}},
+ )
+ for projected in (
+ _project_for_display([row])[0],
+ _history_to_messages([row])[0],
+ ):
+ assert (
+ projected.get(
+ "display_content", projected.get("content", projected.get("text"))
+ )
+ == final
+ )
+
+
[email protected]("final", ["Checking. The answer is 42.", "Checking."])
[email protected]("phase", ["final", "final_answer", None])
+def test_canonical_content_matching_final_item_is_never_stripped(
+ monkeypatch, final, phase
+):
+ from hermes_cli import config as config_mod
+
+ row = _row("Checking.")
+ row["content"] = final
+ item = {
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": final}],
+ }
+ if phase is not None:
+ item["phase"] = phase
+ row["codex_message_items"].append(item)
+ for visible in (True, False):
+ monkeypatch.setattr(
+ config_mod,
+ "load_config",
+ lambda visible=visible: {"display": {"show_commentary": visible}},
+ )
+ for projected in (
+ _project_for_display([row])[0],
+ _history_to_messages([row])[0],
+ ):
+ assert (
+ projected.get(
+ "display_content", projected.get("content", projected.get("text"))
+ )
+ == final
+ )
+ assert projected["display_commentary"] == (["Checking."] if visible else [])
+
+
+def test_mixed_canonical_preserves_final_repetition_of_a_commentary_phrase(monkeypatch):
+ from hermes_cli import config as config_mod
+
+ row = _row("Checking")
+ row["content"] = "Checking\n\nFinal: Checking completed."
+ for visible in (True, False):
+ monkeypatch.setattr(
+ config_mod,
+ "load_config",
+ lambda visible=visible: {"display": {"show_commentary": visible}},
+ )
+ for projected in (
+ _project_for_display([row])[0],
+ _history_to_messages([row])[0],
+ ):
+ assert projected["display_content"] == row["content"]
+ assert projected["display_commentary"] == []
+
+ row["codex_message_items"].append({
+ "type": "message",
+ "role": "assistant",
+ "phase": "commentary",
+ "content": [{"type": "output_text", "text": "Second update"}],
+ })
+ row["content"] = "Checking\n\nSecond update\n\nFinal: Checking completed."
+ monkeypatch.setattr(
+ config_mod, "load_config", lambda: {"display": {"show_commentary": True}}
+ )
+ for projected in (_project_for_display([row])[0], _history_to_messages([row])[0]):
+ assert projected["display_content"] == row["content"]
+ assert projected["display_commentary"] == []
+
+
+def test_legacy_newline_and_ambiguous_repeats_do_not_leak_public_text_into_thinking():
+ row = _row("Public update.")
+ row["reasoning"] = "Private before.\nPublic update.\nPrivate after."
+ assert (
+ _project_for_display([row])[0]["display_reasoning"]
+ == "Private before.\nPrivate after."
+ )
+
+ row["reasoning"] = (
+ "Private before.\n\nPublic update.\n\nPrivate after.\n\nPublic update."
+ )
+ assert (
+ _project_for_display([row])[0]["display_reasoning"]
+ == "Private before.\n\nPrivate after."
+ )
+ assert row["reasoning"].endswith("Public update.")
+
+
+def test_overlapping_public_items_do_not_leave_partial_text_in_final_or_thinking(
+ monkeypatch,
+):
+ from hermes_cli import config as config_mod
+
+ row = _row("Start")
+ row["codex_message_items"].insert(
+ 1,
+ {
+ "type": "message",
+ "role": "assistant",
+ "phase": "commentary",
+ "content": [{"type": "output_text", "text": "Start\nTail public"}],
+ },
+ )
+ row["reasoning"] = "Private.\n\nStart\nTail public"
+ row["content"] = "Start\nTail public\n\nFinal answer."
+
+ for visible in (True, False):
+ monkeypatch.setattr(
+ config_mod,
+ "load_config",
+ lambda visible=visible: {"display": {"show_commentary": visible}},
+ )
+ for projected in (
+ _project_for_display([row])[0],
+ _history_to_messages([row])[0],
+ ):
+ assert projected["display_content"] == row["content"]
+ assert projected["display_reasoning"] == "Private."
+ assert projected["display_commentary"] == []
+
+ # Without an attributable leading commentary span, this belongs to the final.
+ row["content"] = "Leading Start\nTail public trailing"
+ for visible in (True, False):
+ monkeypatch.setattr(
+ config_mod,
+ "load_config",
+ lambda visible=visible: {"display": {"show_commentary": visible}},
+ )
+ for projected in (
+ _project_for_display([row])[0],
+ _history_to_messages([row])[0],
+ ):
+ assert projected["display_content"] == "Leading Start\nTail public trailing"
+ assert projected["display_commentary"] == (
+ ["Start", "Start\nTail public"] if visible else []
+ )
+
+ row["content"] = "Start\nTail publicFinal answer."
+ monkeypatch.setattr(
+ config_mod, "load_config", lambda: {"display": {"show_commentary": True}}
+ )
+ for projected in (_project_for_display([row])[0], _history_to_messages([row])[0]):
+ assert projected["display_content"] == row["content"]
+ assert projected["display_commentary"] == []
diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.py
index 201fff53031..f68f7d2df0d 100644
--- a/tui_gateway/compute_host.py
+++ b/tui_gateway/compute_host.py
@@ -462,7 +462,7 @@ class ComputeHost:
else:
output = server._mirror_slash_side_effects(sid, session, command) if command else ""
with session["history_lock"]:
- messages = server._history_to_messages(list(session.get("history") or []))
+ messages = server._history_to_messages(list(session.get("history") or []), profile_home=session.get("profile_home"))
ack = {"output": output, **_history_meta(session), "messages": messages}
ack["session_info"] = server._session_info(session.get("agent"), session)
return ack
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 05d03d305c1..87af3176b1c 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -399,7 +399,7 @@ def _(rid, params: dict) -> dict:
_schedule_session_cap_enforcement() # trim detached idle sessions over the cap
cwd = _sessions[sid]["cwd"]
override = session_model_override or {}
- messages = _history_to_messages(history) # hidden seed rows are not on the wire; count what is (as resume does)
+ messages = _history_to_messages(history, profile_home=profile_home) # hidden seed rows are not on the wire; count what is (as resume does)
return _ok(rid, {
"session_id": sid, "stored_session_id": key, "message_count": len(messages), "messages": messages,
# Reflect the override now so the client doesn't clobber its sticky pick.
@@ -572,7 +572,7 @@ class _Resume:
return self.db.get_messages_as_conversation(self.target, repair_alternation=repair, include_row_ids=True)
def messages(self, display: list) -> list:
- return [] if self.omit_messages else _history_to_messages(display)
+ return [] if self.omit_messages else _history_to_messages(display, profile_home=self.profile_home)
def read_history(self) -> tuple:
"""One lineage SELECT, two projections: model-fed copy alternation-repaired (healed once
@@ -1794,7 +1794,7 @@ def _(rid, params: dict, session: dict) -> dict:
# use. See #87059.
history = db.get_messages_as_conversation(
session["session_key"], include_ancestors=True, include_row_ids=True)
- return _ok(rid, {"count": len(history), "messages": _history_to_messages(history)})
+ return _ok(rid, {"count": len(history), "messages": _history_to_messages(history, profile_home=session.get("profile_home"))})
@_session_method("session.undo", live=True)
@@ -1869,7 +1869,7 @@ def _compress_via_compute_host(rid, params: dict, session: dict) -> dict:
"status": "compressed", "turn_isolation": True,
# `messages` goes top-level for the transcript replacement; don't duplicate it in the ack.
"host_ack": {key: value for key, value in ack.items() if key != "messages"}, "info": host_info,
- "messages": _history_to_messages(ack.get("messages")) if isinstance(ack.get("messages"), list) else [],
+ "messages": _history_to_messages(ack.get("messages"), profile_home=session.get("profile_home")) if isinstance(ack.get("messages"), list) else [],
"usage": host_info.get("usage") if isinstance(host_info.get("usage"), dict) else {}})
@@ -1914,7 +1914,7 @@ def _compress_live(rid, sid: str, session: dict, focus_topic: str) -> dict:
"status": "aborted" if summary["aborted"] else "compressed", "removed": removed,
"before_messages": before_count, "after_messages": len(messages),
"before_tokens": before_tokens, "after_tokens": after_tokens, "summary": summary,
- "usage": usage, "info": info, "messages": _history_to_messages(messages)})
+ "usage": usage, "info": info, "messages": _history_to_messages(messages, profile_home=session.get("profile_home"))})
finally:
# Always clear the pinned compressing status (success, no-op, or raise).
_status_update(sid, "ready")
@@ -2072,7 +2072,7 @@ def _(rid, params: dict, session: dict) -> dict:
except Exception as e:
return _err(rid, 5000, f"agent init failed on branch: {e}")
return _ok(rid, {"session_id": new_sid, "stored_session_id": new_key, "title": title, "parent": old_key,
- "message_count": len(history), "messages": _history_to_messages(history),
+ "message_count": len(history), "messages": _history_to_messages(history, profile_home=session.get("profile_home")),
"info": _session_info(agent, _sessions.get(new_sid))})
diff --git a/tui_gateway/methods_slash.py b/tui_gateway/methods_slash.py
index 138cf7fc4eb..2bf17d90a12 100644
--- a/tui_gateway/methods_slash.py
+++ b/tui_gateway/methods_slash.py
@@ -99,7 +99,7 @@ def _format_live_history_output(sid: str, session: dict, arg: str) -> str:
with session["history_lock"]:
history = list(session.get("history", []))
db_history = _live_session_messages(session)
- messages = _history_to_messages(history if db_history is None else db_history)
+ messages = _history_to_messages(history if db_history is None else db_history, profile_home=session.get("profile_home"))
if not messages:
return "No conversation history yet."
lines = ["Conversation History", "────────────────────────────────────────"]
@@ -128,12 +128,12 @@ def _format_live_prompt_output(sid: str, session: dict, arg: str) -> str:
def _format_live_context_output(sid: str, session: dict, arg: str) -> str:
from collections import Counter
try:
- messages = _history_to_messages(_live_session_messages(session) or [])
+ messages = _history_to_messages(_live_session_messages(session) or [], profile_home=session.get("profile_home"))
except Exception:
messages = [] # malformed db rows fall back to the live history below
if not messages:
with session["history_lock"]:
- messages = _history_to_messages(list(session.get("history", [])))
+ messages = _history_to_messages(list(session.get("history", [])), profile_home=session.get("profile_home"))
usage = _session_usage_snapshot(session)
mirror = _metadata_mirror(session)
lines = [f"Conversation: {len(messages)} messages" if messages else "Conversation is empty (no messages yet)."]
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index b232f7343fe..88ae448518a 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -2895,7 +2895,7 @@ def _live_session_payload(
history = _live_visible_history(session, db, in_memory_history)
# message_count follows _resume_response: the stored size when messages are omitted, else the wire count
# (a hidden seed row is in ``history`` but never on the wire).
- messages = [] if omit_messages else _history_to_messages(history)
+ messages = [] if omit_messages else _history_to_messages(history, profile_home=session.get("profile_home"))
payload = {
"info": _fallback_session_info(session), "message_count": len(history) if omit_messages else len(messages),
"messages": messages,
diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.py
index b01a4129a35..e322c24e208 100644
--- a/tui_gateway/session_history.py
+++ b/tui_gateway/session_history.py
@@ -197,7 +197,9 @@ _HISTORY_ASSISTANT_DETAIL_KEYS = (
_HISTORY_ROLES = frozenset({"user", "assistant", "tool", "system"})
-def _history_to_messages(history: list[dict]) -> list[dict]:
+def _history_to_messages(history: list[dict], *, profile_home=None) -> list[dict]:
+ from agent.history_commentary import project_history_commentary
+
messages = []
tool_call_args = {}
for m in history:
@@ -263,7 +265,7 @@ def _history_to_messages(history: list[dict]) -> list[dict]:
if m.get("display_metadata"):
msg["display_metadata"] = m["display_metadata"]
messages.append(msg)
- return messages
+ return project_history_commentary(messages, home=profile_home)
def _coerce_seed_history(value: Any) -> list[dict]: