The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(session): resolve a project session's cwd from the bound profile's backend
Bergmann8954e369192655
diff --git a/tests/tui_gateway/test_session_cwd_follow.py b/tests/tui_gateway/test_session_cwd_follow.pyindex 109e0c1693a..2525bc20b36 100644--- a/tests/tui_gateway/test_session_cwd_follow.py+++ b/tests/tui_gateway/test_session_cwd_follow.py@@ -167,7 +167,9 @@ def test_a_settle_adopted_cwd_can_keep_following(session, repo_with_worktree):def test_remote_backends_do_not_reanchor(session, repo_with_worktree, monkeypatch):"""A remote cwd names a path on the host, not one this gateway can probe."""repo, worktree = repo_with_worktree- monkeypatch.setattr(server, "_is_local_terminal_backend", lambda: False)+ # "Remote" is now read via _effective_terminal_backend (env OR config), so a per-profile gateway with+ # terminal.backend=ssh in config (TERMINAL_ENV unset) is correctly seen as remote.+ monkeypatch.setattr(server, "_effective_terminal_backend", lambda: "ssh")terminal_tool.record_session_cwd(session["session_key"], str(worktree))assert server._reconcile_session_cwd_from_terminal(session) is Falsediff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex ee947f35acc..350861004c4 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -1118,6 +1118,151 @@ def test_terminal_task_cwd_ssh_sentinel_cwd_uses_remote_home(monkeypatch):assert server._terminal_task_cwd({"cwd": "/host/session/dir"}) == "~"+def test_completion_cwd_ssh_returns_raw_remote_path(monkeypatch):+ """A non-local (ssh) backend's session cwd is used+ verbatim even though it does not exist on the local host — the local isdir+ gate would otherwise drop the remote project path to os.getcwd()."""+ remote = "/home/felix/projects/xsd-parser" # does not exist on this host+ assert not os.path.isdir(remote)+ monkeypatch.setenv("TERMINAL_ENV", "ssh")+ monkeypatch.delenv("TERMINAL_CWD", raising=False)+ monkeypatch.setattr(server, "_load_cfg", lambda: {})++ assert server._completion_cwd({"cwd": remote}) == remote+++def test_completion_cwd_config_aware_backend_returns_raw_remote_path(monkeypatch):+ """Config-aware detection: an in-process gateway sets terminal.backend in+ config but NOT the TERMINAL_ENV env var — the exemption must still fire."""+ remote = "/home/jonas/projects/pnin"+ assert not os.path.isdir(remote)+ monkeypatch.delenv("TERMINAL_ENV", raising=False)+ monkeypatch.delenv("TERMINAL_CWD", raising=False)+ monkeypatch.setattr(server, "_load_cfg", lambda: {"terminal": {"backend": "ssh"}})++ assert server._completion_cwd({"cwd": remote}) == remote+++def test_completion_cwd_local_backend_still_guards_bad_path(monkeypatch, tmp_path):+ """A local backend keeps the host isdir guard: a non-existent cwd falls+ back to os.getcwd()."""+ monkeypatch.setenv("TERMINAL_ENV", "local")+ monkeypatch.delenv("TERMINAL_CWD", raising=False)+ monkeypatch.setattr(server, "_load_cfg", lambda: {})+ monkeypatch.chdir(tmp_path)+ bad = str(tmp_path / "does_not_exist")++ assert server._completion_cwd({"cwd": bad}) == str(tmp_path)+++def test_session_create_sets_explicit_cwd_for_non_local_backend(monkeypatch):+ """session.create marks explicit_cwd=True for a non-local+ backend when a cwd param is passed, so _terminal_task_cwd_with_source returns+ the session cwd instead of falling back to `~`."""+ remote = "/home/felix/projects/space-crush"+ assert not os.path.isdir(remote)+ monkeypatch.setenv("TERMINAL_ENV", "ssh")+ monkeypatch.delenv("TERMINAL_CWD", raising=False)+ monkeypatch.setattr(server, "_load_cfg", lambda: {})+ monkeypatch.setattr(server, "_schedule_agent_build", lambda sid: None)+ monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda: None)++ resp = server._methods["session.create"]("r1", {"cols": 80, "cwd": remote})+ sid = resp["result"]["session_id"]+ session = server._sessions[sid]+ try:+ assert session["explicit_cwd"] is True+ assert session["cwd"] == remote+ finally:+ server._sessions.pop(sid, None)+++def test_session_create_uses_bound_profile_backend_not_launch(monkeypatch, tmp_path):+ """The regression: launch profile is LOCAL, the session is bound to an SSH profile.+ session.create must read the BOUND profile's backend (via _profile_terminal_backend),+ keep the remote cwd, and mark it explicit — not drop it to the launch dir."""+ remote = "/home/felix/projects/xsd-parser"+ assert not os.path.isdir(remote)+ # Launch process looks local; only the bound profile is ssh.+ monkeypatch.setenv("TERMINAL_ENV", "local")+ monkeypatch.delenv("TERMINAL_CWD", raising=False)+ monkeypatch.setattr(server, "_load_cfg", lambda: {"terminal": {"backend": "local"}})+ monkeypatch.setattr(server, "_profile_home", lambda name: tmp_path if name == "felix" else None)+ monkeypatch.setattr(server, "_profile_terminal_backend", lambda home: "ssh" if home == tmp_path else None)+ monkeypatch.setattr(server, "_schedule_agent_build", lambda sid: None)+ monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda: None)++ resp = server._methods["session.create"]("r1", {"cols": 80, "cwd": remote, "profile": "felix"})+ sid = resp["result"]["session_id"]+ session = server._sessions[sid]+ try:+ assert session["cwd"] == remote # not dropped to getcwd()+ assert session["explicit_cwd"] is True+ finally:+ server._sessions.pop(sid, None)+++def test_display_session_cwd_does_not_heal_remote_cwd_for_bound_ssh_profile(monkeypatch, tmp_path):+ """The regression: a session bound to an ssh profile has a remote cwd that does+ NOT exist on the host. The env-only local check would treat the multiplex gateway+ as local and heal the remote path to a host ancestor (/home), persisting garbage.+ _session_is_local_backend must read the BOUND profile (ssh) and skip healing."""+ remote = "/home/felix/projects/xsd-parser"+ assert not os.path.isdir(remote)+ monkeypatch.setenv("TERMINAL_ENV", "local") # launch process looks local+ monkeypatch.setattr(server, "_profile_terminal_backend", lambda home: "ssh" if home == tmp_path else None)+ # If healing were (wrongly) attempted, this would fire and rewrite the cwd.+ healed = {"called": False}+ def _heal(_cwd):+ healed["called"] = True+ return "/home"+ monkeypatch.setattr(server, "_heal_dead_cwd", _heal)++ session = {"cwd": remote, "profile_home": str(tmp_path)}+ assert server._display_session_cwd(session) == remote+ assert healed["called"] is False+ assert session["cwd"] == remote # not persisted over+++def test_workspace_move_accepts_remote_dir_for_bound_ssh_profile(monkeypatch, tmp_path):+ """session.workspace.move must not reject a remote project dir that does not+ exist on the host when the bound profile is ssh (the 'working directory does+ not exist' error the user hit). Local profiles keep the isdir guard."""+ remote = "/home/felix/projects/xsd-parser"+ assert not os.path.isdir(remote)+ monkeypatch.setenv("TERMINAL_ENV", "local") # launch looks local+ monkeypatch.setattr(server, "_profile_home", lambda name: tmp_path if name == "felix" else None)+ monkeypatch.setattr(server, "_profile_terminal_backend", lambda home: "ssh" if home == tmp_path else None)++ class _DB:+ def get_session(self, key):+ return {"session_key": key}+ def update_session_cwd(self, *a, **k):+ return 1+ import contextlib as _ctx+ monkeypatch.setattr(server, "_profile_db", lambda params: _ctx.nullcontext(_DB()))+ monkeypatch.setattr(server.git_probe, "branch", lambda c: None)+ monkeypatch.setattr(server.git_probe, "common_repo_root", lambda c: None)++ resp = server._methods["session.workspace.move"](+ "r1", {"session_key": "sk1", "cwd": remote, "profile": "felix"})+ assert "result" in resp, resp+ assert resp["result"]["cwd"] == remote+++def test_workspace_move_still_guards_bad_dir_for_local_profile(monkeypatch, tmp_path):+ """A local profile keeps the isdir guard: a non-existent cwd is rejected."""+ monkeypatch.setenv("TERMINAL_ENV", "local")+ monkeypatch.setattr(server, "_profile_home", lambda name: None)+ monkeypatch.setattr(server, "_profile_terminal_backend", lambda home: None)+ bad = str(tmp_path / "nope")++ resp = server._methods["session.workspace.move"](+ "r1", {"session_key": "sk1", "cwd": bad})+ assert "error" in resp+ assert resp["error"]["code"] == 4017++class _ChunkyStdout:def __init__(self):self.parts: list[str] = []diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex a591a96b971..14ab594ea88 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -375,8 +375,17 @@ def _create_session(rid, params: dict, *, copy_parent_history: bool = False) -># Only an explicitly chosen existing workspace persists as cwd; the launch-dir fallback is "No workspace".explicit_cwd = Falseraw_cwd = _str_param(params, "cwd") # unguarded, as on BASE: only the path check is best-effort+ # The BOUND profile's backend (multiplex hasn't rebound HERMES_HOME yet, so the process-global+ # _effective_terminal_backend() would read the launch profile - usually local).+ session_backend = _profile_terminal_backend(profile_home) or _effective_terminal_backend()with contextlib.suppress(Exception):- explicit_cwd = bool(raw_cwd) and os.path.isdir(os.path.abspath(os.path.expanduser(raw_cwd)))+ # A non-local backend's cwd lives inside the target environment, so a LOCAL isdir gate would+ # drop the remote project path and _terminal_task_cwd_with_source would fall to `~`. Mark it+ # explicit whenever a cwd is provided; local backends keep the host isdir check.+ if raw_cwd and session_backend != "local":+ explicit_cwd = True+ else:+ explicit_cwd = bool(raw_cwd) and os.path.isdir(os.path.abspath(os.path.expanduser(raw_cwd)))_enable_gateway_prompts()session_model_override, create_reasoning_override, create_service_tier_override = _create_overrides(params)now = time.time()@@ -428,6 +437,13 @@ def _create_session(rid, params: dict, *, copy_parent_history: bool = False) ->_seed_branch_row(_sessions[sid], key, parent_session_id, history, source, profile_home)elif history:_seed_row(_sessions[sid])+ elif _sessions[sid].get("explicit_cwd"):+ # A session opened INTO a project (explicit cwd) is explicit intent, not an abandoned draft, so the+ # "no eager row" rule above does not apply: persist the row now with its project cwd. Otherwise the+ # per-profile gateway process that runs the first turn mints the row itself (AIAgent INSERT-OR-IGNORE)+ # with cwd=None -- the sidebar then drops the session to Home and the terminal falls back to the+ # profile's ~ dir. Gated on explicit_cwd so plain launches still stay row-less (no "Untitled" litter).+ _ensure_session_db_row(_sessions[sid])# Return immediately so Ink can paint; the AIAgent builds right after the flush._schedule_agent_build(sid)_schedule_session_cap_enforcement() # trim detached idle sessions over the cap@@ -994,14 +1010,24 @@ def _(rid, params: dict) -> dict:if not (raw := _str_param(params, "cwd")):return _err(rid, 4016, "cwd required")from hermes_constants import translate_cwd_for_wsl_backend- resolved = os.path.abspath(os.path.expanduser(translate_cwd_for_wsl_backend(raw)))- if not os.path.isdir(resolved):- return _err(rid, 4017, f"working directory does not exist: {raw}")+ translated = translate_cwd_for_wsl_backend(raw)+ resolved = os.path.abspath(os.path.expanduser(translated))+ # A non-local (ssh/docker) profile's workspace lives inside the target environment: the local isdir+ # gate would reject a valid remote project dir. Read the BOUND profile's backend (not the launch+ # process env) and, when non-local, trust the path raw - mirroring _completion_cwd / _set_session_cwd.+ is_local = _profile_terminal_backend(_profile_home(params.get("profile"))) or _effective_terminal_backend()+ is_local = is_local == "local"+ if is_local:+ if not os.path.isdir(resolved):+ return _err(rid, 4017, f"working directory does not exist: {raw}")+ target_cwd = resolved+ else:+ target_cwd = translated# Snapshot under the lock — concurrent RPCs mutate _sessions.with _sessions_lock:live_sid, live = next(((sid, sess) for sid, sess in list(_sessions.items()) if sess.get("session_key") == target), ("", None))- branch, root = git_probe.branch(resolved), git_probe.common_repo_root(resolved)+ branch, root = git_probe.branch(target_cwd), git_probe.common_repo_root(target_cwd)with _profile_db(params, writer=True) as db:if db is None:return _db_unavailable_error(rid, code=5007)@@ -1011,16 +1037,16 @@ def _(rid, params: dict) -> dict:return _err(rid, 4007, "session not found")else:try:- db.update_session_cwd(target, resolved, branch, root, replace_git_meta=True)+ db.update_session_cwd(target, target_cwd, branch, root, replace_git_meta=True)except Exception as e:return _err(rid, 5007, f"move failed: {e}")if live is not None:try:- _set_session_cwd(live, resolved)+ _set_session_cwd(live, target_cwd)except ValueError as e:return _err(rid, 4017, str(e))- _emit("session.info", live_sid, _cwd_info(live, resolved, branch=branch))- return _ok(rid, {"cwd": resolved, "branch": branch, "git_repo_root": root})+ _emit("session.info", live_sid, _cwd_info(live, target_cwd, branch=branch))+ return _ok(rid, {"cwd": target_cwd, "branch": branch, "git_repo_root": root})@method("session.active_list")diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 3aabe999d6c..a2b53b0a58f 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -628,6 +628,27 @@ def _profile_configured_cwd(profile_home: Path | None) -> str | None:return None+def _profile_terminal_backend(profile_home: Path | None) -> str | None:+ """A non-launch profile's ``terminal.backend`` from ITS config.yaml (fail-open → None).++ Same reason as :func:`_profile_configured_cwd`: at ``session.create`` the multiplex gateway has NOT yet+ rebound HERMES_HOME to the target profile, so ``_effective_terminal_backend()`` reads the LAUNCH profile+ (usually ``local``). A session bound to an ``ssh``/``docker`` profile then loses the non-local cwd+ exemption and its remote workspace is dropped to the launch dir. Read the bound profile's own backend.+ """+ if profile_home is None:+ return None+ with contextlib.suppress(Exception):+ from hermes_cli.config_effective import load_user_config_effective+ p = Path(profile_home) / "config.yaml"+ if p.exists():+ cfg = load_user_config_effective(p)+ terminal_cfg = cfg.get("terminal") if isinstance(cfg, dict) else None+ if isinstance(terminal_cfg, dict):+ return str(terminal_cfg.get("backend") or "").strip().lower() or None+ return None++def _launch_configured_cwd() -> str | None:"""Launch profile's ``terminal.cwd`` from config.yaml: the dashboard's in-memory gateway gets no bridged``TERMINAL_CWD`` env (only the Node PTY child does), so a fresh /chat would otherwise start in ``os.getcwd()``."""@@ -2578,7 +2599,11 @@ def _hydrate_session_cwd(sid: str, key: str, session_db, profile_home: str | Nonif row and row.get("cwd"):with _sessions_lock:if sid in _sessions:+ # A persisted row cwd is the session's authoritative workspace (a project session, or a+ # settled dir), not a launch artifact: mark it explicit so the ssh/remote terminal uses it+ # instead of falling back to the profile's ~ (session_workdir._terminal_task_cwd_with_source)._sessions[sid]["cwd"] = row["cwd"]+ _sessions[sid]["explicit_cwd"] = Trueelif hasattr(db, "update_session_cwd"):try:_persist_session_cwd_and_schedule_git_meta(_sessions[sid], _sessions[sid]["cwd"], db=db)diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex 2618bf8d391..fba3818d037 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -39,8 +39,17 @@ def _completion_cwd(params: dict | None = None) -> str:raw = (client_cwd or _sessions.get(params.get("session_id") or "", {}).get("cwd")or _profile_configured_cwd(_profile_home(params.get("profile"))) or _launch_configured_cwd()or os.environ.get("TERMINAL_CWD") or os.getcwd())+ # The BOUND profile's backend, not the launch profile's: under multiplex HERMES_HOME is not yet rebound at+ # session.create, so the process-global _effective_terminal_backend() would misread an ssh/docker profile as+ # local and drop its remote cwd to getcwd().+ backend = _profile_terminal_backend(_profile_home(params.get("profile"))) or _effective_terminal_backend()with contextlib.suppress(Exception):resolved = os.path.abspath(os.path.expanduser(str(raw)))+ # A non-local backend's cwd lives inside the target environment, not on the host: mirror the+ # exemption _terminal_task_cwd_with_source already has (:58/:65) and pass it raw, skipping the+ # local isdir gate that would otherwise drop the remote project path to getcwd().+ if backend != "local":+ return resolvedif os.path.isdir(resolved):return resolvedreturn os.getcwd()@@ -129,6 +138,23 @@ def _is_local_terminal_backend() -> bool:return not backend or backend == "local"+def _session_is_local_backend(session: dict | None) -> bool:+ """Whether THIS session's terminal backend is local. A multiplexed gateway serves many profiles from+ ONE process, so the env-only _is_local_terminal_backend() reports the LAUNCH profile (usually local)+ for a session actually bound to an ssh/docker profile - which then heals its remote cwd to a host+ ancestor (/home) and persists that. Read the BOUND profile's backend first (profile_home), falling+ back to the process env only when the session carries no profile."""+ profile_home = session.get("profile_home") if session else None+ if profile_home:+ backend = _profile_terminal_backend(Path(profile_home))+ if backend:+ return backend == "local"+ # Fallback must read env OR config (like _terminal_task_cwd_with_source's _effective_terminal_backend), not+ # env alone: a per-profile gateway (hermes -p felix) sets terminal.backend=ssh in config but leaves TERMINAL_ENV+ # unset, so the env-only check reported "local" and healed a live remote cwd (/home/felix/... -> /home).+ return _effective_terminal_backend() == "local"++def _effective_terminal_backend() -> str:"""Active terminal backend name (``local``, ``docker``, ``ssh``, ...): ``TERMINAL_ENV`` when set (launchers bridge``terminal.backend`` into env), else the ``terminal.backend`` config key (in-process gateways skip that bridge)."""@@ -141,7 +167,7 @@ def _effective_terminal_backend() -> str:def _display_session_cwd(session: dict | None) -> str:"""Session cwd for display/probe surfaces, healed past deleted worktrees (healed value persisted back; local only)."""cwd = _session_cwd(session)- if not _is_local_terminal_backend():+ if not _session_is_local_backend(session):return cwdhealed = _heal_dead_cwd(cwd)if healed and healed != cwd and session is not None:@@ -158,7 +184,7 @@ def _reconcile_session_cwd_from_terminal(session: dict | None) -> bool:never overridden. Local backends only (a remote cwd cannot be stat'ed or git-probed here)."""# An explicit choice only moves by another explicit action; a cwd adopted HERE is marked `cwd_from_settle` so# successive settles keep following.- if not session or not _is_local_terminal_backend():+ if not session or not _session_is_local_backend(session):return Falseif session.get("explicit_cwd") and not session.get("cwd_from_settle"):return False@@ -283,9 +309,10 @@ def _ensure_session_db_row(session: dict) -> bool:return _db_error is Nonerow_model, model_config = _workdir_row_model_config(session)try:+ persisted_cwd = _persisted_session_cwd(session)db.create_session(key, source=_session_source(session), model=row_model, model_config=model_config or None,- parent_session_id=session.get("parent_session_id") or None, cwd=_persisted_session_cwd(session),+ parent_session_id=session.get("parent_session_id") or None, cwd=persisted_cwd,# The login this session was opened under, in the same ``<provider>:<id>`` form the agent is# built with — the row is the only place the identity reaches the store, and the upsert can't# add it later (user_id is set at insert). None (no password provider, legacy token, stdio)@@ -298,6 +325,12 @@ def _ensure_session_db_row(session: dict) -> bool:# backfill ran stayed NULL forever: profile-keyed matching then drops them from the sidebar# and deep links can't resolve them (#99222).profile_name=profile_name_for_home(profile_home) or _current_profile_name())+ # create_session is INSERT OR IGNORE: if the AIAgent's lazy create already minted this row WITHOUT a+ # cwd (a non-local project session, where the cwd is only known here), the create above is a no-op and+ # the cwd never lands -> the sidebar tree drops the session to Home. Force the chosen cwd onto the row.+ if persisted_cwd:+ with contextlib.suppress(Exception):+ db.update_session_cwd(key, persisted_cwd)# Born hidden (session.create hidden=true, or set_hidden before the row existed): apply the deferred intent.if session.get("pending_hidden"):try:@@ -551,6 +584,14 @@ def _set_session_cwd(session: dict, cwd: str) -> str:from hermes_constants import translate_cwd_for_wsl_backendcwd = translate_cwd_for_wsl_backend(str(cwd))resolved = os.path.abspath(os.path.expanduser(cwd))+ # A non-local backend's workspace lives inside the target environment, not on the host: the local+ # isdir gate would reject a valid remote project dir ("working directory does not exist"). Trust the+ # bound profile's backend and store the path raw, mirroring _completion_cwd's non-local exemption.+ if not _session_is_local_backend(session):+ session.update(cwd=cwd, explicit_cwd=True, cwd_from_settle=False)+ _register_session_cwd(session)+ _persist_session_cwd_and_schedule_git_meta(session, cwd)+ return cwdif not os.path.isdir(resolved):raise ValueError(f"working directory does not exist: {cwd}")# An explicit user choice: persisted as the workspace (not the launch-dir fallback), superseding a settle-adopted cwd.