Skip to content

The agent that grows with you

fix(terminal): keep delegates in the parent's workspace container; make the key idempotent

Teknium2b8cd0519bca
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 185608e753a..1cd1d6ab088 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -943,11 +943,12 @@ def bind_turn_workspace(policy, task_id):
terminal = json.loads(policy.terminal_json)
if str(terminal.get('TERMINAL_ENV') or '').strip().lower() != 'docker' or not terminal_uses_host_cwd(terminal):
return
- from tools.terminal_tool import register_task_env_overrides, resolve_task_overrides
+ from tools.terminal_tool import register_task_env_overrides, resolve_task_overrides, workspace_key_for
current = resolve_task_overrides(task_id)
if current.get('cwd') == policy.cwd and current.get('cwd_source') == 'session':
return
- register_task_env_overrides(task_id, {**current, 'cwd': policy.cwd, 'cwd_source': 'session'})
+ register_task_env_overrides(task_id, {**current, 'cwd': policy.cwd, 'cwd_source': 'session',
+ 'workspace_key': workspace_key_for(policy.cwd)})
@contextmanager
diff --git a/tests/gateway/test_docker_session_workspace.py b/tests/gateway/test_docker_session_workspace.py
index 5b51f3899ce..e1af9fb7b47 100644
--- a/tests/gateway/test_docker_session_workspace.py
+++ b/tests/gateway/test_docker_session_workspace.py
@@ -105,3 +105,45 @@ def test_backends_that_do_not_mount_the_host_cwd_register_nothing(home, tmp_path
with policy_scope(policy):
bind_turn_workspace(policy, 'local-x')
assert terminal_tool.resolve_task_overrides('local-x') == {}
+
+
+def test_delegated_child_shares_its_parents_persistent_workspace_container(home, tmp_path):
+ # Review probe (@kshitijk4poor W1, @dokterdok 1): parent `default:ws:<h>`, child `default`.
+ from tools.terminal_tool import register_container_alias
+ ws1, ws2 = tmp_path / 'ws1', tmp_path / 'ws2'
+ ws1.mkdir(), ws2.mkdir()
+ keys = {}
+ for sid, ws in (('local-a', ws1), ('local-b', ws2)):
+ with _turn(_policy(home, ws, persistent=True), sid):
+ register_container_alias(f'{sid}-child', sid) # delegate_tool_child_run.seed_workspace
+ keys[sid] = (_plan(sid)[0], _plan(f'{sid}-child')[0])
+ assert keys['local-a'][1] == keys['local-a'][0]
+ assert keys['local-b'][1] == keys['local-b'][0]
+ assert keys['local-a'][0] != keys['local-b'][0] # children of two workspaces never share one
+
+
+def test_workspace_container_key_is_idempotent_and_lazy_setup_creates_the_sessions_own(home, tmp_path, monkeypatch):
+ # Review probe (@kshitijk4poor W2, @dokterdok 2): get_active_env(effective) -> the profile container.
+ from tools import terminal_tool, terminal_tool_lifecycle
+ from tools.terminal_tool import _resolve_container_task_id
+ ws1 = tmp_path / 'ws1'
+ ws1.mkdir()
+ other = object()
+ created = []
+ monkeypatch.setattr(terminal_tool_lifecycle, '_create_configured_env',
+ lambda *a, **kw: created.append(kw['task_id']) or object())
+ monkeypatch.setattr(terminal_tool, '_start_cleanup_thread', lambda: None)
+ saved = dict(terminal_tool._active_environments)
+ terminal_tool._active_environments['default'] = other # a messaging/cron turn's profile container
+ try:
+ with _turn(_policy(home, ws1, persistent=True), 'local-a'):
+ eff = _resolve_container_task_id('local-a')
+ assert ':ws:' in eff and _resolve_container_task_id(eff) == eff
+ assert terminal_tool_lifecycle.get_active_env(eff) is not other
+ env = terminal_tool_lifecycle.ensure_task_env('local-a')
+ assert created == [eff] and env is not other
+ assert terminal_tool_lifecycle.get_active_env('local-a') is env
+ finally:
+ for key in [k for k in terminal_tool._active_environments if k not in saved]:
+ terminal_tool._active_environments.pop(key, None)
+ terminal_tool._active_environments.update(saved)
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index bdfd2679110..38c32c5fcf3 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -526,6 +526,15 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str:
return _workspace_container_key(base, task_id)
+def workspace_key_for(cwd: str) -> str:
+ """The ``:ws:`` digest of a host workspace: computed ONCE when the session binds it
+ (``gateway.session_policy.bind_turn_workspace``), so container keying never depends on live
+ filesystem state at lookup time."""
+ import hashlib
+ resolved = os.path.realpath(os.path.expanduser(cwd))
+ return hashlib.sha256(resolved.encode("utf-8")).hexdigest()[:16]
+
+
def _workspace_container_key(base: str, task_id: Optional[str]) -> str:
"""Persistent Docker key for a session that registered a workspace: one container per
(profile, workspace), not per profile (#140665).
@@ -534,18 +543,28 @@ def _workspace_container_key(base: str, task_id: Optional[str]) -> str:
override (``gateway.session_policy.bind_turn_workspace``). Keyed by profile alone, every
concurrent session shared the container bound to whichever workspace created it first; sessions
in the same folder still share one. Sessions with no registered workspace keep the profile key.
+
+ Idempotent: an already-resolved ``<base>:ws:<digest>`` key maps to itself (``ensure_task_env``
+ hands the resolved key to ``get_active_env``, which resolves again). A ``delegate_task`` child has
+ only a container alias to its parent (``register_container_alias``), so the alias chain is
+ followed: the child runs in its parent's workspace container, never the profile's.
Reads the raw table (not :func:`resolve_task_overrides`, which calls back into key resolution).
"""
- overrides = _task_env_overrides.get(_qualify_task_key(task_id)) if task_id else None
- cwd = overrides.get("cwd") if overrides and overrides.get("cwd_source") == "session" else None
- if not isinstance(cwd, str) or not cwd.strip():
+ if not task_id:
return base
- import hashlib
- try:
- resolved = os.path.realpath(os.path.expanduser(cwd))
- except OSError:
- resolved = cwd
- return f"{base}:ws:{hashlib.sha256(resolved.encode('utf-8')).hexdigest()[:16]}"
+ if task_id.startswith(f"{base}:ws:"):
+ return task_id
+ for key in dict.fromkeys((task_id, _resolve_container_alias(task_id))):
+ overrides = _task_env_overrides.get(_qualify_task_key(key))
+ if not overrides or overrides.get("cwd_source") != "session":
+ continue
+ digest = overrides.get("workspace_key")
+ cwd = overrides.get("cwd")
+ if not digest and isinstance(cwd, str) and cwd.strip() and "\0" not in cwd:
+ digest = workspace_key_for(cwd)
+ if digest:
+ return f"{base}:ws:{digest}"
+ return base
def resolve_task_overrides(task_id: Optional[str]) -> dict[str, Any]: