The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(tui_gateway): add session.archive RPC for Desktop archive parity
Brooklyn Nicholsond3f9ba3cd5c2
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex f5e3d01547f..a8406e2786d 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -3025,6 +3025,17 @@ export interface SessionSetHiddenResult {hidden: booleansession_key: string}+/** ``session_id`` (or its ``session_key`` alias) is a live runtime id first, else a stored id / key / title. */+export interface SessionArchiveParams {+ session_id?: string | null+ session_key?: string | null+ archived?: boolean+ profile?: string | null+}+export interface SessionArchiveResult {+ archived: boolean+ session_key: string+}export interface SessionWorkspaceMoveParams {profile?: string | nullsession_key: string@@ -5013,6 +5024,8 @@ export interface RpcMethods {'session.activate': { params: SessionActivateParams; result: SessionActivateResult }/** Live sessions in this process, insertion order (not a DB browser). */'session.active_list': { params: SessionActiveListParams; result: SessionActiveListResult }+ /** Set/clear archived (soft-hide, messages kept) on a session + lineage; Desktop PATCH parity. */+ 'session.archive': { params: SessionArchiveParams; result: SessionArchiveResult }/** Fork a live session into a new stored child that shares the parent's history so far. */'session.branch': { params: SessionBranchParams; result: SessionBranchResult }/** Whole-session branch of a stored parent: the owning backend reads and copies the transcript, which never crosses the wire (a separate method so an older gateway fails loudly, not with an empty branch). */@@ -5325,6 +5338,7 @@ export const RPC_METHODS = ['rollback.restore','session.activate','session.active_list',+ 'session.archive','session.branch','session.branch_stored','session.branch_whole',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex bf6cd2643c2..d67f318a8df 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -2976,6 +2976,24 @@}}},+ {+ "name": "session.archive",+ "summary": "Set/clear archived (soft-hide, messages kept) on a session + lineage; Desktop PATCH parity.",+ "params": [+ {+ "name": "params",+ "schema": {+ "$ref": "#/components/schemas/SessionArchiveParams"+ }+ }+ ],+ "result": {+ "name": "result",+ "schema": {+ "$ref": "#/components/schemas/SessionArchiveResult"+ }+ }+ },{"name": "session.branch","summary": "Fork a live session into a new stored child that shares the parent's history so far.",@@ -27744,6 +27762,74 @@"title": "SessionActiveListResult","type": "object"},+ "SessionArchiveParams": {+ "additionalProperties": false,+ "description": "``session_id`` (or its ``session_key`` alias) is a live runtime id first, else a stored id / key / title.",+ "properties": {+ "session_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Session Id"+ },+ "session_key": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Session Key"+ },+ "archived": {+ "default": true,+ "title": "Archived",+ "type": "boolean"+ },+ "profile": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Profile"+ }+ },+ "title": "SessionArchiveParams",+ "type": "object"+ },+ "SessionArchiveResult": {+ "additionalProperties": false,+ "properties": {+ "archived": {+ "title": "Archived",+ "type": "boolean"+ },+ "session_key": {+ "title": "Session Key",+ "type": "string"+ }+ },+ "required": [+ "archived",+ "session_key"+ ],+ "title": "SessionArchiveResult",+ "type": "object"+ },"SessionBranchParams": {"additionalProperties": false,"properties": {diff --git a/tests/tui_gateway/test_session_archive_rpc.py b/tests/tui_gateway/test_session_archive_rpc.pynew file mode 100644index 00000000000..dafeab3d3a8--- /dev/null+++ b/tests/tui_gateway/test_session_archive_rpc.py@@ -0,0 +1,99 @@+"""RPC-level tests for ``session.archive`` (tui_gateway, #47168).++Desktop archives sessions via ``PATCH /api/sessions/{id}``; the TUI gateway had no+equivalent JSON-RPC method, so TUI clients had to keep every session visible or+delete it permanently. ``session.archive`` mirrors ``session.set_hidden``:++* a DURABLE stored session id / key archives and un-archives through the profile+ db (``SessionDB.set_session_archived``, whole compression lineage);+* a LIVE runtime session id archives its stored key — and a live session with+ NO row yet defers via ``pending_archived`` so ``_ensure_session_db_row`` applies+ the flag when the first prompt persists the row;+* an unknown id still errors.+"""++import pytest++import tui_gateway.server as srv+import tui_gateway.methods_session # noqa: F401 (registers the RPC methods)+from hermes_state import SessionDB+++def db(tmp_path, monkeypatch):+ database = SessionDB(tmp_path / "state.db")+ monkeypatch.setattr(srv, "_get_db", lambda: database)+ try:+ yield database+ finally:+ database.close()+++def _call(method: str, params: dict) -> dict:+ return srv._methods[method](1, params)+++def _seed(db, sid: str) -> None:+ db.create_session(sid, source="desktop")+ db._conn.execute("UPDATE sessions SET message_count = 1 WHERE id = ?", (sid,))+ db._conn.commit()+++def test_archive_resolves_stored_id_without_live_session(db):+ """A stored (non-live) session id must be archivable — the session.list picker path."""+ _seed(db, "stored-chat")+ assert srv._find_live_session_by_key("stored-chat") is None++ envelope = _call("session.archive", {"session_id": "stored-chat", "archived": True})+ assert "error" not in envelope, envelope+ assert envelope["result"]["archived"] is True+ assert envelope["result"]["session_key"] == "stored-chat"+ assert db.get_session("stored-chat")["archived"] == 1++ # And back — unarchive through the same durable path.+ envelope = _call("session.archive", {"session_id": "stored-chat", "archived": False})+ assert "error" not in envelope, envelope+ assert envelope["result"]["archived"] is False+ assert db.get_session("stored-chat")["archived"] == 0+++def test_archive_accepts_session_key_alias(db):+ """``session_key`` is the documented alias of ``session_id`` (the list rows carry it)."""+ _seed(db, "keyed-chat")+ envelope = _call("session.archive", {"session_key": "keyed-chat", "archived": True})+ assert "error" not in envelope, envelope+ assert db.get_session("keyed-chat")["archived"] == 1+++def test_archive_unknown_id_still_errors(db):+ envelope = _call("session.archive", {"session_id": "no-such-session", "archived": True})+ assert envelope.get("error"), envelope+++def test_archive_through_the_dispatcher_validates_params(db):+ """The wire path: unknown params are rejected by the contract, and a missing id answers 4006."""+ resp = srv.handle_request({"id": "1", "method": "session.archive", "params": {}})+ assert resp["error"]["code"] == 4006++ resp = srv.handle_request(+ {"id": "2", "method": "session.archive", "params": {"session_id": "x", "bogus": 1}})+ assert resp["error"]["code"] == 4000+++def test_archive_live_runtime_session_defers_until_row_exists(db):+ """A live session with no state.db row yet queues ``pending_archived``; the row is born archived."""+ sid = "live-draft"+ srv._sessions[sid] = {"session_key": "20260927_000000_draft", "history": [], "running": False}+ try:+ envelope = _call("session.archive", {"session_id": sid, "archived": True})+ assert "error" not in envelope, envelope+ assert envelope["result"]["session_key"] == "20260927_000000_draft"+ assert db.get_session("20260927_000000_draft") is None # no row yet++ # The first prompt persists the row; the deferred intent must land with it.+ assert srv._ensure_session_db_row(srv._sessions[sid])+ row = db.get_session("20260927_000000_draft")+ assert row is not None+ assert row["archived"] == 1+ finally:+ srv._sessions.pop(sid, None)diff --git a/tui_gateway/contracts/sessions.py b/tui_gateway/contracts/sessions.pyindex be298aebf74..7489036f18c 100644--- a/tui_gateway/contracts/sessions.py+++ b/tui_gateway/contracts/sessions.py@@ -322,6 +322,24 @@ method("session.set_hidden", params=SessionSetHiddenParams, result=SessionSetHiddoc="Set/clear hidden (out of the default list, still resumable by its owner) on a session + lineage.")+class SessionArchiveParams(Params):+ """``session_id`` (or its ``session_key`` alias) is a live runtime id first, else a stored id / key / title."""++ session_id: str | None = None+ session_key: str | None = None+ archived: bool = True+ profile: str | None = None+++class SessionArchiveResult(Result):+ archived: bool+ session_key: str+++method("session.archive", params=SessionArchiveParams, result=SessionArchiveResult,+ doc="Set/clear archived (soft-hide, messages kept) on a session + lineage; Desktop PATCH parity.")++class SessionWorkspaceMoveParams(ProfileParams):session_key: strcwd: strdiff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex 987646341a5..061dc01caf0 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -1149,6 +1149,36 @@ def _(rid, params: dict, session: dict, db) -> dict:return _ok(rid, result)+@method("session.archive")+def _(rid, params: dict) -> dict:+ """Set/clear ``archived`` (out of the default list, messages kept — the Desktop PATCH parity flag)+ on a session + lineage: LIVE runtime id first (unpersisted drafts via ``pending_archived``),+ then a stored id/key in the profile db, like ``session.set_hidden``."""+ archived = is_truthy_value(params.get("archived", True))+ target = str(params.get("session_id") or params.get("session_key") or "")+ if not target:+ return _err(rid, 4006, "session_id required")+ # Quiet live lookup, the set_hidden reasoning: a stored id that is not in memory is this method's+ # expected second tier, not a rejection (session.list rows archive without a live runtime here).+ session = _sessions.get(target)+ with (_profile_db(params, writer=True) if session is None else _session_db(session)) as db:+ if db is None:+ return _db_unavailable_error(rid, code=5007)+ try:+ if session is not None:+ key = session["session_key"]+ if not db.set_session_archived(key, archived):+ session["pending_archived"] = archived # no row yet: _ensure_session_db_row applies it+ else:+ # ``resolve_session_id`` follows key/title aliases like the REST pin/archive path.+ if not (key := db.resolve_session_id(target) if hasattr(db, "resolve_session_id") else target):+ return _err(rid, 4001, "session not found")+ db.set_session_archived(key, archived)+ return _ok(rid, {"archived": archived, "session_key": key})+ except Exception as e:+ return _err(rid, 5007, str(e))++@method("session.set_hidden")def _(rid, params: dict) -> dict:"""Set/clear ``hidden`` (leaves the default list, stays resumable by its owner) on a session + lineage:diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex 9f948120db4..65f9f4c4ed9 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -405,6 +405,13 @@ def _ensure_session_db_row(session: dict) -> bool:session.pop("pending_hidden", None)except Exception:logger.debug("failed to apply pending hidden flag", exc_info=True)+ # Same deferral for session.archive before the row existed (mirrors pending_hidden).+ if session.get("pending_archived"):+ try:+ if db.set_session_archived(key, True):+ session.pop("pending_archived", None)+ except Exception:+ logger.debug("failed to apply pending archived flag", exc_info=True)except Exception as exc:# Disk-full is not a soft failure: swallowed here, prompt.submit returns {"status":"streaming"} and the# message vanishes silently.