Skip to content

The agent that grows with you

fix(tui): queue a Desktop prompt in the gateway owner's FIFO instead of refusing it

Teknium936ec14ee447
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 89e4f176f1c..08d4e4b9754 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -2744,6 +2744,8 @@ export interface PromptSubmitResult {
survivor_user_row_ids?: (number | null)[] | null
survivor_row_id_map?: Record<string, number | null> | null
turn_isolation?: boolean | null
+ admission_id?: string | null
+ forwarded?: boolean | null
}
export type PromptSubmitStatus = 'streaming' | 'queued' | 'steered' | 'redirected'
export interface ClipboardPasteParams {
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index bfaccd5abb6..d691c78a8b6 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -31980,6 +31980,30 @@
],
"default": null,
"title": "Turn Isolation"
+ },
+ "admission_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Admission Id"
+ },
+ "forwarded": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Forwarded"
}
},
"title": "PromptSubmitResult",
diff --git a/tests/tui_gateway/test_legacy_submit_forwards_to_owner.py b/tests/tui_gateway/test_legacy_submit_forwards_to_owner.py
new file mode 100644
index 00000000000..40b1fc9fb00
--- /dev/null
+++ b/tests/tui_gateway/test_legacy_submit_forwards_to_owner.py
@@ -0,0 +1,193 @@
+"""RT-37 (#140385): a Desktop prompt on a session whose gateway owner is running a turn (a Bot Chat
+delivery) is admitted into the OWNER's durable FIFO and runs after that turn, exactly once. It is not
+refused ``SESSION_NOT_OWNED``, nothing runs in the legacy backend, and the Desktop gets a queued
+receipt, then the owner's start and completion for that admission.
+
+Real: the SessionDB, the gateway turn's started admission (``admit_session_input`` +
+``claim_session_input``), the legacy ``prompt.submit`` and its ledger gate, and the owner
+(``SessionAuthority`` + ``AuthorityConnection``: attach, admission, claim stamp, settlement and
+publication). Replaced: only the owner's discovery and socket dial (``owner_forward.discover_owner`` /
+``connect_owner``), by an in-process client speaking to the same ``AuthorityConnection``."""
+import asyncio
+import contextlib
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_state import SessionDB
+from hermes_state_runtime import (
+ admit_session_input, begin_runtime_epoch, claim_session_input, list_session_admissions,
+ recover_session_inputs, settle_session_input,
+)
+from tui_gateway import server
+from tests.waiting import wait_until
+
+
+class _OwnerClient:
+ """``GatewayClient``'s surface (``rpc`` + ``events``) over a real ``AuthorityConnection``."""
+
+ def __init__(self, authority):
+ from gateway.session_controls import AuthorityConnection
+ self.loop, self.events = asyncio.get_running_loop(), asyncio.Queue()
+ self.conn = AuthorityConnection(authority, self, {"user_id": "desktop"})
+
+ def write(self, frame): # the owner's fanout to this socket
+ self.loop.call_soon_threadsafe(self.events.put_nowait, frame)
+ return True
+
+ def close(self):
+ return None
+
+ async def rpc(self, method, **params):
+ reply = await self.conn.dispatch({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
+ if "error" in reply:
+ from hermes_cli.gateway_client import rpc_error
+ raise rpc_error(reply["error"])
+ return reply["result"]
+
+
+def _legacy(monkeypatch, db):
+ monkeypatch.setattr(server, "_get_db", lambda: db)
+ for name in ("_schedule_agent_build", "_schedule_session_cap_enforcement", "_register_session_cwd",
+ "_start_agent_build"):
+ monkeypatch.setattr(server, name, lambda *_a, **_k: None)
+ monkeypatch.setattr(server, "_restart_completed_failed_agent_build", lambda *_a: False)
+ turns, emitted = [], []
+ monkeypatch.setattr(server, "_run_after_agent_ready", lambda *a: turns.append(a[1]))
+ monkeypatch.setattr(server, "_emit", lambda event, sid, payload=None: emitted.append((event, sid, payload)) or True)
+ created = server.handle_request({"id": "c", "method": "session.create", "params": {"source": "desktop"}})
+ return created["result"]["session_id"], created["result"]["stored_session_id"], turns, emitted
+
+
+def _owner(monkeypatch, db, key, epoch):
+ from gateway.session_authority import LiveSession, SessionAuthority
+ authority = SessionAuthority(SimpleNamespace(_draining=False), profile_id="owned", instance_id="gateway",
+ db=db, epoch=epoch)
+ authority.sessions[key] = LiveSession(SimpleNamespace(platform=None, user_id="desktop"), "route")
+ monkeypatch.setattr(authority, "_schedule", lambda ref: None) # the test drives the FIFO
+ try:
+ from tui_gateway import owner_forward
+ except ImportError: # main: no forwarder; the submit is refused and the assertions below fail
+ return authority
+
+ @contextlib.asynccontextmanager
+ async def connect(_home, endpoint):
+ assert endpoint == "ready-owner"
+ yield _OwnerClient(authority)
+ monkeypatch.setattr(owner_forward, "discover_owner", lambda _home: "ready-owner")
+ monkeypatch.setattr(owner_forward, "connect_owner", connect)
+ return authority
+
+
+def test_desktop_prompt_during_a_gateway_turn_runs_after_it_in_the_owner_fifo(monkeypatch, tmp_path):
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key, turns, emitted = _legacy(monkeypatch, db)
+ try:
+ db.create_session(key, "test")
+ epoch = begin_runtime_epoch(db, instance_id="gateway")
+ # The gateway is running a Bot Chat delivery on this session.
+ bot = admit_session_input(db, epoch=epoch, principal_id="bot", session_id=key, request_id="dm-1",
+ payload={"text": "a message_agent DM"})
+ claimed = claim_session_input(db, epoch=epoch, session_id=key)
+ assert claimed["admission_id"] == bot["admission_id"]
+ authority = _owner(monkeypatch, db, key, epoch)
+
+ reply = server.handle_request({"id": "p", "method": "prompt.submit",
+ "params": {"session_id": sid, "text": "my own question"}})
+
+ assert "error" not in reply, reply # main: 4090 SESSION_NOT_OWNED
+ assert reply["result"]["status"] == "queued" and reply["result"]["forwarded"] is True
+ assert turns == [] and db.get_messages_as_conversation(key) == [] # nothing ran here
+ rows = list_session_admissions(db, session_id=key)
+ assert [(r["principal_id"], r["status"]) for r in rows] == [("bot", "started"), (rows[1]["principal_id"], "queued")]
+ mine = rows[1]
+ assert mine["admission_id"] == reply["result"]["admission_id"] and mine["payload"]["text"] == "my own question"
+ # Queued, not a failed turn: the Desktop's pending-submission card, never an ``error``.
+ wait_until(lambda: any(e == "session.info" for e, *_ in emitted), timeout=10)
+ pending = next(p for e, _s, p in emitted if e == "session.info")["pending_submissions"]
+ assert pending == [{"admission_id": mine["admission_id"], "status": "queued", "user": "my own question",
+ "input_id": mine["request_id"]}]
+ assert not any(e == "error" for e, *_ in emitted)
+
+ # The gateway turn ends; the owner's FIFO runs the prompt next, exactly once.
+ assert claim_session_input(db, epoch=epoch, session_id=key) is None # behind the running turn
+ settle_session_input(db, epoch=epoch, admission_id=bot["admission_id"], generation=claimed["generation"],
+ outcome="completed")
+ row = claim_session_input(db, epoch=epoch, session_id=key)
+ assert row["admission_id"] == mine["admission_id"]
+ assert claim_session_input(db, epoch=epoch, session_id=key) is None
+ from gateway.session_contract import SessionRef
+ from gateway.session_settlement_recovery import commit_and_publish
+ ref, live = SessionRef("owned", key), authority.sessions[key]
+ authority._stamp_claim(ref, live, row)
+ with live.event_stream.lock:
+ authority.executing.pop(key, None)
+ commit_and_publish(authority, live, ref, row, "THE ANSWER", "completed", None, {})
+
+ wait_until(lambda: any(e == "message.complete" for e, *_ in emitted), timeout=10)
+ relayed = [(e, p) for e, s, p in emitted if s == sid and e.startswith("message.")]
+ assert relayed[0][0] == "message.start"
+ assert relayed[-1] == ("message.complete", {"text": "THE ANSWER", "status": "complete"})
+ assert [p["pending_submissions"] for e, _s, p in emitted if e == "session.info"][-1] == []
+ assert [r["status"] for r in list_session_admissions(db, session_id=key, pending_only=False)] == [
+ "terminal", "terminal"]
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
+def test_outcome_unknown_work_is_still_refused_and_never_forwarded(monkeypatch, tmp_path):
+ """Only Discard resolves an ``unknown`` admission: a prompt is never queued past it."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key, turns, _emitted = _legacy(monkeypatch, db)
+ try:
+ db.create_session(key, "test")
+ first = begin_runtime_epoch(db, instance_id="gateway-1")
+ admit_session_input(db, epoch=first, principal_id="bot", session_id=key, request_id="dm-1",
+ payload={"text": "lost?"})
+ claim_session_input(db, epoch=first, session_id=key)
+ epoch = begin_runtime_epoch(db, instance_id="gateway-2")
+ recover_session_inputs(db, epoch=epoch)
+ _owner(monkeypatch, db, key, epoch)
+ reply = server.handle_request({"id": "p", "method": "prompt.submit",
+ "params": {"session_id": sid, "text": "hi"}})
+ assert reply["error"]["code"] == 4090 and reply["error"]["data"] == {"reason": "SESSION_NOT_OWNED"}
+ assert len(list_session_admissions(db, session_id=key)) == 1 and turns == []
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
[email protected]("case", ["owner_refused", "rewind"])
+def test_a_prompt_the_owner_cannot_queue_is_refused_with_why_and_when(monkeypatch, tmp_path, case):
+ """Where admission is impossible the refusal names why and says to send when the turn ends,
+ with a transient reason (not SESSION_NOT_OWNED, whose card offers a new chat)."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key, turns, _emitted = _legacy(monkeypatch, db)
+ try:
+ db.create_session(key, "test")
+ epoch = begin_runtime_epoch(db, instance_id="gateway")
+ admit_session_input(db, epoch=epoch, principal_id="bot", session_id=key, request_id="dm-1",
+ payload={"text": "a DM"})
+ claim_session_input(db, epoch=epoch, session_id=key)
+ params = {"session_id": sid, "text": "hi"}
+ _owner(monkeypatch, db, key, epoch)
+ if case == "owner_refused":
+ from tui_gateway import owner_forward
+
+ @contextlib.asynccontextmanager
+ async def refused(_home, _endpoint):
+ raise owner_forward.OwnerUnavailable("the gateway answered with another protocol")
+ yield
+ monkeypatch.setattr(owner_forward, "connect_owner", refused)
+ else:
+ params.update(truncate_before_user_ordinal=0, confirm_truncate=True)
+ reply = server.handle_request({"id": "p", "method": "prompt.submit", "params": params})
+ assert reply["error"]["code"] == 4090 and reply["error"]["data"] == {"reason": "SESSION_OWNER_BUSY"}
+ message = reply["error"]["message"]
+ assert "when the current turn ends" in message and "Nothing was sent" in message
+ assert ("another protocol" in message) if case == "owner_refused" else ("rewind" in message)
+ assert len(list_session_admissions(db, session_id=key)) == 1 and turns == []
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
diff --git a/tui_gateway/contracts/prompt_voice.py b/tui_gateway/contracts/prompt_voice.py
index 022fc6ca1de..a80188064d7 100644
--- a/tui_gateway/contracts/prompt_voice.py
+++ b/tui_gateway/contracts/prompt_voice.py
@@ -73,6 +73,10 @@ class PromptSubmitResult(Result):
survivor_user_row_ids: list[int | None] | None = None
survivor_row_id_map: dict[str, int | None] | None = None
turn_isolation: bool | None = None
+ # RT-37: the gateway's durable ledger held work for this session, so the prompt was admitted into
+ # the OWNER's FIFO (``status: queued``) and runs there after the current turn; nothing runs here.
+ admission_id: str | None = None
+ forwarded: bool | None = None
method("prompt.submit", params=PromptSubmitParams, result=PromptSubmitResult,
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index 49d2d36682e..ff67b32dffa 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -695,6 +695,42 @@ def _run_after_agent_ready(
_TRUNCATION_PARAMS = (
"truncate_before_user_ordinal", "truncate_before_row_id", "truncate_before_message_id")
+#: The refusal reason when the owner's FIFO could not take a typed prompt (RT-37): transient, the
+#: gateway's turn ends on its own, so the client offers "send when the turn ends", not a new chat.
+SESSION_OWNER_BUSY = "SESSION_OWNER_BUSY"
+
+
+def _submit_to_ledger_owner(rid, sid, session, text, params, refusal) -> dict:
+ """The gateway's durable ledger holds work for this session (#140385, RT-37): one owner, one FIFO.
+ Work that ends on its own (a running or queued gateway turn) gets this prompt queued behind it in
+ the OWNER's FIFO (``owner_forward``): the owner runs it once, after the current turn, and nothing
+ runs here. An ``unknown`` admission, or work no running gateway will finish, keeps its refusal
+ (only Discard / a gateway resume resolves it); anything else that cannot be queued is refused
+ with the reason and the advice to send when the turn ends."""
+ from tui_gateway import owner_forward
+ not_owned = _err(rid, 4090, str(refusal), {"reason": getattr(refusal, "reason", None) or "SESSION_NOT_OWNED"})
+ if getattr(refusal, "ledger_status", None) == "unknown":
+ return not_owned
+ why = None
+ if not owner_forward.forwardable(refusal, session, text, params):
+ why = ("a rewind or attachment cannot join its queue" if isinstance(text, str) and text.strip()
+ else "this kind of message cannot join its queue")
+ else:
+ try:
+ receipt = owner_forward.forward_prompt(sid, session, text)
+ except owner_forward.OwnerNotRunning:
+ return not_owned # no gateway runs the ledger's work: it will not end on its own
+ except Exception as exc: # every owner failure is the same named refusal
+ logger.info("forwarding prompt for %s to the owner failed: %s",
+ session.get("session_key") or sid, exc, exc_info=True)
+ why = str(exc) if isinstance(exc, owner_forward.OwnerUnavailable) else "the gateway refused it"
+ else:
+ return _ok(rid, {"status": "queued", "admission_id": receipt.get("admission_id"),
+ "forwarded": True})
+ return _err(rid, 4090, "The gateway is running a turn in this chat and " + why
+ + ". Nothing was sent. Send it again when the current turn ends.",
+ {"reason": SESSION_OWNER_BUSY})
+
def _lock_in_submit_turn(
rid, sid, session, text, params, has_truncation, requested_rebind_ids, hosted_task, display_kind):
@@ -775,6 +811,8 @@ def _(rid, params: dict) -> dict:
if (limit_message := _ensure_active_session_slot(sid, session)) is not None:
# Refused HERE — before the busy queue, db row and agent build — so a refusal
# leaves the session untouched. The reason travels as machine-readable data.
+ if getattr(limit_message, "ledger_status", None) is not None and not internal_hosted_submit:
+ return _submit_to_ledger_owner(rid, sid, session, text, params, limit_message)
reason = getattr(limit_message, "reason", None)
return _err(rid, 4090, str(limit_message), {"reason": reason} if reason else None)
# Rewritten every submit: a session alternates app window / HUD / live voice; a stale value misinforms.
diff --git a/tui_gateway/owner_forward.py b/tui_gateway/owner_forward.py
new file mode 100644
index 00000000000..76c3f19c9e4
--- /dev/null
+++ b/tui_gateway/owner_forward.py
@@ -0,0 +1,193 @@
+"""Serve -> owner cutover for one typed prompt (RT-37, #140385).
+
+A legacy ``hermes serve`` backend (no session authority) refuses a turn while the gateway's durable
+ledger holds work for the same stored session (``session_lifecycle._canonical_ledger_refusal``): a
+legacy turn would run beside the canonical FIFO and write the transcript twice. A Bot Chat the
+gateway also owns hits that on every gateway turn, so the user's own Desktop prompt was refused
+``SESSION_NOT_OWNED`` and the card offered "Start new session".
+
+The #106742 contract is one owner and one FIFO, with clients that submit. So the prompt goes to the
+owner instead: this backend dials the ready gateway serving the session's profile home, attaches to
+the session and admits the prompt into its durable FIFO (``prompt.submit`` with a fresh submission
+id). The owner runs it after the current turn, exactly once; nothing runs here. The owner's frames
+for THAT admission are relayed onto the Desktop's live session, so the client sees an ordinary
+queued send that later streams and completes. If the relay loses the owner, an empty
+``message.complete`` settles the bubble and the client re-reads the stored transcript the owner
+writes. An ``unknown`` admission is never forwarded: only Discard resolves it.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import logging
+import threading
+import uuid
+from concurrent.futures import Future
+from concurrent.futures import TimeoutError as FutureTimeout
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+#: Ledger states a forwarded prompt may wait behind: they end on their own.
+FORWARDABLE_LEDGER_STATES = frozenset({"started", "queued", "registered", "running"})
+#: How long ``prompt.submit`` waits for the owner's admission receipt.
+ADMIT_TIMEOUT_S = 30.0
+#: Ceiling on one relay; the owner keeps the work either way (it is durable).
+RELAY_TIMEOUT_S = 6 * 3600.0
+#: Owner turn frames relayed for the forwarded admission. Not its deltas: a Desktop turn that streamed
+#: nothing re-reads the stored transcript at ``message.complete``, which brings the user's own row
+#: (written by the owner, not by this backend) and the reply in their committed order.
+_RELAYED = frozenset({"message.start", "message.complete"})
+
+
+class OwnerUnavailable(RuntimeError):
+ """The owner could not take the prompt; ``str(exc)`` names why for the refusal."""
+
+
+class OwnerNotRunning(OwnerUnavailable):
+ """No ready gateway serves the home: nothing will end the ledger's work on its own."""
+
+
+def discover_owner(home: Path):
+ """The ready gateway endpoint serving ``home``. Discovery only: never starts one."""
+ from hermes_cli.gateway_runtime import discover_gateway_endpoint
+ discovery = discover_gateway_endpoint(home, timeout=5)
+ if discovery.state != "ready" or discovery.endpoint is None:
+ raise OwnerNotRunning(f"the gateway that owns it is {discovery.state}")
+ return discovery.endpoint
+
+
+async def connect_owner(home: Path, endpoint):
+ """A ``GatewayClient`` on ``endpoint``, the ready gateway serving ``home``."""
+ from hermes_cli.gateway_client import GATEWAY_WS_PROTOCOL, GatewayClient, _session_ticket, gateway_ws_target
+ from websockets.asyncio.client import connect
+
+ ticket = await asyncio.to_thread(_session_ticket, home, endpoint)
+ url, protocols = gateway_ws_target(endpoint, ticket)
+ # Loopback owner dial: never through HTTP(S)_PROXY (websockets>=14 honours it by default).
+ async with connect(url, subprotocols=protocols, open_timeout=10, proxy=None) as ws:
+ if ws.subprotocol != GATEWAY_WS_PROTOCOL:
+ raise OwnerUnavailable("the gateway answered with another protocol")
+ async with GatewayClient(ws) as client:
+ yield client
+
+
+def forwardable(refusal: Any, session: dict, text: Any, params: dict) -> bool:
+ """Whether a ledger refusal of this ``prompt.submit`` can go to the owner instead."""
+ if getattr(refusal, "ledger_status", None) not in FORWARDABLE_LEDGER_STATES:
+ return False
+ return (isinstance(text, str) and bool(text.strip()) and not session.get("attached_images")
+ and not any(params.get(key) is not None for key in (
+ "truncate_before_user_ordinal", "truncate_before_row_id", "truncate_before_message_id")))
+
+
+def _payload_for(event_type: str, payload: Any) -> dict | None:
+ """The owner payload projected onto this wire's contract for ``event_type`` (None: drop it)."""
+ from tui_gateway.contracts.registry import EVENTS
+ contract = EVENTS.get(event_type)
+ if contract is None or contract.payload is None or not isinstance(payload, dict):
+ return None
+ shaped = {key: value for key, value in payload.items() if key in contract.payload.model_fields}
+ try:
+ contract.payload.model_validate(shaped)
+ except Exception:
+ if event_type != "message.complete":
+ return None
+ shaped = {"text": payload.get("text") if isinstance(payload.get("text"), str) else ""}
+ return shaped
+
+
+class _Relay:
+ def __init__(self, sid: str, session: dict, key: str, home: Path, endpoint, text: str, emit):
+ self.sid, self.session, self.key, self.home, self.text, self.emit = sid, session, key, home, text, emit
+ self.endpoint, self.listed = endpoint, None
+ self.admitted: Future = Future()
+ self.request_id = "desktop-forward-" + uuid.uuid4().hex
+
+ def run(self) -> None:
+ try:
+ asyncio.run(self._run())
+ except BaseException as exc: # thread boundary: hand the failure to the waiting submit
+ if not self.admitted.done():
+ self.admitted.set_exception(exc)
+ else:
+ logger.warning("owner relay for %s ended: %s", self.key, exc)
+
+ async def _run(self) -> None:
+ async with connect_owner(self.home, self.endpoint) as client:
+ attached = await client.rpc("session.resume", session_id=self.key)
+ target = str(attached.get("session_id") or self.key)
+ receipt = await client.rpc("prompt.submit", session_id=target, text=self.text,
+ submission_id=self.request_id)
+ admission_id = receipt.get("admission_id")
+ if not isinstance(admission_id, str) or receipt.get("status") not in ("queued", "started", "terminal"):
+ raise OwnerUnavailable("the gateway did not admit it")
+ self.admitted.set_result(receipt)
+ logger.info("forwarded Desktop prompt for %s to the owner FIFO: admission=%s",
+ self.key, admission_id)
+ await self._relay(client, admission_id)
+
+ def _pending(self, params: dict, admission_id: str) -> None:
+ """The owner's pending list as this wire's ``pending_submissions``, this admission only: the
+ Desktop's queued-row card while it waits, retired once the owner starts it."""
+ rows = (params.get("payload") or {}).get("pending")
+ if not isinstance(rows, list):
+ return
+ listed = [{"admission_id": admission_id, "status": "queued", "user": self.text, "input_id": self.request_id}
+ for row in rows if isinstance(row, dict) and row.get("admission_id") == admission_id
+ and row.get("status") == "queued"]
+ if listed != self.listed:
+ self.listed = listed
+ self.emit("session.info", self.sid, {"stored_session_id": self.key, "pending_submissions": listed})
+
+ async def _relay(self, client, admission_id: str) -> None:
+ settled = False
+ try:
+ async with asyncio.timeout(RELAY_TIMEOUT_S):
+ while not settled and not self.session.get("_finalized"):
+ frame = await client.events.get()
+ if isinstance(frame, BaseException):
+ return
+ params = frame.get("params") if isinstance(frame, dict) else None
+ if not isinstance(params, dict):
+ continue
+ if params.get("type") == "session.info":
+ self._pending(params, admission_id)
+ continue
+ if params.get("admission_id") != admission_id:
+ continue
+ event_type = params.get("type")
+ if event_type not in _RELAYED:
+ continue
+ payload = _payload_for(event_type, params.get("payload"))
+ if payload is None:
+ continue
+ self.emit(event_type, self.sid, payload)
+ settled = event_type == "message.complete"
+ finally:
+ if not settled and not self.session.get("_finalized"):
+ # Lost the owner mid-relay: the work is durable and still runs there. An empty
+ # completion settles the bubble; the client re-reads the stored transcript.
+ self.emit("message.complete", self.sid, {"text": ""})
+
+
+def forward_prompt(sid: str, session: dict, text: str, *, emit=None, home: Path | None = None) -> dict:
+ """Admit ``text`` into the owner's FIFO for this session; the owner's receipt.
+
+ Raises ``OwnerNotRunning`` when no gateway serves the home, ``OwnerUnavailable`` (or the
+ client's refusal) when the owner did not take it; nothing was admitted unless the receipt
+ timed out, which is reported as such."""
+ from tui_gateway import server
+ key = str(session.get("session_key") or "")
+ if not key:
+ raise OwnerUnavailable("the chat has no stored session yet")
+ home = Path(home or session.get("profile_home") or server._hermes_home).resolve()
+ relay = _Relay(sid, session, key, home, discover_owner(home), text, emit or server._emit)
+ threading.Thread(target=relay.run, name=f"owner-forward-{key[:24]}", daemon=True).start()
+ try:
+ return relay.admitted.result(timeout=ADMIT_TIMEOUT_S)
+ except FutureTimeout as exc:
+ raise OwnerUnavailable("the gateway did not confirm it in time; check the chat before sending again") from exc
diff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.py
index 9f6c2110e63..f0b6abf9839 100644
--- a/tui_gateway/session_lifecycle.py
+++ b/tui_gateway/session_lifecycle.py
@@ -170,10 +170,14 @@ def _canonical_ledger_refusal(session: dict):
if row is None:
return None
logger.info("Refusing legacy turn for %s: canonical ledger holds %s work", key, row[0])
- return ActiveSessionRefusal(
+ refusal = ActiveSessionRefusal(
f"Session {key} has {'outcome-unknown' if row[0] == 'unknown' else 'pending'} work in the gateway's "
"durable queue. Resume it through the gateway (hermes chat --resume, Desktop or the TUI) to "
"resolve it; nothing was run here.", SESSION_NOT_OWNED)
+ # prompt.submit forwards a typed prompt to the owner's FIFO for work that ends on its own
+ # (tui_gateway/owner_forward.py); an ``unknown`` admission is never forwarded past.
+ refusal.ledger_status = row[0]
+ return refusal
def _attach_lease(session: dict, lease) -> None: