The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): a refused /queue rm or edit says what was refused
Teknium9e5d44281596
diff --git a/hermes_cli/cli_loops_mixin.py b/hermes_cli/cli_loops_mixin.pyindex 50bea7e6eb3..486036db296 100644--- a/hermes_cli/cli_loops_mixin.py+++ b/hermes_cli/cli_loops_mixin.py@@ -397,20 +397,28 @@ class CLILoopsMixin: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."""+ def _queue_gateway_call(self, verb, index, *args):+ """One owner verb on queued item ``index``; its refusal is printed (in its own words), never raised."""from cli import _cprintfrom hermes_cli import gateway_queue+ from hermes_cli.gateway_client import GatewayRPCErrortry: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+ except GatewayRPCError as exc:+ if str(exc) in gateway_queue.STARTED_REFUSALS: # the drain claimed it first: it runs as sent+ _cprint(f" {t('cli.queue.already_started', index=index)}")+ else:+ key = "cli.queue.edit_refused" if verb == "replace" else "cli.queue.remove_refused"+ _cprint(f" {t(key, index=index, error=exc)}")+ except GatewayClientError as exc: # no answer: the owner may have applied it+ _cprint(f" {t('cli.queue.change_unknown', index=index, error=exc)}")+ return Nonedef _queue_clear(self, rest: str) -> None:from cli import _cprintowned = [admission for admission, _ in self._queue_items() if admission]- cleared = sum(1 for admission in owned if self._queue_gateway_call("cancel", admission))+ cleared = sum(1 for idx, admission in enumerate(owned, 1)+ if self._queue_gateway_call("cancel", idx, admission) == "cancelled")before, _ = self._mutate_pending_input(lambda items: [])cleared += len(before)key = "cli.queue.cleared_one" if cleared == 1 else "cli.queue.cleared_other"@@ -427,8 +435,13 @@ class CLILoopsMixin: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):+ verdict = self._queue_gateway_call("cancel", idx, admission)+ if verdict == "cancelled":_cprint(f" {t('cli.queue.removed', index=idx, preview=_preview(str(text)))}")+ elif verdict == "stopped": # claimed between the list and the cancel: the owner interrupted it+ _cprint(f" {t('cli.queue.started_stopped', index=idx)}")+ elif verdict == "started":+ _cprint(f" {t('cli.queue.already_started', index=idx)}")returnlocal = idx - ownedremoved: list = []@@ -454,7 +467,7 @@ class CLILoopsMixin: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):+ if self._queue_gateway_call("replace", idx, items[idx - 1][0], new_text):_cprint(f" {t('cli.queue.updated', index=idx, preview=_preview(new_text))}")returnlocal = idx - owneddiff --git a/hermes_cli/gateway_queue.py b/hermes_cli/gateway_queue.pyindex 759300a92d2..b6cf3657fe3 100644--- a/hermes_cli/gateway_queue.py+++ b/hermes_cli/gateway_queue.py@@ -83,11 +83,24 @@ def published_queue(cli, store) -> list[str]:return [str(row.get("text") or "") for row in rows if row.get("status") == "queued"] + fresh-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"+STARTED_REFUSALS = frozenset({"stale_generation", "admission_started"})+++def cancel(cli, store, admission: str) -> str:+ """Retire one queued admission: ``"cancelled"`` when it never ran, ``"stopped"`` when the drain had+ claimed it and the owner interrupted that run instead (``session_controls.cancel``), ``"started"``+ when it already ran. A turn that ran is still owed a paint, so only a cancelled one leaves+ ``queued_inputs``."""+ receipt = store.call("prompt.cancel", session_id=cli.session_id, admission_id=admission) or {}+ if receipt.get("status") == "terminal" and receipt.get("outcome") == "cancelled":+ state = _state(cli, store)+ state.queued_inputs.pop(admission, None)+ state.missed.discard(admission)+ return "cancelled"+ _state(cli, store).missed.add(admission) # the idle tick paints whatever ran+ if receipt.get("status") == "started" or receipt.get("outcome") == "interrupted":+ return "stopped"+ return "started" # it already ran to its end: nothing was stoppeddef replace(cli, store, admission: str, text: str) -> str | None:diff --git a/locales/af.yaml b/locales/af.yamlindex 36ae6843321..99d022b5047 100644--- a/locales/af.yaml+++ b/locales/af.yaml@@ -2372,6 +2372,11 @@ cli: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."+ remove_refused: "Kon nie tou-item {index} verwyder nie: {error}"+ edit_refused: "Kon nie tou-item {index} wysig nie: {error}"+ already_started: "Tou-item {index} het reeds begin; dit loop soos dit gestuur is."+ started_stopped: "Tou-item {index} het reeds begin; die gateway het dit gestop."+ change_unknown: "Die gateway het nie oor tou-item {index} geantwoord nie ({error}); kyk na /queue list voordat jy weer probeer."reload:env_reloaded: ".env herlaai ({count} veranderlike(s) opgedateer)"steer:diff --git a/locales/ar.yaml b/locales/ar.yamlindex 66507f9c0b4..1de6fc784bc 100644--- a/locales/ar.yaml+++ b/locales/ar.yaml@@ -2372,6 +2372,11 @@ cli:usage_add: "الاستخدام: /queue add <prompt>"gateway_refused: "لم تضعه البوابة في الطابور: {error}. لم يُضف شيء؛ أرسله مرة أخرى عند انتهاء الدور."move_gateway_fifo: "تشغّل البوابة المطالبات في الطابور بترتيب إرسالها؛ عدّل واحدة أو احذفها بدلاً من ذلك."+ remove_refused: "تعذّرت إزالة عنصر الطابور {index}: {error}"+ edit_refused: "تعذّر تعديل عنصر الطابور {index}: {error}"+ already_started: "بدأ عنصر الطابور {index} بالفعل؛ سيُنفَّذ كما أُرسل."+ started_stopped: "كان عنصر الطابور {index} قد بدأ بالفعل؛ أوقفته البوابة."+ change_unknown: "لم تُجب البوابة بشأن عنصر الطابور {index} ({error})؛ راجع /queue list قبل المحاولة مجددًا."reload:env_reloaded: "أُعيد تحميل .env (تم تحديث {count} متغيّر)"steer:diff --git a/locales/de.yaml b/locales/de.yamlindex 3556a341282..831e57e24da 100644--- a/locales/de.yaml+++ b/locales/de.yaml@@ -2372,6 +2372,11 @@ cli: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."+ remove_refused: "Warteschlangeneintrag {index} konnte nicht entfernt werden: {error}"+ edit_refused: "Warteschlangeneintrag {index} konnte nicht bearbeitet werden: {error}"+ already_started: "Warteschlangeneintrag {index} hat bereits begonnen; er läuft wie gesendet."+ started_stopped: "Warteschlangeneintrag {index} hatte bereits begonnen; das Gateway hat ihn gestoppt."+ change_unknown: "Das Gateway hat zu Warteschlangeneintrag {index} nicht geantwortet ({error}); prüfe /queue list, bevor du es erneut versuchst."reload:env_reloaded: ".env neu geladen ({count} Variable(n) aktualisiert)"steer:diff --git a/locales/en.yaml b/locales/en.yamlindex c748a8d7f20..3cac236549c 100644--- a/locales/en.yaml+++ b/locales/en.yaml@@ -2472,6 +2472,11 @@ cli: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."+ remove_refused: "Could not remove queue item {index}: {error}"+ edit_refused: "Could not edit queue item {index}: {error}"+ already_started: "Queue item {index} already started; it runs as it was sent."+ started_stopped: "Queue item {index} had already started; the gateway stopped it."+ change_unknown: "The gateway did not answer about queue item {index} ({error}); check /queue list before trying again."reload:env_reloaded: "Reloaded .env ({count} var(s) updated)"steer:diff --git a/locales/es.yaml b/locales/es.yamlindex f9945b1fb3b..48ebecc233b 100644--- a/locales/es.yaml+++ b/locales/es.yaml@@ -2372,6 +2372,11 @@ cli: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."+ remove_refused: "No se pudo quitar el elemento {index} de la cola: {error}"+ edit_refused: "No se pudo editar el elemento {index} de la cola: {error}"+ already_started: "El elemento {index} de la cola ya empezó; se ejecuta tal como se envió."+ started_stopped: "El elemento {index} de la cola ya había empezado; el gateway lo detuvo."+ change_unknown: "El gateway no respondió sobre el elemento {index} de la cola ({error}); revisa /queue list antes de reintentarlo."reload:env_reloaded: "Se recargó .env ({count} variable(s) actualizada(s))"steer:diff --git a/locales/fr.yaml b/locales/fr.yamlindex f9f2d59d6dd..768899080d3 100644--- a/locales/fr.yaml+++ b/locales/fr.yaml@@ -2645,6 +2645,11 @@ cli: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."+ remove_refused: "Impossible de retirer l'élément {index} de la file : {error}"+ edit_refused: "Impossible de modifier l'élément {index} de la file : {error}"+ already_started: "L'élément {index} de la file a déjà démarré ; il s'exécute tel qu'envoyé."+ started_stopped: "L'élément {index} de la file avait déjà démarré ; le gateway l'a arrêté."+ change_unknown: "Le gateway n'a pas répondu pour l'élément {index} de la file ({error}) ; vérifiez /queue list avant de réessayer."reload:env_reloaded: ".env rechargé ({count} variable(s) mise(s) à jour)"steer:diff --git a/locales/ga.yaml b/locales/ga.yamlindex 6ffe1bff15c..8d6af58bd2f 100644--- a/locales/ga.yaml+++ b/locales/ga.yaml@@ -2372,6 +2372,11 @@ cli: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."+ remove_refused: "Níorbh fhéidir mír {index} a bhaint den scuaine: {error}"+ edit_refused: "Níorbh fhéidir mír {index} den scuaine a chur in eagar: {error}"+ already_started: "Tá mír {index} den scuaine tosaithe cheana; ritheann sí mar a seoladh í."+ started_stopped: "Bhí mír {index} den scuaine tosaithe cheana; stop an geata í."+ change_unknown: "Níor fhreagair an geata faoi mhír {index} den scuaine ({error}); seiceáil /queue list sula ndéanann tú iarracht arís."reload:env_reloaded: "Athlódáladh .env ({count} athróg nuashonraithe)"steer:diff --git a/locales/hu.yaml b/locales/hu.yamlindex 9d14a3d91d9..c9ddef0a3d7 100644--- a/locales/hu.yaml+++ b/locales/hu.yaml@@ -2389,6 +2389,11 @@ cli: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."+ remove_refused: "Nem sikerült eltávolítani a(z) {index}. sorelemet: {error}"+ edit_refused: "Nem sikerült szerkeszteni a(z) {index}. sorelemet: {error}"+ already_started: "A(z) {index}. sorelem már elindult; úgy fut, ahogy elküldték."+ started_stopped: "A(z) {index}. sorelem már elindult; az átjáró leállította."+ change_unknown: "Az átjáró nem válaszolt a(z) {index}. sorelemről ({error}); nézd meg a /queue list kimenetét, mielőtt újra próbálod."reload:env_reloaded: ".env újratöltve ({count} változó frissült)"steer:diff --git a/locales/it.yaml b/locales/it.yamlindex 6e7bf5c01a0..7304a45d477 100644--- a/locales/it.yaml+++ b/locales/it.yaml@@ -2372,6 +2372,11 @@ cli: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."+ remove_refused: "Impossibile rimuovere l'elemento {index} della coda: {error}"+ edit_refused: "Impossibile modificare l'elemento {index} della coda: {error}"+ already_started: "L'elemento {index} della coda è già partito; viene eseguito così come è stato inviato."+ started_stopped: "L'elemento {index} della coda era già partito; il gateway lo ha fermato."+ change_unknown: "Il gateway non ha risposto sull'elemento {index} della coda ({error}); controlla /queue list prima di riprovare."reload:env_reloaded: "Ricaricato .env (variabili aggiornate: {count})"steer:diff --git a/locales/ja.yaml b/locales/ja.yamlindex 104b273c439..fb205b7f0e6 100644--- a/locales/ja.yaml+++ b/locales/ja.yaml@@ -2372,6 +2372,11 @@ cli:usage_add: "使い方: /queue add <prompt>"gateway_refused: "ゲートウェイはキューに追加しませんでした: {error}。何も追加されていません。ターン終了後に再送してください。"move_gateway_fifo: "ゲートウェイはキュー内のプロンプトを送信順に実行します。代わりに編集または削除してください。"+ remove_refused: "キュー項目 {index} を削除できませんでした: {error}"+ edit_refused: "キュー項目 {index} を編集できませんでした: {error}"+ already_started: "キュー項目 {index} はすでに開始しています。送信したとおりに実行されます。"+ started_stopped: "キュー項目 {index} はすでに開始していたため、ゲートウェイが停止しました。"+ change_unknown: "ゲートウェイからキュー項目 {index} の応答がありません ({error})。再試行する前に /queue list を確認してください。"reload:env_reloaded: ".env を再読み込みしました({count} 件の変数を更新)"steer:diff --git a/locales/ko.yaml b/locales/ko.yamlindex cc1f96216a1..d709c2d657a 100644--- a/locales/ko.yaml+++ b/locales/ko.yaml@@ -2372,6 +2372,11 @@ cli:usage_add: "사용법: /queue add <prompt>"gateway_refused: "게이트웨이가 대기열에 넣지 않았습니다: {error}. 아무것도 대기열에 없습니다. 턴이 끝나면 다시 보내세요."move_gateway_fifo: "게이트웨이는 대기 중인 프롬프트를 보낸 순서대로 실행합니다. 대신 편집하거나 삭제하세요."+ remove_refused: "대기열 항목 {index}을(를) 제거할 수 없습니다: {error}"+ edit_refused: "대기열 항목 {index}을(를) 편집할 수 없습니다: {error}"+ already_started: "대기열 항목 {index}은(는) 이미 시작되었습니다. 보낸 그대로 실행됩니다."+ started_stopped: "대기열 항목 {index}은(는) 이미 시작되어 게이트웨이가 중지했습니다."+ change_unknown: "게이트웨이가 대기열 항목 {index}에 응답하지 않았습니다 ({error}). 다시 시도하기 전에 /queue list를 확인하세요."reload:env_reloaded: ".env를 다시 불러왔어요 (변수 {count}개 업데이트됨)"steer:diff --git a/locales/pt.yaml b/locales/pt.yamlindex 00c7b7e57ed..d47ba5fdc2d 100644--- a/locales/pt.yaml+++ b/locales/pt.yaml@@ -2372,6 +2372,11 @@ cli: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."+ remove_refused: "Não foi possível remover o item {index} da fila: {error}"+ edit_refused: "Não foi possível editar o item {index} da fila: {error}"+ already_started: "O item {index} da fila já começou; ele roda como foi enviado."+ started_stopped: "O item {index} da fila já tinha começado; o gateway o parou."+ change_unknown: "O gateway não respondeu sobre o item {index} da fila ({error}); confira /queue list antes de tentar de novo."reload:env_reloaded: ".env recarregado ({count} variável(is) atualizada(s))"steer:diff --git a/locales/ru.yaml b/locales/ru.yamlindex 26db92b5575..ae781f5f11a 100644--- a/locales/ru.yaml+++ b/locales/ru.yaml@@ -2372,6 +2372,11 @@ cli:usage_add: "Использование: /queue add <промпт>"gateway_refused: "Шлюз не поставил это в очередь: {error}. Ничего не поставлено; отправьте снова, когда ход закончится."move_gateway_fifo: "Шлюз выполняет запросы в очереди в порядке отправки; вместо этого измените или удалите один."+ remove_refused: "Не удалось удалить элемент очереди {index}: {error}"+ edit_refused: "Не удалось изменить элемент очереди {index}: {error}"+ already_started: "Элемент очереди {index} уже запущен; он выполняется в отправленном виде."+ started_stopped: "Элемент очереди {index} уже был запущен; шлюз остановил его."+ change_unknown: "Шлюз не ответил по элементу очереди {index} ({error}); проверьте /queue list, прежде чем пробовать снова."reload:env_reloaded: "Файл .env перезагружен (обновлено переменных: {count})"steer:diff --git a/locales/tr.yaml b/locales/tr.yamlindex 9b81348b42c..196e2223495 100644--- a/locales/tr.yaml+++ b/locales/tr.yaml@@ -2372,6 +2372,11 @@ cli: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."+ remove_refused: "Kuyruk öğesi {index} kaldırılamadı: {error}"+ edit_refused: "Kuyruk öğesi {index} düzenlenemedi: {error}"+ already_started: "Kuyruk öğesi {index} zaten başladı; gönderildiği gibi çalışıyor."+ started_stopped: "Kuyruk öğesi {index} zaten başlamıştı; ağ geçidi onu durdurdu."+ change_unknown: "Ağ geçidi kuyruk öğesi {index} için yanıt vermedi ({error}); yeniden denemeden önce /queue list ile kontrol edin."reload:env_reloaded: ".env yeniden yüklendi ({count} değişken güncellendi)"steer:diff --git a/locales/uk.yaml b/locales/uk.yamlindex 3458d8954ac..6471ed9068e 100644--- a/locales/uk.yaml+++ b/locales/uk.yaml@@ -2372,6 +2372,11 @@ cli:usage_add: "Використання: /queue add <prompt>"gateway_refused: "Шлюз не поставив це в чергу: {error}. Нічого не поставлено; надішліть знову, коли хід закінчиться."move_gateway_fifo: "Шлюз виконує запити в черзі в порядку надсилання; натомість відредагуйте або видаліть один."+ remove_refused: "Не вдалося видалити елемент черги {index}: {error}"+ edit_refused: "Не вдалося змінити елемент черги {index}: {error}"+ already_started: "Елемент черги {index} уже запущено; він виконується в надісланому вигляді."+ started_stopped: "Елемент черги {index} уже було запущено; шлюз зупинив його."+ change_unknown: "Шлюз не відповів щодо елемента черги {index} ({error}); перевірте /queue list, перш ніж пробувати знову."reload:env_reloaded: "Перезавантажено .env (оновлено змінних: {count})"steer:diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yamlindex 2f82d163e73..ffa9504abff 100644--- a/locales/zh-hant.yaml+++ b/locales/zh-hant.yaml@@ -2372,6 +2372,11 @@ cli:usage_add: "用法:/queue add <prompt>"gateway_refused: "閘道未將其加入佇列:{error}。未加入任何內容;請在本輪結束後重新傳送。"move_gateway_fifo: "閘道依傳送順序執行佇列中的提示;請改為編輯或刪除其中一則。"+ remove_refused: "無法移除佇列項目 {index}:{error}"+ edit_refused: "無法編輯佇列項目 {index}:{error}"+ already_started: "佇列項目 {index} 已開始執行;將依原樣執行。"+ started_stopped: "佇列項目 {index} 已開始執行;閘道已將其停止。"+ change_unknown: "閘道未回應佇列項目 {index}({error});請先查看 /queue list 再重試。"reload:env_reloaded: "已重新載入 .env(更新了 {count} 個變數)"steer:diff --git a/locales/zh.yaml b/locales/zh.yamlindex 3f64ebe3acd..2aaa281243d 100644--- a/locales/zh.yaml+++ b/locales/zh.yaml@@ -2372,6 +2372,11 @@ cli:usage_add: "用法:/queue add <prompt>"gateway_refused: "网关未将其加入队列:{error}。未加入任何内容;请在本轮结束后重新发送。"move_gateway_fifo: "网关按发送顺序运行队列中的提示;请改为编辑或删除其中一条。"+ remove_refused: "无法移除队列项 {index}:{error}"+ edit_refused: "无法编辑队列项 {index}:{error}"+ already_started: "队列项 {index} 已开始执行;将按原样执行。"+ started_stopped: "队列项 {index} 已开始执行;网关已将其停止。"+ change_unknown: "网关未回应队列项 {index}({error});请先查看 /queue list 再重试。"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.pyindex ea2e47d6138..750aa1e2ea8 100644--- a/tests/hermes_cli/test_cli_queue_gateway_fifo.py+++ b/tests/hermes_cli/test_cli_queue_gateway_fifo.py@@ -411,3 +411,76 @@ def test_a_queued_admission_another_client_cancelled_is_forgotten_not_painted():assert cli._pending_input.empty() and state.queued_inputs == {}finally:conn.close()+++def _queue_command(cli, fn, *args):+ with patch("cli._cprint") as printed:+ fn(*args)+ return " ".join(str(c.args[0]) for c in printed.call_args_list)+++def _owned_cli():+ from tests.hermes_cli.test_gateway_agent import SID+ from tests.hermes_cli.test_gateway_tools_notify import _connected, _idle_cli+ conn, _client = _connected()+ cli = _idle_cli(conn)+ cli._agent_running = True+ conn.state(SID).queued_inputs["adm-q"] = TEXT+ cli._mutate_pending_input = lambda fn: ([], [])+ return conn, cli++[email protected]("verb, args", [("_queue_remove", ("1",)), ("_queue_edit", ("1 new text",))])+def test_a_refused_queue_rm_or_edit_says_what_was_refused(verb, args):+ """Review N5-F4: an rm/edit the owner refuses (unsupported_control, ...) gets its own message, never+ the submit refusal's "Nothing was queued; send it again"."""+ from hermes_cli.gateway_client import GatewayRPCError+ conn, cli = _owned_cli()+ try:+ with patch("hermes_cli.gateway_queue.queued_rows", lambda c, s: [("adm-q", TEXT)]), \+ patch("hermes_cli.gateway_queue.cancel", side_effect=GatewayRPCError("unsupported_control")), \+ patch("hermes_cli.gateway_queue.replace", side_effect=GatewayRPCError("unsupported_control")):+ out = _queue_command(cli, getattr(cli, verb), *args)+ assert "Nothing was queued" not in out and "send it again" not in out, out+ assert "queue item 1" in out.lower() and "unsupported_control" in out, out+ finally:+ conn.close()++[email protected]("verb, args", [("_queue_remove", ("1",)), ("_queue_edit", ("1 new text",))])+def test_an_rm_or_edit_of_a_row_the_drain_already_started_says_it_started(verb, args):+ """The drain claimed the row between the list and the verb (stale_generation): the user is told it+ already started; its turn is still owed a paint."""+ from hermes_cli.gateway_client import GatewayRPCError+ from tests.hermes_cli.test_gateway_agent import SID+ conn, cli = _owned_cli()+ try:+ with patch("hermes_cli.gateway_queue.queued_rows", lambda c, s: [("adm-q", TEXT)]), \+ patch("hermes_cli.gateway_queue.cancel", side_effect=GatewayRPCError("stale_generation")), \+ patch("hermes_cli.gateway_queue.replace", side_effect=GatewayRPCError("stale_generation")):+ out = _queue_command(cli, getattr(cli, verb), *args)+ assert "already started" in out, out+ assert "adm-q" in conn.state(SID).queued_inputs+ finally:+ conn.close()+++def test_an_rm_racing_the_drain_claim_tells_the_user_the_gateway_stopped_it():+ """Owner ``prompt.cancel`` interrupts a row the drain claimed between its read and the cancel commit and+ answers a non-terminal receipt. That rm used to print nothing and forget the admission."""+ from tests.hermes_cli.test_gateway_agent import SID+ conn, cli = _owned_cli()+ try:+ real = cli._session_db.connection.call++ def call(method, **params):+ if method == "prompt.cancel":+ return {"admission_id": "adm-q", "status": "started"}+ return real(method, **params)+ cli._session_db.connection.call = call+ with patch("hermes_cli.gateway_queue.queued_rows", lambda c, s: [("adm-q", TEXT)]):+ out = _queue_command(cli, cli._queue_remove, "1")+ assert "already started" in out and "stopped" in out, out+ assert "adm-q" in conn.state(SID).queued_inputs # its interrupted turn is still painted+ finally:+ conn.close()