main
John Lauer Publish 0.1.0 d8a45ab

name: hydrogen-desktop-sse description: >- How Hydrogen's local workspace API and SSE stream work on Linux, so the workspace's adom-cli controls Hydrogen instead of the cloud: routing, env vars, port discovery, field formats. Use for Hydrogen SSE, the workspace API, add-tab or move-tab, EventSource, ADOM_HYDROGEN_URL, ports.json, or the discovery port.

Hydrogen on Linux: Local Workspace API + SSE

Architecture

Workspace adom-cli (the systemd-nspawn machine Adom-Workspace)
    → http://127.0.0.1:47083 (Hydrogen's proxy)
    → Hydrogen handles workspace commands locally + broadcasts SSE
    → Hydrogen frontend receives SSE, re-fetches workspace, renders

Cloud Docker's adom-cli (unchanged)
    → carbon.adom.inc → Hydrogen web

Hydrogen runs its own workspace API on port 47083 (the reverse proxy's default; see PortConfig) so the workspace's adom-cli controls Hydrogen's UI, not cloud Hydrogen. No cross-talk between environments.

The workspace machine shares the host's network namespace, so 127.0.0.1 is the same inside the workspace and on the host: the workspace reaches Hydrogen's proxy and control API at 127.0.0.1:<port> with no host IP and no /proxy/ hop, and Hydrogen reaches workspace services the same way. Workspace ports are blocked from the LAN by Hydrogen's firewall table.

Port 47083 routing (the hydrogen-proxy / reverse-proxy)

All requests hit port 47083 (reverse proxy, default — see PortConfig). The router in handle_request() decides:

Path pattern Handler Where
/api/workspaces/editor/{owner}/{repo}/current/* Local workspace API In-memory
/api/panels/webview/*, /api/panels/sandbox/* Local panel API SSE broadcast
/containers/* Local container discovery Canned response
/proxy/{port}/{path} Workspace proxy Forward to that port in the workspace
<port>.localhost:<proxy> (Host header) Subdomain form of the same forward Forward to that port in the workspace
Everything else (/api/*, etc.) Carbon proxy HTTPS to carbon.adom.inc

The dev file server on port 1420 forwards /api/* directly to handle_request() (same function, not TCP — supports SSE streaming via BoxBody).

SSE Connection

Endpoint: GET /api/workspaces/editor/{owner}/{repo}/current/events

Uses tokio::sync::broadcast channel. On connect sends {"type":"connected","connectionId":"hydrogen-local"}. Workspace mutations broadcast {"type":"workspace_updated"}.

Other event types: caption, nav, tab_alert, notification_request, screenshot_request, audio_request, recording_request.

Frontend connects in PanelWorkspaceComponent.svelte → setupSSE(). In Tauri mode, $page.params may be empty (adapter-static), so it falls back to owner=local, repo=workspace.

Critical lesson: The onopen handler PUTs the workspace state. This broadcasts workspace_updated, which the frontend re-fetches. Set skipNextSSESync = true before the PUT to prevent the feedback loop that kills the connection.

Container Discovery

adom-cli calls /containers/{slug} to get owner/repo. Any slug gets the same answer.

Response format (must match Carbon's exactly):

{
  "repository": {
    "owner": { "name": "jlauer12" },
    "name": "workspace"
  },
  "slug": "hdlocal",
  "status": "running"
}

NOT {"owner": "jlauer12", "repository": "workspace"} — adom-cli reads container["repository"]["owner"]["name"].

Workspace Env Vars

Hydrogen rewrites these on every launch (the ports are dynamic) into ~/.bashrc, /etc/profile.d/hd-env.sh and a code-server systemd drop-in, so every shell and every AI tool call inherits them:

Var Value Why
ADOM_HYDROGEN_URL http://127.0.0.1:<proxy> Workspace mutations (adom-cli sends these HERE, not to Carbon)
ADOM_CARBON_URL http://127.0.0.1:<proxy> Container discovery + non-workspace API
ADOM_HD_CONTROL_URL http://127.0.0.1:<control> Hydrogen's control API (/ui/*, /ports/all, /claude/*)
VSCODE_PROXY_URI http://{{port}}.localhost:<proxy>/ What code-server hands extensions for a forwarded port
ADOM_DESKTOP_MODE local Tells adom-cli it's a local environment

Discovery files in the workspace, rewritten each launch: ~/.adom/hydrogen-control-url (the control URL, normally http://127.0.0.1:47084), ~/.adom/hd-proxy-url, and ~/.adom/hydrogen-ports.json (hostname, control, proxy, cdp, code_server). Relay ports: ~/.adom/cli-relay-ports.json (fallback 8765 WS / 8766 HTTP).

The API key at /var/run/adom/api-key comes from GET "$(cat ~/.adom/hydrogen-control-url)/auth-token".

Workspace Tree Format

The frontend serializes splits with first/second, NOT children:

{
  "type": "split",
  "id": "desktop-root-split",
  "direction": "horizontal",
  "ratio": 0.5,
  "first": { "type": "leaf", "id": "pane-left", ... },
  "second": { "type": "leaf", "id": "pane-right", ... }
}

All tree traversal functions (find_leaf_path, find_split_path, resolve_path) must handle BOTH children array and first/second keys.

REST Endpoint Field Names (adom-cli vs Hydrogen)

adom-cli sends different field names than you might expect:

Endpoint adom-cli sends Hydrogen must read
POST /tabs {panelId, panelType, displayName, initialState} Construct tab with UUID, merge initialState into panelState
POST /moves {sourcePanelId, tabId, targetPanelId} NOT sourcePanel/targetPanel
DELETE /tabs {panelId, tabId} or {name} Support both

Smoke Test (from inside the workspace)

# 1. Probe — confirms SSE alive
adom-cli hydrogen probe
# → browser_connected: true, sse_connections: 1

# 2. Get workspace
adom-cli hydrogen workspace get

# 3. Add tab
adom-cli hydrogen workspace add-tab \
  --panel-id desktop-pane-right \
  --panel-type adom/a1b2c3d4-0031-4000-a000-000000000031 \
  --display-name "Test Page" \
  --initial-state '{"url":"https://wiki.adom.inc/adom/adom-shotlog"}'

# 4. Move tab
adom-cli hydrogen workspace move-tab \
  --from-panel-id desktop-pane-right \
  --tab-id <tab-id-from-step-3> \
  --to-panel-id desktop-pane-left

# 5. Screenshot to verify
curl -s -X POST "$(cat ~/.adom/hydrogen-control-url)/screenshot" -H 'Content-Type: application/json' -d '{}'

What Broke and Why

SSE never connected on fresh launch

setupSSE() checks $page.params.owner and $page.params.repo. In Tauri mode with adapter-static, these are empty. Fix: fall back to owner=local, repo=workspace when in Tauri mode.

SSE connected then immediately disconnected

The onopen handler PUTs workspace state → broadcasts workspace_updated → frontend re-fetches → gets the state it just PUT → re-applies → triggers autosave → another PUT → loop. Fix: set skipNextSSESync = true before the onopen PUT.

adom-cli "Could not get owner from container info"

Three stacked issues:

  1. VSCODE_PROXY_URI was http://localhost:8080/... → slug parsed as 8080 → called /containers/8080 → Carbon 404
  2. Container info response had flat {"owner": "..."} but adom-cli reads container["repository"]["owner"]["name"]
  3. ADOM_HYDROGEN_URL wasn't set → workspace commands went to hydrogen.adom.inc instead of Hydrogen

add-tab returned "Missing 'tab' in body"

Hydrogen expected {"panelId", "tab": {id, panelType, panelState}} but adom-cli sends {"panelId", "panelType", "displayName", "initialState"} — flat format. Fix: accept both, construct tab with UUID for the flat format.

move-tab returned "Source/target panel not found"

Two issues:

  1. Handler read sourcePanel/targetPanel but adom-cli sends sourcePanelId/targetPanelId
  2. find_leaf_path only traversed children array, not first/second keys

Google showed "blocked" icon

Not a Hydrogen bug. Google sends X-Frame-Options: SAMEORIGIN which prevents iframe embedding. Sites that allow embedding (adom.inc, wiki) load fine.

Port Discovery — How Any Client Finds Hydrogen

Host-side ports are dynamic. The config is ~/.config/hydrogen-desktop/ports.json on the host, rewritten every launch (control prefers 47084, proxy 47083, code-server 7380). Ways in, best first:

  1. Inside the workspace: ~/.adom/hydrogen-control-url / $ADOM_HD_CONTROL_URL.
  2. Discovery responder: GET http://127.0.0.1:<c>/ for c in 47080, 48080, 49180, 50280 (first that answers). Any path works; the JSON carries control, control_url, proxy, code_server, hostname.
  3. From anywhere (another machine, the cloud): the Adom key-value store entry hydrogen.runtime.<hostname>, published every launch.

Then GET <control_url>/ports/all returns the whole port map.

Implementation

Tiny std::net::TcpListener on port 47080 in hydrogen-app/src/lib.rs. Runs on a plain OS thread (no tokio). Reads get_runtime_ports() on each request. Returns raw HTTP response with JSON body.

std::thread::spawn(move || {
    let listener = std::net::TcpListener::bind("127.0.0.1:47080").unwrap();
    for stream in listener.incoming() {
        let ports = hd_control::get_runtime_ports();
        let body = serde_json::json!({ "ok": true, ...ports });
        // write HTTP/1.1 200 OK + JSON
    }
});

Port defaults (PortConfig)

Service Default Notes
Discovery 47080 (walks 48080, 49180, 50280) fixed candidate list
Proxy 47083 dynamic
Control API 47084 dynamic
code-server 7380 inside the workspace, 127.0.0.1 only
Relay WS / HTTP 8765 / 8766 inside the workspace, same port from the host
cdp field 47085 nothing listens on Linux: WebKitGTK has no DevTools protocol; Hydrogen's frame bus does that job (POST /eval, /screenshot)

Files

File What
src-tauri/crates/hydrogen-proxy/src/lib.rs Workspace API, SSE, Carbon proxy, tree mutations (~1500 lines)
src-tauri/crates/hydrogen-control/src/lib.rs /auth-token endpoint, /ports endpoint, /setup/* routes
src-tauri/crates/hydrogen-control-core/src/ports.rs PortConfig load/save/resolve, the discovery candidates
src-tauri/crates/hydrogen-app/src/lib.rs Discovery server on :47080, port resolution at startup
src/lib/stores/portStore.ts Frontend Svelte store, initPorts(), controlUrl(), codeServerUrl()
src/lib/components/editor/workspaces/PanelWorkspaceComponent.svelte Frontend SSE setup, autosave, workspace re-fetch
src-tauri/crates/hydrogen-runtime/src/runtime/ refresh_distro_env(): the env vars and discovery files above