Skip to content

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

feat(console,gateway): stored cloud workspaces with a picker, and no internal id ever shown

richard-epsilla56b487c6fe44
diff --git a/gateway/app.py b/gateway/app.py
index d0bb27b6..412c118a 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -11625,21 +11625,48 @@ class CloudTargetBody(BaseModel):
base_url: str | None = None
-async def _cloud_target() -> dict:
+async def _cloud_targets() -> dict:
+ """{targets: {tkey: {base_url, api_key, org, org_name, workspace, workspace_name}}, last: tkey}.
+
+ Several stored destinations: the operator uploads to wherever they hold a key, and the dialog
+ offers the stored ones in a picker. A v1 single-target doc (one key at the root) is wrapped
+ into the list rather than discarded, so a key pasted before this shape survives."""
v = await _vault_get(GLOBAL_TENANT, _CLOUD_UPLOAD_KEY)
try:
doc = json.loads(v) if v else {}
except Exception: # noqa: BLE001
doc = {}
- return doc if isinstance(doc, dict) else {}
+ if not isinstance(doc, dict):
+ return {"targets": {}, "last": ""}
+ if doc.get("api_key"): # v1: one target at the root
+ tkey = _cloud_tkey(doc)
+ return {"targets": {tkey: doc}, "last": tkey}
+ doc.setdefault("targets", {})
+ doc.setdefault("last", "")
+ return doc
+
+
+async def _cloud_targets_save(doc: dict) -> None:
+ await BACKING.secrets.put(GLOBAL_TENANT, _CLOUD_UPLOAD_KEY, json.dumps(doc), require_encryption=True)
+
+
+def _cloud_label(t: dict) -> str:
+ """What a person sees for a destination. Display names and the account email only: org and
+ workspace ids are internal and never shown (the harness id is the one deliberate exception
+ in the product)."""
+ ws = str(t.get("workspace_name") or "").strip()
+ member = str(t.get("member") or "").strip()
+ if ws and member:
+ return f"{ws} ({member})"
+ return ws or member or "Cloud workspace"
def _cloud_target_public(t: dict) -> dict:
key = str(t.get("api_key") or "")
- return {"configured": bool(key), "base_url": t.get("base_url") or _CLOUD_UPLOAD_DEFAULT_BASE,
+ return {"id": _cloud_tkey(t), "base_url": t.get("base_url") or _CLOUD_UPLOAD_DEFAULT_BASE,
"key_hint": (key[:6] + "…" + key[-4:]) if len(key) >= 10 else ("…" if key else ""),
- "org": t.get("org") or "", "org_name": t.get("org_name") or "",
- "workspace": t.get("workspace") or "", "workspace_name": t.get("workspace_name") or ""}
+ "member": t.get("member") or "", "workspace_name": t.get("workspace_name") or "",
+ "label": _cloud_label(t)}
def _cloud_tkey(target: dict) -> str:
@@ -11757,8 +11784,7 @@ async def _cloud_upload_one(org: str, hid: str, target: dict, records: dict) ->
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')}"}
+ "remote_id": attempt, "target": _cloud_label(target)}
return {"id": hid, "ok": True, "action": action, "name": body["name"], "remote_id": attempt}
detail = ""
try:
@@ -11782,73 +11808,114 @@ def _cloud_status(hid: str, records: dict, fp: str | None, target: dict) -> dict
"changed": bool(fp) and rec.get("fingerprint") != fp}
[email protected]("/v1/cloud-upload/target")
-async def cloud_target_get(request: Request) -> dict:
[email protected]("/v1/cloud-upload/targets")
+async def cloud_targets_get(request: Request) -> dict:
await _principal(request)
- return _cloud_target_public(await _cloud_target())
+ doc = await _cloud_targets()
+ return {"targets": [_cloud_target_public(t) for t in doc["targets"].values()], "last": doc.get("last") or ""}
[email protected]("/v1/cloud-upload/target")
-async def cloud_target_put(body: CloudTargetBody, request: Request) -> dict:
[email protected]("/v1/cloud-upload/targets")
+async def cloud_targets_add(body: CloudTargetBody, request: Request) -> dict:
+ """Add (or refresh) a stored destination: the key is verified before anything is written."""
await _principal(request)
- cur = await _cloud_target()
- key = (body.api_key or "").strip() or str(cur.get("api_key") or "")
- base = (body.base_url or "").strip().rstrip("/") or str(cur.get("base_url") or "") or _CLOUD_UPLOAD_DEFAULT_BASE
+ key = (body.api_key or "").strip()
+ base = (body.base_url or "").strip().rstrip("/") or _CLOUD_UPLOAD_DEFAULT_BASE
if not key:
raise HTTPException(400, "an API key is required")
me = await _cloud_me(base, key)
- doc = {"base_url": base, "api_key": key, "org": me.get("org") or "", "org_name": me.get("org_name") or "",
- "workspace": me.get("workspace") or "", "workspace_name": me.get("workspace_name") or ""}
- await BACKING.secrets.put(GLOBAL_TENANT, _CLOUD_UPLOAD_KEY, json.dumps(doc), require_encryption=True)
- return _cloud_target_public(doc)
-
-
[email protected]("/v1/cloud-upload/target/test")
-async def cloud_target_test(body: CloudTargetBody, request: Request) -> dict:
- """Where would an upload land. Tests the key in the body, or the stored one when omitted."""
+ t = {"base_url": base, "api_key": key, "org": me.get("org") or "", "org_name": me.get("org_name") or "",
+ "workspace": me.get("workspace") or "", "workspace_name": me.get("workspace_name") or "",
+ "member": me.get("member") or ""}
+ doc = await _cloud_targets()
+ doc["targets"][_cloud_tkey(t)] = t
+ doc["last"] = _cloud_tkey(t)
+ await _cloud_targets_save(doc)
+ return _cloud_target_public(t)
+
+
[email protected]("/v1/cloud-upload/targets/test")
+async def cloud_targets_test(body: CloudTargetBody, request: Request) -> dict:
+ """Where would this key land. Nothing is stored."""
await _principal(request)
- cur = await _cloud_target()
- key = (body.api_key or "").strip() or str(cur.get("api_key") or "")
- base = (body.base_url or "").strip().rstrip("/") or str(cur.get("base_url") or "") or _CLOUD_UPLOAD_DEFAULT_BASE
+ key = (body.api_key or "").strip()
+ base = (body.base_url or "").strip().rstrip("/") or _CLOUD_UPLOAD_DEFAULT_BASE
if not key:
raise HTTPException(400, "an API key is required")
me = await _cloud_me(base, key)
- return {"ok": True, "org": me.get("org") or "", "org_name": me.get("org_name") or "",
- "workspace": me.get("workspace") or "", "workspace_name": me.get("workspace_name") or ""}
+ return {"ok": True, "label": _cloud_label(me), "workspace_name": me.get("workspace_name") or "",
+ "member": me.get("member") or ""}
[email protected]("/v1/cloud-upload/target")
-async def cloud_target_delete(request: Request) -> dict:
[email protected]("/v1/cloud-upload/targets")
+async def cloud_targets_remove(request: Request, id: str = "") -> dict:
+ """Remove one stored destination (?id=), or every one of them (no id). Upload records stay:
+ they are history, and re-adding the same workspace's key finds them again."""
await _principal(request)
- await BACKING.secrets.put(GLOBAL_TENANT, _CLOUD_UPLOAD_KEY, "", require_encryption=True)
- return {"configured": False}
+ doc = await _cloud_targets()
+ if id:
+ doc["targets"].pop(id, None)
+ if doc.get("last") == id:
+ doc["last"] = next(iter(doc["targets"]), "")
+ else:
+ doc = {"targets": {}, "last": ""}
+ await _cloud_targets_save(doc)
+ return {"targets": [_cloud_target_public(t) for t in doc["targets"].values()], "last": doc.get("last") or ""}
class CloudUploadBody(BaseModel):
ids: list[str]
+ target: str | None = None # a stored destination's id; the only one when omitted
+
+
+async def _cloud_pick_target(tid: str | None) -> dict:
+ doc = await _cloud_targets()
+ targets = doc["targets"]
+ if not targets:
+ raise HTTPException(400, "no cloud workspace connected")
+ if tid:
+ t = targets.get(tid)
+ if not t:
+ raise HTTPException(400, "that stored workspace is gone; pick another")
+ return t
+ if len(targets) == 1:
+ return next(iter(targets.values()))
+ last = targets.get(doc.get("last") or "")
+ if last:
+ return last
+ raise HTTPException(400, "several workspaces are stored; name one")
+
+
+async def _cloud_remember_last(target: dict) -> None:
+ doc = await _cloud_targets()
+ if doc.get("last") != _cloud_tkey(target) and _cloud_tkey(target) in doc["targets"]:
+ doc["last"] = _cloud_tkey(target)
+ await _cloud_targets_save(doc)
@app.post("/v1/harnesses/upload")
async def cloud_upload_batch(body: CloudUploadBody, request: Request) -> dict:
p = await _principal(request)
- target = await _cloud_target()
- if not target.get("api_key"):
- raise HTTPException(400, "no cloud workspace connected")
+ target = await _cloud_pick_target(body.target)
records = await _cloud_records()
results = [await _cloud_upload_one(p.get("org", ""), str(h), target, records) for h in body.ids[:200]]
await BACKING.secrets.put(GLOBAL_TENANT, _CLOUD_UPLOAD_RECORDS_KEY, json.dumps(records))
+ await _cloud_remember_last(target)
return {"results": results, "target": _cloud_target_public(target)}
+class CloudUploadOneBody(BaseModel):
+ target: str | None = None
+
+
@app.post("/v1/harnesses/{hid}/upload")
-async def cloud_upload_one(hid: str, request: Request) -> dict:
+async def cloud_upload_one(hid: str, request: Request, body: CloudUploadOneBody | None = None) -> dict:
p = await _principal(request)
- target = await _cloud_target()
- if not target.get("api_key"):
- raise HTTPException(400, "no cloud workspace connected")
+ target = await _cloud_pick_target((body.target if body else None))
records = await _cloud_records()
res = await _cloud_upload_one(p.get("org", ""), hid, target, records)
await BACKING.secrets.put(GLOBAL_TENANT, _CLOUD_UPLOAD_RECORDS_KEY, json.dumps(records))
+ await _cloud_remember_last(target)
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, target) | {"changed": False}}
@@ -11859,12 +11926,14 @@ 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()
- target = await _cloud_target()
- if not (records.get("harnesses", {}).get(hid) or {}).get(_cloud_tkey(target)):
+ per = records.get("harnesses", {}).get(hid) or {}
+ if not per:
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, target)
+ rec = max(per.values(), key=lambda r: r.get("uploaded_at") or 0)
+ return {"uploaded": True, "uploaded_at": rec.get("uploaded_at"), "target": rec.get("target"),
+ "changed": bool(fp) and rec.get("fingerprint") != fp}
@app.get("/v1/cloud-upload/status")
@@ -11872,15 +11941,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, per in records.get("harnesses", {}).items():
- if tkey not in per:
+ if not per:
continue
v = 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, target)
+ rec = max(per.values(), key=lambda r: r.get("uploaded_at") or 0)
+ out[hid] = {"uploaded": True, "uploaded_at": rec.get("uploaded_at"), "target": rec.get("target"),
+ "changed": bool(fp) and rec.get("fingerprint") != fp}
return {"harnesses": out}
diff --git a/gateway/tests/test_cloud_upload.py b/gateway/tests/test_cloud_upload.py
index 7e03ea4c..ffbf662a 100644
--- a/gateway/tests/test_cloud_upload.py
+++ b/gateway/tests/test_cloud_upload.py
@@ -73,37 +73,41 @@ def _harness(api, name="Philz one-pager", **extra) -> str:
def test_nothing_is_configured_until_a_key_is_saved(api, cloud):
- assert api.get("/v1/cloud-upload/target").json()["configured"] is False
+ assert api.get("/v1/cloud-upload/targets").json() == {"targets": [], "last": ""}
r = api.post("/v1/harnesses/upload", json={"ids": ["chrn_" + "0" * 32]})
assert r.status_code == 400 and "no cloud workspace" in r.text
assert cloud.calls == []
-def test_test_resolves_the_key_to_a_destination_without_saving(api, cloud):
- r = api.post("/v1/cloud-upload/target/test", json={"api_key": "sk-hr-good", "base_url": CLOUD})
- assert r.status_code == 200 and r.json() == {"ok": True, "org": "org_e", "org_name": "Epsilla",
- "workspace": "ws_r", "workspace_name": "Research"}
- assert api.get("/v1/cloud-upload/target").json()["configured"] is False
+def test_test_resolves_the_key_to_a_label_without_saving_and_shows_no_ids(api, cloud):
+ r = api.post("/v1/cloud-upload/targets/test", json={"api_key": "sk-hr-good", "base_url": CLOUD})
+ assert r.status_code == 200
+ j = r.json()
+ assert j["label"] == "Research (richard)"
+ assert "org_e" not in json.dumps(j) and "ws_r" not in json.dumps(j) # internal ids never shown
+ assert api.get("/v1/cloud-upload/targets").json()["targets"] == []
def test_a_bad_key_and_a_key_without_a_workspace_are_refused(api, cloud):
- assert api.put("/v1/cloud-upload/target", json={"api_key": "sk-hr-wrong", "base_url": CLOUD}).status_code == 401
- r = api.put("/v1/cloud-upload/target", json={"api_key": "sk-hr-nows", "base_url": CLOUD})
+ assert api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-wrong", "base_url": CLOUD}).status_code == 401
+ r = api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-nows", "base_url": CLOUD})
assert r.status_code == 400 and "workspace" in r.text
-def test_saving_the_target_keeps_the_key_out_of_the_response(api, cloud):
- r = api.put("/v1/cloud-upload/target", json={"api_key": "sk-hr-good", "base_url": CLOUD})
+def test_stored_targets_keep_the_key_out_and_can_be_removed(api, cloud):
+ r = api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
assert r.status_code == 200
j = r.json()
- assert j["configured"] and j["workspace_name"] == "Research" and "sk-hr-good" not in json.dumps(j)
+ assert j["label"] == "Research (richard)" and "sk-hr-good" not in json.dumps(j)
assert j["key_hint"].startswith("sk-hr-") and "…" in j["key_hint"]
- # a later PUT without a key keeps the stored one
- assert api.put("/v1/cloud-upload/target", json={"base_url": CLOUD}).json()["configured"] is True
+ lst = api.get("/v1/cloud-upload/targets").json()
+ assert len(lst["targets"]) == 1 and lst["last"] == j["id"]
+ left = api.delete(f"/v1/cloud-upload/targets?id={j['id']}").json()
+ assert left["targets"] == [] and left["last"] == ""
def test_upload_creates_then_replaces_on_the_same_id(api, cloud):
- api.put("/v1/cloud-upload/target", json={"api_key": "sk-hr-good", "base_url": CLOUD})
+ api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
hid = _harness(api)
r = api.post(f"/v1/harnesses/{hid}/upload")
assert r.status_code == 200, r.text
@@ -114,7 +118,7 @@ def test_upload_creates_then_replaces_on_the_same_id(api, cloud):
assert sent["source"] == "selfhost" and sent["workspace"] == "ws_r" # landed in the key's workspace
assert "api_key" not in json.dumps(sent) # nothing secret travels
st = api.get(f"/v1/harnesses/{hid}/upload").json()
- assert st["uploaded"] is True and st["changed"] is False and st["target"] == "Epsilla / Research"
+ assert st["uploaded"] is True and st["changed"] is False and st["target"] == "Research (richard)"
# edit locally: the chip says changed; upload again: replace, in place, same id
api.put(f"/v1/harnesses/{hid}", json={"name": "Philz one-pager v2", "base": "dsh"})
assert api.get(f"/v1/harnesses/{hid}/upload").json()["changed"] is True
@@ -125,7 +129,7 @@ def test_upload_creates_then_replaces_on_the_same_id(api, cloud):
def test_skills_travel_with_their_files_inlined(api, cloud):
- api.put("/v1/cloud-upload/target", json={"api_key": "sk-hr-good", "base_url": CLOUD})
+ api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
big = "x" * (gw._SKILL_INLINE_MAX + 100) # forces the local blob offload
hid = _harness(api, skills=[{"name": "deck", "files": [{"path": "SKILL.md", "content": big}]}])
assert "blob" in json.dumps(asyncio.run(gw._vertex_get(hid)).get("skills")) # offloaded locally
@@ -135,7 +139,7 @@ def test_skills_travel_with_their_files_inlined(api, cloud):
def test_batch_runs_every_row_and_skips_builtins(api, cloud):
- api.put("/v1/cloud-upload/target", json={"api_key": "sk-hr-good", "base_url": CLOUD})
+ api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
a, b = _harness(api, "A"), _harness(api, "B")
r = api.post("/v1/harnesses/upload", json={"ids": [a, "codex", b, "chrn_" + "f" * 32]})
assert r.status_code == 200
@@ -150,7 +154,7 @@ def test_batch_runs_every_row_and_skips_builtins(api, cloud):
def test_a_cloud_error_on_one_row_does_not_stop_the_others(api, cloud, monkeypatch):
- api.put("/v1/cloud-upload/target", json={"api_key": "sk-hr-good", "base_url": CLOUD})
+ api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
a, b = _harness(api, "A"), _harness(api, "B")
real = cloud.handle
@@ -169,7 +173,7 @@ 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})
+ api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-good", "base_url": CLOUD})
hid = _harness(api, "Collision")
real = cloud.handle
@@ -200,20 +204,20 @@ def test_the_same_harness_uploads_to_every_workspace_a_key_points_at(api, cloud)
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})
+ api.post("/v1/cloud-upload/targets", 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
+ api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-ws2", "base_url": CLOUD})
+ assert api.get(f"/v1/harnesses/{hid}/upload").json()["uploaded"] is True # chip: most recent upload anywhere
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"
+ assert st["uploaded"] is True and st["target"] == "Second (richard)"
# 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})
+ api.post("/v1/cloud-upload/targets", 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"] == hid
diff --git a/ui/src/app/revamp.css b/ui/src/app/revamp.css
index d984ffa2..5400ead4 100644
--- a/ui/src/app/revamp.css
+++ b/ui/src/app/revamp.css
@@ -1903,6 +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-remove { text-align: right; }
+ #cloudTo { width: 100%; }
.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); }
diff --git a/ui/src/components/CloudUploadCard.tsx b/ui/src/components/CloudUploadCard.tsx
index 7268e697..a5713f28 100644
--- a/ui/src/components/CloudUploadCard.tsx
+++ b/ui/src/components/CloudUploadCard.tsx
@@ -1,58 +1,67 @@
'use client';
-// Settings: where uploads land. One key, one Test, one sentence of contract. Self-hosted only.
+// Settings: the stored cloud workspaces. Add with a key, remove any time. One sentence of
+// contract. Self-hosted only.
import { useEffect, useState } from 'react';
-import { clearTarget, destination, getTarget, saveTarget, testTarget, type CloudTarget } from '@/lib/cloud-upload';
+import { addTarget, listTargets, removeTarget, testKey, type CloudTarget } from '@/lib/cloud-upload';
export function CloudUploadCard() {
- const [target, setTarget] = useState<CloudTarget | null>(null);
+ const [targets, setTargets] = useState<CloudTarget[] | null>(null);
const [key, setKey] = useState('');
const [tested, setTested] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [err, setErr] = useState<string | null>(null);
- const [savedTick, setSavedTick] = useState(false);
- useEffect(() => { getTarget().then(setTarget).catch(() => setTarget({ configured: false } as CloudTarget)); }, []);
+ useEffect(() => { listTargets().then((r) => setTargets(r.targets)).catch(() => setTargets([])); }, []);
async function test() {
setBusy(true); setErr(null);
- try { setTested(destination(await testTarget(key.trim() || undefined))); }
- catch (e) { setTested(null); setErr(e instanceof Error ? e.message : String(e)); }
+ try { setTested((await testKey(key.trim())).label); }
+ catch (e) { setErr(e instanceof Error ? e.message : String(e)); setTested(null); }
finally { setBusy(false); }
}
- async function save(e: React.FormEvent) {
+ async function add(e: React.FormEvent) {
e.preventDefault(); setBusy(true); setErr(null);
- try { setTarget(await saveTarget(key.trim())); setKey(''); setTested(null); setSavedTick(true); setTimeout(() => setSavedTick(false), 2000); }
+ try { await addTarget(key.trim()); setKey(''); setTested(null); setTargets((await listTargets()).targets); }
catch (er) { setErr(er instanceof Error ? er.message : String(er)); }
finally { setBusy(false); }
}
- async function disconnect() {
+ async function remove(id: string) {
setBusy(true); setErr(null);
- try { await clearTarget(); setTarget({ configured: false } as CloudTarget); setTested(null); }
+ try { setTargets((await removeTarget(id)).targets); }
catch (er) { setErr(er instanceof Error ? er.message : String(er)); }
finally { setBusy(false); }
}
- const shown = tested || (target?.configured ? destination(target) : null);
return (
- <form className="settings-form" onSubmit={save}>
+ <form className="settings-form" onSubmit={add}>
<div className="settings-form-head">
<div><h2>Cloud upload</h2><p>Uploading replaces the cloud copy.</p></div>
<div className="header-actions">
- <span className="save-state">{savedTick ? 'Saved' : target?.configured ? 'Connected' : 'Not connected'}</span>
- {target?.configured && <button className="button" type="button" disabled={busy} onClick={() => void disconnect()}>Disconnect</button>}
- <button className="button primary" type="submit" disabled={busy || !key.trim()}>{busy ? 'Saving…' : 'Save'}</button>
+ <span className="save-state">{targets && targets.length ? `${targets.length} workspace${targets.length === 1 ? '' : 's'}` : 'No workspaces yet'}</span>
</div>
</div>
<section className="form-section">
- <div><h3>Workspace API key</h3></div>
+ <div><h3>Workspaces</h3></div>
<div className="field-stack">
- <div className="field"><label htmlFor="cloudKey">Key</label>
+ {targets && targets.length > 0 && (
+ <div className="table-wrap cloud-rows"><table><tbody>
+ {targets.map((t) => (<tr key={t.id}>
+ <td><strong>{t.label}</strong></td>
+ <td className="cloud-note">{t.key_hint}</td>
+ <td className="cloud-remove"><button className="button quiet small" type="button" disabled={busy} onClick={() => void remove(t.id)}>Remove</button></td>
+ </tr>))}
+ </tbody></table></div>
+ )}
+ <div className="field"><label htmlFor="cloudKey">Add a workspace</label>
<div className="cloud-keyrow">
- <input id="cloudKey" type="password" autoComplete="off" placeholder={target?.configured ? target.key_hint : 'sk-hr-'}
- value={key} onChange={(e) => { setKey(e.target.value); setTested(null); }} />
- <button className="button" type="button" disabled={busy || (!key.trim() && !target?.configured)} onClick={() => void test()}>Test</button>
+ <input id="cloudKey" type="password" autoComplete="off" placeholder="sk-hr-" value={key}
+ onChange={(e) => { setKey(e.target.value); setTested(null); }} />
+ <button className="button" type="button" disabled={busy || !key.trim()} onClick={() => void test()}>Test</button>
+ <button className="button primary" type="submit" disabled={busy || !key.trim()}>Add</button>
</div>
- {shown && <span className="field-help"><span className="status healthy">{shown}</span></span>}
+ {tested
+ ? <span className="field-help"><span className="status healthy">{tested}</span></span>
+ : <span className="field-help">From the cloud console, inside the workspace, under Keys.</span>}
</div>
{err && <div className="notice"><iconify-icon icon="tabler:alert-triangle"></iconify-icon><div>{err}</div></div>}
</div>
diff --git a/ui/src/components/CloudUploadDialog.tsx b/ui/src/components/CloudUploadDialog.tsx
index d5dec41c..0fe698ba 100644
--- a/ui/src/components/CloudUploadDialog.tsx
+++ b/ui/src/components/CloudUploadDialog.tsx
@@ -1,47 +1,52 @@
'use client';
-// One dialog for one harness or many. Without a saved key the key step is inlined on top, so the
-// first upload is two clicks and every later one is one. Rows run independently on the server;
-// each answers for itself here.
+// One dialog for one harness or many. The destination is a picker over the stored workspaces,
+// with "Add a workspace" inline: paste a key, Test shows where it lands, and the upload uses it.
+// Rows run independently on the server; each answers for itself here.
import { useEffect, useState } from 'react';
-import { destination, getTarget, saveTarget, testTarget, uploadMany, type CloudTarget, type UploadRow } from '@/lib/cloud-upload';
+import { addTarget, listTargets, testKey, uploadMany, type CloudTarget, type UploadRow } from '@/lib/cloud-upload';
export interface UploadItem { id: string; name: string; builtin?: boolean; includes?: string; uploaded?: boolean }
+const ADD = '__add__';
export function CloudUploadDialog({ items, onClose, onDone }: {
items: UploadItem[]; onClose: () => void; onDone?: (rows: UploadRow[]) => void;
}) {
- const [target, setTarget] = useState<CloudTarget | null>(null);
+ const [targets, setTargets] = useState<CloudTarget[] | null>(null);
+ const [choice, setChoice] = useState<string>('');
const [key, setKey] = useState('');
- const [tested, setTested] = useState<{ org_name: string; org: string; workspace_name: string; workspace: string } | null>(null);
+ const [tested, setTested] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [err, setErr] = useState<string | null>(null);
const [rows, setRows] = useState<UploadRow[] | null>(null);
- useEffect(() => { getTarget().then(setTarget).catch(() => setTarget({ configured: false } as CloudTarget)); }, []);
+ useEffect(() => {
+ listTargets().then((r) => { setTargets(r.targets); setChoice(r.targets.length ? (r.last || r.targets[0].id) : ADD); })
+ .catch(() => { setTargets([]); setChoice(ADD); });
+ }, []);
const eligible = items.filter((i) => !i.builtin);
const single = items.length === 1;
- const needKey = target !== null && !target.configured;
- const dest = target?.configured ? destination(target) : tested ? destination(tested) : '';
+ const adding = choice === ADD;
async function test() {
setBusy(true); setErr(null);
- try { setTested(await testTarget(key.trim())); }
+ try { setTested((await testKey(key.trim())).label); }
catch (e) { setErr(e instanceof Error ? e.message : String(e)); setTested(null); }
finally { setBusy(false); }
}
async function run() {
setBusy(true); setErr(null);
try {
- if (needKey) setTarget(await saveTarget(key.trim()));
- const r = await uploadMany(eligible.map((i) => i.id));
+ let targetId = choice;
+ if (adding) { const t = await addTarget(key.trim()); targetId = t.id; }
+ const r = await uploadMany(eligible.map((i) => i.id), targetId);
setRows(r.results); onDone?.(r.results);
} catch (e) { setErr(e instanceof Error ? e.message : String(e)); }
finally { setBusy(false); }
}
const title = single ? `Upload "${items[0].name}"` : `Upload ${eligible.length} to cloud`;
- const canUpload = !busy && eligible.length > 0 && (!needKey || (key.trim().length > 0 && tested !== null));
+ const canUpload = !busy && eligible.length > 0 && (!adding || (key.trim().length > 0 && tested !== null));
return (
<div className="modal-backdrop" onClick={onClose}>
@@ -51,12 +56,12 @@ export function CloudUploadDialog({ items, onClose, onDone }: {
<button className="icon-button modal-close" type="button" aria-label="Close dialog" onClick={onClose}><iconify-icon icon="tabler:x"></iconify-icon></button>
</div>
<div className="modal-body">
- {target === null ? <p className="field-help">Loading</p> : rows ? (
+ {targets === null ? <p className="field-help">Loading</p> : rows ? (
<div className="table-wrap cloud-rows"><table><tbody>
{rows.map((r) => {
const it = items.find((i) => i.id === r.id);
return (<tr key={r.id}>
- <td><strong>{it?.name || r.name || r.id}</strong></td>
+ <td><strong>{it?.name || r.name || ''}</strong></td>
<td>{r.ok ? (r.action === 'create' ? 'Created' : 'Replaced') : r.action === 'skip' ? 'Skipped' : 'Failed'}</td>
<td className="cloud-note">{r.ok ? '' : r.error}</td>
</tr>);
@@ -64,22 +69,30 @@ export function CloudUploadDialog({ items, onClose, onDone }: {
</tbody></table></div>
) : (
<div className="field-stack">
- {needKey && (
+ <div className="field"><label htmlFor="cloudTo">To</label>
+ <select id="cloudTo" value={choice} disabled={busy}
+ onChange={(e) => { setChoice(e.target.value); setErr(null); }}>
+ {targets.map((t) => <option key={t.id} value={t.id}>{t.label}</option>)}
+ <option value={ADD}>Add a workspace…</option>
+ </select>
+ </div>
+ {adding && (
<div className="field"><label htmlFor="cloudKey">Workspace API key</label>
<div className="cloud-keyrow">
<input id="cloudKey" type="password" autoComplete="off" placeholder="sk-hr-" value={key}
onChange={(e) => { setKey(e.target.value); setTested(null); }} />
<button className="button" type="button" disabled={busy || !key.trim()} onClick={() => void test()}>Test</button>
</div>
- <span className="field-help">Get one in the cloud console under Keys, inside the workspace.</span>
+ {tested
+ ? <span className="field-help"><span className="status healthy">{tested}</span></span>
+ : <span className="field-help">From the cloud console, inside the workspace, under Keys.</span>}
</div>
)}
- <dl className="cloud-kv">
- <div><dt>To</dt><dd>{dest || '…'}</dd></div>
- {single ? (
+ {single && (
+ <dl className="cloud-kv">
<div><dt>Includes</dt><dd>{items[0].includes || 'instructions'}</dd></div>
- ) : null}
- </dl>
+ </dl>
+ )}
{!single && (
<div className="table-wrap cloud-rows"><table><tbody>
{items.map((i) => (<tr key={i.id}>
diff --git a/ui/src/lib/cloud-upload.ts b/ui/src/lib/cloud-upload.ts
index 5872afae..b48ee72d 100644
--- a/ui/src/lib/cloud-upload.ts
+++ b/ui/src/lib/cloud-upload.ts
@@ -1,24 +1,18 @@
// Upload a local harness to a hosted workspace. One-way: this instance is the source of truth
-// and the hosted copy is a deployment target; an upload replaces it. The key never reaches the
-// browser after Save; the gateway does the upload. Self-hosted only.
+// and the hosted copy is a deployment target; an upload replaces it. Several destinations can be
+// stored; every upload names one. Keys live encrypted on this instance's gateway, which does the
+// upload; the browser never holds them after save. Self-hosted only.
import { gw } from '@/lib/harness';
-export interface CloudTarget {
- configured: boolean; base_url: string; key_hint: string;
- org: string; org_name: string; workspace: string; workspace_name: string;
-}
+export interface CloudTarget { id: string; base_url: string; key_hint: string; member: string; workspace_name: string; label: string }
export interface CloudStatus { uploaded: boolean; uploaded_at?: number; target?: string; changed?: boolean }
-export interface UploadRow { id: string; ok: boolean; action: 'create' | 'replace' | 'skip'; name?: string; error?: string }
+export interface UploadRow { id: string; ok: boolean; action: 'create' | 'replace' | 'skip'; name?: string; remote_id?: string; error?: string }
-export const destination = (t: { org?: string; org_name?: string; workspace?: string; workspace_name?: string }) =>
- `${t.org_name || t.org || ''} / ${t.workspace_name || t.workspace || ''}`;
-
-export const getTarget = () => gw<CloudTarget>('GET', '/v1/cloud-upload/target');
-export const testTarget = (api_key?: string) =>
- gw<{ ok: true; org: string; org_name: string; workspace: string; workspace_name: string }>('POST', '/v1/cloud-upload/target/test', api_key ? { api_key } : {});
-export const saveTarget = (api_key: string) => gw<CloudTarget>('PUT', '/v1/cloud-upload/target', { api_key });
-export const clearTarget = () => gw<{ configured: false }>('DELETE', '/v1/cloud-upload/target');
-export const uploadOne = (id: string) => gw<UploadRow & { status: CloudStatus }>('POST', `/v1/harnesses/${encodeURIComponent(id)}/upload`);
-export const uploadMany = (ids: string[]) => gw<{ results: UploadRow[]; target: CloudTarget }>('POST', '/v1/harnesses/upload', { ids });
+export const listTargets = () => gw<{ targets: CloudTarget[]; last: string }>('GET', '/v1/cloud-upload/targets');
+export const addTarget = (api_key: string) => gw<CloudTarget>('POST', '/v1/cloud-upload/targets', { api_key });
+export const testKey = (api_key: string) => gw<{ ok: true; label: string }>('POST', '/v1/cloud-upload/targets/test', { api_key });
+export const removeTarget = (id: string) => gw<{ targets: CloudTarget[]; last: string }>('DELETE', `/v1/cloud-upload/targets?id=${encodeURIComponent(id)}`);
+export const uploadOne = (id: string, target: string) => gw<UploadRow & { status: CloudStatus }>('POST', `/v1/harnesses/${encodeURIComponent(id)}/upload`, { target });
+export const uploadMany = (ids: string[], target: string) => gw<{ results: UploadRow[]; target: CloudTarget }>('POST', '/v1/harnesses/upload', { ids, target });
export const statusOne = (id: string) => gw<CloudStatus>('GET', `/v1/harnesses/${encodeURIComponent(id)}/upload`);
export const statusAll = () => gw<{ harnesses: Record<string, CloudStatus> }>('GET', '/v1/cloud-upload/status');