Skip to content

The agent that grows with you

feat(tui_gateway): inline_images=false switch on session.resume history reads

Brooklyn Nicholson88039d73b364
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index a8406e2786d..937ce8bc52f 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -2855,6 +2855,7 @@ export interface SessionResumeParams {
omit_messages?: boolean
eager_build?: boolean
close_on_disconnect?: boolean
+ inline_images?: boolean
}
export interface SessionResumeResult {
session_id: string
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index d67f318a8df..98892cf02ce 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -30325,6 +30325,11 @@
"default": false,
"title": "Close On Disconnect",
"type": "boolean"
+ },
+ "inline_images": {
+ "default": true,
+ "title": "Inline Images",
+ "type": "boolean"
}
},
"required": [
diff --git a/tests/tui_gateway/test_history_inline_images.py b/tests/tui_gateway/test_history_inline_images.py
new file mode 100644
index 00000000000..19ab24e616e
--- /dev/null
+++ b/tests/tui_gateway/test_history_inline_images.py
@@ -0,0 +1,119 @@
+"""``inline_images=false`` history reads (#116511): the reachable ``[image]`` projection.
+
+``_history_dict_text(content, *, image_urls)`` has always had both renderings; the API layer
+hard-coded ``image_urls=True`` so a remote client re-transmitted every stored attachment
+(26+ MiB for one measured conversation) on every ``session.resume``. Both history surfaces now
+accept ``inline_images=false`` and route to the placeholder branch:
+
+* ``session.resume`` — every path that carries messages (cold/lazy resume, live reattach);
+* ``GET /api/sessions/{id}/messages`` — the REST pages the Desktop hydrates over.
+
+Contract: the SAME stored row inlines its data URI by default and renders ``[image]``
+when asked; non-image content is byte-identical either way.
+"""
+
+import pytest
+
+import tui_gateway.server as srv
+import tui_gateway.methods_session # noqa: F401 (registers the RPC methods)
+
+DATA_URI = "data:image/png;base64," + "a" * 128
+IMAGE_TURN = [
+ {"role": "user", "content": [
+ {"type": "text", "text": "what is this?"},
+ {"type": "image_url", "image_url": {"url": DATA_URI}},
+ ]},
+ {"role": "assistant", "content": "a chart"},
+]
+
+
+def test_coerce_message_text_switches_image_rendering():
+ """The projection seam: default inlines the URI; ``image_urls=False`` renders ``[image]``."""
+ coerce, history_to_messages = srv._coerce_message_text, srv._history_to_messages # server.py-bound
+ content = IMAGE_TURN[0]["content"]
+ assert DATA_URI in coerce(content)
+ assert DATA_URI not in coerce(content, image_urls=False)
+ assert "[image]" in coerce(content, image_urls=False)
+ # Non-image content is identical either way.
+ assert coerce("plain") == coerce("plain", image_urls=False) == "plain"
+
+
+def test_history_to_messages_honors_the_switch():
+ history_to_messages = srv._history_to_messages # server.py-bound
+ default = history_to_messages(IMAGE_TURN)
+ assert DATA_URI in default[0]["text"]
+
+ inlined_off = history_to_messages(IMAGE_TURN, image_urls=False)
+ assert "[image]" in inlined_off[0]["text"]
+ assert DATA_URI not in inlined_off[0]["text"]
+ assert inlined_off[1] == default[1] == {"role": "assistant", "text": "a chart"}
+
+
+def test_resume_cold_carries_the_switch(tmp_path, monkeypatch):
+ """A cold ``session.resume`` with ``inline_images=false`` returns the placeholder projection."""
+ from hermes_state import SessionDB
+
+ home = tmp_path / ".hermes"
+ home.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr("hermes_state.DEFAULT_DB_PATH", home / "state.db")
+ db = SessionDB(home / "state.db")
+ db.create_session("img-chat", source="desktop")
+ db.append_messages_batch("img-chat", [{"role": "user", "content": IMAGE_TURN[0]["content"]}])
+ try:
+ monkeypatch.setattr(srv, "_get_db", lambda: db)
+ monkeypatch.setattr(srv, "_enable_gateway_prompts", lambda: None)
+ monkeypatch.setattr(srv, "_schedule_agent_build", lambda *a, **k: None)
+ monkeypatch.setattr(srv, "_schedule_session_cap_enforcement", lambda *a, **k: None)
+ monkeypatch.setattr(srv, "_maybe_schedule_auto_continue", lambda *a, **k: None)
+ monkeypatch.setattr(srv, "_stored_session_runtime_overrides", lambda _found: {})
+ known = set(srv._sessions)
+ try:
+ resp = srv._methods["session.resume"](1, {"session_id": "img-chat"})
+ assert "error" not in resp, resp
+ assert DATA_URI in resp["result"]["messages"][0]["text"]
+
+ resp = srv._methods["session.resume"](1, {"session_id": "img-chat", "inline_images": False})
+ assert "error" not in resp, resp
+ assert "[image]" in resp["result"]["messages"][0]["text"]
+ assert DATA_URI not in resp["result"]["messages"][0]["text"]
+ finally:
+ for sid in [s for s in srv._sessions if s not in known]:
+ srv._sessions.pop(sid, None)
+ finally:
+ db.close()
+
+
[email protected]("inline_images", [True, False])
+def test_resume_live_reattach_carries_the_switch(tmp_path, monkeypatch, inline_images):
+ """The live-session fast path projects through ``_live_session_payload`` too."""
+ from hermes_state import SessionDB
+
+ home = tmp_path / ".hermes"
+ home.mkdir(parents=True)
+ db = SessionDB(home / "state.db")
+ record = {
+ # In-memory history (no DB rows for the key): the payload projects from session["history"].
+ "history": list(IMAGE_TURN), "display_history_prefix": [], "last_active": 0.0, "running": False,
+ "session_key": "live-img", "source": "desktop",
+ }
+ monkeypatch.setattr(srv, "_get_db", lambda: db)
+ monkeypatch.setattr(srv, "_find_live_session_by_key", lambda key, *_a: ("live-sid", record))
+ monkeypatch.setattr(srv, "_profile_home", lambda _p: None)
+ monkeypatch.setattr(srv, "_reattach_refusal", lambda *_a: None)
+ monkeypatch.setattr(srv, "_cancel_ws_orphan_reap", lambda *_a: None)
+ monkeypatch.setattr(srv, "_child_run_active", lambda _key: False)
+ known = set(srv._sessions)
+ srv._sessions["live-sid"] = record
+ try:
+ resp = srv._methods["session.resume"](
+ 1, {"session_id": "live-img", "inline_images": inline_images})
+ assert "error" not in resp, resp
+ text = resp["result"]["messages"][0]["text"]
+ assert (DATA_URI in text) is inline_images
+ assert ("[image]" in text) is not inline_images
+ finally:
+ srv._sessions.pop("live-sid", None)
+ for sid in [s for s in srv._sessions if s not in known]:
+ srv._sessions.pop(sid, None)
+ db.close()
diff --git a/tests/tui_gateway/test_ws_orphan_races.py b/tests/tui_gateway/test_ws_orphan_races.py
index 13116a5bbb1..e7969ad4cd9 100644
--- a/tests/tui_gateway/test_ws_orphan_races.py
+++ b/tests/tui_gateway/test_ws_orphan_races.py
@@ -188,7 +188,8 @@ def test_reconnect_cannot_cross_orphan_interrupt_claim(monkeypatch, path, claim)
defer_history=False, target="stored", profile=None,
profile_home=None, profile_resume_cwd=None, found={},
messages=lambda history: [], mint=lambda: ("unused", "tui", "."),
- restore=lambda: ([], [], []), display_prefix=lambda: [])
+ restore=lambda: ([], [], []), display_prefix=lambda: [],
+ inline_images=True)
if path == "eager":
monkeypatch.setattr(server, "_profile_build_scope", lambda *a: nullcontext())
monkeypatch.setattr(server, "_make_agent_in_context", lambda *a, **kw: Mock())
@@ -252,7 +253,8 @@ def test_late_rpc_from_closed_socket_keeps_orphan_reap_armed(monkeypatch, path,
defer_history=False, target="stored", profile=None,
profile_home=None, profile_resume_cwd=None, found={},
messages=lambda history: [], mint=lambda: ("unused", "tui", "."),
- restore=lambda: ([], [], []), display_prefix=lambda: [])
+ restore=lambda: ([], [], []), display_prefix=lambda: [],
+ inline_images=True)
if path == "unpersisted":
response = server._resume_live_unpersisted(ctx, sid, session)
elif path == "reuse":
diff --git a/tui_gateway/contracts/sessions.py b/tui_gateway/contracts/sessions.py
index 7489036f18c..73e0b397ac8 100644
--- a/tui_gateway/contracts/sessions.py
+++ b/tui_gateway/contracts/sessions.py
@@ -181,6 +181,9 @@ class SessionResumeParams(SessionParams):
omit_messages: bool = False
eager_build: bool = False
close_on_disconnect: bool = False
+ # False: render image parts as "[image]" instead of their data URIs — a remote client reads a
+ # transcript in kilobytes instead of re-transmitting every stored attachment (#116511).
+ inline_images: bool = True
class SessionResumeResult(LiveSessionSnapshot):
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 061dc01caf0..70e1b60d6fc 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -581,6 +581,8 @@ class _Resume:
"""Per-call ``session.resume`` state. ``owns_db``: the DEDICATED profile handle is ours
to close (handler ``finally``) until handed to the hydration worker or the agent."""
+ inline_images = True # class default so a ``__new__``-built ctx (tests) projects the full form
+
def __init__(self, rid, params: dict, target: str) -> None:
self.rid, self.params, self.target = rid, params, target
self.db, self.owns_db, self.found, self.profile_resume_cwd = None, False, None, ""
@@ -591,6 +593,8 @@ class _Resume:
self.lazy, self.defer_history = _flag(params, "lazy"), _flag(params, "defer_history")
# Desktop hydrates over REST; suppress the duplicate WS copy only when asked.
self.omit_messages, self.eager_build = _flag(params, "omit_messages"), _flag(params, "eager_build")
+ # inline_images=False renders image parts as "[image]" (#116511); default keeps data URIs.
+ self.inline_images = "inline_images" not in params or _flag(params, "inline_images")
def mint(self, prompts: bool = True) -> tuple:
"""``(runtime sid, source, cwd)`` for the live record this resume registers (+ gateway prompts on)."""
@@ -639,7 +643,8 @@ 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, profile_home=self.profile_home)
+ return [] if self.omit_messages else _history_to_messages(
+ display, profile_home=self.profile_home, image_urls=self.inline_images)
def read_history(self) -> tuple:
"""One lineage SELECT, two projections: model-fed copy alternation-repaired (healed once
@@ -791,7 +796,8 @@ def _resume_reuse_live_locked(ctx: _Resume, sid: str, session: dict) -> dict:
return refusal
_cancel_ws_orphan_reap(sid) # unconditionally: the fast path must never race the reap Timer
payload = _live_session_payload(sid, session, cols=ctx.cols, touch=True, omit_messages=ctx.omit_messages,
- transport=current_transport() or _stdio_transport)
+ transport=current_transport() or _stdio_transport,
+ inline_images=ctx.inline_images)
payload["resumed"] = ctx.target
if ctx.defer_history:
payload.update(messages=[], hydrating=bool(session.get("resume_hydrating")),
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 013c4085294..bad2a42ba70 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -2991,7 +2991,7 @@ def _live_visible_history(session: dict, db, in_memory_fallback: list[dict]) ->
def _live_session_payload(
sid: str, session: dict, *, cols: int | None = None, touch: bool = False,
- transport: Transport | None = None, omit_messages: bool = False) -> dict:
+ transport: Transport | None = None, omit_messages: bool = False, inline_images: bool = True) -> dict:
with session["history_lock"]:
if cols is not None:
session["cols"] = cols
@@ -3013,7 +3013,8 @@ 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, profile_home=session.get("profile_home"))
+ messages = ([] if omit_messages else
+ _history_to_messages(history, profile_home=session.get("profile_home"), image_urls=inline_images))
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 27cd98efc4d..cac6c288734 100644
--- a/tui_gateway/session_history.py
+++ b/tui_gateway/session_history.py
@@ -108,21 +108,23 @@ def _content_display_text(content: Any) -> str:
return "" if content is None else str(content)
-def _coerce_message_text(content: Any) -> str:
+def _coerce_message_text(content: Any, *, image_urls: bool = True) -> str:
"""Render ``message['content']`` (str, parts list, or one structured dict) as a plain string. Image parts
keep their URL inline so the desktop's ``extractEmbeddedImages`` and the resume payload agree with the
- cached message (else the inline image flashed, then vanished); other shapes become a placeholder."""
+ cached message (else the inline image flashed, then vanished); other shapes become a placeholder.
+ ``image_urls=False`` renders ``[image]`` instead — the ``inline_images=false`` read (#116511): a remote
+ client reads a transcript in kilobytes instead of re-transmitting every stored attachment."""
if isinstance(content, list):
chunks: list[str] = []
for part in content:
if isinstance(part, str) or (isinstance(part, dict) and isinstance(part.get("text"), str)):
chunks.append(part if isinstance(part, str) else part["text"])
elif isinstance(part, dict) and part.get("type"):
- rendered = _history_dict_text(part, image_urls=True)
+ rendered = _history_dict_text(part, image_urls=image_urls)
chunks.append(rendered if part["type"] in _HISTORY_TEXT_KINDS else f"\n{rendered}")
return "".join(chunks)
if isinstance(content, dict):
- return _history_dict_text(content, image_urls=True)
+ return _history_dict_text(content, image_urls=image_urls)
return "" if content is None else str(content)
@@ -197,7 +199,9 @@ _HISTORY_ASSISTANT_DETAIL_KEYS = (
_HISTORY_ROLES = frozenset({"user", "assistant", "tool", "system"})
-def _history_to_messages(history: list[dict], *, profile_home=None) -> list[dict]:
+def _history_to_messages(history: list[dict], *, profile_home=None, image_urls: bool = True) -> list[dict]:
+ """``image_urls=False`` is the ``inline_images=false`` projection (#116511): image parts render ``[image]``
+ so a remote client's history read stays kilobytes instead of re-transmitting every stored attachment."""
from agent.history_commentary import project_history_commentary
messages = []
@@ -212,7 +216,7 @@ def _history_to_messages(history: list[dict], *, profile_home=None) -> list[dict
# display_kind="hidden": model-facing scaffolding the "[System:" sniff does not catch.
if role not in _HISTORY_ROLES or m.get("display_kind") == "hidden":
continue
- content_text = _coerce_message_text(m.get("content"))
+ content_text = _coerce_message_text(m.get("content"), image_urls=image_urls)
if _is_display_hidden_marker(role, content_text):
continue
if role == "user":