Skip to content

The agent that grows with you

fix(desktop): persist edit previews before tool-result flush

BearHuddleston6828ffa70f4c
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 7563828d24f..9b18a3d9b76 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -2306,6 +2306,7 @@ _GATEWAY_IDENTITY_PARAMS = (
)
_CALLBACK_PARAMS = (
"tool_progress_callback", "tool_start_callback", "tool_complete_callback",
+ "tool_result_metadata_callback",
"thinking_callback", "reasoning_callback", "clarify_callback",
"read_terminal_callback", "read_preview_callback", "drive_preview_callback",
"read_window_below_callback", "connection_callback", "tour_callback",
@@ -2351,6 +2352,7 @@ def init_agent(
checkpoint_max_file_size_mb: int = 10, pass_session_id: bool = False,
requested_provider: str = None, capabilities: Optional[Dict[str, bool]] = None, cwd: Optional[str] = None,
side_agent: bool = False, memory_manager=None,
+ tool_result_metadata_callback: Optional[Callable[..., dict]] = None,
):
_install_safe_stdio()
diff --git a/agent/display.py b/agent/display.py
index 4eace0251d0..05c7689d85c 100644
--- a/agent/display.py
+++ b/agent/display.py
@@ -643,19 +643,29 @@ def _resolve_skill_manage_paths(args: dict) -> list[Path]:
return [skill_dir / "SKILL.md"] if action in {"edit", "patch"} else []
-def _resolve_local_edit_paths(tool_name: str, function_args: dict | None) -> list[Path]:
+def _resolve_local_edit_paths(tool_name: str, function_args: dict | None, task_id: str | None = None) -> list[Path]:
"""Resolve local filesystem targets for write-capable tools."""
if not isinstance(function_args, dict):
return []
if tool_name == "skill_manage":
return _resolve_skill_manage_paths(function_args)
path = function_args.get("path") if tool_name in {"write_file", "patch"} else None
+ if path and task_id is not None:
+ from tools.file_tools_paths import _resolve_path_for_task, _terminal_env_type_for_task
+
+ # A remote target may happen to exist on this host too. Never persist a
+ # preview of that unrelated file; patch can still supply its own diff.
+ if _terminal_env_type_for_task(task_id) != "local":
+ return []
+ return [Path(_resolve_path_for_task(path, task_id))]
return [_resolved_path(path)] if path else []
-def capture_local_edit_snapshot(tool_name: str, function_args: dict | None) -> LocalEditSnapshot | None:
+def capture_local_edit_snapshot(
+ tool_name: str, function_args: dict | None, *, task_id: str | None = None,
+) -> LocalEditSnapshot | None:
"""Capture before-state for local write previews."""
- paths = _resolve_local_edit_paths(tool_name, function_args)
+ paths = _resolve_local_edit_paths(tool_name, function_args, task_id)
if not paths:
return None
return LocalEditSnapshot(paths=paths, before={str(path): _snapshot_text(path) for path in paths})
diff --git a/agent/tool_executor.py b/agent/tool_executor.py
index b877a637a43..7265d18a244 100644
--- a/agent/tool_executor.py
+++ b/agent/tool_executor.py
@@ -1098,6 +1098,17 @@ def _commit_tool_result(
# string-safe fallback so a rejected image result never poisons history.
_tool_content = agent._tool_result_content_for_active_model(function_name, persisted_result)
tool_message = make_tool_result_message(function_name, _tool_content, tool_call_id, effect_disposition=effect_disposition)
+ # Prepare presentation data before the append. The emitting completion callback
+ # stays below the durability fence; raw tool/model content remains unchanged.
+ prepare_metadata = getattr(agent, "tool_result_metadata_callback", None)
+ if not blocked and prepare_metadata:
+ try:
+ display_args = _redact_tool_args_for_display(function_name, function_args) or function_args
+ metadata = prepare_metadata(tool_call_id, function_name, display_args, function_result)
+ if metadata:
+ tool_message["display_metadata"] = metadata
+ except Exception as callback_error:
+ logging.debug("Tool result metadata callback error: %s", callback_error)
messages.append(tool_message)
if not _flush_session_db_after_tool_progress(agent, messages, stage=f"tool result {function_name}"):
return None
diff --git a/apps/desktop/src/components/assistant-ui/tool/inline-edit-persistence.test.tsx b/apps/desktop/src/components/assistant-ui/tool/inline-edit-persistence.test.tsx
new file mode 100644
index 00000000000..3d8f2372f9b
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/tool/inline-edit-persistence.test.tsx
@@ -0,0 +1,175 @@
+import { readFileSync } from 'node:fs'
+
+import { cleanup, render, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it } from 'vitest'
+
+import { parseAnsi } from '@/lib/ansi'
+import { type ChatMessage, type GatewayEventPayload, toChatMessages, upsertToolPart } from '@/lib/chat-messages'
+import { toRuntimeMessage } from '@/lib/chat-runtime'
+import { getToolDiff } from '@/store/tool-diffs'
+import { $toolDisclosureStates, setHideCodeDiffs, setToolViewMode } from '@/store/tool-view'
+import type { SessionMessage } from '@/types/hermes'
+
+import { stubThreadEnvironment, stubThreadViewportSize, ThreadRuntime } from '../test-utils'
+import { Thread } from '../thread'
+
+stubThreadEnvironment()
+stubThreadViewportSize()
+
+interface Receipt {
+ rows: SessionMessage[]
+ projected: SessionMessage[]
+ completion: GatewayEventPayload
+ changed: boolean
+}
+
+// A self-contained wire-contract fixture. Optionally run this same invariant
+// against receipts produced by test_inline_edit_persistence.py's real tools/DB.
+const diff = "--- a/publish.py\n+++ b/publish.py\n@@ -1 +1 @@\n-print('before')\n+print('after')"
+const result = { success: true, path: 'publish.py', verified: true }
+const metadata = { tool_result_metadata: { inline_diff: diff } }
+
+const tool: SessionMessage = {
+ role: 'tool',
+ name: 'write_file',
+ tool_call_id: 'edit-call',
+ timestamp: 20,
+ content: JSON.stringify(result),
+ display_metadata: metadata
+}
+
+const fixtures: Record<string, Receipt> = {
+ write: {
+ rows: [
+ { role: 'user', content: 'Update the file' },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ {
+ id: tool.tool_call_id,
+ type: 'function',
+ function: { name: tool.name, arguments: '{"path":"publish.py"}' }
+ }
+ ]
+ },
+ tool
+ ],
+ projected: [{ ...tool, args: { path: 'publish.py' }, context: 'publish.py' }],
+ completion: {
+ name: tool.name,
+ tool_id: tool.tool_call_id!,
+ args: { path: 'publish.py' },
+ result,
+ inline_diff: diff
+ },
+ changed: true
+ }
+}
+
+for (const [name, raw] of Object.entries({
+ legacyPatch: { ...result, diff },
+ noop: result,
+ failed: { error: 'Write refused' },
+ falseResult: false,
+ nullResult: null,
+ emptyResult: ''
+})) {
+ const seed = fixtures.write
+
+ fixtures[name] = {
+ rows: seed.rows.map(row =>
+ row.role === 'tool' ? { ...row, content: JSON.stringify(raw), display_metadata: undefined } : row
+ ),
+ projected: seed.projected.map(row => ({ ...row, content: JSON.stringify(raw), display_metadata: undefined })),
+ completion: { ...seed.completion, result: raw, inline_diff: undefined },
+ changed: name === 'legacyPatch'
+ }
+}
+
+const receipts: Record<string, Receipt> = process.env.INLINE_EDIT_RECEIPTS
+ ? JSON.parse(readFileSync(process.env.INLINE_EDIT_RECEIPTS, 'utf8'))
+ : fixtures
+
+beforeEach(() => {
+ expect(getToolDiff('edit-call')).toBe('')
+ $toolDisclosureStates.set({})
+ setHideCodeDiffs(false)
+ setToolViewMode('product')
+})
+afterEach(cleanup)
+
+it.each(Object.entries(receipts))(
+ '%s: cold tool hydration preserves raw results and edit visibility',
+ async (_name, receipt) => {
+ const live: ChatMessage = {
+ id: 'live',
+ role: 'assistant',
+ pending: false,
+ parts: upsertToolPart([], receipt.completion, 'complete')
+ }
+
+ const liveUi = render(
+ <ThreadRuntime messages={[toRuntimeMessage(live)]}>
+ <Thread />
+ </ThreadRuntime>
+ )
+
+ if (receipt.changed) {
+ await waitFor(() => expect(liveUi.container.querySelector('[data-tool-row][data-file-edit]')).not.toBeNull())
+ }
+
+ cleanup()
+
+ // Pending call, already-rendered assistant call, and orphan/RPC projection.
+ const withCommentary = receipt.rows.map(row =>
+ row.role === 'assistant' ? { ...row, content: 'Editing now' } : row
+ )
+
+ for (const rows of [receipt.rows, withCommentary, receipt.projected]) {
+ expect(getToolDiff(receipt.completion.tool_id!)).toBe('')
+
+ for (const serialized of [false, true]) {
+ const history = rows.map(row =>
+ serialized && row.display_metadata ? { ...row, display_metadata: JSON.stringify(row.display_metadata) } : row
+ )
+
+ const cold = toChatMessages(history)
+ const parts = cold.flatMap(message => message.parts).filter(part => part.type === 'tool-call')
+
+ expect(parts).toHaveLength(1)
+ expect(parts[0].toolCallId).toBe(receipt.completion.tool_id)
+ expect(parts[0].result).toEqual(receipt.completion.result)
+ expect(parts[0].toolResultMetadata?.inline_diff).toBe(receipt.completion.inline_diff)
+
+ const ui = render(
+ <ThreadRuntime messages={cold.map(toRuntimeMessage)}>
+ <Thread />
+ </ThreadRuntime>
+ )
+
+ await waitFor(() => {
+ expect(Boolean(ui.container.querySelector('[data-tool-row][data-file-edit]'))).toBe(receipt.changed)
+ })
+
+ if (receipt.changed) {
+ expect(ui.container.textContent).toContain('publish.py')
+ expect(ui.container.textContent).not.toContain('unrelated later edit')
+
+ const diffLines = receipt.completion.inline_diff ?? (receipt.completion.result as { diff: string }).diff
+
+ const addition = parseAnsi(diffLines)
+ .map(segment => segment.text)
+ .join('')
+ .split('\n')
+ .find(line => line.includes('+print('))
+
+ expect(addition).toBeDefined()
+ expect(ui.container.textContent).toContain(addition!.slice(1))
+ }
+
+ cleanup()
+ }
+ }
+ }
+)
diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.ts
index 0b86cbed260..5c698ad3247 100644
--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts
+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts
@@ -755,6 +755,10 @@ export function textFromUnknown(value: unknown, depth = 0): string {
}
function parseStoredToolResult(content: unknown): unknown {
+ if (content === null) {
+ return null
+ }
+
if (content && typeof content === 'object') {
return content
}
@@ -801,11 +805,14 @@ export function toolPartFromStoredCall(
}
}
-export function applyStoredToolResult(messages: ChatMessage[], toolMessage: SessionMessage): boolean {
- const toolCallId = toolMessage.tool_call_id || undefined
- const toolName = toolMessage.tool_name || toolMessage.name || 'tool'
- const content = toolMessage.content || toolMessage.text || toolMessage.context || toolMessage.name
+function storedToolResultMetadata(toolMessage: SessionMessage): ToolResultMetadata | undefined {
+ const display = parseMaybeJsonObject(toolMessage.display_metadata)
+ const metadata = parseMaybeJsonObject(display.tool_result_metadata)
+ return typeof metadata.inline_diff === 'string' ? { inline_diff: metadata.inline_diff } : undefined
+}
+
+export function applyStoredToolResult(messages: ChatMessage[], toolMessage: SessionMessage): boolean {
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i]
@@ -813,24 +820,12 @@ export function applyStoredToolResult(messages: ChatMessage[], toolMessage: Sess
continue
}
- const partIndex = message.parts.findIndex(
- part =>
- part.type === 'tool-call' &&
- ((toolCallId && part.toolCallId === toolCallId) || (!toolCallId && part.toolName === toolName))
- )
+ const parts = applyStoredToolResultToParts(message.parts, toolMessage)
- if (partIndex < 0) {
+ if (!parts) {
continue
}
- const parts = [...message.parts]
- const existing = parts[partIndex]
- parts[partIndex] = {
- ...existing,
- completedAt: toolMessage.timestamp,
- result: parseStoredToolResult(content),
- isError: false
- } as ChatMessagePart
messages[i] = { ...message, parts, serverRowSpan: (message.serverRowSpan ?? 1) + 1 }
return true
@@ -845,7 +840,11 @@ export function applyStoredToolResultToParts(
): ChatMessagePart[] | null {
const toolCallId = toolMessage.tool_call_id || undefined
const toolName = toolMessage.tool_name || toolMessage.name || 'tool'
- const content = toolMessage.content || toolMessage.text || toolMessage.context || toolMessage.name
+
+ const content =
+ toolMessage.content !== undefined
+ ? toolMessage.content
+ : (toolMessage.text ?? toolMessage.context ?? toolMessage.name)
const partIndex = parts.findIndex(
part =>
@@ -863,6 +862,7 @@ export function applyStoredToolResultToParts(
...existing,
completedAt: toolMessage.timestamp,
result: parseStoredToolResult(content),
+ toolResultMetadata: storedToolResultMetadata(toolMessage),
isError: false
} as ChatMessagePart
@@ -888,7 +888,8 @@ export function storedToolMessagePart(toolMessage: SessionMessage, fallbackIndex
argsText: Object.keys(args).length ? JSON.stringify(args) : '',
timestamp: toolMessage.timestamp,
completedAt: toolMessage.timestamp,
- result: context ? { context } : {},
+ result: toolMessage.content !== undefined ? parseStoredToolResult(toolMessage.content) : context ? { context } : {},
+ toolResultMetadata: storedToolResultMetadata(toolMessage),
isError: false
}
}
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index 6a91ec97de9..dbb9d799c7d 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -1,5 +1,7 @@
import type { ConnectionRequestPayload, ToolLabel } from '@hermes/shared'
+import type { ToolResultMetadata } from '@/lib/tool-result-metadata'
+
export type StoredToolCallLabels = Record<string, ToolLabel[]>
export interface ConfigFieldSchema {
@@ -603,6 +605,7 @@ export type TimelineDisplayMetadata =
}
| { display_text: string }
| { reactions: MessageReaction[] }
+ | { tool_result_metadata: ToolResultMetadata }
/** One emoji reaction on a message. One per author, iOS-Tapback style. */
export interface MessageReaction {
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index fd32bc2ce72..434ad9f2e46 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -2788,10 +2788,12 @@ export interface SessionCreateResult {
messages: TranscriptMessage[]
info: SessionLiveInfo
}
-/** One transcript row as the gateway PROJECTS it for renderers (``session_history._project_history``): ``text`` (never ``content``), display-only ``timestamp`` / ``display_kind`` / ``display_metadata``, the durable ``row_id`` rewind targets, and for tool rows ``name`` + ``context`` preview + full ``args``. Assistant detail sidecars (``reasoning``, …) ride as extra keys. */
+/** One transcript row as the gateway PROJECTS it for renderers (``session_history._project_history``): ``text``, display-only ``timestamp`` / ``display_kind`` / ``display_metadata``, the durable ``row_id`` rewind targets, and for tool rows raw ``content``, ``tool_call_id``, ``name``, ``context`` and ``args``. Assistant detail sidecars (``reasoning``, …) ride as extra keys. */
export interface TranscriptMessage {
role: string
text?: string | null
+ content?: unknown | null
+ tool_call_id?: string | null
timestamp?: number | null
row_id?: number | null
display_kind?: string | null
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index a2dfa94aad9..8d8f8a06983 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -34672,7 +34672,7 @@
},
"TranscriptMessage": {
"additionalProperties": true,
- "description": "One transcript row as the gateway PROJECTS it for renderers (``session_history._project_history``):\n``text`` (never ``content``), display-only ``timestamp`` / ``display_kind`` / ``display_metadata``, the\ndurable ``row_id`` rewind targets, and for tool rows ``name`` + ``context`` preview + full ``args``.\nAssistant detail sidecars (``reasoning``, \u2026) ride as extra keys.",
+ "description": "One transcript row as the gateway PROJECTS it for renderers (``session_history._project_history``):\n``text``, display-only ``timestamp`` / ``display_kind`` / ``display_metadata``, the durable ``row_id``\nrewind targets, and for tool rows raw ``content``, ``tool_call_id``, ``name``, ``context`` and ``args``.\nAssistant detail sidecars (``reasoning``, \u2026) ride as extra keys.",
"properties": {
"role": {
"title": "Role",
@@ -34690,6 +34690,28 @@
"default": null,
"title": "Text"
},
+ "content": {
+ "anyOf": [
+ {},
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Content"
+ },
+ "tool_call_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Tool Call Id"
+ },
"timestamp": {
"anyOf": [
{
diff --git a/run_agent.py b/run_agent.py
index bb01bfa06f6..83f121f9684 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -299,6 +299,7 @@ class AIAgent(
pass_session_id: bool = False, requested_provider: str = None,
capabilities: Dict[str, bool] | None = None, cwd: str | None = None,
side_agent: bool = False, memory_manager=None,
+ tool_result_metadata_callback: Optional[Callable[..., dict]] = None,
):
"""Forwarder — see ``agent.agent_init.init_agent`` (same keyword parameters, minus ``tool_delay``)."""
init_kwargs = {k: v for k, v in locals().items() if k not in ("self", "tool_delay")}
diff --git a/tests/agent/test_inline_edit_persistence.py b/tests/agent/test_inline_edit_persistence.py
new file mode 100644
index 00000000000..2398c3ea7b3
--- /dev/null
+++ b/tests/agent/test_inline_edit_persistence.py
@@ -0,0 +1,175 @@
+"""Real edit -> executor -> SQLite -> history projection, without model calls.
+
+The module receipt lives in pytest's temporary root for optional cross-runtime
+renderer verification; the regression itself needs no pre-existing artifacts.
+"""
+import copy
+import contextlib
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from tests.agent.test_tool_call_incremental_persistence import (
+ _attach_real_session_db,
+ _make_agent,
+ _mock_tool_call,
+)
+
+
[email protected](scope="module")
+def receipts(tmp_path_factory):
+ records = {}
+ yield records
+ path = tmp_path_factory.getbasetemp() / "inline-edit-receipts.json"
+ path.write_text(json.dumps(records, indent=2), encoding="utf-8")
+ print(f"INLINE_EDIT_RECEIPTS={path}")
+
+
[email protected]("executor_mode", ["sequential", "concurrent"])
[email protected]("edit", ["create", "replace", "patch", "noop", "failed"])
+def test_edit_preview_is_durable_before_emission_and_display_only(
+ tmp_path, monkeypatch, executor_mode, edit, receipts,
+):
+ from agent.context_compressor import ContextCompressor
+ from agent import secret_scope
+ from agent.turn_context import build_api_messages
+ from hermes_state import SessionDB
+ from tools.environments.local import LocalEnvironment
+ from tools.file_operations import ShellFileOperations
+ from tools.terminal_tool import register_task_env_overrides, clear_task_env_overrides
+ import tools.file_tools as file_tools
+ import model_tools
+ import tui_gateway.server as progress
+
+ assert Path(model_tools.__file__).resolve().parent == Path(__file__).resolve().parents[2]
+ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True)
+ monkeypatch.setattr("agent.title_generator.maybe_auto_title", lambda *a, **kw: None)
+ # Deliberately different from the execution cwd: relative previews must use
+ # the same task target as the real file tool, not today's process directory.
+ process_cwd = tmp_path / "process"
+ process_cwd.mkdir()
+ monkeypatch.chdir(process_cwd)
+ emitted = []
+ at_emission = []
+ monkeypatch.setattr(progress, "_emit_tool_lifecycle", lambda *a: emitted.append(a))
+ homes = {tag: tmp_path / tag for tag in ("alpha", "beta")}
+ for home in homes.values():
+ home.mkdir()
+ (home / "config.yaml").write_text("terminal:\n backend: local\n", encoding="utf-8")
+
+ # Same tool identity reused in separate homes: no process-global diff cache.
+ for visit, tag in enumerate(("alpha", "beta", "alpha")):
+ home = homes[tag]
+ scope = contextlib.ExitStack()
+ scope.enter_context(progress._session_profile_runtime_scope({"profile_home": str(home)}, hydrate_secrets=False))
+ work = home / f"work-{visit}"
+ work.mkdir()
+ env = LocalEnvironment(cwd=str(work), timeout=15)
+ ops = ShellFileOperations(env, cwd=str(work))
+ monkeypatch.setattr(file_tools, "_get_file_ops", lambda task_id="default": ops)
+ path = work / "publish.py"
+ before, after = "print('before')\n", f"print('{tag}-{visit}')\n"
+ tool_name = "patch" if edit == "patch" else "write_file"
+ if edit != "create":
+ path.write_text(before, encoding="utf-8")
+ args = {"path": "publish.py", "content": before if edit == "noop" else after}
+ if edit == "patch":
+ args = {"path": "publish.py", "old_string": before.strip(), "new_string": after.strip()}
+ name = f"{executor_mode}-{edit}-{tag}-{visit}"
+ call_id = "edit-call"
+ agent = _make_agent()
+ agent.valid_tool_names = {tool_name}
+ db_path = home / "state.db"
+ db = _attach_real_session_db(agent, db_path, name)
+ register_task_env_overrides(name, {"cwd": str(work), "env_type": "local"})
+ monkeypatch.setitem(progress._sessions, name, {"agent": agent, "session_key": name})
+ # Wire the real gateway callbacks, including pre-commit preparation.
+ for key, callback in progress._agent_cbs(name).items():
+ setattr(agent, key, callback)
+ if edit in {"replace", "noop"}:
+ file_tools.read_file_tool("publish.py", task_id=name)
+ messages = [
+ {"role": "user", "content": "Update the file"},
+ {"role": "assistant", "content": "", "tool_calls": [{
+ "id": call_id, "type": "function", "function": {
+ "name": tool_name, "arguments": json.dumps(args),
+ },
+ }]},
+ ]
+ agent._flush_messages_to_session_db(messages)
+ emitted.clear()
+ at_emission.clear()
+
+ def emit(kind, sid, name, args, payload):
+ emitted.append((kind, copy.deepcopy(payload)))
+ if kind == "tool.complete":
+ with SessionDB(db_path=db_path) as cold:
+ at_emission.extend(cold.get_messages(sid))
+
+ monkeypatch.setattr(progress, "_emit_tool_lifecycle", emit)
+ try:
+ call = _mock_tool_call(tool_name, json.dumps(args), call_id)
+ getattr(agent, f"_execute_tool_calls_{executor_mode}")(
+ SimpleNamespace(tool_calls=[call]), messages, name,
+ )
+ completion = next(payload for kind, payload in emitted if kind == "tool.complete")
+ row = next(row for row in at_emission if row["role"] == "tool")
+ raw = json.loads(row["content"])
+ assert raw == completion["result"]
+ assert "inline_diff" not in raw
+ changed = edit not in {"noop", "failed"}
+ assert path.read_text(encoding="utf-8") == (after if changed else before)
+ assert bool(raw.get("error")) == (edit == "failed")
+ metadata = (row.get("display_metadata") or {}).get("tool_result_metadata") or {}
+ # This assertion was red on base: completion saw no persisted sidecar.
+ assert bool(metadata.get("inline_diff")) == changed
+ assert metadata.get("inline_diff") == completion.get("inline_diff")
+ if changed:
+ assert after.strip() in metadata["inline_diff"]
+ with SessionDB(db_path=db_path) as cold:
+ rows = cold.get_messages(name)
+ conversation = cold.get_messages_as_conversation(name)
+ projected = progress._history_to_messages(conversation)
+ projected_tool = next(row for row in projected if row["role"] == "tool")
+ assert projected_tool["tool_call_id"] == call_id
+ assert projected_tool["content"] == row["content"]
+ assert projected_tool.get("display_metadata") == row.get("display_metadata")
+ assert projected_tool["timestamp"] == row["timestamp"]
+
+ # Preparation never modifies provider bytes or the cached prefix.
+ agent._current_turn_timestamp = 1.0
+ frozen = copy.deepcopy(messages)
+ def wire(history):
+ return build_api_messages(
+ agent, history, current_turn_user_idx=0, ext_prefetch_cache="",
+ plugin_user_context="", moa_config=None, active_system_prompt="fixed prefix",
+ )
+ without_display = [{k: v for k, v in m.items() if k != "display_metadata"} for m in messages]
+ assert wire(messages) == wire(without_display)
+ before_next_turn = wire(messages)
+ assert wire(messages + [{"role": "user", "content": "Continue"}])[0][:-1] == before_next_turn[0]
+ assert messages == frozen
+
+ # Cold display does not reread the now-changed target. Exercise real
+ # compaction demotion + DB archival, preserving the original tool row.
+ path.write_text("print('unrelated later edit')\n", encoding="utf-8")
+ compacted = copy.deepcopy(conversation)
+ tool_index = next(i for i, m in enumerate(compacted) if m["role"] == "tool")
+ assert ContextCompressor._demote_tool_result_at(
+ compacted, tool_index, {call_id: (tool_name, json.dumps(args))}, 0,
+ )
+ assert compacted[tool_index].get("display_metadata") == row.get("display_metadata")
+ db.archive_and_compact(name, compacted)
+ with SessionDB(db_path=db_path) as cold:
+ archived = cold.get_messages(name, include_compacted=True)
+ active = cold.get_messages_as_conversation(name)
+ assert next(m for m in archived if m["id"] == row["id"])["content"] == row["content"]
+ assert next(m for m in active if m["role"] == "tool").get("display_metadata") == row.get("display_metadata")
+ receipts[name] = {"rows": rows, "projected": projected, "completion": completion, "changed": changed}
+ finally:
+ clear_task_env_overrides(name)
+ db.close()
+ env.cleanup()
+ scope.close()
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index 846a4828bd1..ea799896149 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -2512,6 +2512,7 @@ def test_history_to_messages_preserves_tool_calls_for_resume_display():
"context": "resume",
"name": "search_files",
"role": "tool",
+ "tool_call_id": history[2]["tool_call_id"],
},
{"role": "assistant", "text": "first answer"},
{"role": "user", "text": "second prompt"},
diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.py
index 96ef84db684..115862386b7 100644
--- a/tui_gateway/agent_callbacks.py
+++ b/tui_gateway/agent_callbacks.py
@@ -127,6 +127,8 @@ def _agent_cbs(sid: str) -> dict:
callbacks = {
"tool_start_callback": lambda tc_id, name, args: _on_tool_start(sid, tc_id, name, args),
"tool_complete_callback": lambda tc_id, name, args, result: _on_tool_complete(sid, tc_id, name, args, result),
+ "tool_result_metadata_callback": lambda tc_id, name, args, result: _prepare_tool_result_metadata(
+ 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}),
diff --git a/tui_gateway/contracts/common.py b/tui_gateway/contracts/common.py
index 3351a79625a..434697873be 100644
--- a/tui_gateway/contracts/common.py
+++ b/tui_gateway/contracts/common.py
@@ -154,12 +154,14 @@ class ToolLabel(Payload):
class TranscriptMessage(OpenModel):
"""One transcript row as the gateway PROJECTS it for renderers (``session_history._project_history``):
- ``text`` (never ``content``), display-only ``timestamp`` / ``display_kind`` / ``display_metadata``, the
- durable ``row_id`` rewind targets, and for tool rows ``name`` + ``context`` preview + full ``args``.
+ ``text``, display-only ``timestamp`` / ``display_kind`` / ``display_metadata``, the durable ``row_id``
+ rewind targets, and for tool rows raw ``content``, ``tool_call_id``, ``name``, ``context`` and ``args``.
Assistant detail sidecars (``reasoning``, …) ride as extra keys."""
role: str
text: str | None = None
+ content: JsonValue | None = None
+ tool_call_id: str | None = None
timestamp: float | None = None
row_id: int | None = None
display_kind: str | None = None
diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.py
index e322c24e208..27cd98efc4d 100644
--- a/tui_gateway/session_history.py
+++ b/tui_gateway/session_history.py
@@ -237,6 +237,11 @@ def _history_to_messages(history: list[dict], *, profile_home=None) -> list[dict
# `context` is an 80-char preview; ship args so a full-call renderer isn't truncated.
labels = _bridged_tool_labels(name, args)
messages.append({"role": "tool", "name": name, "context": _tool_ctx(name, args),
+ # Edit cards need the original result; other tool outputs
+ # remain omitted from this compact display projection.
+ **({"content": m.get("content")} if name in {"write_file", "patch", "skill_manage"} else {}),
+ **{key: m[key] for key in ("tool_call_id", "timestamp", "display_metadata")
+ if m.get(key) is not None},
**({"args": args} if args else {}), **({"labels": labels} if labels else {})})
continue
# Assistant detail sidecars can carry the only visible reply or reasoning after resume/reload.
diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.py
index 3c8efff65c4..fe2d1a55f6b 100644
--- a/tui_gateway/tool_progress.py
+++ b/tui_gateway/tool_progress.py
@@ -242,7 +242,8 @@ def _on_tool_start(sid: str, tool_call_id: str, name: str, args: dict):
if session is not None:
with contextlib.suppress(Exception):
from agent.display import capture_local_edit_snapshot
- snapshot = capture_local_edit_snapshot(name, args)
+ task_id = session.get("session_key") or getattr(session.get("agent"), "session_id", None) or sid
+ snapshot = capture_local_edit_snapshot(name, args, task_id=task_id)
if snapshot is not None:
session.setdefault("edit_snapshots", {})[tool_call_id] = snapshot
session.setdefault("tool_started_at", {})[tool_call_id] = time.time()
@@ -260,6 +261,25 @@ def _on_tool_start(sid: str, tool_call_id: str, name: str, args: dict):
_emit_tool_lifecycle("tool.start", sid, name, args, payload)
+def _prepare_tool_result_metadata(sid: str, tool_call_id: str, name: str, args: dict, result: str) -> dict:
+ """Non-emitting preview preparation for the canonical tool-result append.
+
+ Retain the exact preview for the post-flush event, including an empty preview
+ for failed/no-op edits. A cold client reads the same sidecar from SQLite.
+ """
+ session = _sessions.get(sid)
+ snapshot = session.setdefault("edit_snapshots", {}).pop(tool_call_id, None) if session is not None else None
+ metadata = {}
+ with contextlib.suppress(Exception):
+ from agent.display import render_edit_diff_with_delta
+ rendered: list[str] = []
+ if render_edit_diff_with_delta(name, result, function_args=args, snapshot=snapshot, print_fn=rendered.append):
+ metadata["inline_diff"] = "\n".join(rendered)
+ if session is not None:
+ session.setdefault("tool_result_metadata", {})[tool_call_id] = metadata
+ return {"tool_result_metadata": metadata} if metadata else {}
+
+
def _on_tool_complete(sid: str, tool_call_id: str, name: str, args: dict, result: str):
if _connector_lifecycle_is_stale(sid, name, args):
return
@@ -267,7 +287,12 @@ def _on_tool_complete(sid: str, tool_call_id: str, name: str, args: dict, result
if (labels := _tool_labels(name, args)) is not None:
payload["labels"] = labels
session = _sessions.get(sid)
- snapshot = session.setdefault("edit_snapshots", {}).pop(tool_call_id, None) if session is not None else None
+ prepared = session.setdefault("tool_result_metadata", {}) if session is not None else {}
+ if tool_call_id not in prepared:
+ # Native runtimes may emit lifecycle callbacks without the tool executor.
+ metadata = _prepare_tool_result_metadata(sid, tool_call_id, name, args, result)
+ payload.update(metadata.get("tool_result_metadata", {}))
+ payload.update(prepared.pop(tool_call_id, {}))
started_at = session.setdefault("tool_started_at", {}).pop(tool_call_id, None) if session is not None else None
duration_s = time.time() - started_at if started_at else None
if duration_s is not None:
@@ -286,11 +311,6 @@ def _on_tool_complete(sid: str, tool_call_id: str, name: str, args: dict, result
payload.update(todo_state)
if session is not None:
_cache_todo_state(session, todo_state)
- with contextlib.suppress(Exception):
- from agent.display import render_edit_diff_with_delta
- rendered: list[str] = []
- if render_edit_diff_with_delta(name, result, function_args=args, snapshot=snapshot, print_fn=rendered.append):
- payload["inline_diff"] = "\n".join(rendered)
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)):
_emit_tool_lifecycle("tool.complete", sid, name, args, payload)