The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): /queue while a turn runs goes into the gateway's durable FIFO
Teknium8fa422db49f1
diff --git a/hermes_cli/cli_loops_mixin.py b/hermes_cli/cli_loops_mixin.pyindex 8e8c7e0418a..50bea7e6eb3 100644--- a/hermes_cli/cli_loops_mixin.py+++ b/hermes_cli/cli_loops_mixin.py@@ -10,6 +10,7 @@ import threadingimport timefrom agent.i18n import t+from hermes_cli.gateway_client import GatewayClientErrorfrom rich.markup import escape as _escape@@ -352,29 +353,68 @@ class CLILoopsMixin:q.not_empty.notify_all()return before, after+ def _gateway_queue_store(self):+ """The gateway session store when this CLI is a viewer of the gateway's session, else None."""+ from hermes_cli.gateway_tools_notify import gateway_store+ return gateway_store(self) if getattr(self, "session_id", None) else None++ def _queue_items(self) -> list:+ """``[(admission_id | None, item)]``: the owner's queued admissions (run first, in its FIFO+ order), then the turns still waiting in ``_pending_input``."""+ items: list = []+ store = self._gateway_queue_store()+ if store is not None:+ from hermes_cli import gateway_queue+ items = list(gateway_queue.queued_rows(self, store))+ return items + [(None, item) for item in self._pending_input_items()]+def _queue_enqueue(self, text: str) -> None:from cli import _cprintpayload = self._expand_paste_references(text)- self._pending_input.put(payload)+ store = self._gateway_queue_store() if self._agent_running else None+ if store is not None:+ # #134889 N5: the gateway's durable FIFO holds it (committed at accept, kept across an owner+ # restart, run once after the current turn), never this process.+ from hermes_cli import gateway_queue+ try:+ gateway_queue.submit_queued(self, store, payload)+ except GatewayClientError as exc: # the owner refused or is gone: say so, nothing is held here+ _cprint(f" {t('cli.queue.gateway_refused', error=exc)}")+ return+ else:+ self._pending_input.put(payload)key = "cli.queue.queued_next_turn" if self._agent_running else "cli.queue.queued"_cprint(f" {t(key, preview=_preview(payload))}")def _queue_list(self, rest: str) -> None:from cli import _VoiceInputMessage, _cprint- items = self._pending_input_items()+ items = self._queue_items()if not items:_cprint(f" {t('cli.queue.empty')}" + ("" if rest else " " + _queue_usage()))return_cprint(f" {t('cli.queue.pending_header', count=len(items))}")- for idx, item in enumerate(items, 1):+ for idx, (_, item) in enumerate(items, 1):tag = " [voice]" if isinstance(item, _VoiceInputMessage) else ""_cprint(f" {idx}. {_preview(str(item).replace(chr(10), ' '))}{tag}")+ def _queue_gateway_call(self, verb, *args):+ """One owner verb on a queued admission; its refusal is printed, never raised."""+ from cli import _cprint+ from hermes_cli import gateway_queue+ try:+ return getattr(gateway_queue, verb)(self, self._gateway_queue_store(), *args)+ except GatewayClientError as exc:+ _cprint(f" {t('cli.queue.gateway_refused', error=exc)}")+ return None+def _queue_clear(self, rest: str) -> None:from cli import _cprint+ owned = [admission for admission, _ in self._queue_items() if admission]+ cleared = sum(1 for admission in owned if self._queue_gateway_call("cancel", admission))before, _ = self._mutate_pending_input(lambda items: [])- key = "cli.queue.cleared_one" if len(before) == 1 else "cli.queue.cleared_other"- _cprint(f" {t(key, count=len(before))}")+ cleared += len(before)+ key = "cli.queue.cleared_one" if cleared == 1 else "cli.queue.cleared_other"+ _cprint(f" {t(key, count=cleared)}")def _queue_remove(self, rest: str) -> None:from cli import _cprint@@ -383,13 +423,21 @@ class CLILoopsMixin:if idx is None:_cprint(f" {t('cli.queue.usage_remove')}")return+ items = self._queue_items()+ owned = sum(1 for admission, _ in items if admission)+ if 1 <= idx <= owned:+ admission, text = items[idx - 1]+ if self._queue_gateway_call("cancel", admission):+ _cprint(f" {t('cli.queue.removed', index=idx, preview=_preview(str(text)))}")+ return+ local = idx - ownedremoved: list = []before, _ = self._mutate_pending_input(- lambda items: (removed.append(items.pop(idx - 1)) or items) if 1 <= idx <= len(items) else items)+ lambda items: (removed.append(items.pop(local - 1)) or items) if 1 <= local <= len(items) else items)if removed:_cprint(f" {t('cli.queue.removed', index=idx, preview=_preview(str(removed[0])))}")else:- _cprint(f" {t('cli.queue.item_not_found', index=idx, size=len(before))}")+ _cprint(f" {t('cli.queue.item_not_found', index=idx, size=owned + len(before))}")def _queue_edit(self, rest: str) -> None:from cli import _VoiceInputMessage, _cprint@@ -402,18 +450,26 @@ class CLILoopsMixin:returnnew_prompt = bits[1]new_text = self._expand_paste_references(new_prompt.strip())+ items = self._queue_items()+ owned = sum(1 for admission, _ in items if admission)+ if 1 <= idx <= owned:+ # The owner admits the edit as a new admission at the back of its FIFO.+ if self._queue_gateway_call("replace", items[idx - 1][0], new_text):+ _cprint(f" {t('cli.queue.updated', index=idx, preview=_preview(new_text))}")+ return+ local = idx - owneddef _edit(items: list) -> list:- if 1 <= idx <= len(items):+ if 1 <= local <= len(items):# A voice-queued item keeps its sentinel so the concise voice-response# prefix still applies (#65827).- voice = isinstance(items[idx - 1], _VoiceInputMessage)- items[idx - 1] = _VoiceInputMessage(new_text) if voice else new_text+ voice = isinstance(items[local - 1], _VoiceInputMessage)+ items[local - 1] = _VoiceInputMessage(new_text) if voice else new_textreturn itemsbefore, after = self._mutate_pending_input(_edit)if before == after:- _cprint(f" {t('cli.queue.item_not_found', index=idx, size=len(before))}")+ _cprint(f" {t('cli.queue.item_not_found', index=idx, size=owned + len(before))}")else:_cprint(f" {t('cli.queue.updated', index=idx, preview=_preview(new_text))}")@@ -424,6 +480,12 @@ class CLILoopsMixin:if src is None or dst is None:_cprint(f" {t('cli.queue.usage_move')}")return+ owned = sum(1 for admission, _ in self._queue_items() if admission)+ if owned and min(src, dst) <= owned and src != dst:+ # The owner's FIFO runs admissions in the order they were sent; it has no reorder verb.+ _cprint(f" {t('cli.queue.move_gateway_fifo')}")+ return+ src, dst = src - owned, dst - owneddef _move(items: list) -> list:if 1 <= src <= len(items) and 1 <= dst <= len(items):@@ -432,9 +494,9 @@ class CLILoopsMixin:before, after = self._mutate_pending_input(_move)if before == after and src != dst:- _cprint(f" {t('cli.queue.move_out_of_range', size=len(before))}")+ _cprint(f" {t('cli.queue.move_out_of_range', size=owned + len(before))}")else:- _cprint(f" {t('cli.queue.moved', source=src, destination=dst)}")+ _cprint(f" {t('cli.queue.moved', source=src + owned, destination=dst + owned)}")def _cmd_queue(self, cmd_original: str):"""``/queue <prompt>`` enqueues; a leading management verb whose arguments fitdiff --git a/hermes_cli/cli_session_dock.py b/hermes_cli/cli_session_dock.pyindex b5538e6d5c2..117647eb418 100644--- a/hermes_cli/cli_session_dock.py+++ b/hermes_cli/cli_session_dock.py@@ -74,9 +74,16 @@ def _prompt_text(item) -> str:def queued_prompts(cli) -> list[str]:"""One-line previews of the turns waiting in ``_pending_input``, oldest first."""+ from hermes_cli.gateway_tools_notify import gateway_store+ owned: list = []+ store = gateway_store(cli) if getattr(cli, "session_id", None) else None+ if store is not None:+ # The gateway's FIFO runs first (#134889 N5): its queued admissions as the owner last published them.+ from hermes_cli.gateway_queue import published_queue+ owned = published_queue(cli, store)pending = getattr(cli, "_pending_input", None)if pending is None:- return []+ return [text for text in map(_prompt_text, owned) if text]with pending.mutex:items = list(pending.queue)- return [text for text in map(_prompt_text, items) if text]+ return [text for text in map(_prompt_text, owned + items) if text]diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.pyindex 0d2784af698..8ffa0a34e9f 100644--- a/hermes_cli/gateway_connection.py+++ b/hermes_cli/gateway_connection.py@@ -61,6 +61,11 @@ class SessionState:self.request_listeners: list = []# A gateway-admitted notification turn the idle CLI queued a header for (gateway_tools_notify).self.admitted_turn: dict | None = None+ # The owner's pending admissions as last published (snapshot or ``session.info``), and the+ # ``/queue`` inputs this viewer admitted there (``admission_id -> text``), so the turn the owner+ # runs for one is painted like a typed turn (``gateway_tools_notify.queue_admitted_turn``).+ self.pending: list = []+ self.queued_inputs: dict = {}# ``session.replay_gap``s seen, and how many a re-attach covered: the owner retired this viewer's# subscription on overflow, so its frames stop until ``GatewayConnection.reattach``.self.gaps = self.attached_gaps = 0@@ -71,6 +76,8 @@ class SessionState:self.subscription_id = snapshot.get("subscription_id", self.subscription_id)self.execution_generation = snapshot.get("execution_generation", self.execution_generation)self.messages = list(snapshot.get("messages") or [])+ if isinstance(snapshot.get("pending"), list):+ self.pending = list(snapshot["pending"])if self.info.get("title"):self.title = self.info["title"]@@ -83,6 +90,8 @@ class SessionState:def apply_event(self, kind, payload):if kind in ("session.info", "session.updated") and isinstance(payload, dict):self.info.update({k: v for k, v in payload.items() if k != "session_id"})+ if isinstance(payload.get("pending"), list):+ self.pending = list(payload["pending"])if payload.get("title"):self.title = payload["title"]elif kind == "todo.updated" and isinstance(payload, dict):diff --git a/hermes_cli/gateway_queue.py b/hermes_cli/gateway_queue.pynew file mode 100644index 00000000000..23b67fb81c8--- /dev/null+++ b/hermes_cli/gateway_queue.py@@ -0,0 +1,92 @@+"""The classic CLI's ``/queue`` over the gateway's durable FIFO (refs #134889, N5).++On main a prompt queued while a turn ran sat in the CLI's ``_pending_input``: no+``session_admissions`` row, so an owner restart or a disconnect lost it. Over the session authority+``/queue <prompt>`` typed while a turn runs is an ordinary queued admission (``prompt.submit+{queued: true}``, the same path Ink and Desktop queue busy input on): the owner commits it at accept,+keeps it across a restart and runs it once, in FIFO order, after the current turn.++The CLI keeps no copy to resend. It remembers only which admissions it queued+(``SessionState.queued_inputs``) so the turn the owner runs for one is painted like a typed turn+(``gateway_tools_notify.queue_admitted_turn`` adopts it), and ``/queue list|edit|rm|clear`` read and+change the owner's queue (``prompt.receipt`` / ``prompt.replace_queued`` / ``prompt.cancel``).+"""+from __future__ import annotations++import logging+import uuid++from hermes_cli.gateway_client import GatewayClientError++logger = logging.getLogger(__name__)+++def _state(cli, store):+ return store.connection.state(cli.session_id)+++def submit_queued(cli, store, text: str) -> str:+ """Admit ``text`` behind the running turn in the owner's FIFO; returns its admission id."""+ receipt = store.call("prompt.submit", session_id=cli.session_id, submission_id=uuid.uuid4().hex,+ text=text, queued=True)+ admission = (receipt or {}).get("admission_id")+ if not admission:+ raise GatewayClientError("the gateway did not admit the queued prompt")+ _state(cli, store).queued_inputs[admission] = text+ return admission+++def queued_rows(cli, store) -> list[tuple[str, str]]:+ """``[(admission_id, text)]`` still queued in the owner's FIFO, in run order.++ This viewer's own admissions are read back with ``prompt.receipt`` (one it finds started or gone+ is forgotten); other viewers' queued rows come from the last pending list the owner published.+ """+ state = _state(cli, store)+ rows: dict[str, tuple[int, str]] = {}+ for row in state.pending or ():+ if isinstance(row, dict) and row.get("status") == "queued" and row.get("admission_id"):+ rows[row["admission_id"]] = (int(row.get("sequence") or 0), str(row.get("text") or ""))+ for admission, text in list(state.queued_inputs.items()):+ try:+ receipt = store.call("prompt.receipt", session_id=cli.session_id, admission_id=admission)+ except GatewayClientError as exc:+ logger.debug("prompt.receipt %s failed: %s", admission, exc)+ rows.setdefault(admission, (1 << 62, text)) # unread: still shown, never dropped+ continue+ if receipt.get("status") == "queued":+ rows[admission] = (int(receipt.get("sequence") or 0), text)+ else:+ rows.pop(admission, None)+ if receipt.get("status") != "started": # a started one is adopted by the idle tick+ state.queued_inputs.pop(admission, None)+ return [(admission, text) for admission, (_, text) in sorted(rows.items(), key=lambda kv: kv[1][0])]+++def published_queue(cli, store) -> list[str]:+ """The texts the owner last published as queued, plus this viewer's admissions not yet in that list+ (no RPC: the dock repaints on every tick)."""+ state = _state(cli, store)+ rows = [row for row in state.pending or () if isinstance(row, dict)]+ known = {row.get("admission_id") for row in rows}+ return ([str(row.get("text") or "") for row in rows if row.get("status") == "queued"]+ + [text for admission, text in state.queued_inputs.items() if admission not in known])+++def cancel(cli, store, admission: str) -> bool:+ """Retire one queued admission; True when it no longer runs."""+ receipt = store.call("prompt.cancel", session_id=cli.session_id, admission_id=admission)+ _state(cli, store).queued_inputs.pop(admission, None)+ return (receipt or {}).get("status") == "terminal"+++def replace(cli, store, admission: str, text: str) -> str | None:+ """``prompt.replace_queued``: the edited prompt is a new admission at the back of the FIFO."""+ receipt = store.call("prompt.replace_queued", session_id=cli.session_id, admission_id=admission,+ submission_id=uuid.uuid4().hex, text=text)+ state = _state(cli, store)+ state.queued_inputs.pop(admission, None)+ new = (receipt or {}).get("admission_id")+ if new:+ state.queued_inputs[new] = text+ return newdiff --git a/hermes_cli/gateway_tools_notify.py b/hermes_cli/gateway_tools_notify.pyindex 5e176c2b584..57bcda914d7 100644--- a/hermes_cli/gateway_tools_notify.py+++ b/hermes_cli/gateway_tools_notify.py@@ -66,6 +66,15 @@ def queue_admitted_turn(cli, store) -> None:continueif params.get("type") != "message.start" or not params.get("admission_id"):continue+ queued_text = state.queued_inputs.pop(params["admission_id"], None)+ if queued_text is not None:+ # A ``/queue`` prompt this viewer admitted (#134889 N5): the owner runs it now, and main's+ # input path paints and pumps it as a typed turn. Literal: it is a prompt, never a command.+ from cli import _SeededQueryMessage+ state.admitted_turn = {"admission_id": params["admission_id"], "text": queued_text,+ "execution_generation": params.get("execution_generation")}+ _put_first(cli._pending_input, _SeededQueryMessage(queued_text))+ returncard = _card(params)if card is None:continuediff --git a/locales/af.yaml b/locales/af.yamlindex 12f7e9f2d15..36ae6843321 100644--- a/locales/af.yaml+++ b/locales/af.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "Tou-verplasing buite bereik. Huidige grootte: {size}"moved: "Tou-item {source} na {destination} verplaas."usage_add: "Gebruik: /queue add <prompt>"+ gateway_refused: "Die gateway het dit nie in die tou geplaas nie: {error}. Niks is in die tou geplaas nie; stuur dit weer wanneer die beurt eindig."+ move_gateway_fifo: "Die gateway voer toustaande prompts uit in die volgorde waarin dit gestuur is; wysig of verwyder eerder een."reload:env_reloaded: ".env herlaai ({count} veranderlike(s) opgedateer)"steer:diff --git a/locales/ar.yaml b/locales/ar.yamlindex 252ac98aa2f..66507f9c0b4 100644--- a/locales/ar.yaml+++ b/locales/ar.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "النقل خارج نطاق قائمة الانتظار. الحجم الحالي: {size}"moved: "نُقل عنصر قائمة الانتظار من {source} إلى {destination}."usage_add: "الاستخدام: /queue add <prompt>"+ gateway_refused: "لم تضعه البوابة في الطابور: {error}. لم يُضف شيء؛ أرسله مرة أخرى عند انتهاء الدور."+ move_gateway_fifo: "تشغّل البوابة المطالبات في الطابور بترتيب إرسالها؛ عدّل واحدة أو احذفها بدلاً من ذلك."reload:env_reloaded: "أُعيد تحميل .env (تم تحديث {count} متغيّر)"steer:diff --git a/locales/de.yaml b/locales/de.yamlindex b7e520d02b7..3556a341282 100644--- a/locales/de.yaml+++ b/locales/de.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "Verschiebung außerhalb der Warteschlange. Aktuelle Größe: {size}"moved: "Warteschlangeneintrag {source} nach {destination} verschoben."usage_add: "Verwendung: /queue add <prompt>"+ gateway_refused: "Das Gateway hat es nicht eingereiht: {error}. Nichts wurde eingereiht; sende es erneut, wenn der Zug endet."+ move_gateway_fifo: "Das Gateway führt eingereihte Prompts in Sendereihenfolge aus; bearbeite oder entferne stattdessen einen."reload:env_reloaded: ".env neu geladen ({count} Variable(n) aktualisiert)"steer:diff --git a/locales/en.yaml b/locales/en.yamlindex b1ed6a7e01a..c748a8d7f20 100644--- a/locales/en.yaml+++ b/locales/en.yaml@@ -2470,6 +2470,8 @@ cli:move_out_of_range: "Queue move out of range. Current size: {size}"moved: "Moved queue item {source} to {destination}."usage_add: "Usage: /queue add <prompt>"+ gateway_refused: "The gateway did not queue it: {error}. Nothing was queued; send it again when the turn ends."+ move_gateway_fifo: "The gateway runs queued prompts in the order they were sent; edit or remove one instead."reload:env_reloaded: "Reloaded .env ({count} var(s) updated)"steer:diff --git a/locales/es.yaml b/locales/es.yamlindex 2d959af6961..f9945b1fb3b 100644--- a/locales/es.yaml+++ b/locales/es.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "Movimiento fuera de rango en la cola. Tamaño actual: {size}"moved: "Elemento {source} de la cola movido a {destination}."usage_add: "Uso: /queue add <prompt>"+ gateway_refused: "El gateway no lo encoló: {error}. No se encoló nada; envíalo de nuevo cuando termine el turno."+ move_gateway_fifo: "El gateway ejecuta los prompts en cola en el orden de envío; edita o elimina uno en su lugar."reload:env_reloaded: "Se recargó .env ({count} variable(s) actualizada(s))"steer:diff --git a/locales/fr.yaml b/locales/fr.yamlindex c390af1d2f8..f9f2d59d6dd 100644--- a/locales/fr.yaml+++ b/locales/fr.yaml@@ -2643,6 +2643,8 @@ cli:move_out_of_range: "Déplacement hors limites de la file. Taille actuelle : {size}"moved: "Élément {source} de la file déplacé vers {destination}."usage_add: "Usage : /queue add <prompt>"+ gateway_refused: "Le gateway ne l'a pas mis en file : {error}. Rien n'a été mis en file ; renvoyez-le à la fin du tour."+ move_gateway_fifo: "Le gateway exécute les prompts en file dans l'ordre d'envoi ; modifiez ou supprimez-en un à la place."reload:env_reloaded: ".env rechargé ({count} variable(s) mise(s) à jour)"steer:diff --git a/locales/ga.yaml b/locales/ga.yamlindex 0dffd22baac..6ffe1bff15c 100644--- a/locales/ga.yaml+++ b/locales/ga.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "Bogadh scuaine as raon. Méid reatha: {size}"moved: "Bogadh mír scuaine {source} go {destination}."usage_add: "Úsáid: /queue add <prompt>"+ gateway_refused: "Níor chuir an geata sa scuaine é: {error}. Níor cuireadh aon rud sa scuaine; seol arís é nuair a chríochnaíonn an seal."+ move_gateway_fifo: "Ritheann an geata leideanna sa scuaine san ord inar seoladh iad; cuir ceann in eagar nó bain é ina ionad."reload:env_reloaded: "Athlódáladh .env ({count} athróg nuashonraithe)"steer:diff --git a/locales/hu.yaml b/locales/hu.yamlindex 7482e4d7a64..9d14a3d91d9 100644--- a/locales/hu.yaml+++ b/locales/hu.yaml@@ -2387,6 +2387,8 @@ cli:move_out_of_range: "A mozgatás kívül esik a soron. Jelenlegi méret: {size}"moved: "A(z) {source}. sorelem áthelyezve ide: {destination}."usage_add: "Használat: /queue add <prompt>"+ gateway_refused: "Az átjáró nem állította sorba: {error}. Semmi sem került sorba; küldd újra, amikor a kör véget ér."+ move_gateway_fifo: "Az átjáró a sorban álló promptokat küldési sorrendben futtatja; inkább szerkessz vagy távolíts el egyet."reload:env_reloaded: ".env újratöltve ({count} változó frissült)"steer:diff --git a/locales/it.yaml b/locales/it.yamlindex 968974b505a..6e7bf5c01a0 100644--- a/locales/it.yaml+++ b/locales/it.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "Spostamento fuori dai limiti della coda. Dimensione attuale: {size}"moved: "Elemento {source} della coda spostato in posizione {destination}."usage_add: "Uso: /queue add <prompt>"+ gateway_refused: "Il gateway non l'ha accodato: {error}. Nulla è stato accodato; invialo di nuovo a fine turno."+ move_gateway_fifo: "Il gateway esegue i prompt in coda nell'ordine di invio; modificane o rimuovine uno invece."reload:env_reloaded: "Ricaricato .env (variabili aggiornate: {count})"steer:diff --git a/locales/ja.yaml b/locales/ja.yamlindex 0afa6b067dc..104b273c439 100644--- a/locales/ja.yaml+++ b/locales/ja.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "キューの移動先が範囲外です。現在のサイズ: {size}"moved: "キュー項目 {source} を {destination} に移動しました。"usage_add: "使い方: /queue add <prompt>"+ gateway_refused: "ゲートウェイはキューに追加しませんでした: {error}。何も追加されていません。ターン終了後に再送してください。"+ move_gateway_fifo: "ゲートウェイはキュー内のプロンプトを送信順に実行します。代わりに編集または削除してください。"reload:env_reloaded: ".env を再読み込みしました({count} 件の変数を更新)"steer:diff --git a/locales/ko.yaml b/locales/ko.yamlindex 02ca5d75d1d..cc1f96216a1 100644--- a/locales/ko.yaml+++ b/locales/ko.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "대기열 이동 범위를 벗어났어요. 현재 크기: {size}"moved: "대기열 항목 {source}을(를) {destination}으로 이동했어요."usage_add: "사용법: /queue add <prompt>"+ gateway_refused: "게이트웨이가 대기열에 넣지 않았습니다: {error}. 아무것도 대기열에 없습니다. 턴이 끝나면 다시 보내세요."+ move_gateway_fifo: "게이트웨이는 대기 중인 프롬프트를 보낸 순서대로 실행합니다. 대신 편집하거나 삭제하세요."reload:env_reloaded: ".env를 다시 불러왔어요 (변수 {count}개 업데이트됨)"steer:diff --git a/locales/pt.yaml b/locales/pt.yamlindex eadf372ae12..00c7b7e57ed 100644--- a/locales/pt.yaml+++ b/locales/pt.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "Movimento na fila fora do intervalo. Tamanho atual: {size}"moved: "Item {source} da fila movido para {destination}."usage_add: "Uso: /queue add <prompt>"+ gateway_refused: "O gateway não o enfileirou: {error}. Nada foi enfileirado; envie novamente quando o turno terminar."+ move_gateway_fifo: "O gateway executa prompts enfileirados na ordem de envio; edite ou remova um em vez disso."reload:env_reloaded: ".env recarregado ({count} variável(is) atualizada(s))"steer:diff --git a/locales/ru.yaml b/locales/ru.yamlindex 15436723521..26db92b5575 100644--- a/locales/ru.yaml+++ b/locales/ru.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "Перемещение выходит за границы очереди. Текущий размер: {size}"moved: "Элемент очереди {source} перемещён на {destination}."usage_add: "Использование: /queue add <промпт>"+ gateway_refused: "Шлюз не поставил это в очередь: {error}. Ничего не поставлено; отправьте снова, когда ход закончится."+ move_gateway_fifo: "Шлюз выполняет запросы в очереди в порядке отправки; вместо этого измените или удалите один."reload:env_reloaded: "Файл .env перезагружен (обновлено переменных: {count})"steer:diff --git a/locales/tr.yaml b/locales/tr.yamlindex f097a7eebd2..9b81348b42c 100644--- a/locales/tr.yaml+++ b/locales/tr.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "Kuyruk taşıma aralık dışında. Geçerli boyut: {size}"moved: "Kuyruk öğesi {source}, {destination} konumuna taşındı."usage_add: "Kullanım: /queue add <prompt>"+ gateway_refused: "Ağ geçidi bunu kuyruğa almadı: {error}. Hiçbir şey kuyruğa alınmadı; tur bitince yeniden gönderin."+ move_gateway_fifo: "Ağ geçidi kuyruktaki istemleri gönderilme sırasıyla çalıştırır; bunun yerine birini düzenleyin veya kaldırın."reload:env_reloaded: ".env yeniden yüklendi ({count} değişken güncellendi)"steer:diff --git a/locales/uk.yaml b/locales/uk.yamlindex 3405cff3964..3458d8954ac 100644--- a/locales/uk.yaml+++ b/locales/uk.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "Переміщення в черзі поза межами діапазону. Поточний розмір: {size}"moved: "Елемент черги {source} переміщено на {destination}."usage_add: "Використання: /queue add <prompt>"+ gateway_refused: "Шлюз не поставив це в чергу: {error}. Нічого не поставлено; надішліть знову, коли хід закінчиться."+ move_gateway_fifo: "Шлюз виконує запити в черзі в порядку надсилання; натомість відредагуйте або видаліть один."reload:env_reloaded: "Перезавантажено .env (оновлено змінних: {count})"steer:diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yamlindex c7f14ac6a9d..2f82d163e73 100644--- a/locales/zh-hant.yaml+++ b/locales/zh-hant.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "佇列移動超出範圍。目前佇列長度:{size}"moved: "已將佇列項目 {source} 移至 {destination}。"usage_add: "用法:/queue add <prompt>"+ gateway_refused: "閘道未將其加入佇列:{error}。未加入任何內容;請在本輪結束後重新傳送。"+ move_gateway_fifo: "閘道依傳送順序執行佇列中的提示;請改為編輯或刪除其中一則。"reload:env_reloaded: "已重新載入 .env(更新了 {count} 個變數)"steer:diff --git a/locales/zh.yaml b/locales/zh.yamlindex c4f8594d883..3f64ebe3acd 100644--- a/locales/zh.yaml+++ b/locales/zh.yaml@@ -2370,6 +2370,8 @@ cli:move_out_of_range: "队列移动位置超出范围。当前队列长度:{size}"moved: "已将队列项 {source} 移至 {destination}。"usage_add: "用法:/queue add <prompt>"+ gateway_refused: "网关未将其加入队列:{error}。未加入任何内容;请在本轮结束后重新发送。"+ move_gateway_fifo: "网关按发送顺序运行队列中的提示;请改为编辑或删除其中一条。"reload:env_reloaded: "已重新加载 .env(更新了 {count} 个变量)"steer:diff --git a/tests/hermes_cli/test_cli_queue_gateway_fifo.py b/tests/hermes_cli/test_cli_queue_gateway_fifo.pynew file mode 100644index 00000000000..70a92b469af--- /dev/null+++ b/tests/hermes_cli/test_cli_queue_gateway_fifo.py@@ -0,0 +1,175 @@+"""The classic CLI's ``/queue`` goes into the gateway's durable FIFO (refs #134889, N5).++On main ``/queue <prompt>`` typed while a turn runs only ``put`` the text on the CLI's own+``_pending_input``: no ``session_admissions`` row, so an owner restart (or the N2 disconnect) lost or+failed it. Now the CLI submits it as an ordinary queued admission (``prompt.submit``), the way Ink and+Desktop queue busy input, and ``/queue list`` / ``rm`` / ``clear`` read and change the gateway's queue.++Real owners (``initialize_session_authority`` again on the same state.db is the restart), real+``AuthorityConnection.dispatch``, real ``GatewayConnection`` and ``GatewaySessionStore``. The one stub:+the first owner's drain is held (``_schedule`` no-op), which is what a running turn does to the FIFO.+"""+import asyncio+import queue+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import patch++import pytest++from hermes_cli.gateway_client import rpc_error+from hermes_cli.gateway_connection import GatewayConnection+from hermes_cli.gateway_session_store import GatewaySessionStore++TEXT = "N5 queued while the turn runs"+++class _Life:+ def __init__(self, connection, loop):+ self.connection, self.loop = connection, loop+ self.events = asyncio.Queue()++ async def rpc(self, method, *, _timeout=None, **params):+ frame = {'id': 1, 'method': method, 'params': params}+ reply = await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(self.connection.dispatch(frame), self.loop))+ if 'error' in reply:+ raise rpc_error(reply['error'])+ return reply['result']+++class _Owners:+ async def start(self, tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_controls import AuthorityConnection+ from gateway.session_local import create_local_session+ monkeypatch.setattr(run, '_load_gateway_config', lambda *a, **k: {'platform_toolsets': {'cli': []}})+ self.profile, self.loop, self.lives = str(tmp_path), asyncio.get_running_loop(), []+ self.store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ first = await self.boot('first')+ first._schedule = lambda ref: None # a turn is running: the FIFO does not drain+ actor = AuthorityConnection(first, object(), {'user_id': 'owner'}).actor+ self.sid = create_local_session(first, actor, {'cwd': self.profile, 'model': 'm', 'toolsets': [],+ 'request_id': 'n5'}).session_id+ return self++ async def boot(self, instance_id):+ from gateway.session_authority import initialize_session_authority+ owner = SimpleNamespace(session_store=self.store, _session_db=self.store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda route: None, _evict_cached_agent=lambda route: None)+ owner._adapter_for_source = lambda source: owner.adapters.get(source.platform)+ self.current = await initialize_session_authority(owner, profile_id=self.profile, instance_id=instance_id)+ return self.current++ async def _open(self):+ from gateway.session_controls import AuthorityConnection+ self.lives.append(_Life(AuthorityConnection(self.current, object(), {'user_id': 'owner'}), self.loop))+ return self.lives[-1]++ @asynccontextmanager+ async def dial(self):+ yield await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(self._open(), self.loop))++ def rows(self):+ from hermes_state_runtime import list_session_admissions+ return [row for row in list_session_admissions(self.store._db, session_id=self.sid, pending_only=False)+ if row['payload'].get('text') == TEXT]++ async def close(self, conn):+ await asyncio.to_thread(conn.close)+ for life in self.lives:+ await life.connection.close()+ self.store._db.close()+++def _busy_cli(store, sid):+ from cli import HermesCLI+ cli = HermesCLI.__new__(HermesCLI)+ cli.session_id = sid+ cli._pending_input = queue.Queue()+ cli._pending_resume_sessions = None+ cli._session_db = store+ cli._agent_running = True+ return cli+++def _command(cli, text):+ with patch("cli._cprint") as printed:+ assert cli.process_command(text) is True+ return " ".join(str(call.args[0]) for call in printed.call_args_list)+++async def test_queue_while_busy_is_a_durable_admission_that_survives_an_owner_restart(tmp_path, monkeypatch):+ owners = await _Owners().start(tmp_path, monkeypatch)+ conn = GatewayConnection(connect=owners.dial)+ try:+ store = GatewaySessionStore(conn)+ await asyncio.to_thread(store.attach, owners.sid)+ cli = _busy_cli(store, owners.sid)+ await asyncio.to_thread(_command, cli, f"/queue {TEXT}")+ # Not held client-side: one queued admission in state.db, nothing for the CLI to send again.+ assert cli._pending_input.empty()+ assert [row['status'] for row in owners.rows()] == ['queued']+ listed = await asyncio.to_thread(_command, cli, "/queue list")+ assert TEXT in listed++ await owners.boot('restarted') # the owner restarts; state.db keeps the FIFO+ assert [row['status'] for row in owners.rows()] == ['queued']+ assert len({row['admission_id'] for row in owners.rows()}) == 1 # exactly once, never re-submitted+ # The restarted owner lists it to a viewer that attaches now: it is the next turn it runs.+ fresh = GatewayConnection(connect=owners.dial)+ try:+ snapshot = await asyncio.to_thread(GatewaySessionStore(fresh).attach, owners.sid)+ assert [(row['text'], row['status']) for row in snapshot['pending']] == [(TEXT, 'queued')]+ finally:+ await asyncio.to_thread(fresh.close)+ finally:+ await owners.close(conn)+++async def test_queue_rm_and_clear_retire_the_gateway_admissions(tmp_path, monkeypatch):+ owners = await _Owners().start(tmp_path, monkeypatch)+ conn = GatewayConnection(connect=owners.dial)+ try:+ store = GatewaySessionStore(conn)+ await asyncio.to_thread(store.attach, owners.sid)+ cli = _busy_cli(store, owners.sid)+ await asyncio.to_thread(_command, cli, f"/queue {TEXT}")+ await asyncio.to_thread(_command, cli, "/queue second item")+ await asyncio.to_thread(_command, cli, "/queue rm 1")+ assert [row['status'] for row in owners.rows()] == ['terminal']+ listed = await asyncio.to_thread(_command, cli, "/queue list")+ assert "second item" in listed and TEXT not in listed+ await asyncio.to_thread(_command, cli, "/queue clear")+ assert "empty" in (await asyncio.to_thread(_command, cli, "/queue list")).lower()+ finally:+ await owners.close(conn)+++def test_the_owner_claim_of_a_queued_prompt_runs_as_a_typed_turn_without_a_second_submit():+ """When the owner starts the queued admission, the idle CLI paints it as the user's turn and+ ``run_conversation`` pumps that admission (no new ``prompt.submit``: it runs exactly once)."""+ from hermes_cli.gateway_agent import GatewayAgent+ from tests.hermes_cli.test_gateway_agent import SID, frame+ from tests.hermes_cli.test_gateway_tools_notify import _connected, _idle_cli, _play+ conn, client = _connected()+ try:+ cli = _idle_cli(conn)+ conn.state(SID).queued_inputs["adm-q"] = TEXT+ _play(conn, client, [frame("message.start", {}, admission="adm-q"),+ frame("message.delta", {"text": "ran"}, admission="adm-q"),+ frame("message.complete", {"text": "ran", "status": "complete"}, admission="adm-q")])+ cli._drain_process_notifications("cli-idle")+ item = cli._pending_input.get_nowait()+ assert str(item) == TEXT and type(item).__name__ == "_SeededQueryMessage" # literal, never a command+ assert conn.state(SID).queued_inputs == {}+ agent = GatewayAgent(connection=conn, session_id=SID)+ agent._pending_cli_user_message = {"role": "user", "content": TEXT}+ result = agent.run_conversation(TEXT, conversation_history=[])+ assert "prompt.submit" not in [method for method, _ in client.calls]+ assert result["final_response"] == "ran"+ finally:+ conn.close()