Skip to content

The agent that grows with you

fix(cli): move the gateway session into the tree on /worktree new

kshitijk4poord681773682e9
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.py
index f382c193322..f4c154c8b63 100644
--- a/hermes_cli/cli_commands_mixin.py
+++ b/hermes_cli/cli_commands_mixin.py
@@ -1071,16 +1071,16 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):
wt_info = _cli._setup_worktree(repo_root=repo_root, sync_base=sync_base, name=rest or None)
if not wt_info:
return # _setup_worktree already printed the failure
- # Retarget the session's terminal/file tools at the new tree (as `hermes -w` does).
- try:
- os.chdir(wt_info["path"])
- except OSError as e:
- print(f" {_t('worktree.enter_failed', error=e)}")
- os.environ["TERMINAL_CWD"] = wt_info["path"]
# Same keep-if-unpushed cleanup as `hermes -w`. Only one tree is "active" per process;
# an earlier one keeps its own atexit registration (explicit info arg).
- _cli._active_worktree = wt_info
atexit.register(_cli._cleanup_worktree, wt_info)
+ from hermes_cli.gateway_client import GatewayClientError
+ from hermes_cli.gateway_session_store import move_cli_workspace
+ try:
+ move_cli_workspace(self, wt_info["path"]) # the gateway session's tools, then this process
+ except (GatewayClientError, OSError) as e:
+ return print(f" {_t('worktree.enter_failed', error=e)}")
+ _cli._active_worktree = wt_info
_pr(f" {_t('worktree.ready', path=wt_info['path'])}",
f" {_t('worktree.branch', branch=wt_info['branch'])}", f" {_t('worktree.tools_in_worktree')}")
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.py
index 5f716698976..00ca298efbd 100644
--- a/hermes_cli/gateway_session_store.py
+++ b/hermes_cli/gateway_session_store.py
@@ -43,7 +43,7 @@ _GATEWAY_OWNED = frozenset({
"maybe_auto_prune_and_vacuum", "set_meta", "update_token_counts", "close",
})
# Mutations the owner refuses without the execution generation they were read at (hermes_state_runtime).
-_GENERATION_FENCED = frozenset({"delete", "rewind", "reset", "branch", "model", "compress"})
+_GENERATION_FENCED = frozenset({"delete", "rewind", "reset", "branch", "model", "compress", "workspace"})
_COUNTED_REPAIRS = frozenset({"prune_empty_ghost_sessions", "finalize_orphaned_compression_sessions"})
# Launch options main's ``cli.main`` takes that are creation policy on the gateway session.
_LAUNCH_POLICY = ("model", "provider", "toolsets", "reasoning", "api_key", "base_url", "max_turns",
@@ -515,6 +515,18 @@ def _check_resume_launch(launch, snapshot):
raise resume_policy_error(differs)
+def move_cli_workspace(cli, cwd):
+ """``/worktree new``: the session's tools run in the gateway under the cwd frozen in its policy, so
+ move that first (``session.mutate workspace``, Desktop's Move to project; a refusal raises before
+ anything moved). Then this process's cwd and TERMINAL_CWD follow, so a later /new creates its session
+ from the tree; a chdir OSError leaves both where they were (the gateway session has moved by then)."""
+ from hermes_cli.gateway_automation import gateway_connection
+ if gateway_connection(cli) is not None:
+ cli._session_db._mutate(cli.session_id, "workspace", {"cwd": cwd})
+ os.chdir(cwd)
+ os.environ["TERMINAL_CWD"] = cwd
+
+
def session_store():
return GatewaySessionStore()
diff --git a/tests/hermes_cli/test_worktree_command.py b/tests/hermes_cli/test_worktree_command.py
index 6b24dbb98d8..7e778c6cd80 100644
--- a/tests/hermes_cli/test_worktree_command.py
+++ b/tests/hermes_cli/test_worktree_command.py
@@ -123,3 +123,57 @@ def test_new_sanitizes_name(repo):
_run(_Stub(), "/worktree new " + "weird name!@#")
name = os.path.basename(cli_mod._active_worktree["path"])
assert name == "weird-name"
+
+
+def _gateway_stub(rpc=None):
+ """A CLI attached to a (scripted) gateway session: the tools run there, not in this process."""
+ from hermes_cli.gateway_connection import GatewayConnection
+ from hermes_cli.gateway_session_store import GatewaySessionStore
+ from tests.hermes_cli.test_gateway_agent import connect_with
+ from tests.hermes_cli.test_gateway_session_store import FakeClient
+ client = FakeClient(known=("local-s",))
+ if rpc is not None:
+ client.rpc = rpc.__get__(client)
+ conn = GatewayConnection(connect=connect_with(client))
+ conn.start(5)
+ stub = _Stub()
+ stub._session_db, stub._gateway_session_open, stub.session_id = GatewaySessionStore(conn), True, "local-s"
+ return stub, client, conn
+
+
+@requires_git
+def test_new_moves_the_gateway_sessions_workspace_into_the_tree(repo):
+ """CLI-15: the session's tools run in the gateway under its frozen cwd, so /worktree new must move
+ that (``session.mutate workspace``, generation-fenced) — a chdir of this process moved nothing."""
+ stub, client, conn = _gateway_stub()
+ try:
+ out = _run(stub, "/worktree new moved")
+ finally:
+ conn.close()
+ wt = repo / ".worktrees" / "moved"
+ (params,) = [p for method, p in client.calls if method == "session.mutate"]
+ assert (params["operation"], params["payload"], params["session_id"]) == ("workspace", {"cwd": str(wt)}, "local-s")
+ assert params["expected_generation"] == 0
+ assert t("cli.commands.worktree.tools_in_worktree") in out
+
+
+@requires_git
+def test_new_refused_by_the_gateway_never_claims_the_tools_moved(repo):
+ """A refused move (e.g. ``session_busy`` mid-turn) leaves the session where it was: say so, and
+ keep this process (and a later /new's cwd) in the original checkout too."""
+ from hermes_cli.gateway_client import GatewayRPCError
+ from tests.hermes_cli.test_gateway_session_store import snapshot
+
+ async def refuse(self, method, *, _timeout=None, **params):
+ self.calls.append((method, params))
+ if method == "session.mutate":
+ raise GatewayRPCError("session_busy")
+ return snapshot("local-s")
+ stub, _client, conn = _gateway_stub(refuse)
+ try:
+ out = _run(stub, "/worktree new busy")
+ finally:
+ conn.close()
+ assert "session_busy" in out and t("cli.commands.worktree.tools_in_worktree") not in out
+ assert os.path.realpath(os.getcwd()) == os.path.realpath(str(repo))
+ assert "TERMINAL_CWD" not in os.environ and cli_mod._active_worktree is None