The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): release worker unlocks and close CLI vault panels on withdrawal
emozilla80d92daceba3
diff --git a/agent/vault_backends/unlock.py b/agent/vault_backends/unlock.pyindex ee2bb090a6b..0bd216e20e2 100644--- a/agent/vault_backends/unlock.py+++ b/agent/vault_backends/unlock.py@@ -84,6 +84,11 @@ def set_current_session_id(session_id: Optional[str]) -> None:_current_session_tls.sid = session_id+def get_current_session_id() -> Optional[str]:+ """The session bound on this thread (``tools.thread_context`` carries it to tool workers)."""+ return getattr(_current_session_tls, "sid", None)++def _live(backend: str, *, touch: bool) -> Optional[str]:key = _key(backend)with _lock:@@ -117,7 +122,7 @@ def store_session_token(backend: str, token: str, generation: Optional[int] = Noif generation is not None and generation != _generation.get(key, 0):return False_sessions[key] = (token, time.monotonic())- _owner_session[key] = getattr(_current_session_tls, "sid", None)+ _owner_session[key] = get_current_session_id()return Truediff --git a/gateway/session_vault_prompt.py b/gateway/session_vault_prompt.pyindex 90301ed6917..7b4b7f2c52f 100644--- a/gateway/session_vault_prompt.py+++ b/gateway/session_vault_prompt.py@@ -69,7 +69,7 @@ def vault_prompt_scope(turn, agent):return ask("vault.code", {"site": site, "hint": hint}, CODE_TIMEOUT_S)previous = (unlock.get_unlock_prompt_callback(), unlock.get_save_login_prompt_callback(),- unlock.get_code_prompt_callback(), getattr(unlock._current_session_tls, "sid", None))+ unlock.get_code_prompt_callback(), unlock.get_current_session_id())unlock.set_unlock_prompt_callback(unlock_prompt)unlock.set_save_login_prompt_callback(save_login)unlock.set_code_prompt_callback(code_prompt)diff --git a/hermes_cli/cli_modal_mixin.py b/hermes_cli/cli_modal_mixin.pyindex d3e0ab82cfa..8924726dda1 100644--- a/hermes_cli/cli_modal_mixin.py+++ b/hermes_cli/cli_modal_mixin.py@@ -1036,7 +1036,8 @@ class CLIModalMixin:state = self._clarify_stateself._clarify_teardown()state["response_queue"].put(None)- elif method == "sudo" and self._sudo_state:+ elif method in ("sudo", "vault.unlock_prompt", "vault.save_login", "vault.code") and self._sudo_state:+ # The vault prompts reuse the sudo panel's state and queue; "" ends them as declined.self._sudo_state["response_queue"].put("")elif method == "secret" and getattr(self, "_secret_state", None):self._cancel_secret_capture()diff --git a/tests/gateway/test_local_viewer_vault_prompt.py b/tests/gateway/test_local_viewer_vault_prompt.pyindex b436f52543e..64d75291928 100644--- a/tests/gateway/test_local_viewer_vault_prompt.py+++ b/tests/gateway/test_local_viewer_vault_prompt.py@@ -10,6 +10,7 @@ from types import SimpleNamespaceimport pytestfrom gateway.config import Platform+from tests.waiting import wait_untilclass _Peer:@@ -31,13 +32,6 @@ def _events():return events, peer-def _wait_for(predicate, timeout=5.0):- deadline = time.monotonic() + timeout- while not predicate():- assert time.monotonic() < deadline- time.sleep(0.01)--def _turn(events, platform=Platform.LOCAL, session_id='s1'):authority = SimpleNamespace(sessions={session_id: SimpleNamespace(event_stream=events)})return SimpleNamespace(_approval_owner=(authority, session_id, 1),@@ -46,7 +40,7 @@ def _turn(events, platform=Platform.LOCAL, session_id='s1'):def _answer(peer, method, value):from gateway.session_server_requests import is_response_frame, resolve- _wait_for(lambda: any(f.get('method') == method for f in peer.frames))+ wait_until(lambda: any(f.get('method') == method for f in peer.frames), what=f'{method} request')request = next(f for f in peer.frames if f.get('method') == method)from tui_gateway.contracts.registry import SERVER_REQUESTS, validate_paramsassert validate_params(SERVER_REQUESTS[method], request['params'])[1] is None@@ -157,11 +151,12 @@ def test_interrupt_withdraws_the_code_card():out['code'] = unlock.get_code_prompt_callback()('example.com', '')worker = threading.Thread(target=run)worker.start()- _wait_for(lambda: any(f.get('method') == 'vault.code' for f in peer.frames))+ wait_until(lambda: any(f.get('method') == 'vault.code' for f in peer.frames), what='vault.code request')agent._interrupt_requested = Trueworker.join(5)assert out['code'] == ''- _wait_for(lambda: any(f.get('params', {}).get('type') == 'request.cancel' for f in peer.frames))+ wait_until(lambda: any(f.get('params', {}).get('type') == 'request.cancel' for f in peer.frames),+ what='request.cancel')def test_no_attached_viewer_returns_at_once():@@ -235,3 +230,23 @@ def test_closing_the_session_locks_only_the_managers_it_unlocked():finally:unlock.lock('test-backend-a')unlock.lock('test-backend-b')+++def test_a_manager_unlocked_on_a_tool_worker_is_released_with_its_session():+ """browser_vault often runs on a tool worker (parallel calls): the unlock owner must cross that boundary+ with the callbacks, or closing the chat leaves the manager unlocked until its idle timeout."""+ from agent.vault_backends import unlock+ from gateway.session_vault_prompt import release_unlocks, vault_prompt_scope+ from tools.thread_context import propagate_context_to_thread+ events, _ = _events()+ try:+ with vault_prompt_scope(_turn(events, session_id='s1'), SimpleNamespace()):+ worker = threading.Thread(target=propagate_context_to_thread(+ lambda: unlock.store_session_token('test-backend-w', 'token-w')))+ worker.start()+ worker.join(5)+ assert unlock.is_unlocked('test-backend-w')+ release_unlocks('s1')+ assert not unlock.is_unlocked('test-backend-w')+ finally:+ unlock.lock('test-backend-w')diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.pyindex 84062b0b03a..b26800530e3 100644--- a/tests/hermes_cli/test_gateway_agent.py+++ b/tests/hermes_cli/test_gateway_agent.py@@ -907,6 +907,49 @@ def test_another_viewer_completing_the_clarify_batch_releases_mains_panel(make_aassert replies == [("srq-clr", {"answers": {}, "outcome": "cancelled"})][email protected]("method", ["vault.code", "vault.unlock_prompt", "vault.save_login"])+def test_another_viewer_answering_a_vault_prompt_releases_mains_panel(make_agent, method):+ """The vault prompts open main's panels on the sudo panel's state. When a Desktop or Ink viewer answers+ first, the gateway withdraws the request and the CLI's panel must close, or the pump sits in the modal+ until its own 120-180 s deadline instead of reading the rest of the turn."""+ from unittest.mock import MagicMock+ from agent.vault_backends import unlock+ from tests.hermes_cli.test_cli_clarify_batch import _make_cli_stub+ panel = _make_cli_stub()+ panel._sudo_state = None+ panel._sudo_deadline = 0+ panel._ring_bell = lambda **kw: None+ panel._capture_modal_input_snapshot = MagicMock()+ panel._restore_modal_input_snapshot = MagicMock()+ params = {"vault.code": {"site": "example.com", "hint": ""},+ "vault.unlock_prompt": {"backend": "bitwarden", "display_name": "Bitwarden"},+ "vault.save_login": {"origin": "https://example.com", "site": "example.com"}}[method]+ request = {"jsonrpc": "2.0", "id": "srq-vlt", "method": method, "params": {"session_id": SID, **params}}+ withdrawn = frame("request.cancel", {"id": "srq-vlt", "method": method, "reason": "resolved"}, admission=None)+ agent, _client = make_agent([request, "wait", withdrawn, frame("message.complete", {"text": "ok", "outcome": "completed"})],+ modal_withdraw_callback=panel._withdraw_gateway_modal)+ replies = []+ agent.connection.reply = lambda rid, result: replies.append((rid, result)) or True+ out = {}++ def run():+ unlock.set_code_prompt_callback(panel._vault_code_callback)+ unlock.set_unlock_prompt_callback(panel._vault_unlock_callback)+ unlock.set_save_login_prompt_callback(panel._vault_save_login_callback)+ try:+ out.update(agent.run_conversation("sign in"))+ finally:+ unlock.set_code_prompt_callback(None)+ unlock.set_unlock_prompt_callback(None)+ unlock.set_save_login_prompt_callback(None)+ worker = threading.Thread(target=run, daemon=True)+ worker.start()+ worker.join(10)+ assert not worker.is_alive(), "the CLI stayed blocked in its vault panel"+ assert panel._sudo_state is None+ assert replies == [("srq-vlt", {"value": ""})]++def test_a_withdrawal_for_another_request_leaves_the_panel_open(make_agent):agent, _client = make_agent([])closed = []diff --git a/tools/thread_context.py b/tools/thread_context.pyindex 293a4e91675..94025d26185 100644--- a/tools/thread_context.py+++ b/tools/thread_context.py@@ -30,7 +30,9 @@ def _callback_api():(tt._get_sudo_password_callback, tt.set_sudo_password_callback),(vault_unlock.get_unlock_prompt_callback, vault_unlock.set_unlock_prompt_callback),(vault_unlock.get_save_login_prompt_callback, vault_unlock.set_save_login_prompt_callback),- (vault_unlock.get_code_prompt_callback, vault_unlock.set_code_prompt_callback))+ (vault_unlock.get_code_prompt_callback, vault_unlock.set_code_prompt_callback),+ # The unlock owner: a manager unlocked on a worker must still be released with its session.+ (vault_unlock.get_current_session_id, vault_unlock.set_current_session_id))def propagate_context_to_thread(target: Callable) -> Callable: