The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(fs): serve /workspace files from the session's docker workspace sandbox
xxxigmb247d791662e
diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.tsx b/apps/desktop/src/components/assistant-ui/markdown-text.tsxindex 956e5d58445..fd29b74711f 100644--- a/apps/desktop/src/components/assistant-ui/markdown-text.tsx+++ b/apps/desktop/src/components/assistant-ui/markdown-text.tsx@@ -7,6 +7,7 @@ import {type SyntaxHighlighterProps,tailBoundedRemend} from '@assistant-ui/react-streamdown'+import { useStore } from '@nanostores/react'import type { code as streamdownCode } from '@streamdown/code'import {Children,@@ -20,6 +21,7 @@ import {} from 'react'import { defaultRemarkPlugins } from 'streamdown'+import { useSessionView } from '@/app/chat/session-view'import { ExpandableBlock } from '@/components/chat/expandable-block'import { PreviewAttachment } from '@/components/chat/preview-attachment'import { chunkByLines, SyntaxHighlighter } from '@/components/chat/shiki-highlighter'@@ -124,12 +126,18 @@ function preprocessWithTailRepair(text: string): string {}function useOpenMediaFile(path: string) {+ const view = useSessionView()+ const storedId = useStore(view.$storedId)+ const runtimeId = useStore(view.$runtimeId)+ const sessionId = storedId || runtimeId || ''const [openFailed, setOpenFailed] = useState(false)const open = () => {if (window.hermesDesktop && isRemoteGateway()) {setOpenFailed(false)- void downloadGatewayMediaFile(path).catch(() => setOpenFailed(true))+ void downloadGatewayMediaFile(path, sessionId ? { sessionId } : undefined).catch(() =>+ setOpenFailed(true)+ )} else {openExternalLink(mediaExternalUrl(path))}diff --git a/apps/desktop/src/components/chat/preview-attachment.tsx b/apps/desktop/src/components/chat/preview-attachment.tsxindex 7164d98c614..42a6cb01057 100644--- a/apps/desktop/src/components/chat/preview-attachment.tsx+++ b/apps/desktop/src/components/chat/preview-attachment.tsx@@ -50,7 +50,11 @@ export function PreviewAttachment({ target }: { target: string }) {const { t } = useI18n()// This link lives in one session's transcript; resolve it against THAT// session's cwd, not the primary chat's.- const cwd = useStore(useSessionView().$cwd)+ const view = useSessionView()+ const cwd = useStore(view.$cwd)+ const storedId = useStore(view.$storedId)+ const runtimeId = useStore(view.$runtimeId)+ const sessionId = storedId || runtimeId || ''const openSources = useStore($previewTabSources)const [opening, setOpening] = useState(false)const [downloading, setDownloading] = useState(false)@@ -202,7 +206,7 @@ export function PreviewAttachment({ target }: { target: string }) {// Works in both modes: the Electron main process fetches the bytes// through the session's backend connection (local gateway or remote)// and prompts for a save location.- const result = await downloadGatewayMediaFile(target)+ const result = await downloadGatewayMediaFile(target, sessionId ? { sessionId } : undefined)if (mountedRef.current && result.saved) {setDownloaded(true)diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex d609c49b1b0..a2e679c96cb 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -964,37 +964,6 @@ def _parse_docker_volume_mounts() -> list[tuple[Path, Path]]:return mounts-def _docker_sandbox_dir_candidates(session_key: str = "") -> list[str]:- """Candidate host sandbox dir names for the delivering session, best first. Mirrors- ``_resolve_container_task_id`` (tools/terminal_tool.py): containers are PROFILE-scoped- (``default``, else ``profile:<name>``); legacy ``session:<key>`` sandboxes stay as a fallback.- The key is passed explicitly because delivery runs after the turn's contextvars were cleared.-- Takes the key explicitly because the delivery pipeline runs after ``_handle_message_with_agent`` cleared- the turn's session contextvars (#93950) — an ambient lookup here would silently collapse onto- ``default`` and miss the session's real sandbox.- """- try:- from tools.environments.path_utils import sanitize_task_id_for_path- except Exception:- return ["default"]- try:- from hermes_cli.profiles import get_active_profile_name- profile = get_active_profile_name() or "default"- except Exception:- profile = "default"- candidates: list[str] = []- # Explicit trusted-profiles opt-in: one shared container identity.- if shared := _tenv("TERMINAL_DOCKER_SHARED_CONTAINER_KEY", "").strip():- candidates.append(sanitize_task_id_for_path(f"shared:{shared}"))- if profile != "default":- candidates.append(sanitize_task_id_for_path(f"profile:{profile}"))- candidates.append("default")- if session_key: # bug-window legacy layout: per-session sandboxes- candidates.append(sanitize_task_id_for_path(f"session:{session_key}"))- return candidates--_TRUTHY = {"1", "true", "yes", "on"}@@ -1007,35 +976,6 @@ def _docker_persistent_active() -> bool:return _docker_env_active() and _tenv("TERMINAL_CONTAINER_PERSISTENT", "true").strip().lower() in _TRUTHY-def _docker_persistent_sandbox_roots(session_key: str, leaf: str) -> list[Path]:- """Existing ``<sandbox>/docker/<candidate>/<leaf>`` host dirs in candidate order;- the translator tries each until the file resolves. Empty unless Docker + persistent."""- if not _docker_persistent_active():- return []- try:- from tools.environments.base import get_sandbox_dir- base = get_sandbox_dir() / "docker"- return [cand for name in _docker_sandbox_dir_candidates(session_key)- if (cand := (base / name / leaf).resolve(strict=False)).is_dir()]- except Exception:- return []---def _default_docker_workspace_host_roots(session_key: str = "") -> list[Path]:- """Existing host candidates for ``/workspace``: the explicit cwd mount- (``TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE``) if set, else the persistent sandbox layouts."""- if not _docker_persistent_active():- return []- if _tenv("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false").strip().lower() in _TRUTHY:- cwd = _tenv("TERMINAL_CWD") or os.getcwd()- try:- host = Path(os.path.expanduser(cwd)).resolve(strict=False)- except (OSError, RuntimeError, ValueError):- return []- return [host] if host.is_dir() else []- return _docker_persistent_sandbox_roots(session_key, "workspace")--def _cache_dir_container_mounts() -> list[tuple[Path, Path]]:"""(host, container) pairs for the auto-mounted Hermes cache dirs (``/root/.hermes/...`` inMEDIA tags); longer prefixes than the ``/root`` home mount, so longest-prefix match wins."""@@ -1063,9 +1003,15 @@ def _warn_unresolved_docker_media(candidate: Path, session_key: str, reason: strf", session_key={session_key}" if session_key else "")-def _translate_docker_container_media_path(candidate: Path, session_key: str = "", *, quiet: bool = False) -> Optional[Path]:+def _translate_docker_container_media_path(+ candidate: Path, session_key: str = "", workspace_key: str = "", *, quiet: bool = False,+) -> Optional[Path]:"""Container-absolute path -> host path via longest-prefix match over ``docker_volumes``, the- auto-mounted cache dirs (``/root/.hermes/...``), persistent ``/workspace`` and ``/root``."""+ auto-mounted cache dirs (``/root/.hermes/...``), persistent ``/workspace`` and ``/root``.++ ``workspace_key`` is the 16-hex digest of one session's host cwd. It selects that+ session's ``<base>:ws:<digest>`` sandbox and is empty for MEDIA delivery.+ """if not candidate.as_posix().startswith("/"): # POSIX even on Windows gateways (not is_absolute)return None# In-process gateways (Desktop, `hermes serve`) may not have bridged terminal.* config into@@ -1073,17 +1019,24 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = "with contextlib.suppress(Exception):from tools.terminal_tool import _ensure_terminal_env_bridged_ensure_terminal_env_bridged()+ from gateway.platforms.docker_media_paths import (+ _default_docker_workspace_host_roots, _docker_persistent_sandbox_roots,+ )mounts = [*_parse_docker_volume_mounts(), *_cache_dir_container_mounts()]mounted = {c.as_posix() for _, c in mounts}- # Synthetic /workspace mounts: profile-scoped layout first, then legacy per-session.+ # Synthetic /workspace mounts: this session's workspace sandbox, then the+ # shared profile layout, then the legacy per-session dir.if "/workspace" not in mounted:- mounts.extend((root, Path("/workspace")) for root in _default_docker_workspace_host_roots(session_key))+ mounts.extend(+ (root, Path("/workspace"))+ for root in _default_docker_workspace_host_roots(session_key, workspace_key))# Synthetic /root mounts catch stray home writes (/root/out.png; cache mounts are longer# prefixes). /root/.hermes/* that missed a cache mount is the container's credential surface —# translating it via the home mount would dodge the host denylist.if "/root" not in mounted and not candidate.as_posix().startswith("/root/.hermes"):mounts.extend(- (root, Path("/root")) for root in _docker_persistent_sandbox_roots(session_key, "home"))+ (root, Path("/root"))+ for root in _docker_persistent_sandbox_roots(session_key, "home", workspace_key))if not mounts:_warn_unresolved_docker_media(candidate, session_key, "no sandbox mounts resolved", quiet)return Nonediff --git a/gateway/platforms/docker_media_paths.py b/gateway/platforms/docker_media_paths.pynew file mode 100644index 00000000000..0cdf8f7be26--- /dev/null+++ b/gateway/platforms/docker_media_paths.py@@ -0,0 +1,112 @@+"""Host directories that stand in for a Docker container's ``/workspace`` and ``/root``.++``base.py`` is over the file-size ratchet, so the candidate list lives here.+The workspace digest is passed in: delivery runs after the turn's context is+gone, and scanning every ``*_ws_*`` directory would serve another session's file.+"""++from __future__ import annotations++import os+import re+from pathlib import Path++_WORKSPACE_KEY_RE = re.compile(r"^[0-9a-f]{16}$")+++def _scope():+ from gateway.platforms.base import _TRUTHY, _docker_persistent_active, _tenv++ return _tenv, _TRUTHY, _docker_persistent_active+++def _docker_sandbox_dir_candidates(session_key: str = "", workspace_key: str = "") -> list[str]:+ """Candidate host sandbox dir names, best first.++ Mirrors ``_resolve_container_task_id``: profile scope (``default``, else+ ``profile:<name>``), then the legacy ``session:<key>`` layout. A session+ that bound a host workspace also has ``<base>:ws:<digest>`` — a different+ directory from the shared profile sandbox. The digest is explicit because+ an ambient lookup after the turn would collapse onto ``default``.+ """+ tenv, _truthy, _persistent = _scope()+ try:+ from tools.environments.path_utils import sanitize_task_id_for_path+ except Exception: # health: allow BLE001 -- path translation fails closed; a miss is a 404, not a 500+ return ["default"]+ try:+ from hermes_cli.profiles import get_active_profile_name+ profile = get_active_profile_name() or "default"+ except Exception: # health: allow BLE001 -- path translation fails closed; a miss is a 404, not a 500+ profile = "default"+ candidates: list[str] = []+ # Explicit trusted-profiles opt-in: one shared container identity. That+ # key is not a per-workspace container, so a :ws: digest does not apply.+ if shared := tenv("TERMINAL_DOCKER_SHARED_CONTAINER_KEY", "").strip():+ candidates.append(sanitize_task_id_for_path(f"shared:{shared}"))+ elif _WORKSPACE_KEY_RE.fullmatch(workspace_key or ""):+ base = "default" if profile == "default" else f"profile:{profile}"+ candidates.append(sanitize_task_id_for_path(f"{base}:ws:{workspace_key}"))+ if profile != "default":+ candidates.append(sanitize_task_id_for_path(f"profile:{profile}"))+ candidates.append("default")+ if session_key: # bug-window legacy layout: per-session sandboxes+ candidates.append(sanitize_task_id_for_path(f"session:{session_key}"))+ return candidates+++def _docker_persistent_sandbox_roots(+ session_key: str, leaf: str, workspace_key: str = "",+) -> list[Path]:+ """Existing ``<sandbox>/docker/<candidate>/<leaf>`` dirs, candidate order.++ Empty unless Docker + persistent. The translator tries each until the file+ resolves.+ """+ _tenv, _truthy, persistent = _scope()+ if not persistent():+ return []+ try:+ from tools.environments.base import get_sandbox_dir+ base = get_sandbox_dir() / "docker"+ return [cand for name in _docker_sandbox_dir_candidates(session_key, workspace_key)+ if (cand := (base / name / leaf).resolve(strict=False)).is_dir()]+ except Exception: # health: allow BLE001 -- path translation fails closed; a miss is a 404, not a 500+ return []+++def _mounted_workspace_cwd() -> list[Path]:+ tenv, _truthy, _persistent = _scope()+ cwd = tenv("TERMINAL_CWD") or os.getcwd()+ try:+ host = Path(os.path.expanduser(cwd)).resolve(strict=False)+ except (OSError, RuntimeError, ValueError):+ return []+ return [host] if host.is_dir() else []+++def _default_docker_workspace_host_roots(+ session_key: str = "", workspace_key: str = "",+) -> list[Path]:+ """Host dirs that stand in for ``/workspace``.++ A cwd mount is tried first. With no workspace digest that mount is the+ only candidate, so MEDIA delivery (which has no session) stays cwd-only.+ A download that names a digest also tries that session's sandbox after+ the mount: the container key can be ``default:ws:<digest>`` while+ ``/workspace`` is still the sandbox directory, because the host cwd was+ not bind-mounted when the container was created.+ """+ tenv, truthy, persistent = _scope()+ if not persistent():+ return []+ roots: list[Path] = []+ mounted = tenv("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false").strip().lower() in truthy+ if mounted:+ roots.extend(_mounted_workspace_cwd())+ if not _WORKSPACE_KEY_RE.fullmatch(workspace_key or ""):+ return roots+ for root in _docker_persistent_sandbox_roots(session_key, "workspace", workspace_key):+ if root not in roots:+ roots.append(root)+ return rootsdiff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.pyindex 25f9bf936c1..24ee1c50d08 100644--- a/hermes_cli/web_routers/files.py+++ b/hermes_cli/web_routers/files.py@@ -36,7 +36,7 @@ from hermes_cli.web_upload_limit import CHAT_IMAGE_MAX_BYTESfrom hermes_cli.web_server_surface import route_onfrom hermes_cli.web_server_files import (SANDBOX_NOT_FOUND, _agent_fs_path, _fs_path, _hosted_fs_read_guard, _is_unmapped_container_path,- _managed_file_entry, _managed_response_meta, _resolve_managed_path,+ _managed_file_entry, _managed_response_meta, _resolve_managed_path, _session_workspace_key,)from hermes_cli.web_models import (ChatImageUpload, FileTicketRequest, FsWriteText, ManagedDirectoryCreate, ManagedFileDelete,@@ -1088,7 +1088,11 @@ async def _fs_download_path(path: str, profile: Optional[str], session_id: Optioraise HTTPException(status_code=404, detail="Session not found")session = await get_session_detail(session_id, profile)# Validate ownership even for absolute paths; never trust a client cwd.- return _agent_fs_path(path, cwd=session.get("cwd") or "", profile_home=profile_home)+ cwd = session.get("cwd") or ""+ return _agent_fs_path(+ path, cwd=cwd, profile_home=profile_home,+ workspace_key=_session_workspace_key(session_id, cwd),+ )return _agent_fs_path(path, profile_home=profile_home)diff --git a/hermes_cli/web_server_files.py b/hermes_cli/web_server_files.pyindex 25d14262fc5..5b17e5afea0 100644--- a/hermes_cli/web_server_files.py+++ b/hermes_cli/web_server_files.py@@ -105,7 +105,35 @@ def _fs_path(raw_path: str, *, cwd: str | None = None, decode_fallback: bool = Traise HTTPException(status_code=400, detail="Invalid path")-def _translate_agent_path(candidate: Path) -> Path | None:+_WORKSPACE_KEY_RE = re.compile(r"^[0-9a-f]{16}$")+++def _session_workspace_key(session_id: str, cwd: str | None) -> str:+ """16-hex digest of this session's per-workspace Docker sandbox, or ``""``.++ The live override is the key the container was created under. After that+ binding is gone, the session row's host cwd hashes to the same digest.+ ``/workspace`` and ``/root`` are container paths, not host workspaces.+ """+ from tools.terminal_tool import resolve_task_overrides, workspace_key_for++ key = resolve_task_overrides(session_id).get("workspace_key")+ if isinstance(key, str) and _WORKSPACE_KEY_RE.fullmatch(key):+ return key+ host = (cwd or "").strip()+ if not host or "\0" in host or _is_container_cwd(host):+ return ""+ expanded = os.path.expanduser(host)+ if not os.path.isdir(expanded):+ return ""+ return workspace_key_for(expanded)+++def _is_container_cwd(host: str) -> bool:+ return any(host == root or host.startswith(root + "/") for root in ("/workspace", "/root"))+++def _translate_agent_path(candidate: Path, workspace_key: str = "") -> Path | None:"""One translation attempt under whatever scope is bound; None off the docker backend.The gate keeps a local-backend gateway with leftover ``docker_volumes`` from serving@@ -117,7 +145,7 @@ def _translate_agent_path(candidate: Path) -> Path | None:_ensure_terminal_env_bridged()if not _docker_env_active():return None- return _translate_docker_container_media_path(candidate, quiet=True)+ return _translate_docker_container_media_path(candidate, quiet=True, workspace_key=workspace_key)@contextmanager@@ -155,7 +183,9 @@ def _agent_path_scope(profile_home: Path | None = None) -> Iterator[None]:reset_hermes_home_override(home_token)-def _agent_container_path(raw: str, *, profile_home: Path | None = None) -> Path | None:+def _agent_container_path(+ raw: str, *, profile_home: Path | None = None, workspace_key: str = "",+) -> Path | None:"""Map an agent-visible container path to its host bind mount, or None.Docker agents emit container paths (``/workspace/...``, ``/root/...``) in@@ -181,12 +211,12 @@ def _agent_container_path(raw: str, *, profile_home: Path | None = None) -> Pathcandidate = Path(raw)with _agent_path_scope(profile_home):- translated = _translate_agent_path(candidate)+ translated = _translate_agent_path(candidate, workspace_key)if translated is not None or get_terminal_scope() is not None:return translatedtoken = set_terminal_scope(build_profile_terminal_scope(get_hermes_home()))try:- return _translate_agent_path(candidate)+ return _translate_agent_path(candidate, workspace_key)finally:reset_terminal_scope(token)except Exception: # fail open: translation is additive, the host path still serves@@ -199,6 +229,7 @@ SANDBOX_NOT_FOUND = "File not found on the gateway host: the path may live insiddef _agent_fs_path(raw_path: str, *, cwd: str | None = None, profile_home: Path | None = None,+ workspace_key: str = "",) -> Path:"""``_fs_path`` for agent-facing reads; container paths resolve to their hostmount, so callers' boundary guards see the real host target.@@ -213,9 +244,9 @@ def _agent_fs_path(host = _fs_path(raw_path, cwd=cwd)if os.access(host, os.R_OK):return host- translated = _agent_container_path(raw, profile_home=profile_home)+ translated = _agent_container_path(raw, profile_home=profile_home, workspace_key=workspace_key)return translated if translated is not None else host- translated = _agent_container_path(raw, profile_home=profile_home)+ translated = _agent_container_path(raw, profile_home=profile_home, workspace_key=workspace_key)if translated is not None:return translatedif _is_unmapped_container_path(raw, profile_home=profile_home):diff --git a/tests/gateway/test_multiplex_docker_media_delivery_scope.py b/tests/gateway/test_multiplex_docker_media_delivery_scope.pyindex 78eea2d35f1..1a17726f20d 100644--- a/tests/gateway/test_multiplex_docker_media_delivery_scope.py+++ b/tests/gateway/test_multiplex_docker_media_delivery_scope.py@@ -3,7 +3,7 @@ under THAT profile's home + terminal policy on the adapter delivery side.The routed handler runs inside ``_profile_runtime_scope``, but ``_process_message_background``extracts and filters the reply's media AFTER that scope has exited. Docker path translation-(``_docker_sandbox_dir_candidates`` / ``_parse_docker_volume_mounts``) infers the producing+(``docker_media_paths._docker_sandbox_dir_candidates`` / ``_parse_docker_volume_mounts``) infers the producingcontainer from the ACTIVE profile, so a secondary's ``MEDIA:/output/x.png`` resolved through thedefault profile's mounts (a decoy of the same name) or was dropped as "not found on this host"."""diff --git a/tests/hermes_cli/test_web_server_fs.py b/tests/hermes_cli/test_web_server_fs.pyindex 1ef775bd741..5455e204fa5 100644--- a/tests/hermes_cli/test_web_server_fs.py+++ b/tests/hermes_cli/test_web_server_fs.py@@ -807,7 +807,7 @@ def test_fs_reads_translate_after_binding_profile_terminal_scope(client, tmp_patfrom tools.terminal_scope import get_terminal_scope- def translate(path, session_key="", *, quiet=False):+ def translate(path, session_key="", workspace_key="", *, quiet=False):if path == Path("/workspace/isolated report.txt") and get_terminal_scope() is not None:return targetreturn None@@ -1007,7 +1007,7 @@ def test_agent_fs_path_translates_before_host_normalization(monkeypatch, tmp_patmapped = tmp_path / "x.txt"seen = []- def translate(candidate, session_key="", *, quiet=False):+ def translate(candidate, session_key="", workspace_key="", *, quiet=False):seen.append(candidate.as_posix())return mappeddiff --git a/tests/tools/test_terminal_scope_multiplex.py b/tests/tools/test_terminal_scope_multiplex.pyindex bc2b44c7577..495f251c15a 100644--- a/tests/tools/test_terminal_scope_multiplex.py+++ b/tests/tools/test_terminal_scope_multiplex.py@@ -95,6 +95,7 @@ def test_routed_turn_reads_every_terminal_consumer_from_profile(import tools.terminal_tool as ttfrom agent import runtime_cwdfrom gateway.platforms import base as gbase+ from gateway.platforms.docker_media_paths import _docker_sandbox_dir_candidatesfrom tools import env_probe, file_tools_pathsb_cwd = tmp_path / "b-work"@@ -115,7 +116,7 @@ def test_routed_turn_reads_every_terminal_consumer_from_profile(assert tt._resolve_container_task_id(None) == f"home:{os.path.realpath(home)}"assert gbase._parse_docker_volume_mounts() == []assert not any(- "alpha-shared" in c for c in gbase._docker_sandbox_dir_candidates("agent:bee:x")+ "alpha-shared" in c for c in _docker_sandbox_dir_candidates("agent:bee:x"))assert file_tools_paths._configured_terminal_cwd() == str(b_cwd)assert runtime_cwd.resolve_agent_cwd() == b_cwd