Skip to content

The agent that grows with you

fix(tui-gateway): /yolo restore keys on the stored session; pre-first-message toggle persists

Teknium50f8e4db48ac
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index b2892776a59..dfc32cbb5cf 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -8843,117 +8843,37 @@ def test_config_set_yolo_stale_session_id_is_refused_not_process_scoped(monkeypa
assert os.environ["HERMES_YOLO_MODE"] == "0"
-def test_config_set_yolo_session_scope_persists_to_the_session_row(monkeypatch):
- """A TUI /yolo toggle writes model_config.yolo_mode like the CLI's does.
-
- Without the persist, the toggle lives only in the in-memory
- _session_yolo set: --resume never restores it (_restore_session_yolo
- reads the row back) and nothing on disk reflects the flip.
- """
- from contextlib import contextmanager
-
- from tools.approval import clear_session
-
- calls = []
-
- class _RecordingDB:
- def set_session_yolo(self, session_id, enabled):
- calls.append((session_id, enabled))
-
- @contextmanager
- def _fake_session_db(session):
- yield _RecordingDB()
-
- monkeypatch.setattr(server, "_session_db", _fake_session_db)
- agent = types.SimpleNamespace(session_id="live-session-id")
- server._sessions["sid"] = _session(agent=agent)
- try:
- server.handle_request(
- {
- "id": "1",
- "method": "config.set",
- "params": {"session_id": "sid", "key": "yolo"},
- }
- )
- server.handle_request(
- {
- "id": "2",
- "method": "config.set",
- "params": {"session_id": "sid", "key": "yolo"},
- }
- )
- # agent.session_id wins over session_key (post-compression rule).
- assert calls == [("live-session-id", True), ("live-session-id", False)]
- finally:
- clear_session("session-key")
- server._sessions.clear()
-
-
-def test_compression_rotation_carries_the_persisted_yolo_flag(monkeypatch):
- """Rotation persists onto the continuation row, like the CLI's rotation.
-
- The toggle-time persist writes the OLD row; without the rotation carry a
- later `--resume <new_id>` loses the bypass even though yolo survived the
- rotation in memory.
- """
- from contextlib import contextmanager
-
- from tools.approval import clear_session, enable_session_yolo
-
- calls = []
-
- class _RecordingDB:
- def set_session_yolo(self, session_id, enabled):
- calls.append((session_id, enabled))
-
- @contextmanager
- def _fake_session_db(session):
- yield _RecordingDB()
+def test_session_yolo_toggle_survives_a_backend_restart(monkeypatch, tmp_path):
+ """A session /yolo (Shift+Tab / the Desktop zap) is persisted on the row and re-armed when a fresh
+ backend resumes it, including a toggle made before the row existed; switching it off persists too."""
+ from hermes_state import SessionDB
+ from tools.approval import clear_session, is_session_yolo_enabled
- monkeypatch.setattr(server, "_session_db", _fake_session_db)
- monkeypatch.setattr(
- server, "_transfer_active_session_slot", lambda *args, **kwargs: True
- )
- agent = types.SimpleNamespace(session_id="new-continuation-id")
- session = _session(agent=agent)
- enable_session_yolo("session-key")
+ db = SessionDB(db_path=tmp_path / "state.db")
+ monkeypatch.setattr(server, "_get_db", lambda: db)
+ monkeypatch.setattr(server, "_enable_gateway_prompts", lambda: None)
+ monkeypatch.setattr(server, "_schedule_agent_build", lambda sid: None)
try:
- server._sync_session_key_after_compress(
- "sid", session, restart_slash_worker=False
- )
- assert session["session_key"] == "new-continuation-id"
- assert calls == [("new-continuation-id", True)]
- finally:
- clear_session("session-key")
- clear_session("new-continuation-id")
-
+ # Toggled before the first message: the lazily created row must still record it.
+ server._sessions["sid"] = _session(session_key="row-a")
+ server.handle_request({"id": "1", "method": "config.set", "params": {"session_id": "sid", "key": "yolo"}})
+ assert server._ensure_session_db_row(server._sessions["sid"]) is not False
+ assert SessionDB.session_yolo_enabled(db.get_session("row-a"))
-def test_config_set_yolo_session_scope_survives_a_failing_db(monkeypatch):
- """Persistence is best-effort: a broken DB must not break the toggle."""
- from contextlib import contextmanager
-
- from tools.approval import clear_session, is_session_yolo_enabled
-
- @contextmanager
- def _broken_session_db(session):
- raise RuntimeError("db unavailable")
- yield None
+ server._sessions.clear()
+ clear_session("row-a") # a new backend process starts with an empty in-memory set
+ resp = server.handle_request({"id": "2", "method": "session.resume", "params": {"session_id": "row-a"}})
+ assert resp["result"]["session_key"] == "row-a"
+ assert is_session_yolo_enabled("row-a") is True
- monkeypatch.setattr(server, "_session_db", _broken_session_db)
- server._sessions["sid"] = _session()
- try:
- resp = server.handle_request(
- {
- "id": "1",
- "method": "config.set",
- "params": {"session_id": "sid", "key": "yolo"},
- }
- )
- assert resp["result"]["value"] == "1"
- assert is_session_yolo_enabled("session-key") is True
+ server.handle_request(
+ {"id": "3", "method": "config.set", "params": {"session_id": resp["result"]["session_id"], "key": "yolo"}})
+ assert is_session_yolo_enabled("row-a") is False
+ assert not SessionDB.session_yolo_enabled(db.get_session("row-a"))
finally:
- clear_session("session-key")
server._sessions.clear()
+ clear_session("row-a")
+ db.close()
def test_config_set_yolo_global_scope_writes_approvals_mode(tmp_path, monkeypatch):
diff --git a/tui_gateway/methods_config_set.py b/tui_gateway/methods_config_set.py
index 11001ea1755..83487d9df52 100644
--- a/tui_gateway/methods_config_set.py
+++ b/tui_gateway/methods_config_set.py
@@ -286,21 +286,15 @@ def _set_yolo(rid, params, key, value, session):
skey = session["session_key"]
enable = _BOOL_WORDS.get(raw, not is_session_yolo_enabled(skey))
(enable_session_yolo if enable else disable_session_yolo)(skey)
- # Persist to the session row, same contract as the CLI's /yolo
- # (cli.py _persist_session_yolo): without this the toggle lives only in
- # the in-memory session-yolo set, so `--resume` never restores it
- # (_restore_session_yolo reads model_config.yolo_mode back) and nothing
- # on disk reflects the toggle. Best-effort — the in-memory flag stays
- # authoritative for this process either way. Prefer agent.session_id
- # over session_key: after compression the key can be the ended parent
- # while session_id is the live continuation (session finalize, #20001).
+ # Persist like the CLI's /yolo so a resume in a new backend restores it. Row id prefers the agent's
+ # session_id: after compression the key can still name the ended parent (#20001).
row_id = getattr(session.get("agent"), "session_id", None) or skey
try:
with _session_db(session) as db:
- if db is not None and row_id:
+ if db is not None:
db.set_session_yolo(row_id, enable)
except Exception:
- logger.debug("failed to persist session yolo flag", exc_info=True)
+ logger.warning("failed to persist session yolo flag for %s", row_id, exc_info=True)
_emit_session_info(params.get("session_id", ""), session)
else:
enable = _BOOL_WORDS.get(raw, not is_truthy_value(os.environ.get("HERMES_YOLO_MODE")))
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index e066df9dfcd..b82b824cd88 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -616,24 +616,13 @@ def _(rid, params: dict) -> dict:
def _restore_session_yolo(session_key: str, session_meta: dict | None) -> None:
- """Re-enable YOLO bypass for a freshly-minted resume runtime key when the stored session row's
- ``model_config.yolo_mode`` says so. ``session.resume`` always mints a NEW runtime ``session_key``
- (``_new_runtime_ids``), so the in-memory ``tools.approval._session_yolo`` set — keyed on the OLD
- key — never covers it; without this call YOLO silently reverts to per-command approval on every
- reconnect/resume even though the DB row and the UI toggle both still say it's on (mirrors
- ``hermes_cli/cli_session_mixin.py::_restore_session_yolo``, which this surface lacked)."""
- if not session_key:
- return
- try:
- from hermes_state import SessionDB
- from tools.approval import _YOLO_MODE_FROZEN, enable_session_yolo, is_session_yolo_enabled
- except Exception:
- return
- if _YOLO_MODE_FROZEN or not SessionDB.session_yolo_enabled(session_meta):
- return
- if is_session_yolo_enabled(session_key):
- return
- enable_session_yolo(session_key)
+ """Re-arm a persisted session /yolo on resume: a new backend process starts with an empty in-memory
+ approval set. Keyed on the stored id (``ctx.target``), the key approvals are checked under, never
+ the freshly minted runtime sid. Mirrors ``cli_session_mixin._restore_session_yolo``."""
+ from hermes_state import SessionDB
+ from tools.approval import enable_session_yolo
+ if session_key and SessionDB.session_yolo_enabled(session_meta):
+ enable_session_yolo(session_key)
# ── session.resume ───────────────────────────────────────────────────
@@ -982,7 +971,7 @@ def _resume_deferred(ctx: _Resume) -> dict:
resume_message_count=int(ctx.found.get("message_count") or 0))
if (reused := ctx.claim(sid, record)) is not None:
return reused
- _restore_session_yolo(sid, ctx.found)
+ _restore_session_yolo(ctx.target, ctx.found)
# Desktop owns the visible transcript through bounded REST pages, not this model-history restore.
_schedule_resume_hydration(
sid, ctx.target, ctx.db, close_db=ctx.owns_db,
@@ -1008,7 +997,7 @@ def _resume_cold(ctx: _Resume) -> dict:
todo_state=_todo_state_from_history(history))
if (reused := ctx.claim(sid, record)) is not None:
return reused
- _restore_session_yolo(sid, ctx.found)
+ _restore_session_yolo(ctx.target, ctx.found)
_schedule_agent_build(sid)
_schedule_session_cap_enforcement() # trim detached idle sessions over the cap
return _resume_response(ctx, sid, record, info=ctx.info(cwd, overrides), display=display_history,
@@ -1050,7 +1039,7 @@ def _resume_eager(ctx: _Resume) -> dict:
if ctx.owns_db:
_transfer_db_to_agent(agent, ctx.db)
ctx.owns_db = False
- _restore_session_yolo(sid, ctx.found)
+ _restore_session_yolo(ctx.target, ctx.found)
if (session := _sessions.get(sid)) is not None:
if stored_runtime_overrides.get("model_override") is not None:
session["model_override"] = stored_runtime_overrides["model_override"]
diff --git a/tui_gateway/session_compression.py b/tui_gateway/session_compression.py
index 223309b3ccd..f4203e70c1b 100644
--- a/tui_gateway/session_compression.py
+++ b/tui_gateway/session_compression.py
@@ -336,16 +336,10 @@ def _sync_session_key_after_compress(
if approval.is_session_yolo_enabled(old_key):
approval.enable_session_yolo(new_session_id)
approval.disable_session_yolo(old_key)
- # Carry the PERSISTED flag onto the continuation row too, same as
- # the CLI's rotation path: the in-memory swap above alone leaves
- # a later `--resume <new_id>` without the bypass, because the
- # toggle-time persist wrote the now-ended parent row.
- try:
- with _session_db(session) as db:
- if db is not None:
- db.set_session_yolo(new_session_id, True)
- except Exception:
- logger.debug("failed to carry session yolo flag", exc_info=True)
+ # The toggle persisted the now-ended parent row; carry it onto the continuation (CLI parity).
+ with _session_db(session) as db:
+ if db is not None:
+ db.set_session_yolo(new_session_id, True)
with contextlib.suppress(Exception):
approval.register_gateway_notify(new_session_id, lambda data: _emit_approval_request(sid, data))
# Invalidate any in-flight ``_drain_queued_prompt`` claim taken under the pre-rotation key: a raced
diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.py
index 586c199c2af..71ad722d28b 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -475,6 +475,10 @@ def _workdir_row_model_config(session: dict) -> tuple[str, dict]:
model_config[flag] = True
if isinstance(composer_profile := session.get("composer_override_profile"), dict):
model_config["composer_override_profile"] = composer_profile
+ # A /yolo toggled before the first message had no row to persist to (rows are created lazily here).
+ from tools.approval import is_session_yolo_enabled
+ if is_session_yolo_enabled(session.get("session_key") or ""):
+ model_config["yolo_mode"] = True
return row_model, model_config