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
Sync with the hosted tree (2026-09-05): Codex resume, failed turns say why, archive, broker endpoint, card settle (#69)
github-actions[bot]dd2b14988183
diff --git a/gateway/app.py b/gateway/app.pyindex 57cb19e1..4382543c 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -1187,6 +1187,25 @@ async def _image_auth(sid: str, backend: str) -> dict | None:return None+def _codex_family(model: str) -> str:+ """Codex gives gpt-5.3-codex and the other GPT models different tool sets. Measured on+ 2026-09-05: the other models act in a thread gpt-5.3-codex started, but gpt-5.3-codex runs+ without its tools in a thread where any other model has taken a turn, and narrates its work."""+ return "codex" if (model or "").strip().lower().endswith("-codex") else "gpt"+++def _codex_switch_refusal(models_seen, model_req: str) -> str:+ """The sentence a Codex turn fails with when gpt-5.3-codex would run in a thread another+ model family has already used, else empty."""+ if _codex_family(model_req) != "codex":+ return ""+ others = sorted({m for m in (models_seen or []) if m and _codex_family(m) != "codex"})+ if not others:+ return ""+ return (f"Codex cannot run {model_req} in a task that has already used {', '.join(others)}: "+ f"its tools are not available there. Start a new task for {model_req}.")++async def _mapped_integration_conn(backend: str, canonical: str) -> dict | None:"""The synthetic connection for a model→integration mapping, or None when unmapped /unusable by this backend. Shaped exactly like a vault connection so the turn loop treats@@ -2896,6 +2915,32 @@ def _broker_token(request: Request) -> str:return (request.headers.get("api-key") or request.headers.get("x-api-key") or "").strip()+# A direct provider's connection carries only its key: its endpoint is the provider's own and is+# not a thing to ask the user for. Gateways (OpenRouter, Vercel, TokenRouter) and self-hosted+# endpoints carry their base_url on the connection. Without this table an OpenAI key answered+# "connection has no base_url" (2026-09-04).+_PROVIDER_BASE = {"openai": "https://api.openai.com/v1", "anthropic": "https://api.anthropic.com/v1"}+++def _with_provider_base(conn: dict | None) -> dict | None:+ if conn and not str(conn.get("base_url") or "").strip():+ base = _PROVIDER_BASE.get(str(conn.get("provider") or "").lower())+ if base:+ conn = {**conn, "base_url": base}+ return conn+++_PROVIDER_REFUSAL_RE = re.compile(r"\b(401|403|429)\b|unauthori[sz]ed|incorrect api key|invalid_api_key|invalid api key|"+ r"insufficient_quota|rate limit|quota|forbidden|refused", re.IGNORECASE)+++def _turn_failure_message(rec: dict) -> str:+ """What a failed turn says: the org's own key's refusal in plain words when that is why, else+ the list of connections tried."""+ tried = rec.get("tried") or []+ return str(rec.get("error_message") or "") or (json.dumps(tried)[:400] if tried else "turn failed")++async def _broker_resolve(conn_name: str, org: str | None) -> dict | None:"""Resolve a turn credential's connection name back to its credentials.@@ -2912,9 +2957,9 @@ async def _broker_resolve(conn_name: str, org: str | None) -> dict | None:# provider here is the INTEGRATION's own type — it selects the upstream auth header, which# is all the broker needs (the runner-side wiring already happened at turn start).cfg["provider"] = (integ.get("provider") or "").lower()- return cfg+ return _with_provider_base(cfg)conn, _ = await _get_connection(org, conn_name)- return conn+ return _with_provider_base(conn)@app.api_route("/v1/llm/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"])@@ -3209,12 +3254,52 @@ async def _session_cards(org: str, limit: int, cursor: str, member: str, harnessmw = str(m.get("workspace") or "")if mw != workspace and not (ws_default and not mw):return None+ # A card that still says running while the session vertex is terminal is a turn whose+ # tail never finished: the replica wrote the vertex, then died before the finalize that+ # rewrites the card (a roll under a live turn, 2026-09-04). The vertex is the durable+ # truth, so the read repairs the card from it, once, and the list stops lying.+ if str(m.get("status") or "") in _CARD_LIVE and m.get("session_id"):+ fixed = await _card_settle(str(m["session_id"]), m)+ if fixed:+ m = fixedreturn {k: m.get(k) for k in _TRACE_CARD_FIELDS}cards = [c for c in await asyncio.gather(*[_card(it) for it in lst.get("items", [])]) if c]return {"sessions": cards, "cursor": lst.get("cursor") or ""}+_CARD_LIVE = {"running", "starting", "in_progress"}+++async def _card_settle(sid: str, m: dict) -> dict | None:+ """Repair a live-looking card from its session vertex. Returns the settled manifest when the+ vertex is terminal, or its heartbeat is older than the hard turn cap with the turn unadopted;+ None when the turn is genuinely live. The settled manifest is re-indexed so every mirror agrees."""+ v = await _vertex_get(sid) or {}+ vs = str(v.get("turn_status") or v.get("status") or "")+ status = ""+ if vs in ("done", "failed", "cancelled", "incomplete", "max_turns", "timeout"):+ status = vs+ else:+ try:+ hb = float(v.get("heartbeat") or 0)+ except Exception: # noqa: BLE001+ hb = 0+ if hb and time.time() - hb > _GW_MAX_TURN_S:+ status = "failed"+ if not status or status == str(m.get("status") or ""):+ return None+ m = dict(m)+ m["status"] = status+ base = _prefix_from_vertex(sid, v)+ if base:+ try:+ await _index_manifest(base, m)+ except Exception: # noqa: BLE001 — the list still answers from the vertex's truth+ pass+ return m++def _prefix_from_vertex(sid: str, v: dict | None) -> str | None:"""The session's trace prefix. Prefer the stored trace_blob, but RECONSTRUCT the deterministic'{tenant}/{created_at_inv}_{sid}' when trace_blob is missing/blank — so a blank value (e.g. left@@ -4660,6 +4745,16 @@ _IMAGE_VENDOR_MODELS: dict[str, dict[str, str]] = {_VENDOR_MODELS["tokenrouter"] = {c: v for c, v in _VENDOR_MODELS["openrouter"].items()if c not in _TOKENROUTER_NO_CHANNEL}+# OpenRouter dates a slug when a model gets a new snapshot while TokenRouter keeps serving the+# plain name. The shared table holds the name TokenRouter serves (it is where the platform's+# traffic goes); OpenRouter's own list gets the dated name here, after TokenRouter has taken its+# copy. Putting the dated name in the shared table sent TokenRouter "qwen/qwen3.8-max-0902" and+# it answered "No available channel" (Hermes, 2026-09-05).+_OPENROUTER_RESLUG = {+ "qwen3.8-max": "qwen/qwen3.8-max-0902",+}+_VENDOR_MODELS["openrouter"] = {c: _OPENROUTER_RESLUG.get(c, v) for c, v in _VENDOR_MODELS["openrouter"].items()}+# Vercel's AI Gateway carries the same catalogue under nearly the same slugs, so it starts from# OpenRouter's table too. Only the vendor prefix differs on four of them, and it differs because# the two aggregators disagree about who publishes the model, not about which model it is.@@ -5396,6 +5491,25 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, smapped_conn = await _mapped_integration_conn(backend, model_req)candidates: list[tuple[str, dict | None]] = ([(mapped_conn["name"], mapped_conn)] if mapped_conn else [])candidates += [(n, None) for n in chain]+ if backend == "codex" and model_req:+ # The session remembers every model it has run. A gpt-5.3-codex turn after another model+ # family is refused, in words, rather than run without its tools or restarted on a fresh+ # session.+ _v = await _vertex_get(sid) or {}+ seen = [m for m in str(_v.get("models_seen") or "").split(",") if m]+ if not seen and resume:+ try:+ _turns = (await _session_turns_data(sid)).get("turns") or []+ seen = [str(t.get("_model") or "") for t in _turns if t.get("_model")]+ except Exception: # noqa: BLE001+ seen = []+ _why = _codex_switch_refusal(seen, model_req) if resume else ""+ if _why:+ rec["error_message"] = _why+ rec["tried"].append({"connection": "", "status": "refused", "error": _why})+ candidates = []+ elif model_req not in seen:+ await _vertex_upsert(sid, {"models_seen": ",".join(seen + [model_req])})# Independent of which chat connection wins below: images are usually a different provider.image_auth = await _image_auth(sid, backend)vision_auth = await _vision_auth(sid, backend) if backend == "hermes" else None@@ -5575,6 +5689,20 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, srec["tried"].append({"connection": name, "status": st,"error": (s.get("result") or s.get("error") or "")[:200]})break+ _last_err = str(rec["tried"][-1].get("error") or "") if rec["tried"] else ""+ if (not terminal and rec["tried"] and rec["tried"][-1].get("connection") == name+ and rec["tried"][-1].get("status") and _PROVIDER_REFUSAL_RE.search(_last_err)):+ # The provider refused this key. That is configuration, not an outage to route around:+ # falling through to the next connection ran the task on another key while the user+ # believed this one worked. On a self-hosted install every key is the operator's own,+ # so the rule is the refusal itself, not which store the key came from. Other failures+ # (a transient error, a timeout) still move on to the next connection.+ provider = str(conn.get("provider") or "your provider")+ rec["error_message"] = f"Your {provider} key was refused: {_last_err or 'the provider returned an error'}"+ status = "failed"+ rec["status"] = "failed"+ await _vertex_upsert(sid, {"status": "failed", "turn_status": "failed", "last_connection": name})+ breakif terminal:status = terminalrec["status"] = "done" if terminal == "completed" else terminal@@ -5783,6 +5911,24 @@ async def storage_usage() -> dict:return {"by_org": by_org}[email protected]("/internal/sessions/{sid}/recycle", dependencies=[Depends(_internal_only)])+async def recycle_session_sandbox(sid: str) -> dict:+ """Recycle a session's sandbox on purpose: persist the workspace, then hydrate it back into the+ same sandbox, which wipes and restores exactly as a fresh sandbox would after the old one was+ let go. The support matrix uses it to test "a follow-up after the sandbox is gone" for every+ harness and model without waiting out a cooldown. Refused while a turn is live."""+ v = await _vertex_get(sid)+ if not v:+ raise HTTPException(404, "no such session")+ if {"running", "starting"} & {str(v.get("turn_status") or ""), str(v.get("status") or "")}:+ raise HTTPException(409, "a turn is running; recycle after it settles")+ rec: dict = {}+ await _checkpoint(sid, rec)+ await _hydrate(sid, rec)+ return {"session_id": sid, "checkpoint": rec.get("checkpoint") or rec.get("checkpoint_bytes"),+ "hydrated": bool(rec.get("hydrated")), "hydrate": rec.get("hydrate"), "hydrate_error": rec.get("hydrate_error")}++@app.post("/internal/reindex-traces", dependencies=[Depends(_internal_only)])async def reindex_traces(org: str, dry_run: bool = False, max_pages: int = 500) -> dict:"""One-time backfill: mirror every existing flat-index manifest ({org}/idx/) into the narrow@@ -6216,10 +6362,9 @@ async def create_response(body: CreateResponseBody, request: Request):model_req=model_req, user_text=user_text, harness_id=harness_id,max_step=max_step, timeout_s=timeout_s, hdr_vals=hdr_vals,partial_messages=want_partial, codex_appserver=want_appserver, hv=hv)- if status == "failed":- tr.error = {"type": "harness_error", "code": "connections_exhausted",- "message": (json.dumps(rec.get("tried") or [])[:400]) or "turn failed"}- for ev in tr.complete(status, produced):+ # A failed turn says why in the transcript, not only in the response record: fail()+ # carries the message as an error event, which the console prints under the answer.+ for ev in (tr.fail(_turn_failure_message(rec)) if status == "failed" else tr.complete(status, produced)):await bus_emit_bg(ev)await persist(status)except asyncio.CancelledError:@@ -6266,10 +6411,9 @@ async def create_response(body: CreateResponseBody, request: Request):prompt=prompt, files_in=files_in, resume=resume, emit=emit, model_req=model_req,user_text=user_text, harness_id=harness_id, max_step=max_step,timeout_s=timeout_s, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv)- if status == "failed":- tr.error = {"type": "harness_error", "code": "connections_exhausted",- "message": (json.dumps(rec.get("tried") or [])[:400]) or "turn failed"}- for ev in tr.complete(status, produced):+ # A failed turn says why in the transcript, not only in the response record: fail()+ # carries the message as an error event, which the console prints under the answer.+ for ev in (tr.fail(_turn_failure_message(rec)) if status == "failed" else tr.complete(status, produced)):await emit(ev)await persist(status)except asyncio.CancelledError:@@ -6325,10 +6469,9 @@ async def create_response(body: CreateResponseBody, request: Request):prompt=prompt, files_in=files_in, resume=resume, emit=bus_emit, model_req=model_req,user_text=user_text, harness_id=harness_id, max_step=max_step,timeout_s=timeout_s, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv)- if status == "failed":- tr.error = {"type": "harness_error", "code": "connections_exhausted",- "message": (json.dumps(rec.get("tried") or [])[:400]) or "turn failed"}- for ev in tr.complete(status, produced):+ # A failed turn says why in the transcript, not only in the response record: fail()+ # carries the message as an error event, which the console prints under the answer.+ for ev in (tr.fail(_turn_failure_message(rec)) if status == "failed" else tr.complete(status, produced)):await bus_emit(ev)obj = tr._response_obj(status)except Exception as e: # noqa: BLE001@@ -6596,6 +6739,8 @@ async def _session_turns_data(sid: str, limit: int = 0) -> dict:# WHY an incomplete turn is incomplete ("max_steps" | "timeout" |# "interrupted"), so the console can say what actually happened instead of# one banner for every cause. Absent on records from before the field.+ # A failed turn's reason, the sentence its error event carried live.+ "error": ((rec.get("error") or {}).get("message") or None) if isinstance(rec.get("error"), dict) else None,"incomplete_reason": ((rec.get("incomplete_details") or {}).get("reason")or None),"_model": rec.get("model") or "", "_created_at": rec.get("created_at") or 0})@@ -7269,7 +7414,7 @@ async def _container_file_bytes(container_id: str, file_id: str) -> tuple[bytes,if cached is not None and path in cached:data = cached[path]media = mimetypes.guess_type(path)[0] or "application/octet-stream"- return data, media, path.rsplit("/", 1)[-1]+ return data, media, pathtf = await _workspace_tar(container_id)if tf is None:return None@@ -7286,7 +7431,7 @@ async def _container_file_bytes(container_id: str, file_id: str) -> tuple[bytes,if data is None:return Nonemedia = mimetypes.guess_type(path)[0] or "application/octet-stream"- return data, media, path.rsplit("/", 1)[-1]+ return data, media, pathreturn Nonedata = await _blob_get(f"containers/{container_id}/{file_id}", kb=RESP_BLOB_KB)if data is None:@@ -7363,101 +7508,9 @@ class WorkspaceWrite(BaseModel):content_b64: str | None = None # bytes[email protected]("/v1/sessions/{sid}/files/{path:path}")-async def read_session_file(sid: str, path: str, request: Request) -> Response:- """Read ONE file from a session's workspace, by path — the mirror of the PUT below.-- This goes through BACKING.workspace, which is the whole point: self-hosted, that is the live- directory the agent is writing into RIGHT NOW, so an app sees a file the moment a tool call- creates it. The listing route next door reads the checkpoint tarball instead, which only- exists once a turn ENDS — and an app polling it for a file the agent had already written- minutes ago sits there showing a spinner for something that is on disk.-- Unlike writing, reading during a turn is safe and is exactly what a live app wants: a- half-written deck is better than no deck, and the next read gets the rest.- """- await _owned_session(request, sid)- data = await BACKING.workspace.read(sid, path)- if data is None:- # FALL BACK TO THE DURABLE COPY. The live workspace is reaped after HR_WORKSPACE_TTL_HOURS,- # but a file this session PRODUCED was captured to a blob and is still listed by the route- # next door — so the listing showed dashboard.json while this route 404'd it, and the- # dashboard kit (which fetches by path) said "no dashboard has been built for this- # conversation" about a dashboard that existed. Seen live on a 12-day-old session.- # Also accepts a file id as the path, so an id from the listing round-trips here.- got = None- if path.startswith(("cfile_", "wf_")):- got = await _container_file_bytes(sid, path)- else:- try:- byname = await _cfile_by_name(sid)- except Exception: # noqa: BLE001 — blob store unavailable: keep the honest 404- byname = {}- cid = byname.get(path) or byname.get(path.rsplit("/", 1)[-1])- if cid:- got = await _container_file_bytes(sid, cid)- if got is not None:- data, media, _fname = got- return Response(content=data, media_type=media,- headers={"cache-control": "no-store"})- raise uhp_error(404, "file_not_found",- f"No file '{path}' in this session's workspace.", "path")- media = mimetypes.guess_type(path)[0] or "application/octet-stream"- return Response(content=data, media_type=media,- headers={"cache-control": "no-store"})--[email protected]("/v1/sessions/{sid}/files/{path:path}")-async def write_session_file(sid: str, path: str, body: WorkspaceWrite, request: Request) -> dict:- """Write or replace one file in a session's workspace.-- This is what lets an app built on a Harness own state the agent also edits — the slides kit- keeps deck.json here, so the canvas and the agent read and write the same file rather than two- copies that drift.-- Where that file physically lives differs completely by deployment, which is why it goes- through BACKING.workspace: a live directory on the data volume self-hosted, the checkpoint- tarball in blob storage hosted, where between turns that archive IS the workspace.-- REFUSED WHILE A TURN IS RUNNING, and that is the whole conflict story. Hosted, the live- sandbox would overwrite this at its next checkpoint, so the write would appear to succeed and- then vanish. Self-hosted, the agent may be editing the same file. Blocking is honest; both- sides silently racing is not.- """- # The SAME ownership check every other session route uses. Hand-rolling a second one is how- # this shipped broken: it compared v["org"], but a session vertex carries the owner in- # `tenant`, so every write 404'd on a session the caller could plainly read.- _org, v = await _owned_session(request, sid)-- live = {"running", "starting"} & {str(v.get("turn_status") or ""), str(v.get("status") or "")}- if live:- raise uhp_error(409, "session_busy",- "The agent is working on this session. Wait for the turn to finish "- "before writing to its workspace.")-- if body.content_b64 is not None:- try:- data = base64.b64decode(body.content_b64)- except Exception: # noqa: BLE001- raise uhp_error(400, "invalid_request", "content_b64 is not valid base64.") from None- elif body.content is not None:- data = body.content.encode()- else:- raise uhp_error(400, "invalid_request", "Provide content or content_b64.")-- if len(data) > _WS_WRITE_MAX:- raise uhp_error(413, "payload_too_large",- f"A workspace file written this way is limited to {_WS_WRITE_MAX} bytes.")-- ok = await BACKING.workspace.write(sid, path, data)- if not ok:- # The only ways to get here are a path that tried to leave the workspace and a storage- # failure. Both are the caller's problem to see, not something to swallow.- raise uhp_error(400, "write_failed",- "Could not write that path. It must be inside the session workspace.")- return {"session_id": sid, "path": path, "bytes": len(data), "written": True}--+# Declared BEFORE the {path:path} routes below: FastAPI matches routes in declaration order, and+# declared after them "/files/archive" was read as a file named "archive" (404 for every+# download-all click since the route was added).@app.get("/v1/sessions/{sid}/files/archive")async def session_files_archive(sid: str, request: Request, changed: bool = False, files: str = ""):"""Every artifact of a session (or one turn) as a single zip, preserving the workspace's@@ -7495,11 +7548,19 @@ async def session_files_archive(sid: str, request: Request, changed: bool = Falsnput += 1if want_ids:+ # "All" means all: an archive missing a file it was asked for is refused, with the+ # names, rather than handed over as if complete.+ missing: list[str] = []for fid in want_ids:got = await _container_file_bytes(sid, fid)- if got:- data, _media, fname = got- _add_bytes(fname, data)+ if got is None:+ missing.append(_wf_path(fid) or fid)+ continue+ data, _media, fname = got+ _add_bytes(fname, data)+ if missing:+ raise HTTPException(404, f"{len(missing)} of {len(want_ids)} files are no longer available: "+ + ", ".join(missing[:5]) + (", …" if len(missing) > 5 else ""))elif changed:blob = await _blob_get(f"sessions/{sid}/changed.json", kb=RESP_BLOB_KB)try:@@ -7565,6 +7626,101 @@ async def session_files_archive(sid: str, request: Request, changed: bool = Falsf'attachment; filename="{sid[:20]}-{scope}-files.zip"'})[email protected]("/v1/sessions/{sid}/files/{path:path}")+async def read_session_file(sid: str, path: str, request: Request) -> Response:+ """Read ONE file from a session's workspace, by path — the mirror of the PUT below.++ This goes through BACKING.workspace, which is the whole point: self-hosted, that is the live+ directory the agent is writing into RIGHT NOW, so an app sees a file the moment a tool call+ creates it. The listing route next door reads the checkpoint tarball instead, which only+ exists once a turn ENDS — and an app polling it for a file the agent had already written+ minutes ago sits there showing a spinner for something that is on disk.++ Unlike writing, reading during a turn is safe and is exactly what a live app wants: a+ half-written deck is better than no deck, and the next read gets the rest.+ """+ await _owned_session(request, sid)+ data = await BACKING.workspace.read(sid, path)+ if data is None:+ # FALL BACK TO THE DURABLE COPY. The live workspace is reaped after HR_WORKSPACE_TTL_HOURS,+ # but a file this session PRODUCED was captured to a blob and is still listed by the route+ # next door — so the listing showed dashboard.json while this route 404'd it, and the+ # dashboard kit (which fetches by path) said "no dashboard has been built for this+ # conversation" about a dashboard that existed. Seen live on a 12-day-old session.+ # Also accepts a file id as the path, so an id from the listing round-trips here.+ got = None+ if path.startswith(("cfile_", "wf_")):+ got = await _container_file_bytes(sid, path)+ else:+ try:+ byname = await _cfile_by_name(sid)+ except Exception: # noqa: BLE001 — blob store unavailable: keep the honest 404+ byname = {}+ cid = byname.get(path) or byname.get(path.rsplit("/", 1)[-1])+ if cid:+ got = await _container_file_bytes(sid, cid)+ if got is not None:+ data, media, _fname = got+ return Response(content=data, media_type=media,+ headers={"cache-control": "no-store"})+ raise uhp_error(404, "file_not_found",+ f"No file '{path}' in this session's workspace.", "path")+ media = mimetypes.guess_type(path)[0] or "application/octet-stream"+ return Response(content=data, media_type=media,+ headers={"cache-control": "no-store"})++[email protected]("/v1/sessions/{sid}/files/{path:path}")+async def write_session_file(sid: str, path: str, body: WorkspaceWrite, request: Request) -> dict:+ """Write or replace one file in a session's workspace.++ This is what lets an app built on a Harness own state the agent also edits — the slides kit+ keeps deck.json here, so the canvas and the agent read and write the same file rather than two+ copies that drift.++ Where that file physically lives differs completely by deployment, which is why it goes+ through BACKING.workspace: a live directory on the data volume self-hosted, the checkpoint+ tarball in blob storage hosted, where between turns that archive IS the workspace.++ REFUSED WHILE A TURN IS RUNNING, and that is the whole conflict story. Hosted, the live+ sandbox would overwrite this at its next checkpoint, so the write would appear to succeed and+ then vanish. Self-hosted, the agent may be editing the same file. Blocking is honest; both+ sides silently racing is not.+ """+ # The SAME ownership check every other session route uses. Hand-rolling a second one is how+ # this shipped broken: it compared v["org"], but a session vertex carries the owner in+ # `tenant`, so every write 404'd on a session the caller could plainly read.+ _org, v = await _owned_session(request, sid)++ live = {"running", "starting"} & {str(v.get("turn_status") or ""), str(v.get("status") or "")}+ if live:+ raise uhp_error(409, "session_busy",+ "The agent is working on this session. Wait for the turn to finish "+ "before writing to its workspace.")++ if body.content_b64 is not None:+ try:+ data = base64.b64decode(body.content_b64)+ except Exception: # noqa: BLE001+ raise uhp_error(400, "invalid_request", "content_b64 is not valid base64.") from None+ elif body.content is not None:+ data = body.content.encode()+ else:+ raise uhp_error(400, "invalid_request", "Provide content or content_b64.")++ if len(data) > _WS_WRITE_MAX:+ raise uhp_error(413, "payload_too_large",+ f"A workspace file written this way is limited to {_WS_WRITE_MAX} bytes.")++ ok = await BACKING.workspace.write(sid, path, data)+ if not ok:+ # The only ways to get here are a path that tried to leave the workspace and a storage+ # failure. Both are the caller's problem to see, not something to swallow.+ raise uhp_error(400, "write_failed",+ "Could not write that path. It must be inside the session workspace.")+ return {"session_id": sid, "path": path, "bytes": len(data), "written": True}++@app.get("/v1/containers/{container_id}/files/{file_id}/content")async def container_file_content(container_id: str, file_id: str, request: Request):await _owned_session(request, container_id) # V1C02-004: container_id IS the session id@@ -7573,7 +7729,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}"'})+ headers={"Content-Disposition": f'attachment; filename="{fname.rsplit("/", 1)[-1]}"'})# Office types with no faithful browser renderer → convert to PDF server-side (LibreOffice) so thediff --git a/gateway/tests/test_aggregator_slugs.py b/gateway/tests/test_aggregator_slugs.pynew file mode 100644index 00000000..284da35d--- /dev/null+++ b/gateway/tests/test_aggregator_slugs.py@@ -0,0 +1,16 @@+"""TokenRouter keeps the plain slug; OpenRouter's dated rename stays on OpenRouter's list only."""+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import app as gw # noqa: E402+++def test_tokenrouter_serves_the_plain_slug_and_openrouter_the_dated_one():+ assert gw._VENDOR_MODELS["tokenrouter"]["qwen3.8-max"] == "qwen/qwen3.8-max"+ assert gw._VENDOR_MODELS["openrouter"]["qwen3.8-max"] == "qwen/qwen3.8-max-0902"+++def test_the_mapper_hands_each_aggregator_its_own_name():+ assert gw._map_model({"provider": "tokenrouter", "backend": "hermes"}, "qwen3.8-max") == "qwen/qwen3.8-max"+ assert gw._map_model({"provider": "openrouter", "backend": "hermes"}, "qwen3.8-max") == "qwen/qwen3.8-max-0902"diff --git a/gateway/tests/test_broker_provider_base.py b/gateway/tests/test_broker_provider_base.pynew file mode 100644index 00000000..39ed9351--- /dev/null+++ b/gateway/tests/test_broker_provider_base.py@@ -0,0 +1,46 @@+"""A direct provider's key needs no endpoint from the user: the broker knows the provider's own."""+import asyncio+import pathlib+import sys++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+import app as gw # noqa: E402+++def _doc(monkeypatch, integrations):+ async def doc(*_a, **_k):+ return integrations+ monkeypatch.setattr(gw, "_integrations_doc", doc)+++def test_an_openai_key_resolves_to_openais_endpoint(monkeypatch):+ _doc(monkeypatch, [{"name": "default", "provider": "OpenAI", "config": {"api_key": "sk-proj-x"}}])+ conn = asyncio.run(gw._broker_resolve("integration:default", "org.a"))+ assert conn["base_url"] == "https://api.openai.com/v1" and conn["api_key"] == "sk-proj-x"+++def test_an_anthropic_key_resolves_to_anthropics_endpoint(monkeypatch):+ _doc(monkeypatch, [{"name": "k", "provider": "anthropic", "config": {"api_key": "sk-ant-x"}}])+ conn = asyncio.run(gw._broker_resolve("integration:k", "org.a"))+ assert conn["base_url"] == "https://api.anthropic.com/v1"+++def test_a_connection_with_its_own_endpoint_keeps_it(monkeypatch):+ _doc(monkeypatch, [{"name": "v", "provider": "vercel", "config": {"api_key": "vck_x", "base_url": "https://ai-gateway.vercel.sh/v1"}}])+ conn = asyncio.run(gw._broker_resolve("integration:v", "org.a"))+ assert conn["base_url"] == "https://ai-gateway.vercel.sh/v1"+++def test_a_gateway_without_an_endpoint_stays_without_one(monkeypatch):+ _doc(monkeypatch, [{"name": "o", "provider": "openrouter", "config": {"api_key": "sk-or-x"}}])+ conn = asyncio.run(gw._broker_resolve("integration:o", "org.a"))+ assert not conn.get("base_url"), "only direct providers get a default endpoint"+++def test_a_vault_connection_gets_the_default_too(monkeypatch):+ async def get(_org, _name):+ return {"provider": "openai", "api_key": "sk-x"}, "org.a"+ _doc(monkeypatch, [])+ monkeypatch.setattr(gw, "_get_connection", get)+ conn = asyncio.run(gw._broker_resolve("openai", "org.a"))+ assert conn["base_url"] == "https://api.openai.com/v1"diff --git a/gateway/tests/test_card_settle.py b/gateway/tests/test_card_settle.pynew file mode 100644index 00000000..cb8f015e--- /dev/null+++ b/gateway/tests/test_card_settle.py@@ -0,0 +1,45 @@+"""A task card that still says running repairs itself from the session vertex on the next list."""+import asyncio+import sys+import time+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import app as gw # noqa: E402+++def _wire(monkeypatch, vertex, indexed):+ async def vget(sid): return vertex+ async def index(base, m): indexed.append((base, dict(m)))+ monkeypatch.setattr(gw, "_vertex_get", vget)+ monkeypatch.setattr(gw, "_index_manifest", index)+ monkeypatch.setattr(gw, "_prefix_from_vertex", lambda sid, v: "org/1_sid")+++def test_a_terminal_vertex_settles_the_card(monkeypatch):+ indexed = []+ _wire(monkeypatch, {"status": "failed", "turn_status": "failed", "heartbeat": str(time.time())}, indexed)+ m = asyncio.run(gw._card_settle("sid", {"session_id": "sid", "status": "running"}))+ assert m["status"] == "failed"+ assert indexed and indexed[0][1]["status"] == "failed", "every mirror is rewritten"+++def test_a_live_turn_is_left_alone(monkeypatch):+ indexed = []+ _wire(monkeypatch, {"status": "running", "turn_status": "running", "heartbeat": str(time.time())}, indexed)+ assert asyncio.run(gw._card_settle("sid", {"session_id": "sid", "status": "running"})) is None+ assert not indexed+++def test_a_dead_heartbeat_past_the_cap_reads_failed(monkeypatch):+ indexed = []+ _wire(monkeypatch, {"status": "running", "turn_status": "running", "heartbeat": str(time.time() - gw._GW_MAX_TURN_S - 5)}, indexed)+ m = asyncio.run(gw._card_settle("sid", {"session_id": "sid", "status": "running"}))+ assert m["status"] == "failed" and indexed+++def test_an_already_matching_card_is_not_rewritten(monkeypatch):+ indexed = []+ _wire(monkeypatch, {"status": "failed", "turn_status": "failed"}, indexed)+ assert asyncio.run(gw._card_settle("sid", {"session_id": "sid", "status": "failed"})) is None+ assert not indexeddiff --git a/gateway/tests/test_codex_family_switch.py b/gateway/tests/test_codex_family_switch.pynew file mode 100644index 00000000..d841ab6e--- /dev/null+++ b/gateway/tests/test_codex_family_switch.py@@ -0,0 +1,24 @@+"""gpt-5.3-codex cannot run in a Codex task another model family has used: refused in words."""+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import app as gw # noqa: E402+++def test_families():+ assert gw._codex_family("gpt-5.3-codex") == "codex"+ assert gw._codex_family("gpt-5.5") == "gpt" and gw._codex_family("gpt-5.6-sol") == "gpt"+++def test_codex_model_after_another_family_is_refused_in_words():+ why = gw._codex_switch_refusal(["gpt-5.5"], "gpt-5.3-codex")+ assert "already used gpt-5.5" in why and "Start a new task for gpt-5.3-codex." in why+ assert gw._codex_switch_refusal(["gpt-5.3-codex", "gpt-5.6-sol"], "gpt-5.3-codex"), "a switch away and back"+++def test_the_other_models_run_anywhere_and_codex_stays_within_its_own():+ assert gw._codex_switch_refusal(["gpt-5.3-codex"], "gpt-5.5") == "", "measured: gpt-5.5 acts in a gpt-5.3-codex thread"+ assert gw._codex_switch_refusal(["gpt-5.5"], "gpt-5.4") == ""+ assert gw._codex_switch_refusal(["gpt-5.3-codex"], "gpt-5.3-codex") == ""+ assert gw._codex_switch_refusal([], "gpt-5.3-codex") == ""diff --git a/gateway/tests/test_files_archive.py b/gateway/tests/test_files_archive.pynew file mode 100644index 00000000..f97e3d2f--- /dev/null+++ b/gateway/tests/test_files_archive.py@@ -0,0 +1,52 @@+"""The archive of a turn's cited files keeps the workspace's folders, keeps two files that share a+basename, and is refused with the names when a cited file is no longer there: "all" means all."""+import io+import zipfile++from fastapi.testclient import TestClient++import app as gw+++async def _async_value(v):+ return v+++def _wire(monkeypatch, tmp_path, files: dict[str, bytes | None]):+ 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))++ async def bytes_of(sid, fid):+ path = gw._wf_path(fid)+ data = files.get(path)+ return None if data is None else (data, "text/plain", path)+ monkeypatch.setattr(gw, "_container_file_bytes", bytes_of)+++def test_the_archive_keeps_folders_and_same_named_files(monkeypatch, tmp_path):+ files = {"travel/__init__.py": b"a", "output/__init__.py": b"b", "README.md": b"c"}+ _wire(monkeypatch, tmp_path, files)+ ids = ",".join(gw._wf_id(p) for p in files)+ r = TestClient(gw.app).get(f"/v1/sessions/s1/files/archive?files={ids}")+ assert r.status_code == 200+ names = sorted(zipfile.ZipFile(io.BytesIO(r.content)).namelist())+ assert names == ["README.md", "output/__init__.py", "travel/__init__.py"]+++def test_a_missing_cited_file_refuses_the_archive_by_name(monkeypatch, tmp_path):+ files = {"README.md": b"c", "output/gone.json": None}+ _wire(monkeypatch, tmp_path, files)+ ids = ",".join(gw._wf_id(p) for p in files)+ r = TestClient(gw.app).get(f"/v1/sessions/s1/files/archive?files={ids}")+ assert r.status_code == 404+ assert "1 of 2 files" in r.text and "output/gone.json" in r.text+++def test_the_single_download_names_the_file_without_its_folder(monkeypatch):+ async def bytes_of(cid, fid):+ return (b"x", "text/plain", "deep/folder/notes.txt")+ 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"'diff --git a/gateway/tests/test_model_catalog_capabilities.py b/gateway/tests/test_model_catalog_capabilities.pyindex 3dce9b9d..d8b0cb2b 100644--- a/gateway/tests/test_model_catalog_capabilities.py+++ b/gateway/tests/test_model_catalog_capabilities.py@@ -34,7 +34,14 @@ def _vendor_models() -> dict[str, dict[str, str]]:src = open(_SRC).read()m = re.search(r"_VENDOR_MODELS: dict\[str, dict\[str, str\]\] = (\{.*?\n\})\n", src, re.S)assert m, "_VENDOR_MODELS not found in app.py"- return eval(m.group(1), {"__builtins__": {}}, {}) # noqa: S307 — our own literal+ tables = eval(m.group(1), {"__builtins__": {}}, {}) # noqa: S307 — our own literal+ # OpenRouter's own renames are applied at import in app.py, after TokenRouter takes its copy+ # of the shared table; mirror that so this reads what OpenRouter is actually asked for.+ r = re.search(r"_OPENROUTER_RESLUG = (\{.*?\n\})\n", src, re.S)+ if r:+ reslug = eval(r.group(1), {"__builtins__": {}}, {}) # noqa: S307+ tables["openrouter"] = {c: reslug.get(c, v) for c, v in tables["openrouter"].items()}+ return tablesdef _catalog() -> dict[str, dict]:diff --git a/gateway/tests/test_turn_failure_message.py b/gateway/tests/test_turn_failure_message.pynew file mode 100644index 00000000..dd1443e0--- /dev/null+++ b/gateway/tests/test_turn_failure_message.py@@ -0,0 +1,27 @@+"""A failed turn names the org's own key's refusal when that is why it stopped."""+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import app as gw # noqa: E402+++def test_own_key_refusal_is_said_in_words():+ rec = {"tried": [{"connection": "openai", "status": "failed", "error": "OpenAI API error (401): invalid api key"}],+ "error_message": "Your openai key was refused: OpenAI API error (401): invalid api key"}+ assert gw._turn_failure_message(rec) == "Your openai key was refused: OpenAI API error (401): invalid api key"+++def test_an_exhausted_chain_lists_what_was_tried():+ rec = {"tried": [{"connection": "a", "error": "not found"}, {"connection": "b", "status": "failed", "error": "boom"}]}+ m = gw._turn_failure_message(rec)+ assert '"a"' in m and "boom" in m+++def test_nothing_tried_still_says_something():+ assert gw._turn_failure_message({}) == "turn failed"+++def test_only_a_refusal_reads_as_a_refused_key():+ assert gw._PROVIDER_REFUSAL_RE.search("OpenAI API error (401): invalid api key")+ assert not gw._PROVIDER_REFUSAL_RE.search("no rollout found for thread id 01a06ea9")diff --git a/runner/server.py b/runner/server.pyindex b14a3cf6..0f55406f 100644--- a/runner/server.py+++ b/runner/server.py@@ -1266,10 +1266,72 @@ wire_api = "{wire_api}"network_access = trueexclude_slash_tmp = false"""+_CODEX_ALIAS_TMPL = """[model_providers.{alias}]+name = "{name}"+base_url = "{base_url}"+env_key = "{env_key}"+wire_api = "{wire_api}"+"""+++_PROVIDER_REFUSAL = re.compile(r"\b(401|403|429|5\d\d)\b|unauthori[sz]ed|incorrect api key|invalid_api_key|invalid api key|"+ r"insufficient_quota|rate limit|quota|forbidden", re.IGNORECASE)+++def _codex_session_provider_ids(cfg_dir: "pathlib.Path") -> list[str]:+ """Every model provider id the session's rollouts name. Codex looks the recorded id up in the+ config on resume, so a session started under another provider (or under the bare ids of+ before the namespacing) fails to load unless the config still declares it."""+ import glob as _glob+ ids: list[str] = []+ for path in _glob.glob(str(cfg_dir / "sessions" / "**" / "*.jsonl"), recursive=True):+ try:+ for line in pathlib.Path(path).read_text().splitlines():+ if '"model_provider"' not in line:+ continue+ for m in re.finditer(r'"model_provider"\s*:\s*"([^"]+)"', line):+ if m.group(1) not in ids:+ ids.append(m.group(1))+ except OSError:+ continue+ return ids+++# What a follow-up reads when its Codex history is not in the workspace any more: the task goes+# on in the same workspace with its files, without the earlier exchanges.+_CODEX_NO_ROLLOUT_NOTE = "The earlier conversation of this task is no longer available to Codex. Continuing in the same workspace with its files."+++def _codex_resume_thread_id(cfg_dir: "pathlib.Path", wanted: str | None) -> str | None:+ """The thread id the app-server can resume in this CODEX_HOME: the wanted one when its rollout+ is here, else the newest rollout's own id (the home is per session, so the newest rollout IS+ this conversation, the same rule `exec resume --last` relies on; matching the wanted id alone+ missed about a third of the time and answered "no rollout found for thread id"). None when+ there is no rollout at all."""+ import glob as _glob+ paths = _glob.glob(str(cfg_dir / "sessions" / "**" / "*.jsonl"), recursive=True)+ if not paths:+ return None+ ids: list[tuple[float, str]] = []+ for path in paths:+ try:+ with open(path) as fh:+ for line in fh:+ if '"session_meta"' not in line:+ continue+ m = re.search(r'"id"\s*:\s*"([^"]+)"', line)+ if m:+ ids.append((os.path.getmtime(path), m.group(1)))+ break+ except OSError:+ continue+ if wanted and any(i == wanted for _, i in ids):+ return wanted+ return max(ids)[1] if ids else Nonedef _codex_prepare_env(provider: str, auth: Auth, model: str, cwd: str,- env: dict, mcp_toml: str = "") -> "pathlib.Path":+ env: dict, mcp_toml: str = "", resume: bool = False) -> "pathlib.Path":"""Shared codex setup for BOTH exec and app-server: write config.toml (model/provider/base_url +MCP), point CODEX_HOME at the checkpointed workspace, set provider auth + TMPDIR. Returns theCODEX_HOME dir. Mutates env."""@@ -1294,6 +1356,16 @@ def _codex_prepare_env(provider: str, auth: Auth, model: str, cwd: str,model=model, provider=f"hr-{p}", effort=CODEX_REASONING_EFFORT, ctx=CODEX_CONTEXT_WINDOW,name=spec["name"], base_url=base_url, env_key=spec["env_key"],wire_api=auth.wire_api or "responses")+ if resume:+ # A resumed session keeps the provider id it started under; Codex looks that id up in the+ # config and refuses to load without it ("Model provider `azure` not found", a July+ # session continued on 2026-09-05; "hr-tokenrouter not found", a session continued on the+ # org's own key). Every id the session ever ran under is declared, at THIS turn's endpoint.+ for alias in _codex_session_provider_ids(cfg_dir):+ if alias == f"hr-{p}" or alias == "openai": # the current one; a reserved built-in+ continue+ cfg += _CODEX_ALIAS_TMPL.format(alias=alias, name=spec["name"], base_url=base_url,+ env_key=spec["env_key"], wire_api=auth.wire_api or "responses")if mcp_toml: # owner-attached MCP servers via Codex's experimental rmcp HTTP clientcfg += mcp_toml(cfg_dir / "config.toml").write_text(cfg)@@ -1403,8 +1475,9 @@ def _sanitize_codex_rollout(rollouts: list[str]) -> dict:def _build_codex(provider: str, auth: Auth, model: str, prompt: str, cwd: str,- env: dict, mcp_toml: str = "", resume_session_id: str | None = None) -> list[str]:- cfg_dir = _codex_prepare_env(provider, auth, model, cwd, env, mcp_toml)+ env: dict, mcp_toml: str = "", resume_session_id: str | None = None) -> tuple[list[str], str]:+ """The exec command, and the note the transcript must carry when a follow-up's rollout is gone."""+ cfg_dir = _codex_prepare_env(provider, auth, model, cwd, env, mcp_toml, resume=bool(resume_session_id))# Drop --ephemeral so codex PERSISTS the rollout to $CODEX_HOME/sessions (inside the checkpointed# workspace) — that's what makes a follow-up history-aware. Mirror the claude resume guard: only# `resume <id>` if the rollout is actually present in the (re)hydrated workspace, else start fresh@@ -1425,9 +1498,10 @@ def _build_codex(provider: str, auth: Auth, model: str, prompt: str, cwd: str,# the most-recent rollout here IS this conversation. Resume by --last instead of matching# the thread UUID to the rollout filename (that match is codex-version-fragile and missed# ~1/3 of the time). --last is exact here precisely because the home is session-isolated.- return ["codex", "exec", "resume", "--last", *common, prompt]+ return ["codex", "exec", "resume", "--last", *common, prompt], ""print(f"[resume] codex: no rollout in workspace for {resume_session_id} — starting fresh", flush=True)- return ["codex", "exec", *common, "--cd", cwd, prompt]+ return ["codex", "exec", *common, "--cd", cwd, prompt], _CODEX_NO_ROLLOUT_NOTE+ return ["codex", "exec", *common, "--cd", cwd, prompt], ""# ── dsh (DeepSeek Harness) ──────────────────────────────────────────────────────@@ -3007,9 +3081,28 @@ def _opencode_to_claude(obj: dict, state: dict) -> list[dict]:st = part.get("state") if isinstance(part.get("state"), dict) else {}if st.get("status") == "error":state.setdefault("_oc_tool_errors", []).append(str(st.get("error") or ""))- return pre + [{"type": "assistant", "message": {"content": [- {"type": "tool_use", "id": part.get("id") or "tool",- "name": part.get("tool") or "tool", "input": st.get("input") or {}}]}}]+ # opencode reports a tool once it has finished, with its own clock (state.time, ms): the+ # call is stamped at its start and its result at its end, so the trace shows the seconds+ # the tool actually ran. Stamped at arrival, a 25 s command showed as the 15 s AFTER it.+ tid = part.get("id") or "tool"+ tm = st.get("time") if isinstance(st.get("time"), dict) else {}+ try:+ t_start = float(tm.get("start") or 0) / 1000.0+ t_end = float(tm.get("end") or 0) / 1000.0+ except (TypeError, ValueError):+ t_start = t_end = 0.0+ call = {"type": "assistant", "message": {"content": [+ {"type": "tool_use", "id": tid, "name": part.get("tool") or "tool", "input": st.get("input") or {}}]}}+ if t_start > 0:+ call["_ts"] = t_start+ if st.get("status") not in ("completed", "error"):+ return pre + [call]+ res = {"type": "user", "message": {"content": [+ {"type": "tool_result", "tool_use_id": tid, "is_error": st.get("status") == "error",+ "content": str(st.get("output") or st.get("error") or "")}]}}+ if t_end > 0:+ res["_ts"] = max(t_end, t_start)+ return pre + [call, res]if t == "step_finish":_opencode_usage_add(state, part.get("tokens"))return pre@@ -3131,7 +3224,7 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, mexcept Exception: # noqa: BLE001continuefor ev in normalize(obj, state):- ev["_ts"] = time.time()+ ev.setdefault("_ts", time.time())with _turns_lock:rec["events"].append(ev)if ev.get("type") == "system" and ev.get("subtype") == "init" and ev.get("session_id"):@@ -3153,7 +3246,7 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, meof = getattr(normalize, "eof", None)if eof is not None and result_ev is None:for ev in eof(state, rc):- ev["_ts"] = time.time()+ ev.setdefault("_ts", time.time())with _turns_lock:rec["events"].append(ev)if ev.get("type") == "result":@@ -3168,7 +3261,10 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, mif rec["status"] in ("failed", "error", "timeout"):tail = "\n".join(errbuf[-30:]).strip()ev_err = (result_ev or {}).get("result") or (result_ev or {}).get("error") or ""- rec["error"] = (str(ev_err).strip() or tail or f"exit_code={rc}, no diagnostic output")[:2000]+ # The provider's refusal is the line that explains a failure; the CLI's last lines are+ # usually its retries ("Reconnecting... 1/5"). Say the refusal when there is one.+ refusal = next((ln.strip() for ln in errbuf if _PROVIDER_REFUSAL.search(ln)), "")+ rec["error"] = (refusal or str(ev_err).strip() or tail or f"exit_code={rc}, no diagnostic output")[:2000]if result_ev is not None and not str(result_ev.get("result") or "").strip() and tail:result_ev["result"] = tail[:2000] # so the trace's result event isn't empty eitherrec["done"] = True@@ -3181,16 +3277,43 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, m_CODEX_SANDBOX = os.environ.get("CODEX_APPSERVER_SANDBOX", "danger-full-access") # kebab enum; env-tunable+def _codex_thread_request(resume_session_id: str | None, cwd: str, model: str) -> tuple[str, dict]:+ """The app-server request that opens this turn's thread, with its params.++ A resumed thread takes THIS turn's model and settings too, not only its id: a thread resumed+ bare keeps the tool set of the model it started with, and a turn on another model family+ (gpt-5.3-codex after gpt-5.5) then narrates its work instead of calling tools (reproduced+ three times, 2026-09-05). One params dict serves both requests so they cannot drift."""+ params = {"cwd": cwd, "model": model, "sandbox": _CODEX_SANDBOX, "approvalPolicy": "never"}+ if resume_session_id:+ return "thread/resume", {"threadId": resume_session_id, **params}+ return "thread/start", params++def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, prompt: str,resume_session_id: str | None, timeout_seconds: int | None) -> None:rec = _turns[turn_id]state = {"final": ""}def append(ev: dict) -> None:- ev["_ts"] = time.time()+ ev.setdefault("_ts", time.time())with _turns_lock:rec["events"].append(ev)+ # Resume what is actually in this home (see _codex_resume_thread_id), sanitised like the exec+ # path; a follow-up whose rollout is gone starts fresh in the same workspace and says so.+ resume_thread = None+ if resume_session_id:+ cfg_dir = pathlib.Path(env.get("CODEX_HOME") or (pathlib.Path(env.get("HOME") or cwd) / ".codex"))+ resume_thread = _codex_resume_thread_id(cfg_dir, resume_session_id)+ if resume_thread:+ import glob as _glob+ c = _sanitize_codex_rollout(_glob.glob(str(cfg_dir / "sessions" / "**" / "*.jsonl"), recursive=True))+ print(f"[resume] codex app-server: thread {resume_thread}{' (newest rollout, wanted ' + resume_session_id + ')' if resume_thread != resume_session_id else ''}; "+ f"dropped {c['reasoning']} reasoning blob(s), de-referenced {c['deref']} id(s)", flush=True)+ else:+ print(f"[resume] codex app-server: no rollout in workspace for {resume_session_id} — starting fresh", flush=True)+ append({"type": "assistant", "message": {"content": [{"type": "text", "text": _CODEX_NO_ROLLOUT_NOTE}]}})try:proc = subprocess.Popen(["codex", "app-server"], cwd=cwd, env=env, text=True, bufsize=1,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,@@ -3251,9 +3374,7 @@ def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, prompres = msg.get("result") or {}if mid == id_init:send("initialized", {}, notify=True)- id_thread = (send("thread/resume", {"threadId": resume_session_id}) if resume_session_id- else send("thread/start", {"cwd": cwd, "model": model,- "sandbox": _CODEX_SANDBOX, "approvalPolicy": "never"}))+ id_thread = send(*_codex_thread_request(resume_thread, cwd, model))elif mid == id_thread:thread_id = ((res.get("thread") or {}).get("id")) or resume_session_id or ""if thread_id:@@ -3445,7 +3566,7 @@ def _run_hermes_bg(turn_id: str, cwd: str, env: dict, model: str, provider: str,t0 = time.time()def append(ev: dict) -> None:- ev["_ts"] = time.time()+ ev.setdefault("_ts", time.time())with _turns_lock:rec["events"].append(ev)@@ -4062,16 +4183,17 @@ def turn(req: TurnReq, identifier: str = "") -> dict:model = req.model or spec["default_model"]use_appserver = backend == "codex" and bool(req.codex_appserver)cmd = None+ codex_note = ""hermes_provider = ""hermes_mcp: list[str] = []if backend == "codex":model = model or CODEX_DEFAULT_MODELmcp_toml = _codex_mcp_toml(req.mcp_servers)if use_appserver:- _codex_prepare_env(req.provider, auth, model, cwd, env, mcp_toml) # config.toml + CODEX_HOME + auth+ _codex_prepare_env(req.provider, auth, model, cwd, env, mcp_toml, resume=bool(req.resume_session_id)) # config.toml + CODEX_HOME + authelse:- cmd = _build_codex(req.provider, auth, model, req.prompt, cwd, env,- mcp_toml=mcp_toml, resume_session_id=req.resume_session_id)+ cmd, codex_note = _build_codex(req.provider, auth, model, req.prompt, cwd, env,+ mcp_toml=mcp_toml, resume_session_id=req.resume_session_id)elif backend == "hermes":model = model or HERMES_DEFAULT_MODELhermes_provider = (req.provider or "bedrock").lower()@@ -4124,6 +4246,9 @@ def turn(req: TurnReq, identifier: str = "") -> dict:"host": socket.gethostname(), "deduplicated": True, "max_seconds": MAX_TURN_SECONDS}_turns[turn_id] = {"status": "running", "events": [], "result": "", "done": False,"backend": backend, "model": model, "started": time.time()}+ if codex_note: # the follow-up's Codex history was not here: the transcript says so first+ _turns[turn_id]["events"].append({"type": "assistant", "_ts": time.time(),+ "message": {"content": [{"type": "text", "text": codex_note}]}})if key:_turn_by_key[key] = turn_idif use_appserver:diff --git a/runner/tests/test_codex_appserver_thread.py b/runner/tests/test_codex_appserver_thread.pynew file mode 100644index 00000000..aa3b0b33--- /dev/null+++ b/runner/tests/test_codex_appserver_thread.py@@ -0,0 +1,21 @@+"""A resumed Codex app-server thread takes this turn's model and settings, not only its id."""+import pathlib+import sys++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+import server # noqa: E402+++def test_a_resumed_thread_carries_this_turns_model_and_settings():+ method, params = server._codex_thread_request("thr_1", "/work", "gpt-5.3-codex")+ assert method == "thread/resume"+ assert params["threadId"] == "thr_1"+ assert params["model"] == "gpt-5.3-codex" and params["cwd"] == "/work"+ assert params["sandbox"] == server._CODEX_SANDBOX and params["approvalPolicy"] == "never"+++def test_a_fresh_thread_starts_with_the_same_settings():+ method, params = server._codex_thread_request(None, "/work", "gpt-5.5")+ assert method == "thread/start" and "threadId" not in params+ _, resumed = server._codex_thread_request("thr_2", "/work", "gpt-5.5")+ assert {k: v for k, v in resumed.items() if k != "threadId"} == paramsdiff --git a/runner/tests/test_codex_reasoning_strip.py b/runner/tests/test_codex_reasoning_strip.pyindex db50d2f3..a3cdd2d3 100644--- a/runner/tests/test_codex_reasoning_strip.py+++ b/runner/tests/test_codex_reasoning_strip.py@@ -159,3 +159,43 @@ def test_tolerates_missing_and_malformed(tmp_path):assert "not json at all" in textassert "encrypted_content" not in textassert '"rs_1"' in text+++def test_a_resumed_session_keeps_every_provider_id_it_ran_under(tmp_path, monkeypatch):+ """Codex looks the rollout's recorded provider id up in the config on resume. A session started+ on the platform's TokenRouter (hr-tokenrouter), or before the ids were namespaced (azure), and+ continued on the org's own OpenAI key must still load: the config declares those ids too, at+ this turn's endpoint."""+ from server import Auth, _codex_prepare_env+ home = tmp_path / "home"; sess = home / ".codex" / "sessions" / "2026" / "07"; sess.mkdir(parents=True)+ (sess / "rollout-1.jsonl").write_text('{"type": "session_meta", "payload": {"id": "s1", "model_provider": "hr-tokenrouter"}}\n'+ '{"type": "turn_context", "payload": {"model": "gpt-5.5", "model_provider": "azure"}}\n')+ env = {"HOME": str(home)}+ _codex_prepare_env("openai", Auth(api_key="sk-x", base_url="https://broker.example/v1/llm"), "gpt-5.4-mini", str(tmp_path), env, resume=True)+ cfg = (home / ".codex" / "config.toml").read_text()+ assert 'model_provider = "hr-openai"' in cfg and "[model_providers.hr-openai]" in cfg+ assert "[model_providers.hr-tokenrouter]" in cfg and "[model_providers.azure]" in cfg+ assert cfg.count('base_url = "https://broker.example/v1/llm"') == 3, "every alias points at this turn's endpoint"+ fresh = {"HOME": str(tmp_path / "fresh")}+ _codex_prepare_env("openai", Auth(api_key="sk-x", base_url="https://broker.example/v1/llm"), "gpt-5.4-mini", str(tmp_path), fresh, resume=False)+ assert "[model_providers.hr-tokenrouter]" not in (tmp_path / "fresh" / ".codex" / "config.toml").read_text(), "a fresh session declares only its own"+++def test_a_failure_names_the_providers_refusal_over_the_clis_retries():+ from server import _PROVIDER_REFUSAL+ lines = ["Reading prompt from stdin...", "ERROR: 401 Unauthorized: Incorrect API key provided", "Reconnecting... 1/5", "Reconnecting... 2/5"]+ assert next((ln for ln in lines if _PROVIDER_REFUSAL.search(ln)), "") == "ERROR: 401 Unauthorized: Incorrect API key provided"+ assert not _PROVIDER_REFUSAL.search("Reconnecting... 1/5")+++def test_app_server_resumes_the_rollout_that_is_here(tmp_path):+ """The wanted thread when its rollout is here; else the newest rollout's own id; None with no rollout."""+ from server import _codex_resume_thread_id+ home = tmp_path / ".codex"; sess = home / "sessions" / "2026" / "09"; sess.mkdir(parents=True)+ assert _codex_resume_thread_id(home, "t-wanted") is None+ (sess / "rollout-a.jsonl").write_text('{"type": "session_meta", "payload": {"id": "t-old"}}\n')+ import os, time+ os.utime(sess / "rollout-a.jsonl", (time.time() - 100, time.time() - 100))+ (sess / "rollout-b.jsonl").write_text('{"type": "session_meta", "payload": {"id": "t-new"}}\n')+ assert _codex_resume_thread_id(home, "t-old") == "t-old", "the wanted rollout is here"+ assert _codex_resume_thread_id(home, "t-missing") == "t-new", "not here: the newest rollout is this conversation"diff --git a/runner/tests/test_codex_sandbox.py b/runner/tests/test_codex_sandbox.pyindex 8aa012b7..15c59310 100644--- a/runner/tests/test_codex_sandbox.py+++ b/runner/tests/test_codex_sandbox.py@@ -49,7 +49,7 @@ def test_exec_path_passes_bypass_flag(tmp_path):# `codex exec` disables its own sandbox ONLY via this flag; losing it re-enables read-only.home = tmp_path / "home"home.mkdir()- argv = rn._build_codex(+ argv, _ = rn._build_codex("azure",rn.Auth(api_key="sk-test", base_url="https://example.invalid/v1", wire_api="responses"),"gpt-5.5", "hello", str(tmp_path), {"HOME": str(home)},diff --git a/runner/tests/test_opencode_normalize.py b/runner/tests/test_opencode_normalize.pyindex e606a2ce..ffec0f95 100644--- a/runner/tests/test_opencode_normalize.py+++ b/runner/tests/test_opencode_normalize.py@@ -352,3 +352,29 @@ def test_config_lives_under_harness_not_the_workspace_root():assert not os.path.exists(f"{d}/opencode.json")assert os.path.exists(f"{d}/.harness/opencode.json")assert env["OPENCODE_CONFIG"] == f"{d}/.harness/opencode.json"+++def test_a_finished_tool_keeps_its_own_clock_and_carries_its_result():+ """opencode reports a tool once it is done. Its state.time (ms) stamps the call at the start+ and the result at the end, so the seconds in between meter as agent work; the output rides+ on the result so the trace shows it."""+ out, _ = _run([_ev("tool_use", part={"type": "tool", "id": "prt_9", "tool": "bash",+ "state": {"status": "completed", "input": {"command": "sleep 25"},+ "output": "done\n", "time": {"start": 1788600000000, "end": 1788600025300}}})])+ call = [e for e in out if e.get("type") == "assistant"][0]+ res = [e for e in out if e.get("type") == "user"][0]+ assert call["_ts"] == 1788600000.0 and res["_ts"] == 1788600025.3+ r = res["message"]["content"][0]+ assert r["type"] == "tool_result" and r["tool_use_id"] == "prt_9" and r["content"] == "done\n" and r["is_error"] is False+++def test_a_failed_tool_carries_its_error_as_the_result():+ out, _ = _run([_ev("tool_use", part={"type": "tool", "id": "p2", "tool": "bash",+ "state": {"status": "error", "error": "boom", "time": {"start": 1000000, "end": 1002000}}})])+ res = [e for e in out if e.get("type") == "user"][0]["message"]["content"][0]+ assert res["is_error"] is True and res["content"] == "boom" and res["tool_use_id"] == "p2"+++def test_a_tool_without_a_clock_is_stamped_on_arrival():+ out, _ = _run([_ev("tool_use", part={"type": "tool", "id": "p3", "tool": "bash", "state": {"status": "completed", "input": {}}})])+ assert all("_ts" not in e for e in out), "no clock of its own: the runner stamps it when it lands"diff --git a/scripts/support-matrix/README.md b/scripts/support-matrix/README.mdnew file mode 100644index 00000000..042a8381--- /dev/null+++ b/scripts/support-matrix/README.md@@ -0,0 +1,28 @@+# Support matrix suite++Drives the console as one user and, for every harness and every model its menu offers, runs four+scenarios in one session: a first turn, a follow-up, a switch to another model of the harness (then+back), and an artifact (a file the task must produce, checked on the transcript's file cards).+Results are one JSON record per harness x model with the outcome, seconds and reason of each+scenario; `fill-connection.py` stamps each record with the connection its session actually ran on;+`render.py` turns the records into `docs/support-matrix.md`.++```+export BASE=https://your-instance HR_USER=harnessrouter HR_PASS=... PROVIDER=tokenrouter+HARNESSES=claude-code,codex,opencode,pi RESULTS=results-A.json LOG=log-A.txt node run.mjs+HARNESSES=hermes,dsh,qwen,cline RESULTS=results-B.json LOG=log-B.txt node run.mjs+HR_API_KEY=... python3 fill-connection.py results-A.json results-B.json+python3 render.py <(jq -s add results-A.json results-B.json) > ../../docs/support-matrix.md+```++Needs `playwright` (`npm i playwright` next to `run.mjs`, then `npx playwright install chromium`).+Resumable: a pair already recorded is skipped, so a killed worker is relaunched and continues; a+pair whose record carries `error` (the runner's own failure) is re-run. To re-run failed pairs,+delete their records and relaunch. `PROVIDER` is a label for the column: run once per key you+want a column for, with that key wired in Integrations first. `MODELS` (comma list) limits a run+to some models, which is how a single failing pair is reproduced with tracing on. Set+`IGNORE_TLS=1` for an instance on a self-signed certificate.++Rows that fail must carry the reproduced provider error text; a verified list is never inherited+from another instance, since each reaches providers by its own path. Retest a bare `incomplete`+before excluding a model.diff --git a/scripts/support-matrix/fill-connection.py b/scripts/support-matrix/fill-connection.pynew file mode 100644index 00000000..e7f85af9--- /dev/null+++ b/scripts/support-matrix/fill-connection.py@@ -0,0 +1,22 @@+"""Stamp each pair with the connection its session ran on (the session's last_connection, read+from GET /v1/sessions/{id}), so the provider column says what actually served the run.+Usage: BASE=https://your-instance HR_API_KEY=... python3 fill-connection.py results-A.json results-B.json"""+import json, os, ssl, sys, urllib.request+BASE = os.environ["BASE"].rstrip("/"); KEY = os.environ["HR_API_KEY"]+CTX = ssl._create_unverified_context() if os.environ.get("IGNORE_TLS") == "1" else None+def session(sid):+ req = urllib.request.Request(f"{BASE}/api/harness/v1/sessions/{sid}", headers={"authorization": f"Bearer {KEY}"})+ try:+ return json.loads(urllib.request.urlopen(req, timeout=60, context=CTX).read().decode())+ except Exception as e: # noqa: BLE001+ print(sid, "not read:", str(e)[:80]); return {}+for path in sys.argv[1:]:+ try: res = json.load(open(path))+ except Exception: continue+ n = 0+ for k, r in res.items():+ sid = r.get("sid")+ if not sid or r.get("connection"): continue+ v = session(sid).get("last_connection") or ""+ if v: r["connection"] = v; n += 1+ json.dump(res, open(path, "w"), indent=1); print(path, "stamped", n)diff --git a/scripts/support-matrix/render.py b/scripts/support-matrix/render.pynew file mode 100644index 00000000..4212fff9--- /dev/null+++ b/scripts/support-matrix/render.py@@ -0,0 +1,21 @@+"""Render the support matrix JSON as markdown: one table per provider, a row per harness x model."""+import json, sys, collections+res = json.load(open(sys.argv[1]))+mark = lambda r: 'n/a' if not r or r.get('ok') is None else ('pass' if r.get('ok') else 'FAIL')+by = collections.defaultdict(list)+for k, r in res.items(): by[r['provider']].append(r)+out = ["# Harness support matrix", "", "Scenarios: first turn, follow-up in the same session, switch model mid-session, artifact (a file the task must produce). pass = ran and answered as asked, FAIL = failed (reason in the notes), n/a = not run.", ""]+for prov, rows in sorted(by.items()):+ out += [f"## Provider: {prov}", "", "| Harness | Model | First | Follow-up | Switch | Artifact | Notes |", "|---|---|---|---|---|---|---|"]+ for r in sorted(rows, key=lambda r: (r['harness'], r['model'])):+ notes = []+ for sc in ('first', 'followup', 'switch', 'artifact'):+ x = r.get(sc) or {}+ if x.get('ok') is False and x.get('why'): notes.append(f"{sc}: {x['why'][:140]}")+ if r.get('error'): notes.append(f"runner: {r['error'][:100]}")+ sw = r.get('switch') or {}+ out.append(f"| {r['harness']} | {r['model']} | {mark(r.get('first'))} | {mark(r.get('followup'))} | {mark(sw)}{(' ('+sw['to']+')') if sw.get('to') else ''} | {mark(r.get('artifact'))} | {' ; '.join(notes).replace('|', '/')} |")+ ok = sum(1 for r in rows for sc in ('first','followup','switch','artifact') if (r.get(sc) or {}).get('ok') is True)+ tot = sum(1 for r in rows for sc in ('first','followup','switch','artifact') if (r.get(sc) or {}).get('ok') is not None)+ out += ["", f"{len(rows)} pairs, {ok} of {tot} scenario runs passed.", ""]+print("\n".join(out))diff --git a/scripts/support-matrix/run.mjs b/scripts/support-matrix/run.mjsnew file mode 100644index 00000000..85df89c1--- /dev/null+++ b/scripts/support-matrix/run.mjs@@ -0,0 +1,114 @@+// Support matrix runner: harness x model x provider x {first, followup, switch, artifact}.+// Drives the console as one user; one task at a time per worker; resumable (pairs already complete+// in the results file are skipped). Env: BASE, HR_USER, HR_PASS, HARNESSES (comma), PROVIDER+// (a label for the column), RESULTS (json path), LOG (append log), MODELS (optional comma filter),+// IGNORE_TLS=1 for a self-signed instance.+import { chromium } from 'playwright';+import fs from 'node:fs';+const BASE = process.env.BASE, PROVIDER = process.env.PROVIDER, RESULTS = process.env.RESULTS, LOG = process.env.LOG;+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+const log = (s) => { const line = `${new Date().toISOString()} ${s}`; console.log(line); fs.appendFileSync(LOG, line + '\n'); };+const load = () => { try { return JSON.parse(fs.readFileSync(RESULTS, 'utf8')); } catch { return {}; } };+const save = (r) => fs.writeFileSync(RESULTS, JSON.stringify(r, null, 1));+const key = (h, m) => `${PROVIDER}|${h}|${m}`;+async function rt(p, s, v) { await p.$eval(s, (el, x) => { const P = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement : HTMLInputElement; Object.getOwnPropertyDescriptor(P.prototype, 'value').set.call(el, x); el.dispatchEvent(new Event('input', { bubbles: true })); }, v); }+const b = await chromium.launch({ headless: true });+const page = await (await b.newContext({ viewport: { width: 1440, height: 900 }, ignoreHTTPSErrors: process.env.IGNORE_TLS === '1' })).newPage();+const pill = () => page.evaluate(() => document.querySelector('.hx-pill')?.textContent?.trim().toLowerCase() || '');+const transcript = () => page.evaluate(() => (document.querySelector('.wbx-conv-msgs')?.innerText || '').replace(/\s+/g, ' '));+const files = () => page.evaluate(() => [...document.querySelectorAll('.wbx-filecard-name')].map((x) => x.textContent.trim()));+// a modal that took over the page mid-turn (an in-app alert); the first-visit welcome is dismissed at login+const door = () => page.evaluate(() => document.querySelector('[role=dialog]:not(.welcome-overlay)')?.innerText?.replace(/\s+/g, ' ').trim() || '');+const dismissWelcome = async () => { for (let i = 0; i < 4 && (await page.locator('.welcome-overlay').count()); i++) { await page.locator('.welcome-overlay .welcome-wide-close').click().catch(() => {}); await sleep(600); } };+const TERMINAL = new Set(['done', 'completed', 'failed', 'error', 'cancelled', 'incomplete', 'max_turns', 'timeout']);+const sidOf = () => new URL(page.url()).searchParams.get('sid') || '';+// the server's own record of the session's turns, read through the console's proxy (same cookie)+const turnsOf = (sid) => page.evaluate(async (s) => { const r = await fetch(`/api/harness/v1/sessions/${s}/turns`); return r.ok ? ((await r.json()).turns || []) : null; }, sid).catch(() => null);+// send one message on the open session and wait for it to settle; returns the outcome. The turn+// settles on the server's word (the turns feed), not on the task pill: the pill reads the task card,+// which lands a while after the turn does, and a turn scored off it was scored off the previous turn.+async function turn(text, { maxS = 420, expectFiles = false } = {}) {+ const before = await transcript(); const t0 = Date.now(); const secs = () => Math.round((Date.now() - t0) / 10) / 100;+ // the composer refuses a message while the previous turn's stream is still open (its Send is+ // disabled): wait for it to take input again, or the message is dropped on the floor+ const ready = () => page.evaluate(() => { const b = document.querySelector('.wbx-composer .uic-send'); const ta = document.querySelector('.wbx-composer textarea'); return !!ta && !ta.disabled && !!b && !b.disabled; });+ await page.fill('.wbx-composer textarea, textarea', text);+ let canSend = await ready(); for (let i = 0; i < 90 && !canSend; i++) { await sleep(1000); canSend = await ready(); }+ if (!canSend) return { ok: false, s: secs(), tail: '', why: 'the composer stayed busy for 90 s after the previous turn settled' };+ const sid0 = sidOf(); const n0 = sid0 ? ((await turnsOf(sid0)) || []).length : 0;+ await page.keyboard.press('Enter');+ let sid = sid0, turns = null;+ for (let i = 0; i < 120; i++) { await sleep(1000); sid = sid || sidOf(); if (!sid) continue; turns = await turnsOf(sid); if (turns && turns.length > n0) break; }+ if (!turns || turns.length <= n0) return { ok: false, s: secs(), tail: '', why: 'the message was not taken: no turn record after 120 s' };+ // settle on the server's word for the turn: two reads that agree on a terminal status, with the+ // answer (or the reason) stored, and the produced files when the task was asked for one. The+ // status lands a moment before the output does, and once read failed on a turn that completed.+ let last = null, prev = '', agreed = 0, history = [];+ for (let i = 0; i < maxS / 3; i++) {+ await sleep(3000); const d = await door(); if (d) return { ok: false, s: secs(), tail: '', why: 'door: ' + d.slice(0, 160) };+ turns = await turnsOf(sid); last = turns ? turns[turns.length - 1] : null; const st = String(last?.status || '');+ if (st !== prev) { history.push(st); prev = st; }+ if (!TERMINAL.has(st)) { agreed = 0; continue; }+ const stored = !!(last.assistant || last.error || last.incomplete_reason || (last.files || []).length);+ const filesIn = !expectFiles || (last.files || []).length > 0;+ agreed = stored ? agreed + 1 : 0;+ if (agreed >= 2 && (filesIn || agreed >= 8)) break;+ }+ // then let the console render what the server stored+ const head = String(last?.assistant || '').replace(/\s+/g, ' ').trim().slice(0, 40);+ for (let i = 0; i < 12; i++) { const t = await transcript(); if (!/Working…/.test(t.slice(before.length)) && (!head || t.includes(head))) break; await sleep(1500); }+ await sleep(1500);+ const t = await transcript(); const tail = t.slice(before.length).trim().slice(-400);+ const ok = !!last && (last.status === 'done' || last.status === 'completed');+ return { ok, status: last ? last.status : 'none', status_history: history, pill: await pill(), s: secs(), tail, turn_files: (last?.files || []).map((f) => f.filename || f.name || ''), why: ok ? '' : (last?.error || last?.incomplete_reason || tail.slice(-220) || `status ${last?.status}`) };+}+const expectWord = (r, word) => r.ok && (r.tail || '').includes(word) ? r : { ...r, ok: false, why: r.why || `answered without ${word}: ${(r.tail || '').slice(-200)}` };+try {+ await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded' }); await sleep(2500);+ if (page.url().includes('/login')) {+ await rt(page, '#sh-user', process.env.HR_USER || 'harnessrouter'); await rt(page, '#sh-pass', process.env.HR_PASS);+ await page.click('button[type=submit]'); await page.waitForURL((u) => !u.pathname.includes('/login'), { timeout: 60000 });+ }+ await sleep(1500); await dismissWelcome();+ for (const h of process.env.HARNESSES.split(',')) {+ // the menu starts from a placeholder list and takes the gateway's catalog when it lands: wait for that+ const catalog = page.waitForResponse((r) => r.url().includes('/v1/models'), { timeout: 30000 }).catch(() => null);+ await page.goto(`${BASE}/harnesses?h=${h}`, { waitUntil: 'domcontentloaded' }); await catalog; await sleep(3500); await dismissWelcome();+ for (let i = 0; i < 10 && !(await page.locator('.wbx-conv-main.is-hero').count()); i++) { await page.click('button:has-text("New task")').catch(() => {}); await sleep(800); }+ const readMenu = () => page.evaluate(() => [...document.querySelectorAll('.wbx-model-opt')].map((o) => ({ id: o.querySelector('span')?.textContent.trim(), ok: !o.disabled })));+ await page.click('.ar2-chip'); await sleep(600);+ let models = await readMenu();+ for (let i = 0; i < 10; i++) { await sleep(1500); const again = await readMenu(); if (again.length === models.length && models.length) break; models = again; }+ 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);+ log(`HARNESS ${h} models ${models.length} runnable ${enabled.length}: ${enabled.join(',')}`);+ for (const m of enabled) {+ const res = load(); const k = key(h, m);+ if (res[k] && res[k].artifact && !res[k].error) { log(`SKIP ${k} (done)`); continue; } // a runner error is not a result+ const rec = res[k] || { provider: PROVIDER, harness: h, model: m, at: new Date().toISOString() };+ try {+ await page.goto(`${BASE}/harnesses?h=${h}`, { waitUntil: 'domcontentloaded' }); await sleep(3000);+ for (let i = 0; i < 10 && !(await page.locator('.wbx-conv-main.is-hero').count()); i++) { await page.click('button:has-text("New task")').catch(() => {}); await sleep(800); }+ await page.click('.ar2-chip'); await sleep(500); await page.locator('.wbx-model-opt', { hasText: m }).first().click(); await sleep(300);+ rec.first = expectWord(await turn(`Reply with exactly: M1-${m}`), `M1-${m}`); rec.sid = new URL(page.url()).searchParams.get('sid') || '';+ log(`FIRST ${k} ${rec.first.ok ? 'ok' : 'FAIL'} ${rec.first.s}s ${rec.first.why}`);+ 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;+ 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 || ''}`);+ if (other) { await page.click('.ar2-chip'); await sleep(500); await page.locator('.wbx-model-opt', { hasText: m }).first().click(); await sleep(300); }+ const a = await turn(`Create a file named hello-${h}.txt containing exactly the word HELLO, then reply DONE.`, { expectFiles: true });+ // the file cards render from the settled read, a moment after the answer+ let fl = await files(); for (let i = 0; i < 10 && fl.length < (a.turn_files || []).length; i++) { await sleep(1500); fl = await files(); }+ rec.artifact = { ...a, files: fl, ok: a.ok && fl.some((f) => f.includes(`hello-${h}.txt`)), why: a.ok && !fl.some((f) => f.includes(`hello-${h}.txt`)) ? `no file card (files: ${fl.join(',') || 'none'}); ${a.tail.slice(-160)}` : a.why };+ log(`ARTIFACT ${k} ${rec.artifact.ok ? 'ok' : 'FAIL'} ${rec.artifact.s}s ${rec.artifact.why}`);+ } else { rec.followup = { ok: null, why: 'first turn failed' }; rec.switch = { ok: null, why: 'first turn failed' }; rec.artifact = { ok: null, why: 'first turn failed' }; }+ } catch (e) { rec.error = String(e).slice(0, 300); log(`ERROR ${k} ${rec.error}`); if (/has been closed/.test(rec.error)) throw e; } // a closed browser ends the worker; the next launch resumes+ const all = load(); all[k] = rec; save(all); log(`PAIR_DONE ${k}`);+ }+ }+} catch (e) { log(`FATAL ${String(e).slice(0, 300)}`); }+await b.close(); log(`WORKER_DONE ${process.env.HARNESSES}`);diff --git a/ui/src/app/(app)/harnesses/page.tsx b/ui/src/app/(app)/harnesses/page.tsxindex 577e5ab2..d24bf003 100644--- a/ui/src/app/(app)/harnesses/page.tsx+++ b/ui/src/app/(app)/harnesses/page.tsx@@ -28,13 +28,17 @@ import { getConvState, type UserMsg } from '@/lib/conversation';type View = 'index' | 'chat' | 'settings';type TaskState = 'done' | 'running' | 'failed' | 'cancelled' | 'incomplete';+const INCOMPLETE = new Set(['incomplete', 'max_turns', 'timeout', 'interrupted']);function taskState(status?: string): TaskState {const s = status || '';if (TERMINAL_OK.has(s)) return 'done';if (RUNNING.has(s)) return 'running';if (TERMINAL_BAD.has(s)) return 'failed';if (s === 'cancelled') return 'cancelled';- return 'incomplete';+ if (INCOMPLETE.has(s)) return 'incomplete';+ // a card the server has written but not yet given a status is a live task, not a stopped one;+ // the pill flashed "incomplete" in that gap+ return 'running';}/** A harness's loaded tasks: the pages read so far, the cursor for the next, and whether one is in flight. */diff --git a/ui/src/app/hr.css b/ui/src/app/hr.cssindex 0b99a5ea..0038f5a3 100644--- a/ui/src/app/hr.css+++ b/ui/src/app/hr.css@@ -359,6 +359,8 @@ a { color: inherit; text-decoration: none; }font-size: 12.5px; font-weight: 600; font-family: inherit; color: var(--brand); padding: 6px 12px;border-radius: 9px; border: 1px solid var(--brand-soft); background: var(--brand-50); cursor: pointer; }.wbx-zipall:hover { border-color: var(--brand); background: var(--brand-100, #EEEAFE); }+/* the archive was refused: the server's sentence, under the row that asked for it */+.wbx-zipall-err { font-size: 12px; line-height: 1.4; color: #b42318; }.wbx-filecard { display: flex; flex-wrap: nowrap; align-items: center; gap: 10px; min-width: 0; border: 1px solid var(--line);border-radius: 12px; padding: 10px 12px; background: var(--surface); box-shadow: var(--shadow-1); }.wbx-filecard:hover { border-color: var(--brand-soft); }diff --git a/ui/src/components/ChatAttachments.tsx b/ui/src/components/ChatAttachments.tsxindex 89bd712f..345f01d8 100644--- a/ui/src/components/ChatAttachments.tsx+++ b/ui/src/components/ChatAttachments.tsx@@ -5,7 +5,7 @@// own thinner versions instead of these: a text pill with an × where an image thumbnail belongs,// and a bare row where the output card belongs. One definition, so a column in an arena is the// same card as a task, because it is the same card.-import React from 'react';+import React, { useState } from 'react';import { FileTypeIcon } from '@/components/FileTypeIcon';import { containerFileUrl, downloadFile, type RespFile } from '@/lib/chat';@@ -39,6 +39,8 @@ export function AttachCard({ name, dataUri, onRemove }: { name: string; dataUri?export function OutputFiles({ files, onPreview }: {files: RespFile[]; onPreview: (p: { url: string; name: string }) => void;}) {+ // the archive is refused, with the names, when a cited file is no longer there; the row says so+ const [zipErr, setZipErr] = useState('');if (!files.length) return null;const zipUrl = `/api/harness/v1/sessions/${encodeURIComponent(files[0].container_id)}`+ `/files/archive?files=${encodeURIComponent(files.map((f) => f.file_id).join(','))}`;@@ -62,10 +64,11 @@ export function OutputFiles({ files, onPreview }: {Only worth a row when there's more than one file. */}{files.length > 1 && (<button className="wbx-zipall" type="button"- onClick={(e) => { e.stopPropagation(); downloadFile(zipUrl, 'outputs.zip').catch(() => undefined); }}>+ onClick={(e) => { e.stopPropagation(); setZipErr(''); downloadFile(zipUrl, 'outputs.zip').catch((err: unknown) => setZipErr(err instanceof Error ? err.message : 'Could not build the archive.')); }}><IcDl /> Download all ({files.length}) as .zip</button>)}+ {zipErr && <div className="wbx-zipall-err" role="alert">{zipErr}</div>}</div>);}diff --git a/ui/src/components/TaskChat.tsx b/ui/src/components/TaskChat.tsxindex 98d38c9c..f43eb915 100644--- a/ui/src/components/TaskChat.tsx+++ b/ui/src/components/TaskChat.tsx@@ -655,7 +655,7 @@ function Conversation({ harnessId, sessionId, target, models, onModel, onRan, on/><Popover open={modelOpen} anchorRef={modelBtnRef} onClose={() => setModelOpen(false)} width={280} minHeight={120} placement="above" className="wbx-model-pop" label="Model for this task"><div className="wbx-model-head">Model for this task</div>- <div role="listbox" aria-label="Model for this task">+ <div role="listbox" aria-label="Model for this task" className="uic-pop-list">{models.map((m) => {const ok = modelAvailable(target.backend, m);return (diff --git a/ui/src/lib/chat.ts b/ui/src/lib/chat.tsindex 82bc6985..8d0c101a 100644--- a/ui/src/lib/chat.ts+++ b/ui/src/lib/chat.ts@@ -70,7 +70,12 @@ export function containerFileUrl(f: RespFile): string {* artifact bytes is this helper; renderers turn the Blob into an object URL. */export async function fetchFileBlob(url: string): Promise<Blob> {const r = await harnessFetch(url, { headers: authHeaders() });- if (!r.ok) throw new Error(`${r.status}`);+ if (!r.ok) {+ // the server says why (an archive refused by name, a file no longer there); keep its sentence+ let why = '';+ try { why = String(((await r.json()) || {}).detail || ''); } catch { /* no body */ }+ throw new Error(why || `${r.status}`);+ }return r.blob();}diff --git a/ui/src/lib/conversation.ts b/ui/src/lib/conversation.tsindex a84af075..79a83ea3 100644--- a/ui/src/lib/conversation.ts+++ b/ui/src/lib/conversation.ts@@ -65,6 +65,9 @@ export function msgsFromTurns(turns: SessionTurn[]): { msgs: Msg[]; running: booconst blocks: Block[] = [];if (steps.length) blocks.push({ kind: 'tools', reasoning: '', steps });if (t.assistant) blocks.push({ kind: 'text', text: t.assistant });+ // a failed turn's reason, the line the live stream appended as its error event+ const why = (t as { error?: string }).error;+ if (why && (t.status === 'failed' || t.status === 'error')) blocks.push({ kind: 'text', text: (t.assistant ? '\n\n' : '') + 'Error: ' + why });const st: AsstMsg['status'] = t.status === 'failed' || t.status === 'error' ? 'failed': t.status === 'cancelled' ? 'cancelled': (t.status === 'incomplete' || t.status === 'max_turns' || t.status === 'timeout') ? 'incomplete'