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
console + gateway: Deploy to Cloud, one click from a setup's page bar (#574)
github-actions[bot]7fa821e09482
diff --git a/gateway/app.py b/gateway/app.pyindex 78a2c11e..2e36c3dd 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -6113,12 +6113,9 @@ class ConnectBody(BaseModel):instance: str = ""[email protected]("/v1/admin/connect")-async def admin_connect_start(body: ConnectBody, request: Request) -> dict:- """Open a key hand-off with the hosted service: the console opens the returned url in a new- tab and polls the code here; the secret never leaves this gateway."""- await _require_integrations_admin(request)- instance = (body.instance or "").strip() or (request.headers.get("host") or "this instance")+async def _connect_open(instance: str, purpose: str = "") -> dict:+ """Open a key hand-off with the hosted service and keep its secret here: {code, url, expires_in}.+ `purpose` marks a hand-off a route other than Bring your own key reads (Deploy to Cloud)."""try:async with httpx.AsyncClient(timeout=15.0) as c:r = await c.post(HR_HOSTED_CONNECT_URL, json={"instance": instance})@@ -6135,10 +6132,38 @@ async def admin_connect_start(body: ConnectBody, request: Request) -> dict:if now - v["at"] > 3600:_CONNECTS.pop(k, None)_connects_sweep()- _CONNECTS[code] = {"secret": secret, "at": now}+ _CONNECTS[code] = {"secret": secret, "at": now, **({"purpose": purpose} if purpose else {})}return {"code": code, "url": str(j["url"]), "expires_in": j.get("expires_in")}[email protected]("/v1/admin/connect")+async def admin_connect_start(body: ConnectBody, request: Request) -> dict:+ """Open a key hand-off with the hosted service: the console opens the returned url in a new+ tab and polls the code here; the secret never leaves this gateway."""+ await _require_integrations_admin(request)+ instance = (body.instance or "").strip() or (request.headers.get("host") or "this instance")+ return await _connect_open(instance)+++async def _connect_fetch(code: str, entry: dict) -> dict | None:+ """One read of an open hand-off from the hosted service: None while the person is still on its+ page, the hosted answer once the key is ready. Raises 410 when the code expired or was used."""+ try:+ async with httpx.AsyncClient(timeout=15.0) as c:+ r = await c.get(f"{HR_HOSTED_CONNECT_URL}/{code}", headers={"X-Connect-Secret": entry["secret"]})+ except Exception as e: # noqa: BLE001+ raise HTTPException(502, f"HarnessRouter could not be reached: {type(e).__name__}")+ j = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}+ if r.status_code == 202:+ return None+ if r.status_code == 410:+ _CONNECTS.pop(code, None)+ raise HTTPException(410, "That key hand-off expired or was already used. Get a key again.")+ if r.status_code >= 400:+ raise HTTPException(502, f"HarnessRouter answered HTTP {r.status_code} on the key hand-off.")+ return j if isinstance(j, dict) else {}++@app.get("/v1/admin/connect/{code}")async def admin_connect_poll(code: str, request: Request):"""One poll of the hand-off: 202 while the person is still on the hosted page, 200 once with@@ -6147,25 +6172,15 @@ async def admin_connect_poll(code: str, request: Request):await _require_integrations_admin(request)_connects_sweep()entry = _CONNECTS.get(code)- if not entry:+ if not entry or entry.get("purpose"): # none, or another route's (Deploy to Cloud)raise HTTPException(410, "That key hand-off is not open. Get a key again.")if entry.get("ready"):# The hosted side hands the key over once; this side answers every poll after that with the# same body until the code expires, so a slow or dropped answer costs nothing.return entry["ready"]- try:- async with httpx.AsyncClient(timeout=15.0) as c:- r = await c.get(f"{HR_HOSTED_CONNECT_URL}/{code}", headers={"X-Connect-Secret": entry["secret"]})- except Exception as e: # noqa: BLE001- raise HTTPException(502, f"HarnessRouter could not be reached: {type(e).__name__}")- j = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}- if r.status_code == 202:+ j = await _connect_fetch(code, entry)+ if j is None:return JSONResponse({"status": "pending"}, status_code=202)- if r.status_code == 410:- _CONNECTS.pop(code, None)- raise HTTPException(410, "That key hand-off expired or was already used. Get a key again.")- if r.status_code >= 400:- raise HTTPException(502, f"HarnessRouter answered HTTP {r.status_code} on the key hand-off.")key = str(j.get("api_key") or "")endpoint = str(j.get("endpoint") or HR_HOSTED_PROVIDER_BASE)models_url = str(j.get("models_url") or HR_HOSTED_MODELS_URL)@@ -21187,8 +21202,12 @@ async def _cloud_base_refused(base: str) -> str | None:return await _internal_target(u.hostname, u.port or 443)-async def _cloud_me(base_url: str, api_key: str) -> dict:- """Resolve a key to where an upload lands. Raises HTTPException with the hosted side's words."""+async def _cloud_me(base_url: str, api_key: str, *, default_workspace: bool = False) -> dict:+ """Resolve a key to where an upload lands. Raises HTTPException with the hosted side's words.+ `default_workspace`: the key is one HarnessRouter Cloud's sign-in minted for the organization's+ Default Workspace (its get-key page mints with workspace "" and workspace_default), which its+ /v1/me answers with no workspace; what such a key creates is unstamped, and unstamped is the+ Default Workspace's, so that is where the copy lands and what it is called here."""refused = await _cloud_base_refused(base_url)if refused:raise HTTPException(400, f"that address cannot be used: {refused}")@@ -21204,6 +21223,8 @@ async def _cloud_me(base_url: str, api_key: str) -> dict:me = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}if not isinstance(me, dict) or not me.get("org"):raise HTTPException(502, "cloud answered without an org")+ if not me.get("workspace") and default_workspace:+ me = {**me, "workspace": f"{me['org']}__hr_default", "workspace_name": me.get("workspace_name") or "Default Workspace"}if not me.get("workspace"):raise HTTPException(400, "this key is not bound to a workspace; mint one inside the workspace")return me@@ -21319,8 +21340,10 @@ async def _cloud_upload_one(org: str, hid: str, target: dict, records: dict) ->except Exception as e: # noqa: BLE001return {"id": hid, "ok": False, "action": action, "error": f"could not reach cloud: {str(e)[:120]}"}if r.status_code in (200, 201):+ # the form it was sent in (plugins whole, or as their skills and servers): the status+ # compares the setup now against that same formper[tkey] = {"fingerprint": fp, "uploaded_at": int(time.time() * 1000),- "remote_id": attempt, "target": _cloud_label(target)}+ "remote_id": attempt, "target": _cloud_label(target), "plugins_ok": plugins_ok}return {"id": hid, "ok": True, "action": action, "name": body["name"], "remote_id": attempt}detail = ""try:@@ -21400,6 +21423,60 @@ async def cloud_targets_add(body: CloudTargetBody, request: Request) -> dict:return _cloud_target_public(t)+_DEPLOY = "deploy"++[email protected]("/v1/cloud-upload/connect", include_in_schema=False)+async def cloud_connect_start(body: ConnectBody, request: Request) -> dict:+ """Deploy to Cloud, the first time: open the HarnessRouter Cloud sign-in hand-off. The person+ signs in (or up) on the page `url` names, the hosted side mints a key in their workspace, and+ the next poll (cloud_connect_poll) stores it here as the destination of every deploy. No key is+ pasted and none reaches the browser."""+ await _require_integrations_admin(request)+ instance = (body.instance or "").strip() or (request.headers.get("host") or "this instance")+ return await _connect_open(instance, purpose=_DEPLOY)++[email protected]("/v1/cloud-upload/connect/{code}", include_in_schema=False)+async def cloud_connect_poll(code: str, request: Request):+ """One poll of a Deploy to Cloud hand-off: 202 while the person is still on the hosted page;+ 200 with the stored destination (its public view, never the key) once the key has landed, and+ on every poll after that until the code expires; 410 when the code is not one of these."""+ await _require_integrations_admin(request)+ _connects_sweep()+ entry = _CONNECTS.get(code)+ if not entry or entry.get("purpose") != _DEPLOY:+ raise HTTPException(410, "That sign-in is not open any more. Deploy again to start a new one.")+ if entry.get("target"):+ return {"status": "ready", "target": entry["target"]}+ j = await _connect_fetch(code, entry)+ if j is None:+ return JSONResponse({"status": "pending"}, status_code=202)+ key = str(j.get("api_key") or "")+ if not key:+ raise HTTPException(502, "HarnessRouter Cloud answered without a key. Deploy again.")+ # where the key works: the API the hand-off names (its model endpoint is <base>/v1/provider)+ endpoint = str(j.get("endpoint") or "").rstrip("/")+ base = endpoint[: -len("/v1/provider")] if endpoint.endswith("/v1/provider") else _CLOUD_UPLOAD_DEFAULT_BASE+ me = await _cloud_me(base, key, default_workspace=True)+ 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)+ entry["target"] = _cloud_target_public(t)+ return {"status": "ready", "target": entry["target"]}+++def _cloud_open_url(target: dict | None, remote_id: str) -> str:+ """Where a deployed copy opens in HarnessRouter Cloud's console: its setup page, when the+ destination is HarnessRouter Cloud itself ('' for another address, whose console is unknown)."""+ base = str((target or {}).get("base_url") or _CLOUD_UPLOAD_DEFAULT_BASE).rstrip("/")+ return f"{HR_HOSTED_CONSOLE}/studio/{remote_id}" if remote_id and base == HR_HOSTED_BASE else ""++@app.post("/v1/cloud-upload/targets/test")async def cloud_targets_test(body: CloudTargetBody, request: Request) -> dict:"""Where would this key land. Nothing is stored."""@@ -21485,7 +21562,9 @@ async def cloud_upload_one(hid: str, request: Request, body: CloudUploadOneBodyawait _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}}+ return {**res, "open_url": _cloud_open_url(target, str(res.get("remote_id") or "")),+ "target_name": _cloud_label(target),+ "status": _cloud_status(hid, records, None, target) | {"changed": False}}@app.get("/v1/harnesses/{hid}/upload", include_in_schema=False)@@ -21499,10 +21578,14 @@ async def cloud_upload_status(hid: str, request: Request) -> dict: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- rec = max(per.values(), key=lambda r: r.get("uploaded_at") or 0)+ tkey, rec = max(per.items(), key=lambda kv: kv[1].get("uploaded_at") or 0)+ # compared in the form it was sent in: a copy sent to a Cloud that takes plugins whole carries+ # them as such, and read back the other way every deploy there looked changed at once (10-23)+ fp = _cloud_fingerprint(await _cloud_harness_body(p.get("org", ""), hid, v, bool(rec.get("plugins_ok")))) if v else None+ target = (await _cloud_targets())["targets"].get(tkey)return {"uploaded": True, "uploaded_at": rec.get("uploaded_at"), "target": rec.get("target"),- "changed": bool(fp) and rec.get("fingerprint") != fp}+ "changed": bool(fp) and rec.get("fingerprint") != fp,+ "open_url": _cloud_open_url(target, str(rec.get("remote_id") or "")) if target else ""}@app.get("/v1/cloud-upload/status")@@ -21515,8 +21598,8 @@ async def cloud_upload_status_all(request: Request) -> dict:if not per:continuev = await _vertex_get(hid)- fp = _cloud_fingerprint(await _cloud_harness_body(p.get("org", ""), hid, v)) if v else Nonerec = max(per.values(), key=lambda r: r.get("uploaded_at") or 0)+ fp = _cloud_fingerprint(await _cloud_harness_body(p.get("org", ""), hid, v, bool(rec.get("plugins_ok")))) if v else Noneout[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_deploy_to_cloud.py b/gateway/tests/test_deploy_to_cloud.pynew file mode 100644index 00000000..b07583e2--- /dev/null+++ b/gateway/tests/test_deploy_to_cloud.py@@ -0,0 +1,195 @@+"""Deploy to Cloud: a setup's one click to HarnessRouter Cloud. The first time it opens the Cloud sign-in+hand-off (POST /v1/cloud-upload/connect), the person signs in on the page it names, and the key the+hosted side mints lands HERE as the destination (GET /v1/cloud-upload/connect/{code}): the browser+never holds it. Every deploy after that is the existing upload, which now says where the copy opens.+The hosted side is a mock at the HTTP boundary, as in test_cloud_upload."""+import asyncio+import json+import sys+from pathlib import Path++import httpx+import pytest+from fastapi.testclient import TestClient++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import app as gw # noqa: E402 (environment: conftest.py)++from test_cloud_upload import Cloud, ORG # noqa: E402++HOSTED = "https://api.harnessrouter.ai"+++class CloudWithSignIn(Cloud):+ """The hosted side, with its pairing (/v1/connect) in front of the API the key opens."""+ def __init__(self):+ super().__init__()+ self.pairings: dict[str, dict] = {}++ def handle(self, req: httpx.Request) -> httpx.Response:+ p = req.url.path+ if p == "/v1/connect" and req.method == "POST":+ code = f"code{len(self.pairings) + 1}"+ self.pairings[code] = {"secret": f"secret-{code}", "key": "", "instance": json.loads(req.content).get("instance")}+ self.calls.append((req.method, p))+ return httpx.Response(200, json={"code": code, "secret": f"secret-{code}",+ "url": f"https://app.harnessrouter.ai/get-key?code={code}", "expires_in": 1800})+ if p.startswith("/v1/connect/") and req.method == "GET":+ self.calls.append((req.method, p))+ pr = self.pairings.get(p.rsplit("/", 1)[-1])+ if not pr:+ return httpx.Response(410, json={"detail": "gone"})+ if req.headers.get("x-connect-secret") != pr["secret"]:+ return httpx.Response(403, json={"detail": "wrong connection secret"})+ if not pr["key"]:+ return httpx.Response(202, json={"status": "pending"})+ if pr.get("delivered"):+ return httpx.Response(410, json={"detail": "already handed over"})+ pr["delivered"] = True+ return httpx.Response(200, json={"status": "ready", "api_key": pr["key"], "name": "HarnessRouter API",+ "endpoint": f"{HOSTED}/v1/provider"})+ return super().handle(req)++ def sign_in(self, code: str, key: str = "sk-hr-good"):+ """The person finishing on the hosted page: the key minted for their workspace."""+ self.pairings[code]["key"] = key+++def cloud(monkeypatch):+ c = CloudWithSignIn()+ real = httpx.AsyncClient++ class Patched(real):+ def __init__(self, *a, **kw):+ kw["transport"] = httpx.MockTransport(lambda r: c.handle(r))+ super().__init__(*a, **kw)+ monkeypatch.setattr(gw.httpx, "AsyncClient", Patched)+ monkeypatch.setattr(gw, "_checked_clients", {})+ monkeypatch.setattr(gw, "_CONNECTS", {})+ return c+++def api(monkeypatch):+ async def principal(request):+ return {"org": ORG, "member": "me@local"}+ monkeypatch.setattr(gw, "_principal", principal)+ asyncio.run(gw.BACKING.secrets.put(gw.GLOBAL_TENANT, gw._CLOUD_UPLOAD_KEY, "", require_encryption=True))+ asyncio.run(gw.BACKING.secrets.put(gw.GLOBAL_TENANT, gw._CLOUD_UPLOAD_RECORDS_KEY, ""))+ return TestClient(gw.app)+++def _harness(api, name="Weekly feedback summary") -> str:+ r = api.post("/v1/harnesses", json={"name": name, "base": "hermes", "default_model": "gpt-6.1-sol",+ "system_prompt": "Summarize the week's feedback by theme."})+ assert r.status_code == 200, r.text+ return r.json()["id"]+++def test_the_first_deploy_signs_in_and_the_key_lands_here_never_in_the_browser(api, cloud):+ start = api.post("/v1/cloud-upload/connect", json={"instance": "my-box:3000"})+ assert start.status_code == 200, start.text+ code, url = start.json()["code"], start.json()["url"]+ assert url == f"https://app.harnessrouter.ai/get-key?code={code}"+ assert "secret" not in json.dumps(start.json()) # the pairing's secret stays here+ assert cloud.pairings[code]["instance"] == "my-box:3000"+ # still on the hosted page+ assert api.get(f"/v1/cloud-upload/connect/{code}").status_code == 202+ assert api.get("/v1/cloud-upload/targets").json()["targets"] == []+ # signed in: the key is now this instance's destination, and the answer carries no key+ cloud.sign_in(code)+ r = api.get(f"/v1/cloud-upload/connect/{code}")+ assert r.status_code == 200, r.text+ t = r.json()["target"]+ assert r.json()["status"] == "ready" and t["label"] == "Research (richard)" and t["base_url"] == HOSTED+ assert "sk-hr-good" not in r.text+ lst = api.get("/v1/cloud-upload/targets").json()+ assert [x["id"] for x in lst["targets"]] == [t["id"]] and lst["last"] == t["id"]+ # the hosted side hands a key over once; polls after that answer the same destination+ again = api.get(f"/v1/cloud-upload/connect/{code}")+ assert again.status_code == 200 and again.json()["target"] == t+ # and the deploy is one call from here+ hid = _harness(api)+ up = api.post(f"/v1/harnesses/{hid}/upload")+ assert up.status_code == 200, up.text+ assert cloud.harnesses[hid]["system_prompt"] == "Summarize the week's feedback by theme."+++def test_a_deploy_hand_off_and_a_key_hand_off_are_never_each_others(api, cloud):+ deploy = api.post("/v1/cloud-upload/connect", json={}).json()["code"]+ key = api.post("/v1/admin/connect", json={}).json()["code"]+ cloud.sign_in(deploy)+ cloud.sign_in(key)+ # Bring your own key cannot read a deploy hand-off's key, and the other way around+ assert api.get(f"/v1/admin/connect/{deploy}").status_code == 410+ assert api.get(f"/v1/cloud-upload/connect/{key}").status_code == 410+ assert api.get("/v1/cloud-upload/targets").json()["targets"] == []+ assert api.get(f"/v1/cloud-upload/connect/{deploy}").status_code == 200+ assert api.get("/v1/cloud-upload/connect/nope").status_code == 410+++def test_the_sign_in_key_of_the_default_workspace_lands_there_while_a_pasted_one_is_still_refused(api, cloud):+ """Cloud's sign-in mints its key for the organization's Default Workspace (workspace "" with+ workspace_default), and Cloud's /v1/me answers no workspace for it (2026-10-23). What it creates+ is unstamped, which is the Default Workspace's: that is the destination, by that name. A key+ pasted by hand keeps the rule: no workspace, refused."""+ code = api.post("/v1/cloud-upload/connect", json={}).json()["code"]+ cloud.sign_in(code, key="sk-hr-nows")+ r = api.get(f"/v1/cloud-upload/connect/{code}")+ assert r.status_code == 200, r.text+ assert r.json()["target"]["label"] == "Default Workspace (richard)"+ hid = _harness(api)+ assert api.post(f"/v1/harnesses/{hid}/upload").status_code == 200+ assert hid in cloud.harnesses+ pasted = api.post("/v1/cloud-upload/targets", json={"api_key": "sk-hr-nows", "base_url": HOSTED})+ assert pasted.status_code == 400 and "workspace" in pasted.text+++def test_the_deploy_and_the_status_say_where_the_copy_opens_in_cloud(api, cloud):+ code = api.post("/v1/cloud-upload/connect", json={}).json()["code"]+ cloud.sign_in(code)+ api.get(f"/v1/cloud-upload/connect/{code}")+ hid = _harness(api)+ up = api.post(f"/v1/harnesses/{hid}/upload").json()+ assert up["open_url"] == f"https://app.harnessrouter.ai/studio/{up['remote_id']}"+ assert up["target_name"] == "Research (richard)"+ st = api.get(f"/v1/harnesses/{hid}/upload").json()+ assert st["uploaded"] is True and st["changed"] is False and st["open_url"] == up["open_url"]+ # changed here: the status says so, and keeps the link to the copy in Cloud+ assert api.put(f"/v1/harnesses/{hid}", json={"name": "Weekly feedback summary", "base": "hermes",+ "system_prompt": "Summarize it in five bullets."}).status_code == 200+ st = api.get(f"/v1/harnesses/{hid}/upload").json()+ assert st["changed"] is True and st["open_url"] == up["open_url"]+++def test_a_destination_other_than_cloud_itself_has_no_link(api, cloud):+ assert gw._cloud_open_url({"base_url": "https://cloud.test"}, "chrn_x") == ""+ assert gw._cloud_open_url({"base_url": HOSTED + "/"}, "chrn_x") == "https://app.harnessrouter.ai/studio/chrn_x"+ assert gw._cloud_open_url({"base_url": HOSTED}, "") == ""+++def test_a_copy_sent_to_a_cloud_that_takes_plugins_whole_reads_current_until_it_changes(api, cloud):+ """HarnessRouter Cloud takes plugins whole (its /v1/uhp says capabilities.plugins), so a deploy+ sends them that way, and the status compared the setup in the other form: every deploy there+ read "changed" at once, and a reload right after Deploy showed Update Cloud (the review+ instance, 10-23). The status compares in the form the copy was sent in."""+ real = cloud.handle++ def with_uhp(req):+ if req.url.path == "/v1/uhp":+ return httpx.Response(200, json={"capabilities": {"plugins": True}})+ return real(req)+ cloud.handle = with_uhp+ code = api.post("/v1/cloud-upload/connect", json={}).json()["code"]+ cloud.sign_in(code)+ api.get(f"/v1/cloud-upload/connect/{code}")+ hid = _harness(api)+ assert api.post(f"/v1/harnesses/{hid}/upload").status_code == 200+ assert "plugins" in cloud.harnesses[hid] # sent with plugins whole+ assert api.get(f"/v1/harnesses/{hid}/upload").json()["changed"] is False+ assert api.get("/v1/cloud-upload/status").json()["harnesses"][hid]["changed"] is False+ assert api.put(f"/v1/harnesses/{hid}", json={"name": "Weekly feedback summary", "base": "hermes",+ "system_prompt": "Shorter."}).status_code == 200+ assert api.get(f"/v1/harnesses/{hid}/upload").json()["changed"] is True+diff --git a/ui/src/components/hrui/hrui-console.css b/ui/src/components/hrui/hrui-console.cssindex 9d7b8a1e..fcd4e7dd 100644--- a/ui/src/components/hrui/hrui-console.css+++ b/ui/src/components/hrui/hrui-console.css@@ -1023,3 +1023,12 @@#hrui .tk-d .tp-head .th-row{display:flex;align-items:center;gap:16px}#hrui .tk-d .tp-head .th-row>.tp-t{flex:1;min-width:0}#hrui .tk-d .tp-head .th-row>.tk-acts{margin-left:auto}++/* Deploy to Cloud (setup/DeployCloud.tsx): the page bar's second action, beside Set up the app. Its menu+ (In Cloud) hangs under it, right aligned, as the task filter's does (.rng-pop); Update Cloud carries a+ dot; on a phone it folds to its icon like the bar's other action (.ag-act) */+#hrui .dc-w{position:relative;display:inline-flex;flex:none}+#hrui .dc-b{position:relative}+#hrui .dc-b.on>svg{color:var(--accent)}+#hrui .dc-dot{position:absolute;top:5px;right:5px;width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 2px var(--bg)}+#hrui .dc-pop{min-width:232px;white-space:nowrap}diff --git a/ui/src/components/hrui/setup/CloudUploadSheet.tsx b/ui/src/components/hrui/setup/CloudUploadSheet.tsxindex e08b4117..1cc101a5 100644--- a/ui/src/components/hrui/setup/CloudUploadSheet.tsx+++ b/ui/src/components/hrui/setup/CloudUploadSheet.tsx@@ -1,12 +1,13 @@'use client';-// Upload to cloud (a setup's Settings, its row under the layers): this setup copied to a workspace on-// HarnessRouter Cloud, one way. This instance stays the source: an upload creates the cloud copy, and-// each later one replaces it. Where it goes is one of the cloud workspaces this instance keeps a key-// for (the workspace settings' Cloud upload lists them); one can be added here by pasting a key from-// that workspace. The key is kept on this instance and never read back. What is said of the last-// upload (when, and whether the setup changed since) is the server's own status.+// Deploy to another workspace (Deploy to Cloud's menu, DeployCloud.tsx): this setup copied to a+// workspace on HarnessRouter Cloud other than the one its one-click deploy goes to, one way. This+// instance stays the source: a deploy creates the cloud copy, and each later one replaces it. Where it+// goes is one of the cloud workspaces this instance keeps a key for (the workspace settings' Cloud+// upload lists them); one can be added here by pasting a key from that workspace. The key is kept on+// this instance and never read back. What is said of the last deploy (when, and whether the setup+// changed since) is the server's own status.import { useEffect, useRef, useState } from 'react';-import { addTarget, listTargets, statusOne, uploadOne, type CloudStatus, type CloudTarget } from '@/lib/cloud-upload';+import { addTarget, listTargets, uploadOne, type CloudStatus, type CloudTarget } from '@/lib/cloud-upload';import { ago } from '../setups';import { Sheet, SheetTop } from '../Sheet';import { toast } from '../toast';@@ -18,19 +19,7 @@ const ADD = '__add__';export function cloudLine(s: CloudStatus | null): string {if (!s || !s.uploaded) return '';const when = s.uploaded_at ? ago(s.uploaded_at > 1e12 ? s.uploaded_at : s.uploaded_at * 1000) : '';- return s.changed ? `Changed since its upload${when ? ` ${when}` : ''}` : `Uploaded${when ? ` ${when}` : ''}`;-}--/** The setup's cloud status, read once per setup (null while read, or when it could not be). */-export function useCloudStatus(id: string, n = 0): CloudStatus | null {- const [s, setS] = useState<CloudStatus | null>(null);- useEffect(() => {- let alive = true;- setS(null);- statusOne(id).then((x) => { if (alive) setS(x); }).catch(() => { /* the row says nothing of it */ });- return () => { alive = false; };- }, [id, n]);- return s;+ return s.changed ? `Changed since its deploy${when ? ` ${when}` : ''}` : `Deployed${when ? ` ${when}` : ''}`;}export function CloudUploadSheet({ id, name, status, onClose, onDone }: {@@ -73,18 +62,18 @@ export function CloudUploadSheet({ id, name, status, onClose, onDone }: {setBusy(true);try {const r = await uploadOne(id, choice);- if (!r.ok) { toast(plain(new Error(r.error || ''), 'The setup could not be uploaded. Try again.')); return; }- toast(r.action === 'create' ? `${name} is in the cloud workspace.` : `${name}’s cloud copy is replaced.`);+ if (!r.ok) { toast(plain(new Error(r.error || ''), `${name} could not be deployed. Try again.`)); return; }+ toast(r.action === 'create' ? `${name} is deployed to that workspace.` : `${name}’s copy in that workspace is replaced.`);onDone();onClose();- } catch (e) { toast(plain(e, 'The setup could not be uploaded. Try again.')); }+ } catch (e) { toast(plain(e, `${name} could not be deployed. Try again.`)); }finally { setBusy(false); }}const line = cloudLine(status);return (<Sheet onClose={onClose} labelledBy="cuh" className="small-sheet" busy={busy}>- <SheetTop id="cuh" title="Upload to cloud" sub={`Copies ${name} to a workspace on HarnessRouter Cloud. This instance stays the source: uploading again replaces the copy.`} onClose={onClose} />+ <SheetTop id="cuh" title="Deploy to another workspace" sub={`Deploys ${name} to a workspace on HarnessRouter Cloud. This instance stays the source: deploying again replaces the copy.`} onClose={onClose} />{line ? <p className="set-help">{line}.</p> : null}{targets === null ? (failed@@ -114,7 +103,7 @@ export function CloudUploadSheet({ id, name, status, onClose, onDone }: {<div className="sheet-actions"><button type="button" className="btn" disabled={busy} onClick={onClose}>Cancel</button><button type="button" className="btn primary" disabled={busy || adding || !choice || targets === null} onClick={() => void upload()}>- {busy && !adding ? 'Uploading…' : status?.uploaded ? 'Replace the copy' : 'Upload'}+ {busy && !adding ? 'Deploying…' : 'Deploy'}</button></div></Sheet>diff --git a/ui/src/components/hrui/setup/DeployCloud.test.tsx b/ui/src/components/hrui/setup/DeployCloud.test.tsxnew file mode 100644index 00000000..d8696eaa--- /dev/null+++ b/ui/src/components/hrui/setup/DeployCloud.test.tsx@@ -0,0 +1,147 @@+/** @jest-environment jsdom */+// Deploy to Cloud, the setup page bar's second action: one click deploys; the first time it opens the+// HarnessRouter Cloud sign-in in a new tab and goes on by itself once the key lands on this instance;+// it always says where the setup stands (Deploy to Cloud, Update Cloud, In Cloud).+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';++jest.mock('@/lib/cloud-upload', () => ({+ listTargets: jest.fn(), statusOne: jest.fn(), uploadOne: jest.fn(), addTarget: jest.fn(),+ startDeploySignIn: jest.fn(), pollDeploySignIn: jest.fn(),+}));+jest.mock('../toast', () => ({ toast: jest.fn() }));++import { DeployCloud, SIGNIN_EVERY_MS } from './DeployCloud';++const lib = jest.requireMock('@/lib/cloud-upload') as Record<string, jest.Mock>;+const { toast } = jest.requireMock('../toast') as { toast: jest.Mock };+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });++let root: Root;+let host: HTMLElement;+const TARGET = { id: 't1', label: 'Research (richard)', revoked: false, base_url: 'https://api.harnessrouter.ai', key_hint: 'sk-hr-…abcd', member: 'richard', workspace_name: 'Research' };+const flush = async () => { for (let i = 0; i < 6; i++) await act(async () => { await Promise.resolve(); }); };+const btn = () => host.querySelector<HTMLButtonElement>('.dc-b') as HTMLButtonElement;+const label = () => btn().querySelector('.ag-act-l')?.textContent;++async function show() {+ act(() => root.render(<DeployCloud id="chrn_a" name="Weekly feedback summary" />));+ await flush();+}++beforeEach(() => {+ jest.useRealTimers();+ Object.values(lib).forEach((m) => m.mockReset());+ toast.mockReset();+ host = document.createElement('div');+ document.body.appendChild(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => root.unmount());+ host.remove();+});++describe('Deploy to Cloud', () => {+ test('never deployed, a destination kept: one click deploys, and the button says In Cloud', async () => {+ lib.statusOne.mockResolvedValue({ uploaded: false });+ lib.listTargets.mockResolvedValue({ targets: [TARGET], last: 't1' });+ lib.uploadOne.mockResolvedValue({ ok: true, action: 'create', remote_id: 'chrn_a', open_url: 'https://app.harnessrouter.ai/studio/chrn_a',+ status: { uploaded: true, changed: false, target: 'Research (richard)' } });+ const open = jest.spyOn(window, 'open').mockReturnValue(null);+ await show();+ expect(label()).toBe('Deploy to Cloud');+ await act(async () => { btn().click(); });+ await flush();+ expect(lib.uploadOne).toHaveBeenCalledWith('chrn_a', 't1');+ expect(open).not.toHaveBeenCalled(); // no sign-in, no tab+ expect(lib.startDeploySignIn).not.toHaveBeenCalled();+ expect(toast).toHaveBeenCalledWith('Weekly feedback summary is deployed to HarnessRouter Cloud.');+ expect(label()).toBe('In Cloud');+ open.mockRestore();+ });++ test('the first time: the click opens the Cloud sign-in in a new tab, and the deploy goes on by itself once signed in', async () => {+ jest.useFakeTimers();+ lib.statusOne.mockResolvedValue({ uploaded: false });+ lib.listTargets.mockResolvedValue({ targets: [], last: '' });+ lib.startDeploySignIn.mockResolvedValue({ code: 'c1', url: 'https://app.harnessrouter.ai/get-key?code=c1' });+ lib.pollDeploySignIn.mockResolvedValueOnce('waiting').mockResolvedValueOnce(TARGET);+ lib.uploadOne.mockResolvedValue({ ok: true, action: 'create', remote_id: 'chrn_a', open_url: 'https://app.harnessrouter.ai/studio/chrn_a',+ status: { uploaded: true, changed: false } });+ const tab = { location: { href: '' }, opener: {} as unknown, close: jest.fn() };+ const open = jest.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);+ await show();+ await act(async () => { btn().click(); });+ expect(open).toHaveBeenCalledWith('about:blank', '_blank'); // opened in the click, so it is not blocked+ await flush();+ expect(tab.opener).toBeNull();+ expect(tab.location.href).toBe('https://app.harnessrouter.ai/get-key?code=c1');+ expect(label()).toBe('Finish signing in');+ await act(async () => { jest.advanceTimersByTime(SIGNIN_EVERY_MS); });+ await flush();+ expect(lib.uploadOne).not.toHaveBeenCalled(); // still on the Cloud page+ await act(async () => { jest.advanceTimersByTime(SIGNIN_EVERY_MS); });+ await flush();+ expect(lib.uploadOne).toHaveBeenCalledWith('chrn_a', 't1'); // the key landed: deployed to it+ expect(label()).toBe('In Cloud');+ open.mockRestore();+ });++ test('changed since its deploy: Update Cloud, with its dot, and one click replaces the copy', async () => {+ lib.statusOne.mockResolvedValue({ uploaded: true, changed: true });+ lib.listTargets.mockResolvedValue({ targets: [TARGET], last: 't1' });+ lib.uploadOne.mockResolvedValue({ ok: true, action: 'replace', status: { uploaded: true, changed: false } });+ await show();+ expect(label()).toBe('Update Cloud');+ expect(host.querySelector('.dc-dot')).not.toBeNull();+ await act(async () => { btn().click(); });+ await flush();+ expect(lib.uploadOne).toHaveBeenCalledWith('chrn_a', 't1');+ expect(toast).toHaveBeenCalledWith('Weekly feedback summary is updated in HarnessRouter Cloud.');+ expect(label()).toBe('In Cloud');+ });++ test('In Cloud: its menu opens the copy in Cloud, deploys again, or deploys to another workspace', async () => {+ lib.statusOne.mockResolvedValue({ uploaded: true, changed: false, open_url: 'https://app.harnessrouter.ai/studio/chrn_a' });+ lib.listTargets.mockResolvedValue({ targets: [TARGET], last: 't1' });+ const open = jest.spyOn(window, 'open').mockReturnValue(null);+ await show();+ expect(label()).toBe('In Cloud');+ expect(btn().getAttribute('aria-haspopup')).toBe('menu');+ await act(async () => { btn().click(); });+ const items = [...host.querySelectorAll<HTMLButtonElement>('.dc-pop [role="menuitem"]')];+ expect(items.map((b) => b.textContent)).toEqual(['Open in HarnessRouter Cloud ↗', 'Deploy again', 'Deploy to another workspace…']);+ await act(async () => { items[0].click(); });+ expect(open).toHaveBeenCalledWith('https://app.harnessrouter.ai/studio/chrn_a', '_blank', 'noopener');+ expect(host.querySelector('.dc-pop')).toBeNull();+ open.mockRestore();+ });++ test('a deploy the server refuses says so in its words and the button is back as it was', async () => {+ lib.statusOne.mockResolvedValue({ uploaded: false });+ lib.listTargets.mockResolvedValue({ targets: [TARGET], last: 't1' });+ lib.uploadOne.mockRejectedValue(new Error('the cloud workspace rejected this key'));+ await show();+ await act(async () => { btn().click(); });+ await flush();+ expect(toast).toHaveBeenCalledWith('The cloud workspace rejected this key.');+ expect(label()).toBe('Deploy to Cloud');+ expect(btn().disabled).toBe(false);+ });++ test('Cloud cannot be reached for the sign-in: the tab it opened closes and the reason is said', async () => {+ lib.statusOne.mockResolvedValue({ uploaded: false });+ lib.listTargets.mockResolvedValue({ targets: [], last: '' });+ lib.startDeploySignIn.mockRejectedValue(new Error('502'));+ const tab = { location: { href: '' }, opener: null, close: jest.fn() };+ const open = jest.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);+ await show();+ await act(async () => { btn().click(); });+ await flush();+ expect(tab.close).toHaveBeenCalled();+ expect(toast).toHaveBeenCalledWith('HarnessRouter Cloud could not be reached just now. Try again.');+ expect(label()).toBe('Deploy to Cloud');+ open.mockRestore();+ });+});diff --git a/ui/src/components/hrui/setup/DeployCloud.tsx b/ui/src/components/hrui/setup/DeployCloud.tsxnew file mode 100644index 00000000..5cd71a24--- /dev/null+++ b/ui/src/components/hrui/setup/DeployCloud.tsx@@ -0,0 +1,151 @@+'use client';+// Deploy to Cloud: the setup page bar's second action, beside Set up the app (Richard, 10-23: "one click+// deploy the local harness into HarnessRouter cloud"). One button, in the one place a setup's actions+// live, and it always says where the setup stands:+// - Deploy to Cloud: never deployed. One click deploys it. The first time this instance has no cloud+// workspace yet, so the click opens HarnessRouter Cloud's sign-in in a new tab (the same hand-off+// Bring your own key's Get a key uses). The person signs in or up there, the key minted for their+// workspace lands on this instance's server (never in this page), and the deploy goes on by itself.+// - Update Cloud: deployed, and the setup changed since. One click replaces the cloud copy.+// - In Cloud: deployed and current. Its menu opens the copy in HarnessRouter Cloud, deploys again, or+// deploys to another workspace (the destinations this instance keeps: CloudUploadSheet).+// The cloud copy is one way: this instance stays the source, and every deploy replaces the copy under+// the same cloud id. What it says of the copy (deployed, changed since) is the server's own status.+import { useCallback, useEffect, useRef, useState } from 'react';+import { listTargets, pollDeploySignIn, startDeploySignIn, statusOne, uploadOne, type CloudStatus, type CloudTarget } from '@/lib/cloud-upload';+import { toast } from '../toast';+import { CloudUploadSheet } from './CloudUploadSheet';+import { plain } from './settingsModel';++const UP_IC = <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M7 18a4.5 4.5 0 0 1-.9-8.9A6 6 0 0 1 17.6 8 4 4 0 0 1 17 18" /><path d="M12 12v8M9 15l3-3 3 3" /></svg>;+const OK_IC = <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M7 18a4.5 4.5 0 0 1-.9-8.9A6 6 0 0 1 17.6 8 4 4 0 0 1 17 18H7z" /><path d="M9.5 13.5l2 2 3.5-3.5" /></svg>;+/** Between reads of an open sign-in. */+export const SIGNIN_EVERY_MS = 2000;+/** A sign-in left open this long has ended on the hosted side (its code's lifetime). */+export const SIGNIN_MAX_MS = 30 * 60_000;++type Phase = 'idle' | 'signin' | 'deploying';++export function DeployCloud({ id, name }: { id: string; name: string }) {+ const [status, setStatus] = useState<CloudStatus | null>(null);+ // the destinations this instance keeps (null while read): known before the click, so the click+ // decides at once whether it deploys or opens the sign-in (a tab opened after a wait is blocked)+ const [targets, setTargets] = useState<{ list: CloudTarget[]; last: string } | null>(null);+ const [phase, setPhase] = useState<Phase>('idle');+ const [signinUrl, setSigninUrl] = useState('');+ const [menu, setMenu] = useState(false);+ const [another, setAnother] = useState(false);+ const alive = useRef(true);+ const wrap = useRef<HTMLSpanElement | null>(null);+ useEffect(() => () => { alive.current = false; }, []);++ const readStatus = useCallback(() => {+ statusOne(id).then((s) => { if (alive.current) setStatus(s); }).catch(() => { /* the button says Deploy to Cloud */ });+ }, [id]);+ const readTargets = useCallback(() => {+ listTargets().then((r) => { if (alive.current) setTargets({ list: r.targets.filter((t) => !t.revoked), last: r.last }); })+ .catch(() => { if (alive.current) setTargets(null); });+ }, []);+ useEffect(() => { setStatus(null); readStatus(); readTargets(); }, [readStatus, readTargets]);++ // the menu closes on a click outside it and on Escape+ useEffect(() => {+ if (!menu) return;+ const down = (e: MouseEvent) => { if (!wrap.current?.contains(e.target as Node)) setMenu(false); };+ const key = (e: KeyboardEvent) => { if (e.key === 'Escape') setMenu(false); };+ document.addEventListener('mousedown', down);+ document.addEventListener('keydown', key);+ return () => { document.removeEventListener('mousedown', down); document.removeEventListener('keydown', key); };+ }, [menu]);++ const deployTo = async (target: string) => {+ setPhase('deploying');+ try {+ const r = await uploadOne(id, target);+ if (!alive.current) return;+ if (!r.ok) { toast(plain(new Error(r.error || ''), `${name} could not be deployed. Try again.`)); return; }+ setStatus({ ...r.status, open_url: r.open_url || r.status?.open_url || '' });+ toast(r.action === 'create' ? `${name} is deployed to HarnessRouter Cloud.` : `${name} is updated in HarnessRouter Cloud.`);+ } catch (e) {+ if (alive.current) toast(plain(e, `${name} could not be deployed. Try again.`));+ } finally {+ if (alive.current) setPhase('idle');+ }+ };++ // the first deploy: sign in to HarnessRouter Cloud in a new tab, then deploy as soon as the key lands+ const signIn = async () => {+ // opened now, in the click itself, so the browser lets it open; pointed at the sign-in once known+ const tab = typeof window !== 'undefined' ? window.open('about:blank', '_blank') : null;+ if (tab) tab.opener = null;+ setPhase('signin');+ let code = '';+ try {+ const s = await startDeploySignIn();+ code = s.code;+ setSigninUrl(s.url);+ if (tab) tab.location.href = s.url;+ } catch (e) {+ tab?.close();+ if (alive.current) { setPhase('idle'); toast(plain(e, 'HarnessRouter Cloud could not be reached just now. Try again.')); }+ return;+ }+ const until = Date.now() + SIGNIN_MAX_MS;+ while (alive.current && Date.now() < until) {+ await new Promise((ok) => setTimeout(ok, SIGNIN_EVERY_MS));+ if (!alive.current) return;+ let got: CloudTarget | 'waiting';+ try { got = await pollDeploySignIn(code); }+ catch (e) { setPhase('idle'); setSigninUrl(''); toast(plain(e, 'The sign-in ended. Deploy again.')); return; }+ if (got === 'waiting') continue;+ setSigninUrl('');+ setTargets({ list: [got], last: got.id });+ await deployTo(got.id);+ return;+ }+ if (alive.current) { setPhase('idle'); setSigninUrl(''); toast('The sign-in ended. Deploy again.'); }+ };++ const deploy = () => {+ setMenu(false);+ if (phase === 'signin') { if (signinUrl) window.open(signinUrl, '_blank'); return; }+ if (phase !== 'idle') return;+ const pick = targets?.list.find((t) => t.id === targets.last) || targets?.list[0];+ if (pick) void deployTo(pick.id);+ else void signIn();+ };++ const deployed = !!status?.uploaded;+ const current = deployed && !status?.changed;+ const label = phase === 'deploying' ? 'Deploying…'+ : phase === 'signin' ? 'Finish signing in'+ : current ? 'In Cloud' : deployed ? 'Update Cloud' : 'Deploy to Cloud';+ const tip = phase === 'signin' ? 'Finish signing in to HarnessRouter Cloud in the tab it opened. The deploy goes on by itself.'+ : current ? `${name} is deployed to HarnessRouter Cloud${status?.target ? `, ${status.target}` : ''}.`+ : deployed ? `${name} changed since its deploy. Update the copy in HarnessRouter Cloud.`+ : `Deploy ${name} to HarnessRouter Cloud.`;+ return (+ <span ref={wrap} className="dc-w">+ <button type="button" className={`btn small ag-act dc-b${current ? ' on' : ''}`} aria-label={label} title={tip}+ aria-haspopup={current ? 'menu' : undefined} aria-expanded={current ? menu : undefined}+ aria-busy={phase !== 'idle' || undefined} disabled={phase === 'deploying'}+ onClick={() => (current && phase === 'idle' ? setMenu(!menu) : deploy())}>+ {current ? OK_IC : UP_IC}<span className="ag-act-l">{label}</span>+ {deployed && !current && phase === 'idle' ? <i className="dc-dot" aria-hidden="true" /> : null}+ </button>+ {menu ? (+ <span className="rng-pop dc-pop" role="menu" aria-label="In HarnessRouter Cloud">+ {status?.open_url ? (+ <button type="button" role="menuitem" onClick={() => { setMenu(false); window.open(status.open_url, '_blank', 'noopener'); }}>Open in HarnessRouter Cloud ↗</button>+ ) : null}+ <button type="button" role="menuitem" onClick={deploy}>Deploy again</button>+ <button type="button" role="menuitem" onClick={() => { setMenu(false); setAnother(true); }}>Deploy to another workspace…</button>+ </span>+ ) : null}+ {another ? (+ <CloudUploadSheet id={id} name={name} status={status} onClose={() => setAnother(false)}+ onDone={() => { readStatus(); readTargets(); }} />+ ) : null}+ </span>+ );+}diff --git a/ui/src/components/hrui/setup/SetupSettings.parts.test.tsx b/ui/src/components/hrui/setup/SetupSettings.parts.test.tsxindex 5f1bf6f0..3dbf97a2 100644--- a/ui/src/components/hrui/setup/SetupSettings.parts.test.tsx+++ b/ui/src/components/hrui/setup/SetupSettings.parts.test.tsx@@ -2,7 +2,7 @@// A setup's plugins, skills and tools as a person sees them (Richard, 10-18): every place reads// setupParts.ts and says which list it shows: the Capabilities tabs list everything, built-ins// included; the Agent stack and the layers line beside it count only what a person added. Then what-// Settings shows when a read fails (no fallbacks), the Plugins tab's switches, and Upload to cloud.+// Settings shows when a read fails (no fallbacks), the Plugins tab's switches, and that it ends with Delete setup.import { act, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import type { BaseInfo, CustomHarness, HarnessPlugin, Plug } from '@/lib/harness';@@ -302,21 +302,12 @@ describe('the Plugins tab: the workspace’s connected plugins, a switch each',});});-describe('Upload to cloud', () => {- test('its row says what the server says of the cloud copy, and opens its sheet', async () => {- cloudLib.statusOne.mockResolvedValueOnce({ uploaded: true, uploaded_at: Date.now() - 3 * 60_000, changed: true });- cloudLib.listTargets.mockResolvedValue({ targets: [{ id: 't1', label: 'Acme · Production', revoked: false }], last: 't1' });+describe('Deploy to Cloud lives in the page bar, not here', () => {+ test('the settings end with Delete setup alone', async () => {await settings(setup(), 'harness');- const row = el.querySelector('.lg-rows .ly-n.lg-up') as HTMLButtonElement;- expect(row.querySelector('small')?.textContent).toBe('Changed since its upload 3 min ago');- await act(async () => { row.click(); });- await flush();- expect(el.querySelector('[data-sheet] #cloudTo')).not.toBeNull();- expect(button('Replace the copy')).toBeTruthy();- });- test('never uploaded: it says what it does', async () => {- await settings(setup(), 'harness');- expect(el.querySelector('.lg-rows .ly-n.lg-up small')?.textContent).toBe('Copy this setup to a HarnessRouter Cloud workspace');+ expect(el.querySelector('.lg-rows .ly-n.lg-up')).toBeNull();+ expect([...el.querySelectorAll('.lg-rows .lg-dz .ly-n')].map((b) => b.textContent)).toEqual(['Delete setup']);+ expect(el.textContent).not.toContain('Upload to cloud');});});diff --git a/ui/src/components/hrui/setup/SetupSettings.tsx b/ui/src/components/hrui/setup/SetupSettings.tsxindex a6916512..f2939c78 100644--- a/ui/src/components/hrui/setup/SetupSettings.tsx+++ b/ui/src/components/hrui/setup/SetupSettings.tsx@@ -13,12 +13,11 @@// Capabilities tab counts the ones on of one of setupParts.ts's lists (setupPlugins, setupSkills,// setupTools); Skills and Tools list it, Plugins lists the workspace's connected plugins with a switch// each, beside what the setup includes (PluginSwitches.tsx); the layers list's Capabilities line counts-// what a person added, as the Agent stack and Studio's card do. Under the layers: Upload to cloud-// (this setup copied to a HarnessRouter Cloud workspace, CloudUploadSheet.tsx), then Delete setup.+// what a person added, as the Agent stack and Studio's card do. Under the layers: Delete setup.+// (Deploy to Cloud is the page bar's, beside Set up the app: DeployCloud.tsx.)// Every value, list, default and ceiling shown is read from the services: the setup's record, the// bases document (tools, built-in skills, thinking levels, runtime defaults), the model catalog,-// the workspace's plugins and environments, and the setup's cloud status. What is not read yet-// shows nothing.+// and the workspace's plugins and environments. What is not read yet shows nothing.import { useRouter } from 'next/navigation';import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';import {@@ -52,7 +51,6 @@ import { SkillSheet, skillDraft, skillFiles, skillSlug, splitSkillMd, type Skillimport {DeleteSetupSheet, EnvPickSheet, PackageSheet, DuplicateSheet,} from './settingsSheets';-import { CloudUploadSheet, cloudLine, useCloudStatus } from './CloudUploadSheet';type Skill = CustomHarness['skills'][number];const isOwn = isOwnSkill;@@ -80,7 +78,7 @@ const LAYER_ORDER = SET_LAYERS.map(([k]) => k);type Pop =| { k: 'mcp'; i: number | null } | { k: 'delmcp'; i: number } | { k: 'plugin' } | { k: 'env' } | { k: 'pkg'; name: string }- | { k: 'skill'; ed: SkillDraft } | { k: 'delskill'; s: Skill } | { k: 'del' } | { k: 'dup' } | { k: 'cloud' };+ | { k: 'skill'; ed: SkillDraft } | { k: 'delskill'; s: Skill } | { k: 'del' } | { k: 'dup' };export function SetupSettings({ r, onSaved, layer, cap, onLayer, onDirty, onNewTask }: {r: SetupRow;@@ -157,9 +155,6 @@ export function SetupSettings({ r, onSaved, layer, cap, onLayer, onDirty, onNewTconst wsId = wsCurrent.id || wsDefault;// the workspace's plugins, each with its state here (lib/plugs, read again after one is connected)const ws = usePlugins(wsId, { counts: false });- // the setup's cloud copy, as the server says (Upload to cloud's row), read again after an upload- const [cloudRead, setCloudRead] = useState(0);- const cloud = useCloudStatus(id, cloudRead);// the record says whether it has a plugins binding at all: asking for an absent one is a 404const hasPlugs = (rec.mcpServers || []).some((m) => m.id === PLUGS_ENTRY_ID);const [included, setIncluded] = useState<HarnessPlugs | null | undefined>(undefined);@@ -637,16 +632,11 @@ export function SetupSettings({ r, onSaved, layer, cap, onLayer, onDirty, onNewTconst pkg = pop?.k === 'pkg' ? pkgs.find((p) => p.name === pop.name) || null : null;const mcpEdit = pop?.k === 'mcp' && pop.i != null ? c.mcp[pop.i] || null : null;- // Upload to cloud, then Delete setup: the settings' last rows, a layer row's anatomy, past a hairline- // and outside the layers' tablist; Delete setup red, its name alone (the sheet says what deleting- // does, Richard 10-18). They are drawn at any width (hrui-console.css): `rail` under the layers,- // else at the foot of the open layer.- const cl = cloudLine(cloud);+ // Delete setup: the settings' last row, a layer row's anatomy, past a hairline and outside the+ // layers' tablist; red, its name alone (the sheet says what deleting does, Richard 10-18). Drawn at+ // any width (hrui-console.css): `rail` under the layers, else at the foot of the open layer.const delRow = (where: 'rail' | 'foot') => (<div className="lg-dz" data-where={where}>- <button type="button" className="ly-n lg-up" aria-haspopup="dialog" onClick={() => setPop({ k: 'cloud' })}>- <b>Upload to cloud</b><small>{cl || 'Copy this setup to a HarnessRouter Cloud workspace'}</small>- </button><button type="button" className="ly-n" aria-haspopup="dialog" onClick={() => setPop({ k: 'del' })}><b>Delete setup</b></button></div>);@@ -701,9 +691,6 @@ export function SetupSettings({ r, onSaved, layer, cap, onLayer, onDirty, onNewTonClose={() => setPop(null)} />) : null}{pop?.k === 'env' ? <EnvPickSheet envs={envs} failed={envsFailed} retry={readEnvs} current={rec.environment || ''} busy={!!busy} onPick={(eid) => void pickEnv(eid)} onClose={() => setPop(null)} /> : null}- {pop?.k === 'cloud' ? (- <CloudUploadSheet id={id} name={rec.name} status={cloud} onClose={() => setPop(null)} onDone={() => setCloudRead((n) => n + 1)} />- ) : null}{pop?.k === 'pkg' && pkg ? (<PackageSheet p={pkg} hid={id} busy={!!busy} onClose={() => setPop(null)}onToggle={() => void apply((h) => ({ plugins: (h.plugins || []).map((x) => (x.name === pkg.name ? { ...x, enabled: x.enabled === false } : x)) }), 'The plugin was not changed. Try again.')}diff --git a/ui/src/components/hrui/setup/parts.tsx b/ui/src/components/hrui/setup/parts.tsxindex 6970e685..81af2070 100644--- a/ui/src/components/hrui/setup/parts.tsx+++ b/ui/src/components/hrui/setup/parts.tsx@@ -15,6 +15,7 @@ import { liveTower, runningNames } from './stackLive';import { recordNames } from './setupParts';import type { LayerKey } from './settingsModel';import { OVERLAY_MAX, readFold, stackOff, STACK_KEY, toggled, writeFold, type Fold } from './stackFold';+import { DeployCloud } from './DeployCloud';export type SetupTab = 'tasks' | 'settings';const SETUP_TABS: readonly SetupTab[] = ['tasks', 'settings'];@@ -42,7 +43,8 @@ async function copy(text: string) {}/** The setup page's one bar (agentHead): back to Harness Studio; the name on the first line, its- * agent harness, model and Harness ID on the second; Tasks · Settings; and Set up the app. */+ * agent harness, model and Harness ID on the second; Tasks · Settings; and the setup's two actions,+ * Deploy to Cloud (DeployCloud.tsx) and Set up the app. */// A tab chosen with the keyboard keeps the keyboard on it. The page changes its address for the new tab and// draws the bar again, often as a new tree, so the focus tabKeys gave the new tab was lost to the page body// (audit, 10-21): the bar that draws next puts it back on the selected tab.@@ -91,8 +93,10 @@ export function AgentHead({ r, tab, onTab, onSetUpApp, dirty }: {{tb('settings', <>Settings{dirty ? <i className="dirty-dot" role="img" aria-label="Unsaved changes" /> : null}</>)}</div><div className="ag-right">- {/* the design's one action. On a phone it folds to its icon (its words stay its name and- tooltip), so the setup's name keeps the row */}+ {/* the setup's two actions: where it runs (Deploy to Cloud), and connecting your app to it+ (Set up the app, the primary one). On a phone each folds to its icon (its words stay its+ name and tooltip), so the setup's name keeps the row */}+ <DeployCloud id={r.h.id} name={r.h.name} />{act('Set up the app', PLUG_IC, onSetUpApp, true)}</div></header>diff --git a/ui/src/components/hrui/start/open.test.ts b/ui/src/components/hrui/start/open.test.tsindex b6d6ee67..a054ef3f 100644--- a/ui/src/components/hrui/start/open.test.ts+++ b/ui/src/components/hrui/start/open.test.ts@@ -106,6 +106,7 @@ const RUNTIME = /(router\.(push|replace)|location\.(assign|replace))\(\s*(?![`'"const RUNTIME_ALLOWED: Entry[] = [['app/(app)/studio/[id]/page.tsx', 'router.replace(pgHref(', 'the setup’s own address (the open task)'],['app/(app)/studio/[id]/page.tsx', "router.replace(t === 'tasks' ? pgHref(testSid)", 'the setup’s own address (its tab)'],+ ['components/hrui/setup/DeployCloud.tsx', 'if (tab) tab.location.href = s.url;', 'Deploy to Cloud’s sign-in, in the new tab it opened: this page stays where it is'],];describe('Harness Studio is never where a create lands', () => {diff --git a/ui/src/lib/cloud-upload.ts b/ui/src/lib/cloud-upload.tsindex 6930ac0b..8ca8546f 100644--- a/ui/src/lib/cloud-upload.ts+++ b/ui/src/lib/cloud-upload.ts@@ -5,8 +5,9 @@import { gw } from '@/lib/harness';export interface CloudTarget { id: string; base_url: string; key_hint: string; member: string; workspace_name: string; revoked: boolean; 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; remote_id?: string; error?: string }+/** `open_url`: where the copy opens in HarnessRouter Cloud's console ('' when the destination is another address). */+export interface CloudStatus { uploaded: boolean; uploaded_at?: number; target?: string; changed?: boolean; open_url?: string }+export interface UploadRow { id: string; ok: boolean; action: 'create' | 'replace' | 'skip'; name?: string; remote_id?: string; error?: string; open_url?: string; target_name?: string }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 });@@ -15,3 +16,15 @@ export const uploadOne = (id: string, target: string) => gw<UploadRow & { statusexport 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');++// Deploy to Cloud, the first time: the HarnessRouter Cloud sign-in hand-off. This instance opens it+// (the page to sign in on, `url`), and its poll answers 202 until the person has signed in, then the+// destination this instance now keeps (the key stays on this instance's server, never here).+export const startDeploySignIn = () => gw<{ code: string; url: string; expires_in?: number }>('POST', '/v1/cloud-upload/connect',+ { instance: typeof window !== 'undefined' ? window.location.host : '' });+/** One read of the sign-in: the destination once it is ready, 'waiting' while it is not. A code that+ * is gone (expired, or not a deploy sign-in) throws, as any refused call does. */+export async function pollDeploySignIn(code: string): Promise<CloudTarget | 'waiting'> {+ const r = await gw<{ status: string; target?: CloudTarget }>('GET', `/v1/cloud-upload/connect/${encodeURIComponent(code)}`);+ return r?.status === 'ready' && r.target ? r.target : 'waiting';+}