Skip to content

The agent that grows with you

fix(cli): `chat -c <title> --create-if-missing` creates the session on the gateway

Tekniumef899e9359bf
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.py
index ac05bfbd160..e628ab89cdd 100644
--- a/hermes_cli/gateway_session_store.py
+++ b/hermes_cli/gateway_session_store.py
@@ -248,3 +248,19 @@ def _creation_policy(launch):
def session_store():
return GatewaySessionStore()
+
+def create_titled_session(title):
+ """``chat -c <title> --create-if-missing`` for the classic CLI: the gateway's ``session.create``
+ with ``title`` (it resolves-or-creates under one owner lock), so this process writes no row.
+ Main's ``_create_titled_session`` minted the id and wrote the row itself. Returns the id, or
+ None when the gateway refused (the caller prints main's "could not be created" copy)."""
+ params = _creation_policy({})
+ params["cwd"] = os.path.realpath(os.getenv("TERMINAL_CWD") or os.getcwd())
+ params["source"] = "cli" # main's titled row is `cli` (hermes_cli.main._create_titled_session)
+ try:
+ snapshot = GatewayConnection.shared().call("session.create", request_id=uuid.uuid4().hex,
+ title=title, **params)
+ except GatewayClientError as exc:
+ logger.warning("Failed to create titled session %r on the gateway: %s", title, exc)
+ return None
+ return snapshot["stored_session_id"]
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index cba9bf702d1..a228ab23307 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -1434,8 +1434,13 @@ def _resolve_continue_arg(args, *, use_tui: bool) -> None:
# "send to this named thread, making it if needed" — without it
# a quiet send to a not-yet-existing session silently no-ops.
# --create-if-missing: no session matches the title — create a new session with that title
- # and proceed. See #86794.
- new_sid = _create_titled_session(continue_val)
+ # and proceed. See #86794. The classic CLI's gateway writes it (the single writer);
+ # the TUI keeps main's local row.
+ if use_tui:
+ new_sid = _create_titled_session(continue_val)
+ else:
+ from hermes_cli.gateway_session_store import create_titled_session
+ new_sid = create_titled_session(continue_val)
if new_sid:
args.resume = new_sid
else:
diff --git a/tests/hermes_cli/test_chat_c_fail_loudly.py b/tests/hermes_cli/test_chat_c_fail_loudly.py
index 351a8263f7f..ee7a884f9c3 100644
--- a/tests/hermes_cli/test_chat_c_fail_loudly.py
+++ b/tests/hermes_cli/test_chat_c_fail_loudly.py
@@ -134,9 +134,15 @@ class TestChatCFailLoudlyOnStderr:
assert not stderr_lines[0].startswith("Use 'hermes sessions list'")
def test_create_if_missing_sets_resume(self, isolated_home, monkeypatch):
- """--create-if-missing resolves to a new session id on args.resume."""
+ """--create-if-missing resolves to a new session id on args.resume. The classic CLI's
+ gateway is the single writer: the titled session is the gateway's ``session.create`` (with
+ ``title``), and this process writes no state.db row."""
import hermes_cli.main as main_mod
+ import hermes_cli.gateway_session_store as store_mod
+ created = []
+ monkeypatch.setattr(store_mod, "create_titled_session",
+ lambda title: created.append(title) or "local-" + "a" * 64, raising=False)
args = type(
"Args",
(),
@@ -149,6 +155,17 @@ class TestChatCFailLoudlyOnStderr:
main_mod._resolve_continue_arg(args, use_tui=False)
+ assert args.resume == "local-" + "a" * 64, "resume should be set to the new session id"
+ assert created == ["Bot Chat"]
+ assert not (isolated_home / "state.db").exists(), "the CLI must not write the titled row itself"
+
+ def test_tui_create_if_missing_keeps_the_local_titled_row(self, isolated_home):
+ """The TUI launch is unchanged: main's titled row, then the TUI resumes it."""
+ import hermes_cli.main as main_mod
+
+ args = type("Args", (), {"continue_last": "Bot Chat", "resume": None, "create_if_missing": True})()
+ main_mod._resolve_continue_arg(args, use_tui=True)
+
assert args.resume, "resume should be set to the new session id"
from hermes_state import SessionDB
diff --git a/tests/hermes_cli/test_gateway_chat_title_live.py b/tests/hermes_cli/test_gateway_chat_title_live.py
index ed5d34acdf7..9c05af2cdfd 100644
--- a/tests/hermes_cli/test_gateway_chat_title_live.py
+++ b/tests/hermes_cli/test_gateway_chat_title_live.py
@@ -1,4 +1,5 @@
-"""Title-keyed resume on the canonical CLI client against an ordinary daemon."""
+"""Title-keyed resume on the classic CLI (main's HermesCLI, gateway-backed) against an ordinary daemon.
+The CLI process may read state.db but never writes it: the gateway is the single writer."""
import json
import os
from pathlib import Path
@@ -33,10 +34,24 @@ def test_title_create_if_missing_then_resume_by_title_is_deterministic(tmp_path,
wrapper.write_text(encoding='utf-8', data=f'''import json, runpy, sys
owners = []
def trace(frame, event, arg):
+ # A read-only state.db reader is allowed in the CLI (maintainer ruling); a writer is not.
if event == 'call' and frame.f_code.co_name == '__init__':
- if type(frame.f_locals.get('self')).__name__ in {{'AIAgent', 'SessionDB', 'GatewayRunner'}}:
- owners.append(type(frame.f_locals.get('self')).__name__)
+ name = type(frame.f_locals.get('self')).__name__
+ if name in {{'AIAgent', 'GatewayRunner'}} or (name == 'SessionDB' and not frame.f_locals.get('read_only')):
+ owners.append(name)
sys.setprofile(trace)
+import sqlite3
+_connect = sqlite3.connect
+def connect(database, *a, **k):
+ conn = _connect(database, *a, **k)
+ if 'state.db' in str(database):
+ def deny(action, table, *rest):
+ if action in (sqlite3.SQLITE_INSERT, sqlite3.SQLITE_UPDATE, sqlite3.SQLITE_DELETE) and table != 'sqlite_master':
+ owners.append('write:' + str(table))
+ return sqlite3.SQLITE_OK
+ conn.set_authorizer(deny)
+ return conn
+sqlite3.connect = connect
try:
runpy.run_module('hermes_cli.main', run_name='__main__')
finally:
@@ -48,8 +63,9 @@ finally:
result = subprocess.run([sys.executable, str(wrapper), "--cli", "chat", *args, "-Q"], env=env,
cwd=tmp_path, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=90, check=False)
assert json.loads(witness.read_text(encoding="utf-8")) == [], witness.read_text(encoding="utf-8")
- sid = next((line.split("Session: ", 1)[1].strip() for line in result.stderr.splitlines()
- if "Session: " in line), None)
+ # Main's -Q prints `session_id: <id>` on stderr.
+ sid = next((line.split("session_id: ", 1)[1].strip() for line in result.stderr.splitlines()
+ if line.startswith("session_id: ")), None)
return result, sid
title = "wave36 titled thread"