Skip to content

The agent that grows with you

refactor(tui): preview-restart history helper takes a message list

Teknium3345a172a3c1
diff --git a/gateway/session_tui_side.py b/gateway/session_tui_side.py
index 8b72d38a297..22e2a0dfcf9 100644
--- a/gateway/session_tui_side.py
+++ b/gateway/session_tui_side.py
@@ -198,8 +198,7 @@ async def preview_restart(connection, ref, params):
preview_cwd = preview_cwd if preview_cwd and os.path.isdir(preview_cwd) else ''
except (OSError, ValueError):
preview_cwd = ''
- history = _preview_restart_history({'history': authority.db.get_messages_as_conversation(target)
- if target else []})
+ history = _preview_restart_history(authority.db.get_messages_as_conversation(target) if target else [])
prompt = '\n'.join(line for line in [
'The desktop preview pane cannot load a local server URL.', f'Preview URL: {url.strip()}',
f"Current working directory: {cwd or '(unknown)'}",
diff --git a/tests/gateway/test_session_tui_side.py b/tests/gateway/test_session_tui_side.py
index eae6af4053e..de2f7b9d93d 100644
--- a/tests/gateway/test_session_tui_side.py
+++ b/tests/gateway/test_session_tui_side.py
@@ -99,6 +99,9 @@ def test_preview_restart_runs_a_hidden_terminal_agent_and_reports_on_the_session
async def probe():
async with websocket(home, desc) as ws:
sid = (await rpc(ws, 'session.create', request_id='pv', source='tui', toolsets=[]))['result']['session_id']
+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='warm', text='DEV_SERVER_TURN')
+ await settled(home)
+ before = (await rpc(ws, 'session.resume', session_id=sid))['result']['messages']
reply, event = await call_and_await_event(
ws, 'preview.restart', 'preview.restart.complete', session_id=sid,
url='http://127.0.0.1:5173/', cwd=str(tmp_path), context='PREVIEW_CONSOLE')
@@ -108,6 +111,8 @@ def test_preview_restart_runs_a_hidden_terminal_agent_and_reports_on_the_session
assert event['payload'] == {'task_id': task, 'text': 'CONTROL_ACK'}, event
sent = json.dumps(peer.requests[-1])
assert 'http://127.0.0.1:5173/' in sent and 'PREVIEW_CONSOLE' in sent
+ # The stored transcript is the restart agent's context (the trimmed history list).
+ assert 'DEV_SERVER_TURN' in sent, sent
tools = {t['function']['name'] for t in peer.requests[-1].get('tools') or []}
assert 'terminal' in tools and 'delegate_task' not in tools, tools
for params, reason in [({'session_id': sid, 'url': ' '}, 'invalid_params'),
@@ -115,6 +120,18 @@ def test_preview_restart_runs_a_hidden_terminal_agent_and_reports_on_the_session
({'session_id': sid, 'url': 'http://x', 'profile': 'foreign'}, 'profile_mismatch')]:
denied = await rpc(ws, 'preview.restart', **params)
assert denied.get('error', {}).get('message') == reason, denied
- assert not admissions(home)
- assert not (await rpc(ws, 'session.resume', session_id=sid))['result']['messages']
+ assert [r[0] for r in admissions(home)] == ['warm']
+ assert (await rpc(ws, 'session.resume', session_id=sid))['result']['messages'] == before
asyncio.run(probe())
+
+
+def test_preview_restart_history_trims_a_plain_message_list():
+ """TUI-12: the trimming helper takes a message snapshot, not a session-shaped dict, so the
+ owner passes its stored transcript directly (the legacy sidecar snapshots under its lock)."""
+ from tui_gateway.agent_callbacks import _preview_restart_history
+ messages = [{'role': 'user', 'content': 'run vite'}, {'role': 'assistant', 'content': 'ok', 'reasoning': 'r'},
+ {'role': 'tool', 'content': 'x' * 50, 'tool_call_id': 't'}]
+ trimmed = _preview_restart_history(messages, max_tool_chars=10)
+ assert [m['role'] for m in trimmed] == ['user', 'assistant', 'tool']
+ assert 'reasoning' not in trimmed[1] and trimmed[2]['content'].startswith('x' * 10 + '\n... (truncated')
+ assert _preview_restart_history([]) == [] and _preview_restart_history(None) == []
diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.py
index 26249132cb7..0863f12b5e0 100644
--- a/tui_gateway/agent_callbacks.py
+++ b/tui_gateway/agent_callbacks.py
@@ -448,15 +448,13 @@ def _side_agent_session_db(parent_db):
release_or_close(db)
-def _preview_restart_history(session: dict, max_messages: int = 24, max_tool_chars: int = 1200) -> list[dict]:
+def _preview_restart_history(messages: list[dict] | None, max_messages: int = 24,
+ max_tool_chars: int = 1200) -> list[dict]:
"""Distill recent parent history for the ephemeral preview-restart agent (else it guesses
app/cwd/port from the bare URL): last ``max_messages`` back to the last user turn, tool
- results truncated to ``max_tool_chars``."""
- try:
- with session["history_lock"]:
- history = list(session.get("history") or [])
- except Exception:
- history = list(session.get("history") or [])
+ results truncated to ``max_tool_chars``. ``messages`` is a snapshot the caller owns (the
+ legacy session's history taken under its ``history_lock``, or the owner's stored transcript)."""
+ history = list(messages or [])
if not history:
return []
last_user = next((i for i in range(len(history) - 1, -1, -1) if history[i].get("role") == "user"), None)
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index 8bf0a854813..ac8c35f571f 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -1148,7 +1148,9 @@ def _(rid, params: dict) -> dict:
return _err(rid, 4012, "url required")
task_id = f"preview_{uuid.uuid4().hex[:6]}"
parent = params.get("session_id", "")
- parent_history = _preview_restart_history(session)
+ with session.get("history_lock") or contextlib.nullcontext():
+ snapshot = list(session.get("history") or [])
+ parent_history = _preview_restart_history(snapshot)
prompt = "\n".join(
line
for line in [