HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
fix(workspaces): the registry joins its records on the server — two laptops, one truth
richard-epsilla46a9953278c9
diff --git a/gateway/app.py b/gateway/app.pyindex 10b13af0..426ec063 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -11203,6 +11203,109 @@ async def delete_harness(org: str, hid: str, request: Request) -> dict:return {"id": hid, "deleted": True}+# ── workspaces: the DIRECTORY, server-side (fix for the localStorage split-brain) ──────+# Harnesses, tasks and keys were always stamped with a workspace id in the store — but the+# REGISTRY of workspaces (id, name, description) had no server-side home on self-host: the+# console served it from each browser's localStorage. Two laptops on one instance therefore+# saw two different workspace lists, and records stamped with a workspace one browser had+# never minted were unreachable from it. The registry now lives with the stamps. Hosted keeps+# its Spaces service; these routes are what the console's existing /v1/hr/workspaces calls+# expect, same shapes, so the provider and switcher are unchanged.+_WORKSPACE_DEFAULT_ID = "default"+++def _workspace_slug(name: str, taken: set[str]) -> str:+ """Same minting rules the localStorage store used, so ids stay stable across the migration+ (a browser-minted 'research' and a server-minted 'research' must be the same workspace)."""+ base = re.sub(r"^-|-$", "", re.sub(r"[^a-z0-9]+", "-", (name or "").strip().lower())) or "workspace"+ if base not in taken:+ return base+ n = 2+ while f"{base}-{n}" in taken:+ n += 1+ return f"{base}-{n}"+++def _workspace_out(v: dict) -> dict:+ return {"id": str(v.get("ws_id") or ""), "name": str(v.get("name") or "Untitled"),+ "description": str(v.get("description") or "")}+++async def _workspace_rows(org: str) -> list[dict]:+ rows = [v for v in await _vg_list_by_org("Workspace", org)+ if str(v.get("deleted") or "0") != "1"]+ rows.sort(key=lambda v: (str(v.get("ws_id")) != _WORKSPACE_DEFAULT_ID,+ str(v.get("created_at") or "")))+ return rows++[email protected]("/v1/hr/workspaces")+async def workspaces_list(request: Request) -> dict:+ org, member = await _pub_org_member(request)+ rows = await _workspace_rows(org)+ if not any(str(v.get("ws_id")) == _WORKSPACE_DEFAULT_ID for v in rows):+ # Ensured idempotently on read, exactly as the hosted engine does — which also lazily+ # backfills instances that predate server-side workspaces.+ props = {"kind": "workspace", "org": org, "member": member,+ "ws_id": _WORKSPACE_DEFAULT_ID, "name": "Default Workspace",+ "description": "All harnesses and tasks on this instance.",+ "created_at": str(int(time.time() * 1000)), "deleted": "0"}+ await _vg_upsert("Workspace", f"ws.{org}.{_WORKSPACE_DEFAULT_ID}", props)+ rows = [props] + rows+ return {"workspaces": [_workspace_out(v) for v in rows],+ "default_workspace_id": _WORKSPACE_DEFAULT_ID}+++class WorkspaceBody(BaseModel):+ name: str | None = None+ description: str | None = None+ id: str | None = None # migration only: adopt a browser-minted id verbatim++[email protected]("/v1/hr/workspaces")+async def workspaces_create(body: WorkspaceBody, request: Request) -> dict:+ org, member = await _pub_org_member(request)+ name = (body.name or "").strip()+ if not name:+ raise HTTPException(400, "a workspace needs a name")+ rows = await _workspace_rows(org)+ taken = {str(v.get("ws_id")) for v in rows} | {_WORKSPACE_DEFAULT_ID}+ if body.id:+ # Migration path: the console pushes localStorage-era workspaces up with their exact+ # browser-minted ids so existing stamped records reattach. An id that is already here+ # is simply that workspace (idempotent merge), never a duplicate.+ wid = re.sub(r"[^a-z0-9-]", "", body.id.strip().lower())[:64]+ if not wid:+ raise HTTPException(400, "invalid workspace id")+ if wid in taken:+ existing = next((v for v in rows if str(v.get("ws_id")) == wid), None)+ if existing is not None:+ return _workspace_out(existing)+ return {"id": wid, "name": "Default Workspace", "description": ""}+ else:+ wid = _workspace_slug(name, taken)+ props = {"kind": "workspace", "org": org, "member": member, "ws_id": wid, "name": name,+ "description": (body.description or "").strip(),+ "created_at": str(int(time.time() * 1000)), "deleted": "0"}+ await _vg_upsert("Workspace", f"ws.{org}.{wid}", props, raise_on_fail=True)+ return _workspace_out(props)++[email protected]("/v1/hr/workspaces/{wid}")+async def workspaces_update(wid: str, body: WorkspaceBody, request: Request) -> dict:+ org, _member = await _pub_org_member(request)+ rows = await _workspace_rows(org)+ v = next((r for r in rows if str(r.get("ws_id")) == wid), None)+ if v is None:+ raise HTTPException(404, "workspace not found")+ if body.name is not None and body.name.strip():+ v["name"] = body.name.strip()+ if body.description is not None:+ v["description"] = body.description.strip()+ await _vg_upsert("Workspace", f"ws.{org}.{wid}", v, raise_on_fail=True)+ return _workspace_out(v)++# ── PUBLIC harness CRUD (Bearer sk-hr-... API key; org resolved from the key) ──────────# This is what a vibe coder's agent (driven by AGENTS.md) calls — no org id, no internal header.async def _pub_org_member(request: Request) -> tuple[str, str]:diff --git a/gateway/tests/test_workspaces.py b/gateway/tests/test_workspaces.pynew file mode 100644index 00000000..5b3a5b09--- /dev/null+++ b/gateway/tests/test_workspaces.py@@ -0,0 +1,81 @@+"""The server-side workspace registry — the fix for the localStorage split-brain.++The defect: harnesses/tasks/keys were stamped with workspace ids in the store, but the+REGISTRY (id, name, description) lived in each browser's localStorage on self-host, so two+laptops on one instance saw different workspace lists and could not reach each other's+records. These tests pin the contract the console's existing calls expect, plus the two+properties the migration depends on: browser-minted ids are adopted verbatim, and the+server's slug rules match the old localStorage minting exactly.+"""+import os+import sys++import pytest+from fastapi.testclient import TestClient++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+import app as gw # noqa: E402+++def client(monkeypatch):+ store: dict[str, dict] = {}++ async def fake_upsert(label, vid, props, *, raise_on_fail=False):+ store[vid] = {**props}++ async def fake_list(label, org):+ return [v for v in store.values() if v.get("org") == org and label == "Workspace"]++ async def fake_principal(request):+ return {"org": "local", "member": "local@localhost", "workspace": "", "workspace_default": False}++ monkeypatch.setattr(gw, "_vg_upsert", fake_upsert)+ monkeypatch.setattr(gw, "_vg_list_by_org", fake_list)+ monkeypatch.setattr(gw, "_principal", fake_principal)+ return TestClient(gw.app)+++def test_list_seeds_default_idempotently(client):+ for _ in range(2):+ r = client.get("/v1/hr/workspaces")+ assert r.status_code == 200+ d = r.json()+ assert d["default_workspace_id"] == "default"+ assert [w["id"] for w in d["workspaces"]].count("default") == 1+++def test_create_and_list_across_clients(client):+ r = client.post("/v1/hr/workspaces", json={"name": "Research", "description": "papers"})+ assert r.status_code == 200+ assert r.json() == {"id": "research", "name": "Research", "description": "papers"}+ # "another laptop" is just another GET: the registry is server truth now+ ids = [w["id"] for w in client.get("/v1/hr/workspaces").json()["workspaces"]]+ assert "research" in ids and "default" in ids+++def test_slug_rules_match_the_old_localstorage_mint(client):+ assert client.post("/v1/hr/workspaces", json={"name": "My Team!"}).json()["id"] == "my-team"+ assert client.post("/v1/hr/workspaces", json={"name": "My Team?"}).json()["id"] == "my-team-2"+++def test_migration_adopts_browser_minted_id_verbatim_and_idempotently(client):+ r1 = client.post("/v1/hr/workspaces", json={"id": "research", "name": "Research"})+ assert r1.json()["id"] == "research"+ # a second tab racing the migration lands on the SAME workspace, not a duplicate+ r2 = client.post("/v1/hr/workspaces", json={"id": "research", "name": "Research"})+ assert r2.json()["id"] == "research"+ ids = [w["id"] for w in client.get("/v1/hr/workspaces").json()["workspaces"]]+ assert ids.count("research") == 1+++def test_rename_persists(client):+ client.post("/v1/hr/workspaces", json={"name": "Ops"})+ r = client.patch("/v1/hr/workspaces/ops", json={"name": "Operations"})+ assert r.status_code == 200 and r.json()["name"] == "Operations"+ names = {w["id"]: w["name"] for w in client.get("/v1/hr/workspaces").json()["workspaces"]}+ assert names["ops"] == "Operations"+++def test_unknown_workspace_404s(client):+ assert client.patch("/v1/hr/workspaces/nope", json={"name": "x"}).status_code == 404diff --git a/ui/src/lib/workspace-local.ts b/ui/src/lib/workspace-local.tsdeleted file mode 100644index 5e9ff685..00000000--- a/ui/src/lib/workspace-local.ts+++ /dev/null@@ -1,86 +0,0 @@-// Local workspace store for the self-hosted edition.-//-// Hosted, workspaces are Spaces in a separate service. A self-hosted box has no such service —-// but workspaces are still wanted: one instance, several isolated sets of harnesses and tasks.-//-// So this is a STORE swap, not a second implementation. It answers the exact three requests the-// workspace provider makes, with the exact JSON the hosted API returns, from localStorage. The-// provider, the switcher UI, the scoping headers and every consumer stay identical — which is-// the same adapter seam the backend uses to run on SQLite instead of the hosted graph.-const KEY = 'hr.selfhost.workspaces';-const DEFAULT_ID = 'default';--export interface StoredWorkspace { id: string; name: string; description: string }--const seed = (): StoredWorkspace[] => [{- id: DEFAULT_ID,- name: 'Default Workspace',- description: 'All harnesses and tasks on this instance.',-}];--function read(): StoredWorkspace[] {- if (typeof window === 'undefined') return seed();- try {- const raw = JSON.parse(window.localStorage.getItem(KEY) || 'null');- return Array.isArray(raw) && raw.length ? (raw as StoredWorkspace[]) : seed();- } catch {- return seed();- }-}--function write(rows: StoredWorkspace[]): void {- try { window.localStorage.setItem(KEY, JSON.stringify(rows)); } catch { /* private mode */ }-}--/** Turn a name into a stable id. Ids scope stored records, so they must not change when a- * workspace is renamed — this only runs at creation. */-function mint(name: string, taken: Set<string>): string {- const base = name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'workspace';- if (!taken.has(base)) return base;- for (let n = 2; ; n++) if (!taken.has(`${base}-${n}`)) return `${base}-${n}`;-}--const json = (body: unknown, status = 200) =>- new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });--/** Drop-in for authFetch over /v1/hr/workspaces, serving the same shapes from localStorage. */-export async function localWorkspaceFetch(path: string, init: RequestInit = {}): Promise<Response> {- const method = (init.method || 'GET').toUpperCase();- const rows = read();-- if (method === 'GET') {- return json({ workspaces: rows, default_workspace_id: DEFAULT_ID });- }-- const body = (() => {- try { return JSON.parse(String(init.body || '{}')) as Partial<StoredWorkspace>; }- catch { return {} as Partial<StoredWorkspace>; }- })();-- if (method === 'POST') {- const name = String(body.name || '').trim();- if (!name) return json({ detail: 'a workspace needs a name' }, 400);- const created: StoredWorkspace = {- id: mint(name, new Set(rows.map((w) => w.id))),- name,- description: String(body.description || ''),- };- write([...rows, created]);- return json(created);- }-- if (method === 'PATCH') {- const id = decodeURIComponent(path.split('/').pop() || '');- const idx = rows.findIndex((w) => w.id === id);- if (idx < 0) return json({ detail: 'workspace not found' }, 404);- rows[idx] = {- ...rows[idx],- ...(body.name !== undefined ? { name: String(body.name) } : {}),- ...(body.description !== undefined ? { description: String(body.description) } : {}),- };- write(rows);- return json(rows[idx]);- }-- return json({ detail: `unsupported method ${method}` }, 405);-}diff --git a/ui/src/lib/workspace.tsx b/ui/src/lib/workspace.tsxindex 8539da6c..b1375fc9 100644--- a/ui/src/lib/workspace.tsx+++ b/ui/src/lib/workspace.tsx@@ -10,11 +10,38 @@import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';import { authFetch, getSession } from '@/lib/auth';import { SELF_HOSTED } from '@/lib/edition';-import { localWorkspaceFetch } from '@/lib/workspace-local';-/** Where workspaces live. Hosted, that's the Spaces service behind the engine; self-hosted,- * localStorage — same requests, same shapes, so everything below is unchanged either way. */-const wsFetch = SELF_HOSTED ? localWorkspaceFetch : authFetch;+/** Where workspaces live. Hosted, the Spaces service behind the engine; self-hosted, the+ * gateway's own store via the BFF — same requests, same shapes. The registry used to be+ * localStorage on self-host, which meant every browser had its own workspace list while the+ * records those workspaces scoped sat server-side: two laptops on one instance disagreed+ * about what existed. The directory now lives with the data it scopes. */+const selfhostWsFetch = (path: string, init?: RequestInit) =>+ fetch('/api/harness' + path, { ...init, cache: 'no-store' });+const wsFetch = SELF_HOSTED ? selfhostWsFetch : authFetch;++/** One-time migration: push any localStorage-era workspaces up to the server WITH their+ * browser-minted ids, so records stamped by them reattach. Idempotent server-side (an id+ * that already exists is that workspace), so racing tabs are harmless. The key is left in+ * place after a marker is set — recovery data beats tidiness until a release later. */+const LS_LEGACY = 'hr.selfhost.workspaces';+const LS_MIGRATED = 'hr.selfhost.workspaces.migrated';+async function migrateLegacyWorkspaces(): Promise<void> {+ if (!SELF_HOSTED || typeof window === 'undefined') return;+ try {+ if (localStorage.getItem(LS_MIGRATED)) return;+ const rows = JSON.parse(localStorage.getItem(LS_LEGACY) || '[]') as+ { id?: string; name?: string; description?: string }[];+ for (const w of Array.isArray(rows) ? rows : []) {+ if (!w?.id || w.id === 'default' || !w.name) continue;+ await selfhostWsFetch('/v1/hr/workspaces', {+ method: 'POST', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ id: w.id, name: w.name, description: w.description || '' }),+ }).catch(() => undefined);+ }+ localStorage.setItem(LS_MIGRATED, '1');+ } catch { /* private mode: nothing stored, nothing to migrate */ }+}export interface Workspace {id: string;@@ -87,6 +114,7 @@ export function WorkspaceProvider({ children }: { children: React.ReactNode }) {const org = getSession()?.orgId;if (!org) { setLoading(false); return; }try {+ await migrateLegacyWorkspaces();const wanted = getCurrentWorkspaceRef()?.id || '';let rows: Workspace[] = [];let def = '';