Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

fix(session delete): the tree drops the deleted task, late writes cannot resurrect it, and the runner removes its folder

richard-epsilla1612cc31b07e
diff --git a/gateway/app.py b/gateway/app.py
index cf0cbabc..2eff3cfd 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -1447,6 +1447,15 @@ async def _index_manifest(base: str, manifest: dict) -> None:
list that still says "running" for a session that finished, or that lists one deleted. So a
missing scope field inherits from the card being replaced; the mirror set never shrinks by
accident."""
+ # A write that lands after the session's delete (a finalize or reconcile racing it) must not
+ # resurrect the card: the tombstone on the vertex is the durable, replica-safe answer.
+ _sid = str(manifest.get("session_id") or base.rsplit("_", 1)[-1])
+ try:
+ _v = await _vertex_get(_sid)
+ except Exception: # noqa: BLE001
+ _v = None
+ if _v and str(_v.get("status") or "") == "deleted":
+ return
missing = [k for k in _SCOPE_FIELDS if not manifest.get(k)]
if missing:
prior = await _prior_manifest(base)
@@ -3529,11 +3538,15 @@ async def delete_trace(sid: str, request: Request) -> dict:
await _deindex_manifest(base, manifest, _session_trace.get(sid) or {}, v or {})
# 2) durable session workspace tarball, and anything the media server holds for it
await _blob_delete(_ws_blob(sid), kb=BLOB_KB)
- # The live working folder is the session's memory on this box (the tarball is its durable
- # copy); §6 says deletion frees it, so it goes too. The runner shares this volume.
- _wsroot = os.environ.get("HARNESS_WORKSPACE") or ""
- if _wsroot and sid and os.path.isdir(os.path.join(_wsroot, sid)):
- shutil.rmtree(os.path.join(_wsroot, sid), ignore_errors=True)
+ # The live working folder is the session's memory on this box (the tarball above is its
+ # durable copy); §6 says deletion frees it. Only the runner can remove it: the folder belongs
+ # to the session's own uid, and this process is not root. Best effort, never the reason a
+ # delete fails — the session is already unreadable by the time this runs.
+ if POOL_ENDPOINT:
+ try:
+ await _sandbox("/workspace", sid, "DELETE")
+ except Exception: # noqa: BLE001
+ pass
await _media_session_purge(sid)
# 3) tombstone the session vertex + drop in-process state
try:
diff --git a/runner/server.py b/runner/server.py
index 28530847..b14a3cf6 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -4145,6 +4145,38 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
"host": socket.gethostname(), "max_seconds": cap}
[email protected]("/workspace")
+async def delete_workspace(identifier: str = "") -> dict:
+ """Remove a session's working folder for good (session delete, Sessions §6).
+
+ This lives in the runner and not the gateway on purpose: the gateway runs as an unprivileged
+ user and each session's folder belongs to that session's own uid (mode 700), so only the
+ process that made the wall can take it down. The folder is the session's memory on this box;
+ the durable tarball is the gateway's to delete. A shared root (sandbox-per-session) is never
+ removed. The gateway stops any live turn before asking; turn records here carry no session
+ identity, so this end cannot second-guess that."""
+ ident = (identifier or "").strip()
+ if not ident:
+ raise HTTPException(status_code=400, detail="identifier required")
+ if _SANDBOX_PER_SESSION:
+ return {"identifier": ident, "removed": False, "reason": "shared workspace root"}
+ ws = _ws(ident)
+ if os.path.realpath(ws) in (os.path.realpath(WORKSPACE_ROOT), "/"):
+ raise HTTPException(status_code=400, detail="refusing to remove the workspace root")
+ if not os.path.isdir(ws):
+ return {"identifier": ident, "removed": False, "reason": "no folder"}
+ uid = _session_uid(ws)
+ shutil.rmtree(ws, ignore_errors=True)
+ if uid is not None:
+ # the session's passwd/group entries were only ever for this folder
+ try:
+ subprocess.run(["userdel", f"hs{uid}"], capture_output=True)
+ subprocess.run(["groupdel", f"hs{uid}"], capture_output=True)
+ except OSError:
+ pass
+ return {"identifier": ident, "removed": not os.path.isdir(ws)}
+
+
@app.post("/turn/{turn_id}/cancel")
def cancel_turn(turn_id: str) -> dict:
"""Kill a running turn's CLI process on demand (user-initiated stop). The reader loop
diff --git a/runner/tests/test_workspace_delete.py b/runner/tests/test_workspace_delete.py
new file mode 100644
index 00000000..13f2c748
--- /dev/null
+++ b/runner/tests/test_workspace_delete.py
@@ -0,0 +1,33 @@
+"""A session's working folder is removed on session delete, by the runner (Sessions §6).
+
+Sessions own their folders (per-session uid, mode 700), so the gateway asks the runner, the one
+process with the authority. The root is never removed, and a missing folder is not an error.
+"""
+import asyncio
+import os
+import pathlib
+import sys
+import tempfile
+
+_ROOT = tempfile.mkdtemp(prefix="hr-runner-ws-")
+os.environ["HARNESS_WORKSPACE"] = _ROOT
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+import server as S # noqa: E402
+from fastapi import HTTPException # noqa: E402
+
+
+def test_the_folder_goes_and_the_root_and_a_missing_folder_are_safe():
+ sid = "hsess0123456789abcdef0123456789abcdef"
+ ws = S._ws(sid)
+ os.makedirs(os.path.join(ws, "sub"), exist_ok=True)
+ open(os.path.join(ws, "sub", "f.txt"), "w").write("x")
+ out = asyncio.run(S.delete_workspace(sid))
+ assert out["removed"] is True and not os.path.isdir(ws)
+ assert os.path.isdir(_ROOT), "the workspace root must survive"
+ again = asyncio.run(S.delete_workspace(sid))
+ assert again["removed"] is False and again["reason"] == "no folder"
+ try:
+ asyncio.run(S.delete_workspace(""))
+ assert False, "an empty identifier must be refused"
+ except HTTPException as e:
+ assert e.status_code == 400
diff --git a/ui/src/app/(app)/harnesses/page.tsx b/ui/src/app/(app)/harnesses/page.tsx
index 62a13b37..c3fe0e61 100644
--- a/ui/src/app/(app)/harnesses/page.tsx
+++ b/ui/src/app/(app)/harnesses/page.tsx
@@ -372,6 +372,12 @@ export default function HarnessesPage() {
track('task_deleted', { harness: confirmDel.hid });
const wasOpen = confirmDel.sid === sid;
setConfirmDel(null);
+ // The refresh below keeps rows the first page no longer returns, on purpose:
+ // they may be deeper pages. A deleted task is not, so it leaves here.
+ setPerHarness((p) => p[confirmDel.hid]
+ ? { ...p, [confirmDel.hid]: { ...p[confirmDel.hid], list: p[confirmDel.hid].list.filter((c) => c.session_id !== confirmDel.sid) } }
+ : p);
+ setCards((cs) => cs.filter((c) => c.session_id !== confirmDel.sid));
await loadTasks(confirmDel.hid);
refresh();
if (wasOpen) go({ h: confirmDel.hid });