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
fix(gateway,console): an upload lands wherever the key points, and the chip stops looking glued
richard-epsilla538bd9d1f164
diff --git a/gateway/app.py b/gateway/app.pyindex 32fb96b3..d0bb27b6 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -11642,13 +11642,27 @@ def _cloud_target_public(t: dict) -> dict:"workspace": t.get("workspace") or "", "workspace_name": t.get("workspace_name") or ""}+def _cloud_tkey(target: dict) -> str:+ """One hosted copy per (org, workspace): the record key a target owns."""+ return f"{target.get('org') or ''}|{target.get('workspace') or ''}"++async def _cloud_records() -> dict:+ """{harness id: {target key: {remote_id, fingerprint, uploaded_at, target}}}.++ Per harness AND per target: the same local harness uploads to as many workspaces as the+ operator connects over time, each keeping its own hosted copy. A v1 flat record (one target,+ implicit) predates that and is discarded rather than guessed at: it never shipped."""v = await _vault_get(GLOBAL_TENANT, _CLOUD_UPLOAD_RECORDS_KEY)try:doc = json.loads(v) if v else {}except Exception: # noqa: BLE001doc = {}- return doc if isinstance(doc, dict) else {}+ if not isinstance(doc, dict) or (doc and doc.get("v") != 2):+ return {"v": 2, "harnesses": {}}+ if not doc:+ return {"v": 2, "harnesses": {}}+ return docasync def _cloud_me(base_url: str, api_key: str) -> dict:@@ -11713,28 +11727,55 @@ async def _cloud_upload_one(org: str, hid: str, target: dict, records: dict) ->return {"id": hid, "ok": False, "action": "skip", "error": "not found"}body = await _cloud_harness_body(org, hid, v)fp = _cloud_fingerprint(body)- action = "replace" if hid in records else "create"- try:- async with httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=8.0)) as c:- r = await c.put(f"{target['base_url']}/v1/harnesses/{hid}", json=body,- headers={"authorization": f"Bearer {target['api_key']}"})- except Exception as e: # noqa: BLE001- return {"id": hid, "ok": False, "action": action, "error": f"could not reach cloud: {str(e)[:120]}"}- if r.status_code not in (200, 201):+ per = records.setdefault("harnesses", {}).setdefault(hid, {})+ tkey = _cloud_tkey(target)+ rec = per.get(tkey)+ action = "replace" if rec else "create"+ # The hosted id is the local id when that id is free, and a minted one when it is not. Hosted+ # ids are global across orgs, and the hosted side answers 404 for an id owned by another org,+ # deliberately indistinguishable from missing. That is a legitimate situation, not an error:+ # the same local harness uploaded to a second org (a changed key, a shared instance, an id+ # claimed by an earlier test) must land, so on that 404 the upload retries once under a fresh+ # id and the record keeps the mapping. Stability holds per target: every later upload replaces+ # the same hosted copy.+ # This target's hosted id: its own record first; else the local id, but only when no OTHER+ # target has claimed it (a second workspace in the SAME org would otherwise silently update+ # the first workspace's copy rather than creating its own); else minted.+ if rec:+ remote_id = str(rec.get("remote_id") or hid)+ elif per:+ remote_id = "chrn" + uuid.uuid4().hex+ else:+ remote_id = hid+ last_error = ""+ for attempt in (remote_id, "chrn" + uuid.uuid4().hex):+ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=8.0)) as c:+ r = await c.put(f"{target['base_url']}/v1/harnesses/{attempt}", json=body,+ headers={"authorization": f"Bearer {target['api_key']}"})+ except Exception as e: # noqa: BLE001+ return {"id": hid, "ok": False, "action": action, "error": f"could not reach cloud: {str(e)[:120]}"}+ if r.status_code in (200, 201):+ per[tkey] = {"fingerprint": fp, "uploaded_at": int(time.time() * 1000),+ "remote_id": attempt,+ "target": f"{target.get('org_name') or target.get('org')} / {target.get('workspace_name') or target.get('workspace')}"}+ return {"id": hid, "ok": True, "action": action, "name": body["name"], "remote_id": attempt}detail = ""try:j = r.json()detail = str((j.get("error") or {}).get("message") or j.get("detail") or "")except Exception: # noqa: BLE001detail = r.text[:160]- return {"id": hid, "ok": False, "action": action, "error": f"cloud answered {r.status_code}: {detail}"[:300]}- records[hid] = {"fingerprint": fp, "uploaded_at": int(time.time() * 1000),- "target": f"{target.get('org_name') or target.get('org')} / {target.get('workspace_name') or target.get('workspace')}"}- return {"id": hid, "ok": True, "action": action, "name": body["name"]}+ last_error = f"cloud answered {r.status_code}: {detail}"[:300]+ if r.status_code != 404:+ break # only the taken-id case is worth a second attempt+ return {"id": hid, "ok": False, "action": action, "error": last_error}-def _cloud_status(hid: str, records: dict, fp: str | None) -> dict:- rec = records.get(hid)+def _cloud_status(hid: str, records: dict, fp: str | None, target: dict) -> dict:+ """Status against the CURRENTLY connected workspace: other targets' copies exist but are not+ this chip's business."""+ rec = (records.get("harnesses", {}).get(hid) or {}).get(_cloud_tkey(target))if not rec:return {"uploaded": False}return {"uploaded": True, "uploaded_at": rec.get("uploaded_at"), "target": rec.get("target"),@@ -11810,7 +11851,7 @@ async def cloud_upload_one(hid: str, request: Request) -> dict:await BACKING.secrets.put(GLOBAL_TENANT, _CLOUD_UPLOAD_RECORDS_KEY, json.dumps(records))if not res.get("ok"):raise HTTPException(400 if res.get("action") == "skip" else 502, res.get("error") or "upload failed")- return {**res, "status": _cloud_status(hid, records, None) | {"changed": False}}+ return {**res, "status": _cloud_status(hid, records, None, target) | {"changed": False}}@app.get("/v1/harnesses/{hid}/upload")@@ -11818,11 +11859,12 @@ async def cloud_upload_status(hid: str, request: Request) -> dict:"""The chip on the harness page: never uploaded, uploaded, or changed since."""p = await _principal(request)records = await _cloud_records()- if hid not in records:+ target = await _cloud_target()+ if not (records.get("harnesses", {}).get(hid) or {}).get(_cloud_tkey(target)):return {"uploaded": False}v = await _vertex_get(hid)fp = _cloud_fingerprint(await _cloud_harness_body(p.get("org", ""), hid, v)) if v else None- return _cloud_status(hid, records, fp)+ return _cloud_status(hid, records, fp, target)@app.get("/v1/cloud-upload/status")@@ -11830,11 +11872,15 @@ async def cloud_upload_status_all(request: Request) -> dict:"""For the list: which harnesses have been uploaded, and whether each changed since."""p = await _principal(request)records = await _cloud_records()+ target = await _cloud_target()+ tkey = _cloud_tkey(target)out = {}- for hid in records:+ for hid, per in records.get("harnesses", {}).items():+ if tkey not in per:+ continuev = await _vertex_get(hid)fp = _cloud_fingerprint(await _cloud_harness_body(p.get("org", ""), hid, v)) if v else None- out[hid] = _cloud_status(hid, records, fp)+ out[hid] = _cloud_status(hid, records, fp, target)return {"harnesses": out}diff --git a/gateway/tests/test_cloud_upload.py b/gateway/tests/test_cloud_upload.pyindex 03d9043d..7e03ea4c 100644--- a/gateway/tests/test_cloud_upload.py+++ b/gateway/tests/test_cloud_upload.py@@ -163,3 +163,57 @@ def test_a_cloud_error_on_one_row_does_not_stop_the_others(api, cloud, monkeypatassert rows[a]["ok"] is False and "hosted hiccup" in rows[a]["error"]assert rows[b]["ok"] is Trueassert api.get(f"/v1/harnesses/{a}/upload").json()["uploaded"] is False # a failed upload leaves no record+++def test_an_id_claimed_by_another_org_lands_under_a_minted_id(api, cloud):+ """The same local harness uploaded to a second org is legitimate: hosted ids are global and+ the hosted side answers 404 for a foreign-owned id, indistinguishable from missing. The+ upload retries once under a fresh id and every later upload replaces that same hosted copy."""+ api.put("/v1/cloud-upload/target", json={"api_key": "sk-hr-good", "base_url": CLOUD})+ hid = _harness(api, "Collision")+ real = cloud.handle++ def owned_elsewhere(req):+ if req.method == "PUT" and req.url.path.endswith(hid):+ return httpx.Response(404, json={"error": {"message": "No harness with that id."}})+ return real(req)+ cloud.handle = owned_elsewhere+ r = api.post(f"/v1/harnesses/{hid}/upload")+ assert r.status_code == 200, r.text+ remote = r.json()["remote_id"]+ assert remote != hid and remote.startswith("chrn")+ assert cloud.harnesses[remote]["name"] == "Collision"+ assert api.get(f"/v1/harnesses/{hid}/upload").json()["uploaded"] is True+ r2 = api.post(f"/v1/harnesses/{hid}/upload")+ assert r2.json()["remote_id"] == remote and r2.json()["action"] == "replace"+ assert len([k for k in cloud.harnesses if k.startswith("chrn")]) == 1++ def flaky(req):+ return httpx.Response(500, json={"error": {"message": "boom"}})+ cloud.handle = flaky+ assert api.post(f"/v1/harnesses/{hid}/upload").status_code == 502 # a non-404 mints nothing+++def test_the_same_harness_uploads_to_every_workspace_a_key_points_at(api, cloud):+ """It is just an upload: wherever there is a key, it lands. Each target keeps its own hosted+ copy and its own chip state; a second workspace in the SAME org gets its own copy rather+ than silently updating the first one's."""+ cloud.keys["sk-hr-ws2"] = {"org": "org_e", "org_name": "Epsilla", "workspace": "ws_2",+ "workspace_name": "Second", "member": "richard"}+ api.put("/v1/cloud-upload/target", json={"api_key": "sk-hr-good", "base_url": CLOUD})+ hid = _harness(api, "Everywhere")+ r1 = api.post(f"/v1/harnesses/{hid}/upload").json()+ assert r1["action"] == "create" and r1["remote_id"] == hid # first target keeps the local id+ # switch the key to another workspace of the same org: its own copy, its own id+ api.put("/v1/cloud-upload/target", json={"api_key": "sk-hr-ws2", "base_url": CLOUD})+ assert api.get(f"/v1/harnesses/{hid}/upload").json()["uploaded"] is False # chip is per target+ r2 = api.post(f"/v1/harnesses/{hid}/upload").json()+ assert r2["action"] == "create" and r2["remote_id"] != hid+ assert cloud.harnesses[hid]["workspace"] == "ws_r"+ assert cloud.harnesses[r2["remote_id"]]["workspace"] == "ws_2"+ st = api.get(f"/v1/harnesses/{hid}/upload").json()+ assert st["uploaded"] is True and st["target"] == "Epsilla / Second"+ # back to the first workspace: its record is intact, replace goes to the original id+ api.put("/v1/cloud-upload/target", json={"api_key": "sk-hr-good", "base_url": CLOUD})+ r3 = api.post(f"/v1/harnesses/{hid}/upload").json()+ assert r3["action"] == "replace" and r3["remote_id"] == hiddiff --git a/ui/src/app/(app)/harnesses/[id]/page.tsx b/ui/src/app/(app)/harnesses/[id]/page.tsxindex 7c461c18..94c6ff63 100644--- a/ui/src/app/(app)/harnesses/[id]/page.tsx+++ b/ui/src/app/(app)/harnesses/[id]/page.tsx@@ -146,7 +146,7 @@ export default function HarnessSettingsPage() {{SELF_HOSTED && !readOnly && cloud?.uploaded && (<span className={'cloud-chip' + (cloud.changed ? ' changed' : '')} title={cloud.target || ''}><iconify-icon icon={cloud.changed ? 'tabler:cloud-up' : 'tabler:cloud-check'}></iconify-icon>- {cloud.changed ? 'Changed since upload' : `Uploaded ${timeAgo(cloud.uploaded_at ?? null)}`}+ <span>{cloud.changed ? 'Changed since upload' : `Uploaded ${timeAgo(cloud.uploaded_at ?? null)}`}</span></span>)}</div>diff --git a/ui/src/app/(app)/harnesses/page.tsx b/ui/src/app/(app)/harnesses/page.tsxindex 6af8206e..c9d1365a 100644--- a/ui/src/app/(app)/harnesses/page.tsx+++ b/ui/src/app/(app)/harnesses/page.tsx@@ -143,7 +143,7 @@ export default function HarnessesPage() {<td className="object-cell"><div className="object-title"><span className="object-icon"><iconify-icon icon={r.kind === 'builtin' ? 'tabler:box' : 'tabler:terminal-2'}></iconify-icon></span><div className="object-copy"><strong>{r.name}</strong><span>{r.kind === 'builtin' ? `Built-in · ${r.purpose}` : r.purpose}{cloud[r.id]?.uploaded ? (- <span className={'cloud-chip' + (cloud[r.id].changed ? ' changed' : '')} title={cloud[r.id].target || ''}> · <iconify-icon icon={cloud[r.id].changed ? 'tabler:cloud-up' : 'tabler:cloud-check'}></iconify-icon>{cloud[r.id].changed ? 'Changed since upload' : 'Uploaded'}</span>+ <span className={'cloud-chip' + (cloud[r.id].changed ? ' changed' : '')} title={cloud[r.id].target || ''}><iconify-icon icon={cloud[r.id].changed ? 'tabler:cloud-up' : 'tabler:cloud-check'}></iconify-icon><span>{cloud[r.id].changed ? 'Changed since upload' : 'Uploaded'}</span></span>) : null}</span></div></div></td><td className="harness-desktop-col" onClick={(e) => e.stopPropagation()}><CopyId value={r.id} /></td>diff --git a/ui/src/app/revamp.css b/ui/src/app/revamp.cssindex b0e21bdd..d984ffa2 100644--- a/ui/src/app/revamp.css+++ b/ui/src/app/revamp.css@@ -1903,7 +1903,8 @@ main .hr-wrap { max-width: 1320px; margin: 0 auto; padding: 28px 32px 64px; }.cloud-rows td { padding: 10px 12px; }.modal .modal-actions { position: sticky; bottom: 0; background: #fff; padding-bottom: 2px; }.cloud-note { color: var(--muted); font-size: 12px; }- .cloud-chip { display: inline-flex; align-items: center; gap: 5px; color: var(--muted); font-size: 12px; white-space: nowrap; }+ .cloud-chip { display: inline-flex; align-items: center; gap: 5px; margin-left: 10px; vertical-align: middle; color: var(--muted); font-size: 12px; white-space: nowrap; }+ .header-actions .cloud-chip { margin-left: 0; }.cloud-chip.changed { color: var(--ink); }.cloud-chip iconify-icon { font-size: 14px; }/* The selection bar is FIXED to the viewport bottom, same recipe as the harness settings