The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a workspace move drops the session's live terminal
kshitijk4poor640d6afb4c3b
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex 755b462349d..cb04183f797 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -286,6 +286,17 @@ async def _project_result(authority, ref, live, params, result, editor_servers,from gateway.session_local_mcp import retire_editor_mcpawait asyncio.to_thread(retire_editor_mcp, authority, ref.session_id)if operation not in {*_POLICY, 'reset', 'compress', 'rewind'} or owns_projection:+ if operation == 'workspace':+ # Main's move drops the terminal environment so the next command starts in the new folder: the+ # route-keyed one a turn built and the cwd its commands recorded, which would win over the move.+ # Off-loop (a remote teardown takes seconds) and before the policy publishes and the queue runs,+ # so no turn starts on the old environment.+ from gateway.session_policy_refresh import drop_session_terminal+ try:+ await asyncio.to_thread(drop_session_terminal, authority, ref)+ except Exception: # health: allow BLE001 -- the move is committed: it must still publish+ logger.warning('Session %s moved without dropping its terminal environment', ref.session_id,+ exc_info=True)_project_committed(authority, ref, operation, result)if live is not None:if operation == 'rewind' and owns_projection:@@ -317,12 +328,6 @@ def _project_committed(authority, ref, operation, result):from gateway.session_local import local_session_infoauthority.sessions[ref.session_id].event_stream.publish(ref.session_id, local_session_info(authority, ref), event_type='session.info')- if operation == 'workspace':- # Main's move drops the terminal environment so the next command starts in the new folder.- from hermes_state_local import local_receipt- from tools.terminal_tool_lifecycle import cleanup_vm- for sid in {ref.session_id, local_receipt(authority.db, ref.session_id)['entry']['session_id']}:- cleanup_vm(sid)if operation == 'branch':from gateway.session_local_recovery import restore_local_sessionrestore_local_session(authority, result['branched_session_id'])diff --git a/gateway/session_policy_refresh.py b/gateway/session_policy_refresh.pyindex 62d68e15a23..d42244615cc 100644--- a/gateway/session_policy_refresh.py+++ b/gateway/session_policy_refresh.py@@ -260,7 +260,7 @@ async def refresh_resumed_policy(authority, ref, *, attached=False):ref.session_id, reason)-def _drop_terminal(authority, ref):+def drop_session_terminal(authority, ref):"""The session's own cached terminal environments (keyed by its route, or its ids under per-sessionisolation): the terminal tool reuses one by key whatever backend built it. A profile-shared one stays.Its recorded cwd (keyed by its route or task id) goes too: it wins over the new binding's directory."""@@ -284,7 +284,7 @@ def _drop_terminal(authority, ref):async def _publish(authority, ref, moved=False):from gateway.session_local import local_session_info, publish_local_policyif moved: # before the drain can run a turn on the new binding with the old environment- await asyncio.to_thread(_drop_terminal, authority, ref)+ await asyncio.to_thread(drop_session_terminal, authority, ref)publish_local_policy(authority, ref.session_id)# A drain that ran during the off-loop commit saw the new stored policy beside the old live one and# paused; with both equal again, anything admitted meanwhile runs.diff --git a/tests/gateway/test_session_resume_config_refresh.py b/tests/gateway/test_session_resume_config_refresh.pyindex 561228ec2ca..4ac51dd55a3 100644--- a/tests/gateway/test_session_resume_config_refresh.py+++ b/tests/gateway/test_session_resume_config_refresh.py@@ -510,6 +510,10 @@ class _Backend:pass+def _raise(*_):+ raise RuntimeError('teardown failed')++def _terminal(authority, sid, command):"""One terminal call as the session's turn makes it: its route's session context, its policy's scope."""from gateway.session_context import clear_session_vars, set_session_vars@@ -559,6 +563,53 @@ async def test_the_next_command_after_a_terminal_refresh_runs_on_the_new_backendstore.close_all_db_handles()+async def test_the_next_command_after_a_workspace_move_runs_in_the_new_folder(tmp_path, monkeypatch):+ """Move to project and the CLI's /worktree new (CLI-15): once the session's terminal has run, its cached+ environment and the directory its commands recorded would win over the moved binding, so the move drops+ both and the next command runs in the new folder. The teardown (seconds on a remote backend) runs off the+ owner's loop, so other clients never stall behind it."""+ import threading+ from tools import terminal_tool++ class _Torn(_Backend):+ def cleanup(self):+ torn_on.append(threading.get_ident())+ built, torn_on = [], []+ monkeypatch.setattr(terminal_tool, '_active_environments', {})+ monkeypatch.setattr(terminal_tool, '_session_cwd', {})+ monkeypatch.setattr(terminal_tool, '_pre_exec_block', lambda *a, **k: None)+ monkeypatch.setattr(terminal_tool, '_create_configured_env',+ lambda config, env_type, **k: built.append(_Torn(env_type, k['cwd'])) or built[-1])++ home = _home(monkeypatch)+ moved = tmp_path / 'tree'+ moved.mkdir()+ store, authority = await _owner_authority(home)+ owner = _connect(authority)+ try:+ sid = (await _call(owner, 'session.create', request_id='t', source='cli', cwd=str(tmp_path)))['session_id']+ _terminal(authority, sid, 'pwd')+ await _mutate(owner, store, sid, 'move', 'workspace', {'cwd': str(moved)})+ assert torn_on and threading.get_ident() not in torn_on, 'the teardown ran on the owner loop'+ _terminal(authority, sid, 'pwd')+ assert built[-1].ran[-1] == str(moved), [(backend.cwd, backend.ran) for backend in built]++ # A teardown that fails must not leave the committed move unpublished (the queue would stall).+ from gateway import session_policy_refresh+ from gateway.session_policy import restore_policy+ from hermes_state_local import local_receipt+ monkeypatch.setattr(session_policy_refresh, 'drop_session_terminal', _raise)+ again = tmp_path / 'again'+ again.mkdir()+ await _mutate(owner, store, sid, 'again', 'workspace', {'cwd': str(again)})+ stored = restore_policy(local_receipt(authority.db, sid)['policy']).cwd+ assert (stored, _policy(authority, sid).cwd) == (str(again), str(again))+ finally:+ await owner.close()+ store.close_all_db_handles()++@pytest.mark.asyncioasync def test_a_second_resume_during_terminal_cleanup_waits_for_the_refresh(tmp_path, monkeypatch, caplog):"""A refresh that moves the terminal binding commits, then tears the session's sandbox down (10-15 s on a