Skip to content

The agent that grows with you

fix(tui_gateway): TUI/Desktop /save json exports the stored session and obeys the export cap

kshitijk4poorb5648159956b
diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.py
index 6a6ccdcf791..dbaba802025 100644
--- a/gateway/slash_commands_session.py
+++ b/gateway/slash_commands_session.py
@@ -716,8 +716,7 @@ class GatewaySessionCommandsMixin:
"""Handle /save — export the current session and send it as a document."""
import tempfile
from hermes_cli.session_export import (
- SAVE_TRANSCRIPT_FORMATS, SAVE_USAGE, default_save_filename, drop_undone_rows, export_projection,
- normalize_save_format, render_session_for_save)
+ SAVE_USAGE, default_save_filename, load_save_snapshot, normalize_save_format, render_session_for_save)
parts = event.get_command_args().split()
redact = bool(parts) and parts[-1].lower() in ("redact", "--redact")
@@ -738,17 +737,14 @@ class GatewaySessionCommandsMixin:
# Never trust path separators from chat input; the filename is only echoed to the platform.
filename = parts[1] if len(parts) > 1 else default_save_filename(session_id, fmt)
filename = os.path.basename(filename) or default_save_filename(session_id, fmt)
- if fmt not in SAVE_TRANSCRIPT_FORMATS:
- from hermes_state import SessionExportTooLargeError
- try:
- await self._session_db.assert_export_safe(session_id) # the JSON backup loads every stored row
- except SessionExportTooLargeError as e:
- return str(e)
- export_data = await self._session_db.export_session(session_id, **export_projection(fmt in SAVE_TRANSCRIPT_FORMATS))
+ from hermes_state import SessionExportTooLargeError
+ try:
+ # One off-loop hop for the cap check + read; the helper is shared with the CLI and TUI /save.
+ export_data = await asyncio.to_thread(load_save_snapshot, self._session_db._db, session_id, fmt)
+ except SessionExportTooLargeError as e:
+ return str(e)
if not export_data:
return t("gateway.save.no_messages", session_id=session_id)
- if fmt not in SAVE_TRANSCRIPT_FORMATS:
- drop_undone_rows(export_data)
if redact:
from hermes_cli.session_export_md import redact_session_data
export_data = redact_session_data(export_data)
diff --git a/hermes_cli/cli_session_mixin.py b/hermes_cli/cli_session_mixin.py
index dc6faf17be0..cd4459b310e 100644
--- a/hermes_cli/cli_session_mixin.py
+++ b/hermes_cli/cli_session_mixin.py
@@ -631,8 +631,7 @@ class CLISessionMixin:
"""
from cli import datetime
from hermes_cli.session_export import (
- SAVE_TRANSCRIPT_FORMATS, SAVE_USAGE, drop_undone_rows, export_projection, normalize_save_format,
- render_session_for_save)
+ SAVE_USAGE, load_save_snapshot, normalize_save_format, render_session_for_save)
parts = cmd.split()[1:]
redact = bool(parts) and parts[-1].lower() in ("redact", "--redact")
@@ -655,19 +654,14 @@ class CLISessionMixin:
_db = getattr(self, "_session_db", None)
_sid = getattr(self, "session_id", None)
if _db and _sid:
- if fmt not in SAVE_TRANSCRIPT_FORMATS:
- from hermes_state import SessionExportTooLargeError
- try:
- _db.assert_export_safe(_sid) # the JSON backup loads every stored row, like `sessions export`
- except SessionExportTooLargeError as e:
- print(f"(._.) {e}")
- return
+ from hermes_state import SessionExportTooLargeError
try:
- session_data = _db.export_session(_sid, **export_projection(fmt in SAVE_TRANSCRIPT_FORMATS))
+ session_data = load_save_snapshot(_db, _sid, fmt)
+ except SessionExportTooLargeError as e:
+ print(f"(._.) {e}")
+ return
except Exception:
session_data = None
- if session_data and fmt not in SAVE_TRANSCRIPT_FORMATS:
- drop_undone_rows(session_data)
if not session_data:
if not self.conversation_history:
print(t("cli.session.save_nothing"))
diff --git a/hermes_cli/session_export.py b/hermes_cli/session_export.py
index 19c2585462a..517e8a4495b 100644
--- a/hermes_cli/session_export.py
+++ b/hermes_cli/session_export.py
@@ -227,6 +227,19 @@ def drop_undone_rows(export: Dict[str, Any]) -> Dict[str, Any]:
return export
+def load_save_snapshot(db: Any, session_id: str, fmt: str) -> Optional[Dict[str, Any]]:
+ """The stored session a ``/save <fmt>`` writes, or None when it has no row. A JSON snapshot loads every
+ stored row in memory, so it is refused past ``sessions.max_export_messages`` (raises
+ ``SessionExportTooLargeError``), like ``hermes sessions export``."""
+ transcript = fmt in SAVE_TRANSCRIPT_FORMATS
+ if not transcript:
+ db.assert_export_safe(session_id)
+ export = db.export_session(session_id, **export_projection(transcript))
+ if export and not transcript:
+ drop_undone_rows(export)
+ return export
+
+
SAVE_USAGE = """/save — export the current session to a file
Usage: /save <format> [filename] [redact]
diff --git a/tests/hermes_cli/test_save_transcript_history.py b/tests/hermes_cli/test_save_transcript_history.py
index 2d84c5c7f19..27488dd8392 100644
--- a/tests/hermes_cli/test_save_transcript_history.py
+++ b/tests/hermes_cli/test_save_transcript_history.py
@@ -1,4 +1,4 @@
-"""/save md (CLI and gateway) carries the display history, compaction-archived turns included."""
+"""/save md (CLI and gateway) carries the display history; /save json (CLI, gateway, TUI/Desktop) every kept row."""
import asyncio
import contextlib
import io
@@ -60,6 +60,40 @@ def _gateway_save(db, fmt, out):
return delivered["text"] if reply == "Export complete." else reply
+def _tui_save(db, fmt, out, *, host=False):
+ """TUI/Desktop ``session.save`` (JSON only); ``host`` forwards it as a control frame to a turn-isolated compute
+ host, whose own session runs the handler in-process."""
+ import json
+ import threading
+ from unittest import mock
+
+ from tui_gateway import server
+ from tui_gateway.compute_host import ComputeHost
+
+ assert fmt == "json"
+
+ def session():
+ return {"agent": SimpleNamespace(model="m", session_id="s1"), "session_key": "s1", "history": [],
+ "profile_home": str(out.parent), "history_lock": threading.Lock()}
+
+ parent, child = session(), session()
+
+ def control(sid, **frame): # the host's own control handler, answered over its stdout wire
+ wire = io.StringIO()
+ with mock.patch.dict(server._sessions, {sid: child}):
+ ComputeHost(stdout=wire, heartbeat_secs=0)._handle_control({"sid": sid, **frame})
+ return json.loads(wire.getvalue())
+
+ with mock.patch.dict(server._sessions, {"tui-save": parent}), \
+ mock.patch.object(server, "_session_uses_compute_host", lambda s: host and s is parent), \
+ mock.patch.object(server, "_send_compute_host_control", control):
+ resp = server._methods["session.save"]("1", {"session_id": "tui-save"})
+ if "error" in resp:
+ assert resp["error"]["code"] == 4131 # the export-cap refusal, through the host too
+ return resp["error"]["message"]
+ return open(resp["result"]["file"], encoding="utf-8").read()
+
+
@pytest.mark.parametrize("save", [_cli_save, _gateway_save], ids=["cli", "gateway"])
def test_save_transcript_holds_display_history(tmp_path, monkeypatch, save):
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
@@ -71,7 +105,8 @@ def test_save_transcript_holds_display_history(tmp_path, monkeypatch, save):
assert [f"answer {i}" in text for i in range(1, 7)] == [True] * 6
[email protected]("save", [_cli_save, _gateway_save], ids=["cli", "gateway"])
[email protected]("save", [_cli_save, _gateway_save, _tui_save, lambda *a: _tui_save(*a, host=True)],
+ ids=["cli", "gateway", "tui", "tui-compute-host"])
def test_save_json_restores_compacted_history_as_archived(tmp_path, monkeypatch, save):
"""/save json is the snapshot the dashboard import restores: the turns compaction archived come back
in the display history, and stay out of the live context."""
diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.py
index 50042bb3897..62a7c244515 100644
--- a/tui_gateway/compute_host.py
+++ b/tui_gateway/compute_host.py
@@ -436,7 +436,7 @@ class ComputeHost:
else:
ack = self._control_ack(server, frame, session)
if "error" in ack:
- self._reply("control.error", sid, request_id, message=ack["error"])
+ self._reply("control.error", sid, request_id, message=ack["error"], code=ack.get("code"))
else:
self._reply("control.ack", sid, request_id, route_name=route_name, **ack)
@@ -468,7 +468,7 @@ class ComputeHost:
response = server._methods[route_name](frame.get("request_id"), params)
if "error" in response:
failure = _CONTROL_FAILURES[route_name]
- return {"error": str(response["error"].get("message") or failure)}
+ return {"error": str(response["error"].get("message") or failure), "code": response["error"].get("code")}
ack = {"result": response.get("result") or {}}
if route_name == "session.save":
return ack
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 6373e6a2f4b..52f9ebb6016 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -2048,7 +2048,7 @@ def _save_via_compute_host(rid, params: dict) -> dict:
ack = _send_compute_host_control(str(params.get("session_id") or ""), route_name="session.save", wait=True)
except Exception as exc:
return _err(rid, 5011, f"compute-host session save failed: {exc}")
- if (resp := _compute_host_ack_error(rid, ack, 5011, "compute-host session save failed")) is not None:
+ if (resp := _compute_host_ack_error(rid, ack, ack.get("code") or 5011, "compute-host session save failed")) is not None:
return resp
if not isinstance(result := ack.get("result"), dict):
return _err(rid, 5011, "compute-host session save returned an invalid response")
@@ -2167,32 +2167,32 @@ def _(rid, params: dict) -> dict:
def _(rid, params: dict, session: dict) -> dict:
if _session_uses_compute_host(session):
return _save_via_compute_host(rid, params)
- agent = session["agent"]
- # Classic CLI /save: under the profile home, with the system prompt (dashboard parity). The SESSION's
- # profile: this handler runs unscoped, so get_hermes_home() alone names the launch profile.
- home = session.get("profile_home")
- saved_dir = (Path(home) if home else get_hermes_home()) / "sessions" / "saved"
+ from hermes_cli.session_export import load_save_snapshot, render_session_for_save
+ from hermes_state import SessionExportTooLargeError
+ # As CLI/messaging /save json, under the SESSION's profile config + home (runs unscoped); a failed read falls back.
try:
- saved_dir.mkdir(parents=True, exist_ok=True)
- except Exception as e:
- return _err(rid, 5011, f"failed to create save directory {saved_dir}: {e}")
- path = saved_dir / f"hermes_conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
- with session["history_lock"]:
- messages = list(session.get("history", []))
- # Prefer the agent's session_start (classic CLI export); else the gateway created_at.
- started = getattr(agent, "session_start", None)
- if not isinstance(started, datetime):
- created_at = session.get("created_at")
- started = datetime.fromtimestamp(created_at) if isinstance(created_at, (int, float)) else None
+ with _session_profile_runtime_scope(session, hydrate_secrets=False), _session_db(session) as db:
+ data = db and load_save_snapshot(db, _submit_row_target_key(session), "json")
+ except SessionExportTooLargeError as e:
+ return _err(rid, 4131, str(e))
+ except Exception:
+ logger.warning("session.save: stored-session read failed; saving the in-memory history", exc_info=True)
+ data = None
+ path = Path(session.get("profile_home") or get_hermes_home()) / "sessions/saved" / f"hermes_conversation_{datetime.now():%Y%m%d_%H%M%S}.json"
+ if not data: # No stored row: the in-memory history, with the agent's session_start else created_at.
+ started = getattr(agent := session["agent"], "session_start", None)
+ if not isinstance(started, datetime) and isinstance(created := session.get("created_at"), (int, float)):
+ started = datetime.fromtimestamp(created)
+ with session["history_lock"]:
+ data = {"model": getattr(agent, "model", ""), "messages": list(session.get("history", [])),
+ "session_id": getattr(agent, "session_id", None) or session.get("session_key") or "",
+ "session_start": started.isoformat() if isinstance(started, datetime) else "",
+ "system_prompt": getattr(agent, "_cached_system_prompt", "") or ""}
try:
- with open(path, "w", encoding="utf-8") as f:
- json.dump({"model": getattr(agent, "model", ""),
- "session_id": getattr(agent, "session_id", None) or session.get("session_key") or "",
- "session_start": started.isoformat() if started else "",
- "system_prompt": getattr(agent, "_cached_system_prompt", "") or "",
- "messages": messages}, f, indent=2, ensure_ascii=False)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(render_session_for_save(data, "json"), encoding="utf-8")
except Exception as e:
- return _err(rid, 5011, str(e))
+ return _err(rid, 5011, f"failed to save {path}: {e}")
return _ok(rid, {"file": str(path)})
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index 5f8e9fbca13..7247c53d24e 100644
--- a/website/docs/user-guide/sessions.md
+++ b/website/docs/user-guide/sessions.md
@@ -385,7 +385,7 @@ hermes sessions export ~/exports/ --session-id 20250305_091523_a1b2c3d4
hermes sessions export backup.jsonl --redact
```
-Exported files contain one JSON object per line with full session metadata and every stored message, each with its `active`/`compacted` flags. That includes turns archived by in-place compaction and messages removed by rewind or edit. Importing the file (the dashboard's session import) restores those rows as archived history, not as live model context. A CLI or messaging `/save json` snapshot holds the same rows. Treat a backup as holding everything the session ever contained. To share a conversation, export a display format (`--format md` or `html`, which holds only the history the session shows) with `--redact`. Each session's backup is built in memory, so a session with more stored rows than `sessions.max_export_messages` is refused (see [Oversized-Transcript Guards](#oversized-transcript-guards)).
+Exported files contain one JSON object per line with full session metadata and every stored message, each with its `active`/`compacted` flags. That includes turns archived by in-place compaction and messages removed by rewind or edit. Importing the file (the dashboard's session import) restores those rows as archived history, not as live model context. A `/save json` snapshot (CLI, messaging, TUI, or Desktop) holds the same rows. Treat a backup as holding everything the session ever contained. To share a conversation, export a display format (`--format md` or `html`, which holds only the history the session shows) with `--redact`. Each session's backup is built in memory, so a session with more stored rows than `sessions.max_export_messages` is refused (see [Oversized-Transcript Guards](#oversized-transcript-guards)).
Filtered exports include matching pinned and archived sessions. Pinning protects a session from pruning, rather than excluding it from a backup. If an explicit `--session-id` cannot be resolved, export exits with a non-zero status and creates no output file.
@@ -458,7 +458,7 @@ hermes sessions export --format md --model sonnet --min-messages 50 --redact
hermes sessions export --format md --session-id 20250305_091523_a1b2c3d4 --delete-after-verified --yes
```
-Markdown/QMD export writes one `.md` or `.qmd` file per exported session plus a `manifest.jsonl` with the file path, message count, lineage ids, and SHA-256. Bulk export requires at least one filter; a bare bulk export is refused. `--delete-after-verified` is intentionally limited to `--session-id` and requires `--yes`. Because deleting a parent session also removes its delegate/subagent sessions, this mode exports and verifies each delegate in a separate file before deleting anything. Markdown/QMD files hold the full history shown by the session, including turns archived by in-place compaction. Deletion compares that exact display transcript and the delegate set again inside the same database transaction that performs the delete; any intervening append, rewrite, rewind, compaction, or delegate change refuses deletion. The same display-history rule applies to `--format html`, `--only user-prompts` (with either Markdown or JSONL output), and `/save md|html`. Full-session JSON/JSONL exports (`hermes sessions export` without `--only`) and CLI/messaging `/save json` are backups of every stored row, archived rows included (see [Export Sessions](#export-sessions)). `--redact` scrubs secrets (API keys, tokens, credentials) from message content and tool output before writing — recommended for any export you plan to share.
+Markdown/QMD export writes one `.md` or `.qmd` file per exported session plus a `manifest.jsonl` with the file path, message count, lineage ids, and SHA-256. Bulk export requires at least one filter; a bare bulk export is refused. `--delete-after-verified` is intentionally limited to `--session-id` and requires `--yes`. Because deleting a parent session also removes its delegate/subagent sessions, this mode exports and verifies each delegate in a separate file before deleting anything. Markdown/QMD files hold the full history shown by the session, including turns archived by in-place compaction. Deletion compares that exact display transcript and the delegate set again inside the same database transaction that performs the delete; any intervening append, rewrite, rewind, compaction, or delegate change refuses deletion. The same display-history rule applies to `--format html`, `--only user-prompts` (with either Markdown or JSONL output), and `/save md|html`. Full-session JSON/JSONL exports (`hermes sessions export` without `--only`) and `/save json` (CLI, messaging, TUI, Desktop) are backups of every stored row, archived rows included (see [Export Sessions](#export-sessions)). `--redact` scrubs secrets (API keys, tokens, credentials) from message content and tool output before writing — recommended for any export you plan to share.
### Delete a Session
@@ -1128,7 +1128,7 @@ sessions:
```
`max_export_messages` applies per session to the JSON/JSONL backup (`hermes sessions export`,
-`sessions export` in `hermes console`, and CLI/messaging `/save json`). It counts every stored row, archived included, because
+`sessions export` in `hermes console`, and `/save json` in the CLI, messaging, TUI and Desktop). It counts every stored row, archived included, because
the backup holds all of them. A heavily compacted session with a small live tail can still exceed it.
The dashboard Sessions page's Export action streams the rows instead and is not capped.
@@ -1147,7 +1147,8 @@ history of the conversation:
When a resume is refused the client receives error code `4130` with the count
and the scope it was measured against (`across its lineage` or
-`in its tip segment`). `hermes sessions export` still works for such sessions; its JSON/JSONL
+`in its tip segment`). A TUI/Desktop `/save` refused by `max_export_messages` returns error code `4131`.
+`hermes sessions export` still works for such sessions; its JSON/JSONL
backup needs each session to stay under `max_export_messages`.
### Manual Cleanup