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.

Hosted ports: task keeps its model on reopen, bus tasks held, Google unknown-field resend; a self-hosted sandbox reaches the broker on loopback (#84)

github-actions[bot]cebd9f7050e4
diff --git a/gateway/app.py b/gateway/app.py
index f8de9f28..7d16c932 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -629,6 +629,39 @@ async def _redis_pump() -> None:
_bus_deliver(m["org"], m["harness"], m["member"], m["sid"], m["rid"], m["ev"])
+# The bus tasks are HELD here for the life of the process. asyncio keeps only a weak reference to
+# a task, so a task created and dropped is collected at some later GC pass, mid-await, and its
+# coroutine is closed: "Task was destroyed but it is pending!" and, from the pubsub listen loop,
+# "aclose(): asynchronous generator is already running". Measured 2026-09-06 08:07Z to 08:10Z: every
+# gateway replica lost its Redis subscriber that way within minutes of booting, cross-replica events
+# stopped, and _redis_ok["sub"] stayed True, so the polling fallback never engaged and a console saw
+# another replica's turn only through its own re-reads. A held task is never collected; one that
+# ends for any reason is logged and started again.
+_BG_TASKS: dict[str, asyncio.Task] = {}
+
+
+def _spawn_forever(name: str, fn) -> asyncio.Task:
+ """Run `fn()` as a held background task; whenever it ends (return, error), say so and restart it."""
+ loop = asyncio.get_running_loop()
+
+ def _done(t: asyncio.Task) -> None:
+ if _BG_TASKS.get(name) is not t:
+ return # superseded (tests, a restart already made)
+ _BG_TASKS.pop(name, None)
+ if t.cancelled():
+ return # shutdown
+ print(f"[bus] task {name} ended: {t.exception()!r}; restarting", flush=True)
+ if name == "redis-listen":
+ _redis_ok["sub"] = False # until the new listener subscribes
+ if not loop.is_closed():
+ loop.call_later(1.0, _spawn_forever, name, fn)
+
+ t = loop.create_task(fn(), name=name)
+ _BG_TASKS[name] = t
+ t.add_done_callback(_done)
+ return t
+
+
async def _redis_listen() -> None:
"""Every replica tails the shared channel and delivers into its own buffers + subscribers."""
while True:
@@ -895,10 +928,22 @@ def _auth_from_conn(conn: dict, sid: str = "") -> dict | None:
flush=True)
return None
out["api_key"] = _mint_turn_cred(sid, str(conn.get("name") or ""))
- out["base_url"] = f"{PUBLIC_BASE_URL}/v1/llm"
+ out["base_url"] = f"{_sandbox_broker_origin()}/v1/llm"
return out
+def _sandbox_broker_origin() -> str:
+ """Where a sandbox reaches the broker. Hosted, the public base URL. Self-hosted, the runner is
+ a process beside the gateway and loopback is the broker's own door: the public URL is the
+ console's, whose sign-in wall turns away any client that does not present a Bearer token
+ (an Anthropic-shape client sends x-api-key), so opencode on a direct Anthropic key answered
+ "Not Found" on every turn (2026-09-06 support matrix)."""
+ local = os.environ.get("HARNESS_GATEWAY_URL", "").rstrip("/")
+ if local and _pool_is_local():
+ return local
+ return PUBLIC_BASE_URL
+
+
def _conn_public(conn: dict) -> dict:
"""Connection metadata with secret fields stripped (for admin listing)."""
secret = {"api_key", "aws_secret_access_key", "aws_session_token", "aws_bearer_token", "gcp_sa_json"}
@@ -2509,8 +2554,8 @@ async def _start_bus() -> None:
global _redis_out
if REDIS_URL:
_redis_out = asyncio.Queue(maxsize=100_000)
- asyncio.create_task(_redis_pump())
- asyncio.create_task(_redis_listen())
+ _spawn_forever("redis-pump", _redis_pump)
+ _spawn_forever("redis-listen", _redis_listen)
@app.on_event("startup")
@@ -2929,6 +2974,34 @@ def _strip_unsupported(body: bytes, provider: str = "", byok: bool = False, path
return json.dumps(doc).encode() if changed else body
+_GOOGLE_UNKNOWN_RE = re.compile(r'Unknown name \\?"([A-Za-z_][A-Za-z0-9_]*)\\?"(?! at \')')
+
+
+def _google_unknown_field(refused: bytes) -> str:
+ """The top-level request field Google's OpenAI-compatible endpoint refused as unknown, or "".
+ A field named inside an object ("at 'tools[0].function'") is not one this relay drops."""
+ try:
+ text = refused.decode("utf-8", "replace")
+ except Exception: # noqa: BLE001
+ return ""
+ if "Cannot find field" not in text:
+ return ""
+ m = _GOOGLE_UNKNOWN_RE.search(text)
+ return m.group(1) if m else ""
+
+
+def _without_field(body: bytes, field: str) -> bytes:
+ """The JSON request without one top-level field; a body that is not a JSON object is returned as is."""
+ try:
+ doc = json.loads(body or b"")
+ except (ValueError, UnicodeDecodeError):
+ return body
+ if not isinstance(doc, dict) or field not in doc:
+ return body
+ doc.pop(field)
+ return json.dumps(doc).encode()
+
+
def _broker_token(request: Request) -> str:
"""CLIs differ in how they present a key (Bearer / api-key / x-api-key) — accept all three
rather than special-casing per backend, which would be three paths for one decision."""
@@ -3048,6 +3121,28 @@ async def llm_broker(path: str, request: Request):
rc = _relay_client()
req = rc.build_request(request.method, url, headers=headers, content=body or None)
up = await rc.send(req, stream=True)
+ if provider == "google" and up.status_code == 400:
+ # Google's OpenAI-compatible endpoint refuses a request that names any field it does not
+ # know ("Unknown name \"store\": Cannot find field."), and the harnesses send OpenAI's
+ # optional fields freely (pi and dsh: store, seed; measured 2026-09-06 on gemini-3.6-flash).
+ # The refusal names the field; the request goes again without it, a few fields at most.
+ refused = await up.aread()
+ for _ in range(4):
+ unknown = _google_unknown_field(refused)
+ if not unknown:
+ break
+ await up.aclose()
+ body = _without_field(body, unknown)
+ print(f"[broker] google refused field {unknown!r}; sent again without it sid={sid}", flush=True)
+ req = rc.build_request(request.method, url, headers=headers, content=body or None)
+ up = await rc.send(req, stream=True)
+ if up.status_code != 400:
+ break
+ refused = await up.aread()
+ if up.status_code == 400:
+ return Response(content=refused, status_code=400, media_type=up.headers.get("content-type"),
+ headers={k: val for k, val in up.headers.items()
+ if k.lower() not in ("content-length", "transfer-encoding", "connection")})
async def pump():
try:
diff --git a/gateway/tests/test_broker_google_unknown.py b/gateway/tests/test_broker_google_unknown.py
new file mode 100644
index 00000000..a9ac59e3
--- /dev/null
+++ b/gateway/tests/test_broker_google_unknown.py
@@ -0,0 +1,32 @@
+"""Google's OpenAI-compatible endpoint names the request field it does not know; the relay drops
+that top-level field and sends again (pi and dsh on gemini-3.6-flash, 2026-09-06: store, seed)."""
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from app import _google_unknown_field, _without_field # noqa: E402
+
+STORE = json.dumps([{"error": {"code": 400, "message": 'Invalid JSON payload received. Unknown name "store": Cannot find field.', "status": "INVALID_ARGUMENT"}}]).encode()
+SEED = json.dumps({"error": {"code": 400, "message": 'Invalid JSON payload received. Unknown name "seed": Cannot find field.'}}).encode()
+NESTED = json.dumps({"error": {"code": 400, "message": 'Invalid JSON payload received. Unknown name "strict" at \'tools[0].function\': Cannot find field.'}}).encode()
+QUOTA = json.dumps({"error": {"code": 429, "message": "You exceeded your current quota"}}).encode()
+
+
+def test_names_the_refused_top_level_field():
+ assert _google_unknown_field(STORE) == "store"
+ assert _google_unknown_field(SEED) == "seed"
+
+
+def test_nested_or_unrelated_refusals_are_not_retried():
+ assert _google_unknown_field(NESTED) == ""
+ assert _google_unknown_field(QUOTA) == ""
+ assert _google_unknown_field(b"<html>bad gateway</html>") == ""
+
+
+def test_without_field_drops_only_that_field():
+ body = json.dumps({"model": "gemini-3.6-flash", "messages": [{"role": "user", "content": "hi"}], "store": False, "seed": 7}).encode()
+ out = json.loads(_without_field(body, "store"))
+ assert "store" not in out and out["seed"] == 7 and out["messages"]
+ assert _without_field(body, "absent") == body
+ assert _without_field(b"not json", "store") == b"not json"
diff --git a/gateway/tests/test_bus_tasks.py b/gateway/tests/test_bus_tasks.py
new file mode 100644
index 00000000..465be705
--- /dev/null
+++ b/gateway/tests/test_bus_tasks.py
@@ -0,0 +1,46 @@
+"""The Redis bus tasks are held and restarted: asyncio keeps only a weak reference to a task, so
+the unreferenced create_task() of the pump and the listener was collected mid-await ("Task was
+destroyed but it is pending!") and every replica silently lost its subscriber (2026-09-06)."""
+import asyncio
+import gc
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import app as gw # noqa: E402
+
+
+async def test_held_task_survives_gc():
+ async def fn():
+ await asyncio.sleep(3600)
+ t = gw._spawn_forever("t-gc", fn)
+ gc.collect()
+ await asyncio.sleep(0.05)
+ assert gw._BG_TASKS["t-gc"] is t and not t.done()
+ t.cancel()
+ await asyncio.sleep(0.01)
+ assert "t-gc" not in gw._BG_TASKS # a cancelled task (shutdown) is not restarted
+
+
+async def test_task_that_ends_is_restarted_and_flags_the_subscriber(capsys):
+ starts = []
+ gw._redis_ok["sub"] = True
+
+ async def fn():
+ starts.append(1)
+ if len(starts) == 1:
+ raise RuntimeError("boom")
+ await asyncio.sleep(3600)
+ t = gw._spawn_forever("redis-listen", fn)
+ await asyncio.sleep(0.05)
+ assert t.done() and gw._redis_ok["sub"] is False
+ assert "task redis-listen ended: RuntimeError('boom'); restarting" in capsys.readouterr().out
+ await asyncio.sleep(1.2)
+ t2 = gw._BG_TASKS["redis-listen"]
+ assert t2 is not t and not t2.done() and len(starts) == 2
+ t2.cancel()
+ await asyncio.sleep(0.01)
diff --git a/gateway/tests/test_sandbox_broker_origin.py b/gateway/tests/test_sandbox_broker_origin.py
new file mode 100644
index 00000000..1042c394
--- /dev/null
+++ b/gateway/tests/test_sandbox_broker_origin.py
@@ -0,0 +1,32 @@
+"""A self-hosted sandbox reaches the broker on loopback; a hosted one on the public base URL."""
+import os
+import pathlib
+import sys
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+os.environ.setdefault("HR_BACKING", "local")
+import app as gw # noqa: E402
+
+
+def test_self_hosted_hands_the_sandbox_the_loopback_gateway(monkeypatch):
+ monkeypatch.setenv("HARNESS_GATEWAY_URL", "http://127.0.0.1:8080/")
+ monkeypatch.setattr(gw, "PUBLIC_BASE_URL", "https://console.example")
+ monkeypatch.setattr(gw, "_pool_is_local", lambda: True)
+ assert gw._sandbox_broker_origin() == "http://127.0.0.1:8080"
+
+
+def test_hosted_hands_the_sandbox_the_public_base(monkeypatch):
+ monkeypatch.setenv("HARNESS_GATEWAY_URL", "http://gateway.internal")
+ monkeypatch.setattr(gw, "PUBLIC_BASE_URL", "https://app.example")
+ monkeypatch.setattr(gw, "_pool_is_local", lambda: False)
+ assert gw._sandbox_broker_origin() == "https://app.example"
+
+
+def test_the_sandbox_auth_carries_that_origin(monkeypatch):
+ monkeypatch.setenv("HARNESS_GATEWAY_URL", "http://127.0.0.1:8080")
+ monkeypatch.setattr(gw, "PUBLIC_BASE_URL", "https://console.example")
+ monkeypatch.setattr(gw, "_pool_is_local", lambda: True)
+ monkeypatch.setattr(gw, "SANDBOX_TRUST", "")
+ monkeypatch.setattr(gw, "_mint_turn_cred", lambda sid, name: "hrt_x")
+ out = gw._auth_from_conn({"provider": "anthropic", "api_key": "sk-ant-real", "name": "Anthropic"}, "sid1")
+ assert out["base_url"] == "http://127.0.0.1:8080/v1/llm" and out["api_key"] == "hrt_x" and "sk-ant-real" not in str(out)
diff --git a/scripts/support-matrix/run.mjs b/scripts/support-matrix/run.mjs
index c617bb92..a5fcb0fb 100644
--- a/scripts/support-matrix/run.mjs
+++ b/scripts/support-matrix/run.mjs
@@ -91,7 +91,10 @@ try {
for (let i = 0; i < 40 && models.length < served; i++) { await page.keyboard.press('Escape'); await sleep(1500); await page.click('.ar2-chip'); await sleep(400); models = await readMenu(); }
if (models.length < served) log(`MENU ${h} shows ${models.length} of ${served} served models after 60 s`);
await page.keyboard.press('Escape'); await sleep(300);
- const enabled = models.filter((m) => m.ok && (!process.env.MODELS || process.env.MODELS.split(',').includes(m.id))).map((m) => m.id);
+ // MODELS pins which PAIRS run (a re-run of the missing ones); the switch scenario still needs another
+ // model this harness can run, so the switch target comes from the whole runnable list, not the pinned one.
+ const runnableAll = models.filter((m) => m.ok).map((m) => m.id);
+ const enabled = runnableAll.filter((id) => !process.env.MODELS || process.env.MODELS.split(',').includes(id));
log(`HARNESS ${h} models ${models.length} runnable ${enabled.length}: ${enabled.join(',')}`);
for (const m of enabled) {
const res = load(); const k = key(h, m);
@@ -106,7 +109,7 @@ try {
if (rec.first.ok) {
rec.followup = expectWord(await turn(`Reply with exactly: M2-${m}`), `M2-${m}`);
log(`FOLLOWUP ${k} ${rec.followup.ok ? 'ok' : 'FAIL'} ${rec.followup.s}s ${rec.followup.why}`);
- const other = enabled.find((x) => x !== m) || null;
+ const other = runnableAll.find((x) => x !== m) || null;
if (other) { await page.click('.ar2-chip'); await sleep(500); await page.locator('.wbx-model-opt', { hasText: other }).first().click(); await sleep(300); rec.switch = { to: other, ...expectWord(await turn(`Reply with exactly: M3-${other}`), `M3-${other}`) }; }
else rec.switch = { to: null, ok: null, why: 'only one model' };
log(`SWITCH ${k} -> ${other} ${rec.switch.ok ? 'ok' : rec.switch.ok === null ? 'n/a' : 'FAIL'} ${rec.switch.s || ''}s ${rec.switch.why || ''}`);
diff --git a/ui/src/components/TaskChat.tsx b/ui/src/components/TaskChat.tsx
index f43eb915..d9898bc4 100644
--- a/ui/src/components/TaskChat.tsx
+++ b/ui/src/components/TaskChat.tsx
@@ -236,6 +236,16 @@ export function ConfigChat({ oob, ch, harnessId, harnessName, deepSid, onClearDe
if (models.includes(bare)) return bare;
return fallbackModel || m;
};
+ // A task's own model is taken as stored: it ran with it. Only the claude- prefix is tolerated;
+ // the fallback to the harness default is for a harness's saved default, never for a task, since
+ // the option list may not have loaded yet or may no longer list the model, and either way the
+ // task continues on its model or fails saying so, it does not silently move to another.
+ const exactModel = (m: string): string => {
+ if (models.includes(m)) return m;
+ if (models.includes('claude-' + m)) return 'claude-' + m;
+ const bare = m.replace(/^claude-/, '');
+ return models.includes(bare) ? bare : m;
+ };
const [model, setModel] = useState(oob ? (oobDefaultModel(oob) || '') : normModel(ch?.defaultModel));
// Re-sync the active model to the harness's saved default whenever the config loads or its default
// changes (ch arrives async after mount; without ch in deps the saved default was never applied).
@@ -266,6 +276,9 @@ export function ConfigChat({ oob, ch, harnessId, harnessName, deepSid, onClearDe
// Kept SEPARATE from selectedSid so a new chat reporting its own session id highlights the row
// WITHOUT remounting the live conversation (the Conversation is keyed by selectedSid).
const [activeSid, setActiveSid] = useState<string | null>(deepSid || null);
+ // The session this tab created itself (its id comes back from the first turn): the only task
+ // whose card need not be read, its conversation and its model are already here.
+ const bornHere = useRef<string | null>(null);
useEffect(() => { onActiveSid?.(activeSid); }, [activeSid]); // eslint-disable-line react-hooks/exhaustive-deps
// Deep-linked session validation: confirm the manifest exists; 404 -> visible error + New Task.
// A 200 manifest also serves as the title/meta fallback when the session isn't in MY recents
@@ -274,8 +287,12 @@ export function ConfigChat({ oob, ch, harnessId, harnessName, deepSid, onClearDe
const [deepCard, setDeepCard] = useState<TraceCard | null>(null);
useEffect(() => {
// A session born in this tab needs no lookup: its conversation is already here, and the
- // index may not list it for a moment, which would read as a task that does not exist.
- if (!deepSid || deepSid === activeSid) return;
+ // index may not list it for a moment, which would read as a task that does not exist. Every
+ // other task shown by URL (a reload, a new tab, a link) is read: its card says which model it
+ // ran with. The guard used to be deepSid === activeSid, which a reload satisfies from the
+ // first render (activeSid starts as deepSid), so a reopened task never had a card and its
+ // next turn went to the harness default model (measured 2026-09-06: gpt-5.6-sol became gpt-5.5).
+ if (!deepSid || deepSid === bornHere.current) return;
let alive = true;
harnessFetch(`/api/harness/v1/traces/${encodeURIComponent(deepSid)}`)
.then(async (r) => {
@@ -309,8 +326,6 @@ export function ConfigChat({ oob, ch, harnessId, harnessName, deepSid, onClearDe
// Narrow screens alternate between the task list and the detail pane (CSS ≤820px); desktop
// ignores this. Narrow DEFAULTS to the detail view (list collapsed), the title-row toggle
// expands the list; picking a task collapses it again.
- // The task cards (lifted from RecentsPanel) drive the detail header's title + meta row.
- const [cards, setCards] = useState<TraceCard[]>([]);
const backend = oob?.backend ?? (oobById(draft?.base || '')?.backend ?? null);
const startNew = () => {
@@ -331,17 +346,14 @@ export function ConfigChat({ oob, ch, harnessId, harnessName, deepSid, onClearDe
}, [deepSid]); // eslint-disable-line react-hooks/exhaustive-deps
const shownSid = activeSid ?? selectedSid;
- const selCard = shownSid
- ? cards.find((c) => c.session_id === shownSid)
- || (deepCard && deepCard.session_id === shownSid ? deepCard : null)
- : null;
+ const selCard = shownSid && deepCard && deepCard.session_id === shownSid ? deepCard : null;
const chip = selCard ? statusChip(selCard.status) : { cls: 'healthy', label: 'Ready' };
// An existing task's selector shows the model IT actually ran with last turn (from the trace
// card), not the harness default, resuming a conversation must not silently switch models.
const taskModel = selCard?.model || '';
useEffect(() => {
if (!shownSid || !taskModel) return;
- setModel(normModel(taskModel));
+ setModel(exactModel(taskModel));
}, [shownSid, taskModel]); // eslint-disable-line react-hooks/exhaustive-deps
const fmtDur = (s?: number) => {
if (!s) return '';
@@ -378,7 +390,7 @@ export function ConfigChat({ oob, ch, harnessId, harnessName, deepSid, onClearDe
runtime: (oob ?? oobById(draft?.base || ''))?.name, defaultModel: oob ? (oobDefaultModel(oob) || '') : normModel(ch?.defaultModel) }}
additionalHeaders={(draft?.additionalHeaders || []).filter(Boolean)}
models={models} onModel={(m) => setModel(m)}
- onSession={(sid) => { setActiveSid(sid); setRecentsKey((k) => k + 1); }}
+ onSession={(sid) => { bornHere.current = sid; setActiveSid(sid); setRecentsKey((k) => k + 1); }}
onTotals={onTotals}
onRan={() => { setRecentsKey((k) => k + 1); onActivity?.(); }} />
</div>