The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): hide reasoning and tool chrome when show_reasoning is off
brooklyn!5f32e201c988
diff --git a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsxindex 69762b37d99..f274ee77909 100644--- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx@@ -27,6 +27,7 @@ import { useI18n } from '@/i18n'import { mcpTargets, toolLabels } from '@/lib/connector-tools'import { generatedImageFromResult } from '@/lib/generated-images'import { separateGluedReasoningBlocks } from '@/lib/reasoning-blocks'+import { isCardTool } from '@/lib/tool-render-class'import { isTodoToolName } from '@/lib/todos'import { useEnterAnimation } from '@/lib/use-enter-animation'import { cn } from '@/lib/utils'@@ -75,6 +76,8 @@ const DelegateToolPart: FC<TimelineToolCallProps> = props => {}const ChainToolFallback: FC<TimelineToolCallProps> = props => {+ const showReasoning = useStore($showReasoning)+// todo parts are hoisted to a dedicated panel above the message content.if (isTodoToolName(props.toolName)) {return null@@ -139,6 +142,13 @@ const ChainToolFallback: FC<TimelineToolCallProps> = props => {return <ConnectorExecution {...props} />}+ // Answer-only: process chrome (reads, searches, commands) stays off the+ // transcript. Cards, approvals, and failed calls the user must act on remain.+ // reasoning_effort is not a display switch.+ if (!showReasoning && !props.isError && !isCardTool(props.toolName)) {+ return null+ }+return <ToolFallback {...props} />}diff --git a/apps/desktop/src/components/assistant-ui/tool/answer-only-chrome.test.tsx b/apps/desktop/src/components/assistant-ui/tool/answer-only-chrome.test.tsxnew file mode 100644index 00000000000..fa32e12980d--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/tool/answer-only-chrome.test.tsx@@ -0,0 +1,110 @@+import { type ThreadMessage } from '@assistant-ui/react'+import { cleanup, render, screen } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'++import { stubThreadEnvironment, stubThreadViewportSize, ThreadRuntime } from '@/components/assistant-ui/test-utils'+import { Thread } from '@/components/assistant-ui/thread'+import { clearAllPrompts, setApprovalRequest } from '@/store/prompts'+import { $showReasoning } from '@/store/reasoning-disclosure'+import { $activeSessionId } from '@/store/session'++stubThreadEnvironment()+stubThreadViewportSize()++const createdAt = new Date('2026-06-03T00:00:00.000Z')++function answerOnlyMessage(): ThreadMessage {+ return {+ id: 'assistant-answer-only',+ role: 'assistant',+ content: [+ {+ type: 'reasoning',+ text: 'hidden chain of thought',+ timestamp: createdAt.getTime() / 1000 + 1,+ completedAt: createdAt.getTime() / 1000 + 2+ },+ {+ type: 'tool-call',+ toolCallId: 'read-1',+ toolName: 'read_file',+ args: { path: '/repo/src/status.tsx' },+ argsText: JSON.stringify({ path: '/repo/src/status.tsx' }),+ result: { content: 'export const Status = () => null' }+ },+ {+ type: 'tool-call',+ toolCallId: 'search-1',+ toolName: 'search_files',+ args: { query: 'toolRuns' },+ argsText: JSON.stringify({ query: 'toolRuns' }),+ result: { matches: [] }+ },+ {+ type: 'tool-call',+ toolCallId: 'fail-1',+ toolName: 'terminal',+ args: { command: 'deploy' },+ argsText: JSON.stringify({ command: 'deploy' }),+ isError: true,+ result: { error: 'disk full, act now' }+ },+ {+ type: 'text',+ text: 'final answer only'+ }+ ],+ status: { type: 'complete', reason: 'stop' },+ createdAt,+ metadata: {+ unstable_state: null,+ unstable_annotations: [],+ unstable_data: [],+ steps: [],+ custom: {}+ }+ } as unknown as ThreadMessage+}++function Harness() {+ return (+ <ThreadRuntime messages={[answerOnlyMessage()]}>+ <Thread />+ </ThreadRuntime>+ )+}++beforeEach(() => {+ clearAllPrompts()+ $activeSessionId.set('sess-1')+ $showReasoning.set(true)+})++afterEach(() => {+ cleanup()+ clearAllPrompts()+ $activeSessionId.set(null)+ $showReasoning.set(true)+})++describe('answer-only display policy', () => {+ it('hides reasoning and non-essential tool chrome without requiring reasoning_effort none', async () => {+ $showReasoning.set(false)+ setApprovalRequest({ command: 'rm -rf /tmp/x', description: 'dangerous command', sessionId: 'sess-1' })++ const { container } = render(<Harness />)++ expect(await screen.findByText('final answer only')).toBeTruthy()+ expect(container.querySelector('[data-slot="aui_thinking-disclosure"]')).toBeNull()+ expect(container.querySelector('[data-tool-summary]')).toBeNull()+ expect(screen.getByRole('button', { name: /Run/ })).toBeTruthy()+ expect(container.querySelectorAll('[data-tool-row]')).toHaveLength(1)+ })++ it('still shows tool chrome when reasoning blocks are on', async () => {+ const { container } = render(<Harness />)++ expect(await screen.findByText(/Explored 2 files/)).toBeTruthy()+ expect(container.querySelector('[data-slot="aui_thinking-disclosure"]')).not.toBeNull()+ })+})diff --git a/apps/desktop/src/components/assistant-ui/tool/approval.tsx b/apps/desktop/src/components/assistant-ui/tool/approval.tsxindex 72d90f58d29..5fafa4af148 100644--- a/apps/desktop/src/components/assistant-ui/tool/approval.tsx+++ b/apps/desktop/src/components/assistant-ui/tool/approval.tsx@@ -35,6 +35,7 @@ import {sessionApprovalRequests,sessionApprovalStackSize} from '@/store/prompts'+import { $showReasoning } from '@/store/reasoning-disclosure'import { setToolDisclosureOpen } from '@/store/tool-view'import { isApprovalActivity } from './approval-activity'@@ -78,6 +79,7 @@ export const PendingApprovalStack: FC = () => {function ApprovalActivity({ floating, visible }: { floating: boolean; visible: boolean }) {const { t } = useI18n()const reduced = useReducedMotion()+ const showReasoning = useStore($showReasoning)const summary = useAuiState(state => {if (!visible) {@@ -118,6 +120,12 @@ function ApprovalActivity({ floating, visible }: { floating: boolean; visible: b.join('\n')})+ // The pending approval stays. The run summary beside it is process chrome+ // and follows the same display flag as reasoning blocks.+ if (!showReasoning) {+ return null+ }+return (<AnimatePresence initial={false}>{visible && (diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx b/apps/desktop/src/components/assistant-ui/tool/fallback.tsxindex 97155c5a587..ab30d1a7a92 100644--- a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx+++ b/apps/desktop/src/components/assistant-ui/tool/fallback.tsx@@ -50,6 +50,7 @@ import { useEnterAnimation } from '@/lib/use-enter-animation'import { cn } from '@/lib/utils'import { recordPreviewArtifact } from '@/store/preview-status'import { sessionApprovalRequest } from '@/store/prompts'+import { $showReasoning } from '@/store/reasoning-disclosure'import { $toolInlineDiff } from '@/store/tool-diffs'import { $toolRowDismissed, dismissToolRow } from '@/store/tool-dismiss'import {@@ -1044,6 +1045,8 @@ export const ToolGroupSlot: FC<PropsWithChildren<{ endIndex: number; startIndex:endIndex,startIndex}) => {+ const showReasoning = useStore($showReasoning)+// Joined rather than returned as an array: assistant-ui compares selector// results with `Object.is` and re-runs them on every store update, so a// fresh array would re-render the whole group on every text delta.@@ -1064,6 +1067,13 @@ export const ToolGroupSlot: FC<PropsWithChildren<{ endIndex: number; startIndex:const items = useMemo(() => splitRunItems(toolNameKey.split('\u0000')), [toolNameKey])const rows = Children.toArray(children)+ // Answer-only skips the run scaffold ("Explored N files"). Children still+ // mount so clarify, diffs, and failed calls can render on their own.+ // reasoning_effort is not a display switch.+ if (!showReasoning) {+ return children+ }+return (<ToolEmbedContext.Provider value={false}>{items.map(item =>diff --git a/tests/tui_gateway/test_show_reasoning_display_gate.py b/tests/tui_gateway/test_show_reasoning_display_gate.pynew file mode 100644index 00000000000..3331d8d6cf8--- /dev/null+++ b/tests/tui_gateway/test_show_reasoning_display_gate.py@@ -0,0 +1,121 @@+"""display.show_reasoning false is answer-only on the live callback path.++The session flag, not reasoning_effort, decides whether reasoning/thinking+deltas and non-essential tool chrome leave the gateway.+"""++import json+from types import SimpleNamespace++from tui_gateway import server+++def _capture(monkeypatch):+ events = []+ monkeypatch.setattr(+ server, "_emit", lambda event_type, sid, payload=None: events.append((event_type, sid, payload))+ )+ return events+++def _session(monkeypatch, sid, *, show_reasoning, effort="high"):+ monkeypatch.setitem(+ server._sessions,+ sid,+ {+ "show_reasoning": show_reasoning,+ "tool_progress_mode": "all",+ "tool_started_at": {},+ "edit_snapshots": {},+ "agent": SimpleNamespace(reasoning_config={"enabled": True, "effort": effort}),+ },+ )+++def test_hidden_reasoning_does_not_emit_reasoning_deltas(monkeypatch):+ events = _capture(monkeypatch)+ _session(monkeypatch, "hide-deltas", show_reasoning=False, effort="high")++ callbacks = server._agent_cbs("hide-deltas")+ callbacks["reasoning_callback"]("chain of thought from any provider")+ # thinking.delta is the wait/spinner line, not a reasoning block.+ callbacks["thinking_callback"]("⏳ waiting on the provider")++ assert [event[0] for event in events] == ["thinking.delta"]+ assert events[0][2]["text"] == "⏳ waiting on the provider"+++def test_shown_reasoning_still_emits_reasoning_delta(monkeypatch):+ events = _capture(monkeypatch)+ _session(monkeypatch, "show-deltas", show_reasoning=True, effort="high")++ server._agent_cbs("show-deltas")["reasoning_callback"]("visible thought")++ assert [event[0] for event in events] == ["reasoning.delta"]+ assert events[0][2]["text"] == "visible thought"+++def test_child_mirror_skips_reasoning_delta_when_hidden(monkeypatch):+ events = _capture(monkeypatch)+ _session(monkeypatch, "child-sid", show_reasoning=False)+ monkeypatch.setattr(+ server, "_find_live_session_by_key", lambda key: ("child-sid", {"agent": None, "show_reasoning": False})+ )++ server._mirror_subagent_to_child(+ "subagent.thinking", {"child_session_id": "child-key", "text": "delegated thought"}+ )++ assert not any(event[0] == "reasoning.delta" for event in events)+++def test_hidden_reasoning_drops_completed_reasoning_block(monkeypatch):+ events = _capture(monkeypatch)+ _session(monkeypatch, "hide-available", show_reasoning=False, effort="medium")++ server._on_tool_progress("hide-available", "reasoning.available", "_thinking", "finished thought", None)++ assert events == []+++def test_hidden_reasoning_suppresses_nonessential_tool_chrome_without_effort_none(monkeypatch):+ events = _capture(monkeypatch)+ _session(monkeypatch, "hide-tools", show_reasoning=False, effort="high")++ server._on_tool_start("hide-tools", "tool-read", "read_file", {"path": "README.md"})+ server._on_tool_complete("hide-tools", "tool-read", "read_file", {"path": "README.md"}, "contents")+ server._agent_cbs("hide-tools")["tool_gen_callback"]("terminal")++ clarify_args = {"question": "Pick one", "choices": ["A", "B"]}+ server._on_tool_start("hide-tools", "tool-clarify", "clarify", clarify_args)+ server._on_tool_complete(+ "hide-tools",+ "tool-clarify",+ "clarify",+ clarify_args,+ json.dumps({"question": "Pick one", "user_response": "A"}),+ )+ server._on_tool_complete(+ "hide-tools",+ "tool-fail",+ "terminal",+ {"command": "deploy"},+ json.dumps({"error": "disk full"}),+ )++ kinds = [event[0] for event in events]+ assert "tool.generating" not in kinds+ assert not any(event[2].get("name") == "read_file" for event in events)+ assert [event[0] for event in events if event[2].get("name") == "clarify"] == ["tool.start", "tool.complete"]+ failed = [event for event in events if event[2].get("tool_id") == "tool-fail"]+ assert [event[0] for event in failed] == ["tool.complete"]+ assert failed[0][2]["result"]["error"] == "disk full"+++def test_hidden_reasoning_drops_moa_reference_chrome(monkeypatch):+ events = _capture(monkeypatch)+ _session(monkeypatch, "hide-moa", show_reasoning=False, effort="high")++ server._on_tool_progress("hide-moa", "moa.reference", "reference-a", "other model's thoughts", None)++ assert events == []diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.pyindex 1507c5202ac..8444ea736eb 100644--- a/tui_gateway/agent_callbacks.py+++ b/tui_gateway/agent_callbacks.py@@ -57,19 +57,27 @@ def _mirror_subagent_to_child(event_type: str, payload: dict) -> None:# thinking/text/start (the child's goal, as a one-time header) are plain deltas.if event_type in _CHILD_DELTA_EVENTS:if text:- _emit(_CHILD_DELTA_EVENTS[event_type], csid,- {"text": f"{text}\n" if event_type == "subagent.start" else text})+ mapped = _CHILD_DELTA_EVENTS[event_type]+ if mapped == "reasoning.delta" and not _session_show_reasoning(csid):+ return+ _emit(mapped, csid, {"text": f"{text}\n" if event_type == "subagent.start" else text})returnif event_type not in ("subagent.tool", "subagent.complete"):returnif st["open_tool"]:- _emit("tool.complete", csid, st["open_tool"])+ open_tool = st["open_tool"]+ st["open_tool"] = None+ if _process_tool_chrome_enabled(csid) or _tool_lifecycle_required_for_ui(str(open_tool.get("name") or "")):+ _emit("tool.complete", csid, open_tool)if event_type == "subagent.tool":st["seq"] += 1- tool = {"name": str(payload.get("tool_name") or "tool"),+ tool_name = str(payload.get("tool_name") or "tool")+ tool = {"name": tool_name,"tool_id": f"submirror:{child_key}:{st['seq']}", "args": {}}if preview := str(payload.get("tool_preview") or payload.get("text") or ""):tool["preview"] = preview+ if not _process_tool_chrome_enabled(csid) and not _tool_lifecycle_required_for_ui(tool_name):+ returnst["open_tool"] = tool_emit("tool.start", csid, tool)else:@@ -102,6 +110,8 @@ def _agent_status_update(sid: str, kind: str, text: str | None = None) -> None:def _agent_thinking_update(sid: str, text: str) -> None:from gateway.warning_notifications import DiagnosticText+ # Wait notices and the quiet spinner share this callback with diagnostics.+ # They are not reasoning blocks; display.show_reasoning must not swallow them.if not _agent_presentation_enabled(sid, diagnostic=isinstance(text, DiagnosticText)):return_emit("thinking.delta", sid, {"text": text})@@ -116,6 +126,12 @@ def _agent_notice_update(sid: str, notice) -> None:"ttl_ms": notice.ttl_ms, "key": notice.key, "id": notice.id})+def _emit_reasoning_delta(sid: str, text: str) -> None:+ if not _session_show_reasoning(sid):+ return+ _emit("reasoning.delta", sid, {"text": text, **({"verbose": True} if _session_verbose(sid) else {})})++def _agent_cbs(sid: str) -> dict:def _read_block(method: str, timeout: int):# read_terminal / read_preview (desktop GUI): server request like clarify; the preview@@ -131,12 +147,11 @@ def _agent_cbs(sid: str) -> dict:sid, tc_id, name, args, result),"tool_progress_callback": lambda event_type, name=None, preview=None, args=None, **kwargs: _on_tool_progress(sid, event_type, name, preview, args, **kwargs),- "tool_gen_callback": lambda name: _tool_progress_enabled(sid) and _emit("tool.generating", sid, {"name": name}),+ "tool_gen_callback": lambda name: _process_tool_chrome_enabled(sid) and _emit("tool.generating", sid, {"name": name}),"thinking_callback": lambda text: _agent_thinking_update(sid, text),# Affection reaction (ily / <3 / good bot) → hearts; core-detected so TUI/desktop share it."reaction_callback": lambda kind: _emit("reaction", sid, {"kind": kind}),- "reasoning_callback": lambda text: _emit(- "reasoning.delta", sid, {"text": text, **({"verbose": True} if _session_verbose(sid) else {})}),+ "reasoning_callback": lambda text: _emit_reasoning_delta(sid, text),"status_callback": lambda kind, text=None: _agent_status_update(sid, kind, text),# Credits/notice spine: AgentNotice → notification.show; recovery → notification.clear."notice_callback": lambda n: _agent_notice_update(sid, n),diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 13a0c942117..8f07cf65fbb 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2006,6 +2006,19 @@ def _session_verbose(sid: str) -> bool:return _session_tool_progress_mode(sid) == "verbose"+def _session_show_reasoning(sid: str) -> bool:+ """Session display flag. Missing means the config default, not hidden."""+ session = _sessions.get(sid) or {}+ if "show_reasoning" in session:+ return bool(session["show_reasoning"])+ return _load_show_reasoning()+++def _process_tool_chrome_enabled(sid: str) -> bool:+ """Non-essential tool rows follow display.show_reasoning, not reasoning_effort."""+ return _session_show_reasoning(sid) and _tool_progress_enabled(sid)++def _tool_progress_enabled(sid: str) -> bool:return _session_tool_progress_mode(sid) != "off"diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.pyindex c2d60b2107c..49fec5fef52 100644--- a/tui_gateway/tool_progress.py+++ b/tui_gateway/tool_progress.py@@ -188,6 +188,22 @@ def _todo_state_from_history(history) -> dict | None:return None+def _tool_result_needs_user(result: object) -> bool:+ """A failed call the user still has to see. Display policy must not swallow it."""+ if not isinstance(result, str) or not result:+ return False+ try:+ data = json.loads(result)+ except Exception:+ return False+ if not isinstance(data, dict):+ return False+ if data.get("success") is False or data.get("ok") is False:+ return True+ error = data.get("error")+ return isinstance(error, str) and bool(error.strip())++def _tool_labels(name: str, args: dict) -> list[dict] | None:from agent.display import tool_labels_for_call@@ -250,7 +266,7 @@ def _on_tool_start(sid: str, tool_call_id: str, name: str, args: dict):# A preview prepared for an earlier call whose completion never fired (failed# flush) must not attach to a provider that reuses the same call id.session.setdefault("tool_result_metadata", {}).pop(tool_call_id, None)- if (_tool_progress_enabled(sid) or _tool_lifecycle_required_for_ui(name)+ if (_process_tool_chrome_enabled(sid) or _tool_lifecycle_required_for_ui(name)or _connector_tool_lifecycle(name, args)):payload: dict[str, object] = {"tool_id": tool_call_id, "name": name, "context": _tool_ctx(name, args)}if (labels := _tool_labels(name, args)) is not None:@@ -316,8 +332,9 @@ def _on_tool_complete(sid: str, tool_call_id: str, name: str, args: dict, resultpayload.update(todo_state)if session is not None:_cache_todo_state(session, todo_state)- if (_tool_progress_enabled(sid) or payload.get("inline_diff") or _tool_lifecycle_required_for_ui(name)- or name in _TODO_TOOL_NAMES or _connector_tool_lifecycle(name, args)):+ if (_process_tool_chrome_enabled(sid) or payload.get("inline_diff") or _tool_lifecycle_required_for_ui(name)+ or name in _TODO_TOOL_NAMES or _connector_tool_lifecycle(name, args)+ or _tool_result_needs_user(result)):_emit_tool_lifecycle("tool.complete", sid, name, args, payload)# Task state is application data, not tool-progress chrome: a dedicated full-snapshot event lets# every client reconcile without parsing tool args.@@ -339,11 +356,15 @@ def _progress_output_risk(sid, name, preview, kw):def _progress_reasoning(sid, name, preview, kw):+ if not _session_show_reasoning(sid):+ return_emit("reasoning.available", sid, {"text": str(preview), **({"verbose": True} if _session_verbose(sid) else {})})def _progress_moa_reference(sid, name, preview, kw):- # MoA reference-model output, rendered as a labelled block before the aggregator's response.+ # Reference-model output lands in the reasoning disclosure. Answer-only drops it.+ if not _session_show_reasoning(sid):+ return# `name` is the slot label, `preview` the text.ref_payload: dict[str, object] = {"label": str(name), "text": str(preview or "")}for key, out in (("moa_index", "index"), ("moa_count", "count")):@@ -355,10 +376,7 @@ def _progress_moa_reference(sid, name, preview, kw):def _progress_moa_progress(sid, name, preview, kw):# Drives the status-bar `MOA: 2/3 refs done`; both counters required for deterministic rendering.refs_done, refs_total = kw.get("moa_refs_done"), kw.get("moa_refs_total")- # Per-reference completion — drives the status-bar progress indicator (`MOA: 2/3 refs done`) requested- # in issue #59546. Only emitted when both counters are present so the client can render- # deterministically.- if refs_done is None or refs_total is None:+ if not _session_show_reasoning(sid) or refs_done is None or refs_total is None:return_emit("moa.progress", sid, {"label": str(name or ""), "refs_done": int(refs_done), "refs_total": int(refs_total)})@@ -366,7 +384,7 @@ def _progress_moa_progress(sid, name, preview, kw):def _progress_moa_phase(sid, name, preview, kw):# Currently only phase="aggregator" fires, once fan-out completes.phase = kw.get("moa_phase")- if not phase:+ if not phase or not _session_show_reasoning(sid):returnphase_payload: dict[str, object] = {"phase": str(phase)}for key, out in (("moa_refs_done", "refs_done"), ("moa_refs_total", "refs_total")):