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.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
files: a filename the header cannot spell no longer costs the download; pin the MCP SDK the bridge imports (#189)
github-actions[bot]d63e2ed863ef
diff --git a/gateway/app.py b/gateway/app.pyindex 2edde026..4c333aab 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -8065,10 +8065,33 @@ async def delete_response(response_id: str, request: Request):# `shared`/`share_token` props on the HarnessSession vertex (token reused across re-enables so a# re-shared link keeps working; disable flips `shared` off which kills the whole surface).+# A response header is latin-1 on the wire: that is what ASGI defines and what Starlette encodes+# to. So a filename with a Chinese character or an emoji cannot go into the quoted `filename` at+# all — it raises UnicodeEncodeError inside the server and the download becomes a 500 with no+# clue in it. RFC 6266 is the way out and this is the ONE place that builds the header: an ASCII+# fallback every client can read, plus `filename*` carrying the real name percent-encoded, which+# every current browser prefers when both are present.+_CD_STRIP = re.compile(r'[\x00-\x1f\x7f"\\]')+++def _content_disposition(kind: str, filename: str) -> str:+ """`attachment`/`inline` with a filename any client can take, whatever its characters."""+ name = re.split(r"[\\/]", str(filename or ""))[-1].strip()+ if name in ("", ".", ".."):+ name = "download"+ # The fallback: every byte a header can hold, with everything else standing in as `_` so the+ # extension survives. A name that is entirely non-ASCII still leaves a usable "__.txt".+ ascii_name = _CD_STRIP.sub("", name.encode("ascii", "replace").decode("ascii").replace("?", "_"))+ if ascii_name.strip(" .") == "":+ ascii_name = "download"+ return (f'{kind}; filename="{ascii_name[:120]}"; '+ f"filename*=UTF-8''{urllib.parse.quote(name, safe='')}")++def _artifact_headers(media: str, fname: str) -> dict:# Browser-renderable types serve INLINE so html/css/js/img/pdf render directly (relative# asset urls in an html page resolve to sibling paths under the same route prefix).- return {"Content-Disposition": f'inline; filename="{fname}"',+ return {"Content-Disposition": _content_disposition("inline", fname),"Cache-Control": "private, max-age=60","X-Content-Type-Options": "nosniff"}@@ -8882,7 +8905,7 @@ async def session_files_archive(sid: str, request: Request, changed: bool = Falsbg = BackgroundTask(os.unlink, zpath)return FileResponse(zpath, media_type="application/zip", background=bg,headers={"Content-Disposition":- f'attachment; filename="{sid[:20]}-{scope}-files.zip"'})+ _content_disposition("attachment", f"{sid[:20]}-{scope}-files.zip")})@app.get("/v1/sessions/{sid}/files/{path:path}")@@ -8988,7 +9011,7 @@ async def container_file_content(container_id: str, file_id: str, request: Requeraise HTTPException(404, "file not found")data, media, fname = gotreturn Response(content=data, media_type=media,- headers={"Content-Disposition": f'attachment; filename="{fname.rsplit("/", 1)[-1]}"'})+ headers={"Content-Disposition": _content_disposition("attachment", fname)})# Office types with no faithful browser renderer → convert to PDF server-side (LibreOffice) so thediff --git a/gateway/requirements.txt b/gateway/requirements.txtindex aec1a449..6665f716 100644--- a/gateway/requirements.txt+++ b/gateway/requirements.txt@@ -1,7 +1,7 @@fastapi==0.115.6uvicorn[standard]==0.34.0httpx==0.28.1-pydantic==2.10.4+pydantic==2.11.9python-multipart==0.0.20azure-identity==1.19.0azure-cosmos==4.9.0diff --git a/gateway/tests/test_files_archive.py b/gateway/tests/test_files_archive.pyindex f97e3d2f..221b3815 100644--- a/gateway/tests/test_files_archive.py+++ b/gateway/tests/test_files_archive.py@@ -49,4 +49,7 @@ def test_the_single_download_names_the_file_without_its_folder(monkeypatch):monkeypatch.setattr(gw, "_container_file_bytes", bytes_of)monkeypatch.setattr(gw, "_owned_session", lambda request, sid: _async_value(None))r = TestClient(gw.app).get("/v1/containers/s1/files/wf_x/content")- assert r.status_code == 200 and r.headers["content-disposition"] == 'attachment; filename="notes.txt"'+ # RFC 6266 since #187: the ASCII fallback plus filename*, the same for every name.+ assert r.status_code == 200+ assert r.headers["content-disposition"] == (+ 'attachment; filename="notes.txt"; filename*=UTF-8\'\'notes.txt')diff --git a/gateway/tests/test_unicode_filename.py b/gateway/tests/test_unicode_filename.pynew file mode 100644index 00000000..0310deb6--- /dev/null+++ b/gateway/tests/test_unicode_filename.py@@ -0,0 +1,105 @@+"""A filename the header cannot spell must not cost the download (issue #187).++A response header is bytes: ASGI defines them as latin-1, so a name carrying a Chinese character+or an emoji cannot go into the quoted `filename` at all. It raised UnicodeEncodeError inside the+server, and the caller saw a 500 with nothing in it to explain why an ASCII name had worked a+moment earlier. Every route that names a file now builds the header the same way, through+`_content_disposition`: an ASCII fallback any client can read, plus RFC 6266 `filename*` carrying+the real name. These tests hold each route to that, and hold the builder to producing something a+header can actually carry, whatever it is handed.+"""+import pytest+from fastapi.testclient import TestClient++import app as gw++UNICODE_NAMES = ["notes.txt", "报告.txt", "plan-🚀.txt", "отчёт.md", "ملف.txt"]+++async def _async_value(v):+ return v+++def _client() -> TestClient:+ return TestClient(gw.app, raise_server_exceptions=False)+++def _parts(header: str) -> tuple[str, str]:+ """(the quoted fallback, the percent-encoded filename*) of a Content-Disposition."""+ fallback = header.split('filename="', 1)[1].split('"', 1)[0]+ star = header.split("filename*=UTF-8''", 1)[1]+ return fallback, star+++# ── the routes ────────────────────────────────────────────────────────────────────────────[email protected]("filename", UNICODE_NAMES)+def test_a_download_carries_any_filename(monkeypatch, filename):+ monkeypatch.setattr(gw, "_owned_session", lambda request, sid: _async_value(None))+ monkeypatch.setattr(gw, "_container_file_bytes",+ lambda cid, fid: _async_value((b"example", "text/plain", filename)))+ r = _client().get("/v1/containers/s1/files/wf_x/content")+ assert r.status_code == 200 and r.content == b"example"+ cd = r.headers["content-disposition"]+ fallback, star = _parts(cd)+ assert cd.startswith("attachment; ")+ assert star == gw.urllib.parse.quote(filename, safe=""), "the real name rides in filename*"+ assert fallback.isascii() and fallback, "the fallback is spellable in a header"++[email protected]("filename", UNICODE_NAMES)+def test_a_preview_carries_any_filename(monkeypatch, filename):+ monkeypatch.setattr(gw, "_session_shared", lambda sid: _async_value(True))+ monkeypatch.setattr(gw, "_container_file_bytes",+ lambda sid, fid: _async_value((b"hello", "text/plain", filename)))+ r = _client().get(f"/w/h1/s1/workspace/{filename}")+ assert r.status_code == 200 and r.content == b"hello"+ cd = r.headers["content-disposition"]+ assert cd.startswith("inline; ") and _parts(cd)[1] == gw.urllib.parse.quote(filename, safe="")+++def test_an_archive_names_itself_the_same_way(monkeypatch, tmp_path):+ monkeypatch.setattr(gw, "_owned_session", lambda request, sid: _async_value(None))+ monkeypatch.setattr(gw, "_reap_spool_dir", lambda: None)+ monkeypatch.setattr(gw, "_WS_TAR_DIR", str(tmp_path))+ monkeypatch.setattr(gw, "_container_file_bytes",+ lambda sid, fid: _async_value((b"x", "text/plain", "报告.txt")))+ r = _client().get(f"/v1/sessions/s1/files/archive?files={gw._wf_id('报告.txt')}")+ assert r.status_code == 200+ cd = r.headers["content-disposition"]+ assert cd.startswith('attachment; filename="s1-turn-files.zip"') and "filename*=UTF-8''" in cd+++# ── the builder ───────────────────────────────────────────────────────────────────────────[email protected]("name", UNICODE_NAMES + [+ "deep/folder/notes.txt", "back\\slash\\x.bin", 'we"ird\\name.txt', "", ".", "..",+ "日本語", "a" * 300 + ".txt", "line\nbreak.txt", "tab\there.txt", "\x7f.bin",+])+def test_every_header_it_builds_is_one_a_header_can_carry(name):+ for kind in ("attachment", "inline"):+ value = gw._content_disposition(kind, name)+ value.encode("latin-1") # what used to raise, which is the whole bug+ assert value.startswith(f"{kind}; filename=")+ fallback, star = _parts(value)+ assert fallback.isascii() and fallback.strip(" .") != ""+ assert '"' not in fallback and "\\" not in fallback+ assert not any(ord(c) < 32 or ord(c) == 127 for c in value)+ assert len(fallback) <= 120+++def test_the_name_is_a_basename_and_never_empty():+ assert _parts(gw._content_disposition("attachment", "deep/folder/notes.txt")) == ("notes.txt", "notes.txt")+ assert _parts(gw._content_disposition("attachment", "back\\slash\\x.bin")) == ("x.bin", "x.bin")+ for empty in ("", " ", ".", ".."):+ assert _parts(gw._content_disposition("attachment", empty)) == ("download", "download")+++def test_an_ascii_name_is_unchanged_in_both_halves():+ assert (gw._content_disposition("attachment", "notes.txt")+ == 'attachment; filename="notes.txt"; filename*=UTF-8\'\'notes.txt')+++def test_the_fallback_keeps_the_extension_so_a_save_stays_openable():+ fallback, _ = _parts(gw._content_disposition("attachment", "报告.txt"))+ assert fallback.endswith(".txt") and fallback == "__.txt"+ fallback, _ = _parts(gw._content_disposition("attachment", "plan-🚀.txt"))+ assert fallback == "plan-_.txt", "one placeholder per character, astral or not"diff --git a/runner/requirements.txt b/runner/requirements.txtindex 5b207265..4b2b20ad 100644--- a/runner/requirements.txt+++ b/runner/requirements.txt@@ -1,4 +1,12 @@fastapi==0.115.6uvicorn[standard]==0.34.0-pydantic==2.10.4+pydantic==2.11.9pyyaml==6.0.2+# The MCP SDK, for mcp_bridge.py: the runner hands the bridge to a client whose own transport+# cannot reach a remote server (codex, dsh, goose take no SSE), and the bridge imports this.+# Without the pin the image installs no mcp at all and every bridged server dies at start. The+# bridge is not in a release yet (it landed after v0.17.2), so this is the next release's bug+# rather than a shipped one, caught before the tag. The version matches the hosted runner image+# (docker/runner.Dockerfile.reference). It requires pydantic 2.11, which is why the pin above+# moved: gateway and runner share one environment in this image.+mcp==1.28.1diff --git a/runner/tests/test_requirements_cover_imports.py b/runner/tests/test_requirements_cover_imports.pynew file mode 100644index 00000000..2eda6515--- /dev/null+++ b/runner/tests/test_requirements_cover_imports.py@@ -0,0 +1,63 @@+"""Everything the runner imports at module level must be something the image installs.++`mcp_bridge.py` imported the MCP SDK and no requirements file pinned it. The image installs those+files and nothing else into the one environment gateway and runner share, so the bridge would die+the moment a client tried to start it, and the only symptom would be an MCP server that never+connected. The bridge landed after v0.17.2, so the next release would have been the first to carry+it; verified against a real image built from this branch's requirements before and after.++The check is derived rather than typed: every module-level third-party import in every runner+module has to be pinned in `runner/requirements.txt` or `gateway/requirements.txt`. Module level is+the line that matters: that import decides whether the file loads at all. An import inside a+function is the code saying "only on this path", which is how the backend runtimes that install+themselves (the DeepSeek harness in its own environment) are reached, and those are not pinned+here on purpose.+"""+import ast+import pathlib+import re+import sys++RUNNER = pathlib.Path(__file__).resolve().parents[1]+GATEWAY = RUNNER.parent / "gateway"+# Module name -> the distribution that provides it, where the two differ.+DISTRIBUTION = {"yaml": "pyyaml"}+++def _module_level_imports(path: pathlib.Path) -> set[str]:+ mods: set[str] = set()+ for node in ast.parse(path.read_text()).body: # body, not walk: top level only+ if isinstance(node, ast.Import):+ mods |= {a.name.split(".")[0] for a in node.names}+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:+ mods.add(node.module.split(".")[0])+ local = {p.stem for p in RUNNER.glob("*.py")}+ return {m for m in mods+ if m not in sys.stdlib_module_names and m not in local and not m.startswith("_")}+++def _pinned() -> set[str]:+ out: set[str] = set()+ for f in (RUNNER / "requirements.txt", GATEWAY / "requirements.txt"):+ for line in f.read_text().splitlines():+ if line.strip() and not line.startswith("#"):+ out.add(re.split(r"[=<>\[]", line, 1)[0].strip().lower())+ return out+++def test_every_module_level_runner_import_is_pinned():+ pinned, missing = _pinned(), {}+ for f in sorted(RUNNER.glob("*.py")):+ for mod in _module_level_imports(f):+ if DISTRIBUTION.get(mod, mod).lower() not in pinned:+ missing.setdefault(f.name, set()).add(mod)+ assert not missing, (+ f"these runner modules import something no requirements file pins: {missing}. "+ "The image installs those files and nothing else, so the import fails at run time.")+++def test_the_bridge_names_the_sdk_it_needs():+ """The specific regression: the bridge's SDK, pinned to the version the hosted image bakes."""+ assert "mcp" in _module_level_imports(RUNNER / "mcp_bridge.py")+ assert re.search(r"^mcp==", (RUNNER / "requirements.txt").read_text(), re.M), \+ "mcp_bridge.py cannot start without the MCP SDK"diff --git a/ui/src/app/data/workspaces/[sid]/[...path]/route.ts b/ui/src/app/data/workspaces/[sid]/[...path]/route.tsindex 2f348e7d..7deaad0c 100644--- a/ui/src/app/data/workspaces/[sid]/[...path]/route.ts+++ b/ui/src/app/data/workspaces/[sid]/[...path]/route.ts@@ -18,6 +18,23 @@import { NextResponse, type NextRequest } from 'next/server';import { LOCAL_MEMBER, LOCAL_ORG, SELF_HOSTED } from '@/lib/edition';+// A header value is bytes, not text: `Headers.set` throws a TypeError the moment a filename+// carries a Chinese character or an emoji, and the download dies with it. RFC 6266 is the way+// out, and it is the same shape the gateway sends: an ASCII fallback every client can read,+// plus `filename*` with the real name percent-encoded. encodeURIComponent leaves ! ' ( ) * ~+// alone and RFC 5987 does not allow them unescaped, so those are escaped here too.+function contentDisposition(kind: 'inline' | 'attachment', filename: string): string {+ let name = (filename || '').split(/[\\/]/).pop()?.trim() || '';+ if (name === '' || name === '.' || name === '..') name = 'download';+ // One `_` per character, not per UTF-16 unit, so an emoji leaves one placeholder and the+ // fallback matches what the gateway sends for the same file.+ let ascii = name.replace(/[^\x20-\x7e]/gu, '_').replace(/["\\]/g, '').slice(0, 120);+ if (ascii.replace(/[\s.]/g, '') === '') ascii = 'download';+ const star = encodeURIComponent(name).replace(/[!'()*~]/g,+ (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());+ return `${kind}; filename="${ascii}"; filename*=UTF-8''${star}`;+}+export const dynamic = 'force-dynamic';const GATEWAY = (process.env.HARNESS_GATEWAY_URL || 'https://api.harnessrouter.ai').replace(/\/$/, '');@@ -76,7 +93,7 @@ export async function GET(req: NextRequest, ctx: { params: Promise<{ sid: string// Attacker-influenceable content served from the console's own origin: nosniff so a text/plain// artifact can never be re-interpreted as script, and a filename so a save keeps its extension.out.set('x-content-type-options', 'nosniff');- out.set('content-disposition', `inline; filename="${name.replace(/"/g, '')}"`);+ out.set('content-disposition', contentDisposition('inline', name));out.set('cache-control', 'private, no-store');return new NextResponse(res.body, { status: 200, headers: out });}