Skip to content

The agent that grows with you

fix(tui): keep docker/other backends on host checks; drop per-turn row write

kshitijk4poorf4470b76fe4e
diff --git a/tests/tui_gateway/test_session_cwd_follow.py b/tests/tui_gateway/test_session_cwd_follow.py
index 2525bc20b36..1c1719026ce 100644
--- a/tests/tui_gateway/test_session_cwd_follow.py
+++ b/tests/tui_gateway/test_session_cwd_follow.py
@@ -57,7 +57,7 @@ def _no_db(monkeypatch):
monkeypatch.setattr(server, "_get_db", lambda: None)
monkeypatch.setattr(server, "_persist_session_git_meta", lambda *_a: None)
monkeypatch.setattr(server, "_register_session_cwd", lambda _s: None)
- monkeypatch.setattr(server, "_is_local_terminal_backend", lambda: True)
+ monkeypatch.setattr(server, "_effective_terminal_backend", lambda: "local")
def test_settling_in_a_worktree_reanchors_the_session(session, repo_with_worktree):
@@ -167,8 +167,6 @@ 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
- # "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))
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index 7dd0502f264..ba4f147f496 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -1118,156 +1118,6 @@ 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_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_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, **_kw: _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
-
-
[email protected]("launch_backend", ["ssh", "local"])
-def test_ssh_named_profile_cwd_beats_launch_terminal_cwd(monkeypatch, tmp_path, launch_backend):
- """A named SSH profile's terminal.cwd is on the remote. The desktop must use
- it even when that path does not exist on this host and the process
- TERMINAL_CWD still names the launch profile."""
- remote = "/home/kali"
- launch = "/home/ubuntu/hermes_sync"
- assert not os.path.isdir(remote)
- home = tmp_path / "hunter"
- home.mkdir()
- (home / "config.yaml").write_text(
- "terminal:\n backend: ssh\n cwd: /home/kali\n",
- encoding="utf-8",
- )
- monkeypatch.setenv("TERMINAL_ENV", launch_backend)
- monkeypatch.setenv("TERMINAL_CWD", launch)
- monkeypatch.setattr(server, "_profile_home", lambda name: home if name == "hunter" else None)
-
- assert server._completion_cwd(
- {"profile": "hunter", "cwd": launch, "cwd_explicit": False}
- ) == remote
- assert server._terminal_task_cwd(
- {"cwd": launch, "explicit_cwd": False, "profile_home": str(home)}
- ) == remote
- assert server._terminal_task_cwd(
- {"cwd": "/opt/picked", "explicit_cwd": True, "profile_home": str(home)}
- ) == "/opt/picked"
- # A local launch profile must not "heal" the remote dir to its nearest host ancestor (/home).
- assert server._display_session_cwd({"cwd": remote, "profile_home": str(home)}) == remote
-
-
-def test_named_profile_without_backend_stays_local_under_ssh_launch(monkeypatch, tmp_path):
- """A named profile that declares no terminal.backend is local; the launch profile's ssh backend must not
- turn its terminal.cwd into a remote path."""
- home = tmp_path / "plain"
- home.mkdir()
- (home / "config.yaml").write_text("terminal:\n cwd: /srv/not-on-this-host\n", encoding="utf-8")
- launch = str(tmp_path)
- monkeypatch.setenv("TERMINAL_ENV", "ssh")
- monkeypatch.setattr(server, "_profile_home", lambda name: home if name == "plain" else None)
-
- assert server._completion_cwd({"profile": "plain", "cwd": launch, "cwd_explicit": False}) == launch
- assert server._session_is_local_backend({"profile_home": str(home)}) is True
-
-
-
class _ChunkyStdout:
def __init__(self):
self.parts: list[str] = []
@@ -22555,3 +22405,102 @@ def test_load_cfg_raw_sees_replacement_with_pinned_mtime_and_size(monkeypatch, t
shutil.copy2(other, cfg)
os.utime(cfg, ns=(st.st_atime_ns, st.st_mtime_ns))
assert server._load_cfg_raw()["model"]["default"] == "aaaa-route"
+
+
+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_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, **_kw: _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
+
+
+
[email protected]("launch_backend", ["ssh", "local"])
+def test_ssh_named_profile_cwd_beats_launch_terminal_cwd(monkeypatch, tmp_path, launch_backend):
+ """A named SSH profile's terminal.cwd is on the remote. The desktop must use
+ it even when that path does not exist on this host and the process
+ TERMINAL_CWD still names the launch profile."""
+ remote = "/home/kali"
+ launch = "/home/ubuntu/hermes_sync"
+ assert not os.path.isdir(remote)
+ home = tmp_path / "hunter"
+ home.mkdir()
+ (home / "config.yaml").write_text(
+ "terminal:\n backend: ssh\n cwd: /home/kali\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("TERMINAL_ENV", launch_backend)
+ monkeypatch.setenv("TERMINAL_CWD", launch)
+ monkeypatch.setattr(server, "_profile_home", lambda name: home if name == "hunter" else None)
+
+ assert server._completion_cwd(
+ {"profile": "hunter", "cwd": launch, "cwd_explicit": False}
+ ) == remote
+ assert server._terminal_task_cwd(
+ {"cwd": launch, "explicit_cwd": False, "profile_home": str(home)}
+ ) == remote
+ assert server._terminal_task_cwd(
+ {"cwd": "/opt/picked", "explicit_cwd": True, "profile_home": str(home)}
+ ) == "/opt/picked"
+ # A local launch profile must not "heal" the remote dir to its nearest host ancestor (/home).
+ assert server._display_session_cwd({"cwd": remote, "profile_home": str(home)}) == remote
+
+
+
+def test_named_profile_without_backend_stays_local_under_ssh_launch(monkeypatch, tmp_path):
+ """A named profile that declares no terminal.backend is local; the launch profile's ssh backend must not
+ turn its terminal.cwd into a remote path."""
+ home = tmp_path / "plain"
+ home.mkdir()
+ (home / "config.yaml").write_text("terminal:\n cwd: /srv/not-on-this-host\n", encoding="utf-8")
+ launch = str(tmp_path)
+ monkeypatch.setenv("TERMINAL_ENV", "ssh")
+ monkeypatch.setattr(server, "_profile_home", lambda name: home if name == "plain" else None)
+
+ assert server._completion_cwd({"profile": "plain", "cwd": launch, "cwd_explicit": False}) == launch
+ assert server._session_is_local_backend({"profile_home": str(home)}) is True
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index d6b56df9e17..a14f8fed84f 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -375,17 +375,10 @@ 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 = False
raw_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 = _bound_terminal_backend(profile_home)
+ # An ssh profile's cwd lives on the remote host, where the host isdir check cannot vouch for it.
+ remote_cwd = _cwd_is_remote(profile_home)
with contextlib.suppress(Exception):
- # 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)))
+ explicit_cwd = bool(raw_cwd) and (remote_cwd or 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()
@@ -437,7 +430,7 @@ 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 explicit_cwd and session_backend != "local":
+ elif explicit_cwd and remote_cwd:
# A remote project session persists its row now: the per-profile gateway that runs the first turn mints
# the row itself (AIAgent INSERT-OR-IGNORE) with cwd=None, and the sidebar then drops it to Home. Local
# project drafts stay lazy — their cwd reaches the row on the first prompt (no "Untitled" litter).
@@ -963,11 +956,7 @@ def _(rid, params: dict) -> dict:
_resume_follow_tip(ctx)
if (resp := _resume_guard(ctx)) is not None:
return resp
- ctx.profile_resume_cwd = (
- _str_param(ctx.found, "cwd")
- or _profile_configured_cwd(ctx.profile_home)
- or _declared_remote_profile_cwd(ctx.profile_home)
- )
+ ctx.profile_resume_cwd = _str_param(ctx.found, "cwd") or _profile_workspace_cwd(ctx.profile_home)
# Fast path: reuse a session live IN THIS PROFILE (never another profile's runtime).
with _session_resume_lock:
live = _find_live_session_by_key(ctx.target, ctx.profile_home)
@@ -1012,21 +1001,17 @@ 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
- 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.
- if _bound_terminal_backend(_profile_home(params.get("profile"))) == "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))
+ # The live session's profile decides (as _set_session_cwd below does); an ssh workspace is never host-validated.
+ home = live.get("profile_home") if live is not None else _profile_home(params.get("profile"))
+ target_cwd = translate_cwd_for_wsl_backend(raw)
+ if not _cwd_is_remote(home):
+ target_cwd = os.path.abspath(os.path.expanduser(target_cwd))
+ if not os.path.isdir(target_cwd):
+ return _err(rid, 4017, f"working directory does not exist: {raw}")
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:
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 56b291344c0..7c23575d3df 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -619,33 +619,37 @@ def _profile_configured_cwd(profile_home: Path | None) -> str | None:
env var (issue #40334). Returns an absolute, existing directory, or None for placeholders / missing /
invalid paths.
"""
- return _configured_cwd_from_cfg({"terminal": _profile_terminal_cfg(profile_home)}) if profile_home else None
-
-
-def _profile_terminal_cfg(profile_home: Path | str | None) -> dict:
- """A named profile's ``terminal:`` section from ITS config.yaml ({} for the launch profile / fail-open)."""
if profile_home is None:
- return {}
+ return None
with contextlib.suppress(Exception):
from hermes_cli.config_effective import load_user_config_effective
p = Path(profile_home) / "config.yaml"
- cfg = load_user_config_effective(p) if p.exists() else {}
- terminal_cfg = cfg.get("terminal") if isinstance(cfg, dict) else None
- return terminal_cfg if isinstance(terminal_cfg, dict) else {}
- return {}
+ return _configured_cwd_from_cfg(load_user_config_effective(p)) if p.exists() else None
+ return None
+
+
+def _profile_terminal_policy(profile_home: Path | str | None) -> dict:
+ """A named profile's effective ``TERMINAL_*`` policy — the one its turns run under
+ (``tools/terminal_scope.py::build_profile_terminal_scope``: defaults <- ``.env`` <- ``config.yaml``).
+ {} for the launch profile or an unreadable profile."""
+ if profile_home is None:
+ return {}
+ from tools.terminal_scope import TerminalPolicyUnavailable, build_profile_terminal_scope
+ try:
+ return build_profile_terminal_scope(profile_home)
+ except TerminalPolicyUnavailable:
+ return {}
def _profile_terminal_backend(profile_home: Path | str | None) -> str | None:
- """A named profile's ``terminal.backend`` from ITS config.yaml; None for the launch profile.
+ """A named profile's terminal backend; None for the launch profile.
- 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.
- A missing key is ``local`` (the default) — never the launch profile's backend, which would make a local
- profile's paths look remote whenever the app was launched from an ssh profile.
+ At ``session.create`` the multiplex gateway has NOT yet rebound HERMES_HOME to the target profile, so
+ ``_effective_terminal_backend()`` reads the LAUNCH profile's backend, which must never leak into a named one.
"""
if profile_home is None:
return None
- return str(_profile_terminal_cfg(profile_home).get("backend") or "").strip().lower() or "local"
+ return str(_profile_terminal_policy(profile_home).get("TERMINAL_ENV") or "local").strip().lower() or "local"
def _launch_configured_cwd() -> str | None:
@@ -2596,12 +2600,13 @@ def _hydrate_session_cwd(sid: str, key: str, session_db, profile_home: str | Non
if db is not None:
row = db.get_session(key) if hasattr(db, "get_session") else None
if row and row.get("cwd"):
+ # An ssh session's stored cwd is its workspace: explicit, so the remote terminal uses it instead of
+ # the profile's ~. Other backends keep main's semantics (resolved outside the sessions lock: I/O).
+ remote = _cwd_is_remote(profile_home)
with _sessions_lock:
if sid in _sessions:
_sessions[sid]["cwd"] = row["cwd"]
- # A remote session's stored cwd is its workspace: explicit, so the ssh/docker terminal uses
- # it instead of the profile's ~. Local rows keep settle-following as before.
- if not _session_is_local_backend(_sessions[sid]):
+ if remote:
_sessions[sid]["explicit_cwd"] = True
elif hasattr(db, "update_session_cwd"):
try:
diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.py
index 83b20a2af9f..7ef7ac3966f 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -29,31 +29,23 @@ def _completion_cwd(params: dict | None = None) -> str:
# workspace pick (``cwd_explicit``) wins over the profile config. Path equality
# cannot tell the two apart, so the desktop ships the flag alongside the path.
client_cwd = params.get("cwd")
+ profile_home = _profile_home(params.get("profile"))
if not params.get("cwd_explicit") and client_cwd:
- profile_home = _profile_home(params.get("profile"))
- profile_cwd = _profile_configured_cwd(profile_home)
- if profile_cwd:
+ if profile_cwd := _profile_workspace_cwd(profile_home):
return profile_cwd
- # An ssh profile's terminal.cwd is not on this host, so the isdir check above drops it.
- if remote_cwd := _declared_remote_profile_cwd(profile_home):
- return remote_cwd
# A session bound to another profile resolves its workspace from THAT profile's config before the launch profile's
# env var; the dashboard's in-memory gateway does NOT inherit the PTY child's bridged TERMINAL_CWD, so a configured
# terminal.cwd is read directly.
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 _profile_workspace_cwd(profile_home) 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().
- # A non-local backend's cwd lives inside the target environment, not on the host: pass it raw (as
- # _terminal_task_cwd_with_source does) instead of the local isdir gate that would drop it to getcwd().
- if _bound_terminal_backend(_profile_home(params.get("profile"))) != "local":
- return str(raw)
with contextlib.suppress(Exception):
resolved = os.path.abspath(os.path.expanduser(str(raw)))
if os.path.isdir(resolved):
return resolved
+ # An ssh cwd lives on the remote host, so the host isdir check above cannot vouch for it: pass it raw.
+ if _cwd_is_remote(profile_home):
+ return str(raw)
return os.getcwd()
@@ -67,24 +59,34 @@ def _workdir_terminal_cfg(key: str) -> str:
def _bound_terminal_backend(profile_home) -> str:
- """Terminal backend of the profile a session/RPC is bound to: a named profile's own config, else the process's."""
- return _profile_terminal_backend(Path(profile_home) if profile_home else None) or _effective_terminal_backend()
+ """Terminal backend of the profile a session/RPC is bound to: a named profile's own policy, else the process's."""
+ return _profile_terminal_backend(profile_home) or _effective_terminal_backend()
+
+
+def _cwd_is_remote(profile_home) -> bool:
+ """Whether the bound profile's working directory lives on another host (ssh), so a host ``isdir`` check cannot
+ vouch for it. Docker and the other backends mount or copy HOST paths and keep the host checks."""
+ return _bound_terminal_backend(profile_home) == "ssh"
def _declared_remote_profile_cwd(profile_home) -> str | None:
"""A named ssh profile's own ``terminal.cwd`` (``~``, ``~/…`` or absolute), unchecked against this host.
``_profile_configured_cwd`` requires ``os.path.isdir``; an ssh working directory lives on the remote, so that
- check drops it and the launch profile's ``TERMINAL_CWD`` wins. Only a profile that itself declares
- ``backend: ssh`` qualifies — placeholders (``.``/``auto``/``cwd``) fail the shape check.
+ check drops it and the launch profile's ``TERMINAL_CWD`` wins.
"""
- terminal = _profile_terminal_cfg(profile_home)
- if str(terminal.get("backend") or "").strip().lower() != "ssh":
+ policy = _profile_terminal_policy(profile_home)
+ if str(policy.get("TERMINAL_ENV") or "").strip().lower() != "ssh":
return None
- raw = str(terminal.get("cwd") or "").strip()
+ raw = str(policy.get("TERMINAL_CWD") or "").strip()
return raw if raw == "~" or raw.startswith("~/") or os.path.isabs(raw) else None
+def _profile_workspace_cwd(profile_home) -> str | None:
+ """A named profile's configured workspace: a host dir, or an ssh profile's remote dir."""
+ return _profile_configured_cwd(profile_home) or _declared_remote_profile_cwd(profile_home)
+
+
def _terminal_task_cwd(session: dict | None) -> str:
"""The cwd terminal_tool should use for this TUI session (NOT host-validated: a non-local backend's cwd lives
inside the target environment)."""
@@ -95,13 +97,14 @@ def _terminal_task_cwd_with_source(session: dict | None) -> tuple[str, str]:
"""``(cwd, source)``: ``"session"`` for THIS session's workspace (``explicit_cwd``/tracked dir), ``"process"`` for
the global ``TERMINAL_CWD``/``terminal.cwd`` fallback — under per-session docker isolation that is a PREVIOUS
session's launch artifact, so terminal_tool refuses it as a bind-mount source."""
- backend = _bound_terminal_backend((session or {}).get("profile_home"))
+ profile_home = (session or {}).get("profile_home")
+ backend = _bound_terminal_backend(profile_home)
if backend != "local":
# THIS session's explicit workspace beats the LAST session's env var.
if session and session.get("explicit_cwd") and session.get("cwd"):
return str(session["cwd"]), "session"
# Process TERMINAL_CWD is the launch profile's; a named ssh profile's own terminal.cwd wins over it.
- if remote_cwd := _declared_remote_profile_cwd((session or {}).get("profile_home")):
+ if remote_cwd := _declared_remote_profile_cwd(profile_home):
return remote_cwd, "session"
raw = os.environ.get("TERMINAL_CWD", "").strip() or _workdir_terminal_cfg("cwd")
if raw and raw not in {".", "auto", "cwd"}:
@@ -157,19 +160,11 @@ def _heal_dead_cwd(cwd: str) -> str:
return probe
-def _is_local_terminal_backend() -> bool:
- backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()
- 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."""
- # The process fallback reads env OR config: a per-profile gateway (hermes -p felix) sets terminal.backend=ssh
- # in config but leaves TERMINAL_ENV unset, so an env-only check would heal a live remote cwd to /home.
+ """Whether THIS session's cwd can be stat'ed / git-probed here. The bound profile's backend, not the launch
+ process's: one multiplexed gateway serves many profiles, and a per-profile gateway (``hermes -p x``) may set
+ ``terminal.backend`` in config without ``TERMINAL_ENV`` — either way an env-only check would heal a live remote
+ cwd to its nearest host ancestor (``/home``) and persist that."""
return _bound_terminal_backend(session.get("profile_home") if session else None) == "local"
@@ -327,10 +322,9 @@ def _ensure_session_db_row(session: dict) -> bool:
return _db_error is None
row_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_cwd,
+ parent_session_id=session.get("parent_session_id") or None, cwd=_persisted_session_cwd(session),
# 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)
@@ -343,12 +337,6 @@ 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:
@@ -601,17 +589,13 @@ def _persist_session_cwd_and_schedule_git_meta(session: dict, cwd: str, *, db=No
def _set_session_cwd(session: dict, cwd: str) -> str:
from hermes_constants import translate_cwd_for_wsl_backend
cwd = 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 cwd
- if not os.path.isdir(resolved):
- raise ValueError(f"working directory does not exist: {cwd}")
+ # An ssh workspace lives on the remote host: stored raw, never host-validated.
+ if _cwd_is_remote(session.get("profile_home")):
+ resolved = cwd
+ else:
+ resolved = os.path.abspath(os.path.expanduser(cwd))
+ if 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.
session.update(cwd=resolved, explicit_cwd=True, cwd_from_settle=False)
_register_session_cwd(session)