Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
246 changes: 246 additions & 0 deletions docs/desktop-shell-contract.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
# The desktop orchestrator's shell contract

The desktop app is a shell around a local HTTP server. The shell is what starts it, keeps it
alive, and talks to it; the server — a Bun process shipped with the desktop build — is the part
that holds projects, threads and sessions. This document is the observable contract *of that
shell boundary*, recovered from a shipped install, so that other clients (a test harness, a
native shell, an automation script) can drive the same server without re-deriving it.

Nothing here is private: it is the shape of a loopback interface, not any user's data.

## Provenance

Written against the installed **Freebuff Desktop `0.0.206`** build. Every claim below is a literal in
one of these files, recorded with the hash of the copy it was read from:

| Artifact | SHA-256 (first 16) |
|---|---|
| `resources/app.asar` (the Electron shell) | `b768b8c718179c6e` |
| `app/electron/orchestrator-startup.cjs` | `e5731573abb8a3b4` |
| `app/electron/shell-lifetime.cjs` | `9affdeff0595e928` |
| `app/electron/launch-bootstrap.cjs` | `e7b2390dbc95f2ae` |
| `resources/orchestrator/orchestrator.js` (the bundled server) | `4ea1f56d54dda08b` |
| `resources/orchestrator/build-info.json` | commit `17d3359f1349b40a`, built `2026-11-26T19:57:12Z` |

**Name the build, not the hash.** `resources/orchestrator/build-info.json` is written at build time
and ships beside the server:

```json
{"commitSha":"17d3359f1349b40a2e2a4c82a2ef621f5e49a415",
"builtAt":"2026-11-26T19:57:12.527Z",
"apiOrigin":"https://www.codebuff.com","webOrigin":"https://freebuff.com"}
```

That is the durable anchor. The hashes above are one release's record; a client that reports
`commitSha` and `builtAt` from this file can say which server it actually ran, and a bug report can
be tied to a commit instead of to "whatever was installed". The shell does the same: it reads
`build-info.json` for its own crash grouping. Two releases are already enough to show why the hashes
are not the anchor — `0.0.203` shipped `app.asar` `af684513edb0c024` and `orchestrator.js`
`c0267ead585538d3`, and neither is the file above.

The bundle keeps its source paths, which are the fastest way to check these against the real tree:
`src/server/boot-phase.ts` (the phase list), `src/server/services/orchestrator-lock.ts` (the profile
lock and the exit code), and the shell modules named above.

| Claim | Where | Literal |
|---|---|---|
| the nine phases, in order | `orchestrator-startup.cjs:22` | `const BOOT_PHASES = new Set([` … `'projects_boot_end',` |
| phase line prefix | `orchestrator-startup.cjs:19` | `const PHASE_PREFIX = '[orchestrator-phase] '` |
| 30 s spawn → ready | `orchestrator-startup.cjs:35` | `const READY_LINE_BUDGET_MS = 30_000` |
| 60 s ready → `/healthz` | `orchestrator-startup.cjs:52` | `const HEALTH_BUDGET_MS = 60_000` |
| ready line shape | `orchestrator.js` | ``console.log(`[orchestrator-ready] ${JSON.stringify({ launchId: LAUNCH_ID, pid: process.pid, port: serverPort })}`)`` |
| stdin bootstrap line | `launch-bootstrap.cjs:20` | `function launchBootstrapLine({ shellLifetimeToken, launchId, cdpBridgeToken, mcpConsentToken })` |
| 3 s ping | `shell-lifetime.cjs:9` | `const DEFAULT_PING_MS = 3000` |
| HMAC labels | `shell-lifetime.cjs:37,46` | `` `client:${challenge}:${clientChallenge}` ``, `` `server:${challenge}:${clientChallenge}` `` |
| `/api/*` gate | `orchestrator.js:98701` | `pathname.startsWith("/api/")` |
| header and cookie names | `orchestrator.js:98704–98706` | `var LAUNCH_TOKEN_HEADER = "x-freebuff-launch-id"`, `` `freebuff_launch_${port}` `` |
| 401 body | `orchestrator.js:253740` | `json4({ error: "invalid launch id" }, 401)` |
| exit code 75 | `orchestrator.js:252976` | `var PROFILE_BUSY_EXIT = 75` … `process.exit(PROFILE_BUSY_EXIT)` |
| profile lock file | `orchestrator.js:240134` | `` `${statePath}.orchestrator-lock.sqlite` ``, opened with `PRAGMA busy_timeout = 0` |
| lock wait default | `main.cjs:1015` | `FREEBUFF_PROFILE_LOCK_WAIT_MS: '10000'` |
| bundle entry, when offered | `main.cjs:620` | `bundleArgs: bunLaunchArgs(path.join(orchDir, 'orchestrator-loader.mjs'))` |
| bundle protocol | `orchestrator-bundle.cjs:36` | `const ORCHESTRATOR_SHELL_ABI = 1` |
| host gate | `orchestrator.js` | `isAllowedLoopbackHost(req.headers.get("host"), guard.port)`, `json4({ error: "forbidden host" }, 403)` |
| origin gate | `orchestrator.js` | `ALLOWED_FETCH_SITES = new Set(["same-origin", "none"])`, `refuse(403, "forbidden origin")` |
| `/healthz` gate | `orchestrator.js` | `isAuthorizedApiRequest(LAUNCH_ID, req.headers.get("x-freebuff-launch-id"))` |

Re-checking a claim is one grep, no build:

```bash
npx @electron/asar extract "<install>/resources/app.asar" app
grep -n "READY_LINE_BUDGET_MS\|HEALTH_BUDGET_MS" app/electron/orchestrator-startup.cjs
grep -n "PROFILE_BUSY_EXIT\|invalid launch id\|LAUNCH_TOKEN_HEADER" \
"<install>/resources/orchestrator/orchestrator.js"
cat "<install>/resources/orchestrator/build-info.json"
```

**Across versions.** None of the handshake constants is negotiated — no boot handshake carries a
protocol version — so a build that renames a phase or moves a budget breaks a client silently
instead of saying so. `build-info.json` is what makes that recoverable after the fact: a client logs
it once at boot, and a mismatch is then "this build" rather than "some build". The parts worth
relying on are the shape: a phase line on stdout, a ready line carrying a launch id, a bootstrap
line on stdin, an HMAC lifetime socket, a launch-id header on `/api/*`, and the bundle handshake
below. The constants next to them are the part to re-read when a release changes.

## The two-process shape

```
shell ──spawn──▶ bun resources/orchestrator/orchestrator.js (cwd = …/orchestrator)
│ │ stdout = boot progress lines
│ └─▶ http://127.0.0.1:<PORT> (Bun.serve, host 127.0.0.1)
└── owns the lifetime socket; the server stops when it closes
```

The shell picks a free loopback port and passes it as `PORT`. The server binds `127.0.0.1` only.

One exception to the entry point above: when the shell has a downloaded *hot bundle* to run, it
launches `orchestrator-loader.mjs` instead. See "Hot bundles" below — a client that skips it still
works, it just runs the server shipped with the app rather than the one the app would run.

## Boot progress on stdout

The server prints one whitelisted phase per step; anything else on stdout is ignored by the
shell.

```
[orchestrator-phase] <phase>
```

The phases, in order: `started, bootstrap, profile_lock, auth, recover_setups, terminals,
listen, projects_boot_start, projects_boot_end`. Only these nine names are reported.

When the HTTP server is up it prints:

```
[orchestrator-ready] {"launchId":…,"pid":…,"port":…}
```

The shell's two budgets, from the shipped startup code:

1. spawn → ready line: **30 seconds**
2. ready line → first healthy `GET /healthz`: **60 seconds**

`/healthz` answers plain `ok` when the server has no launch id, or
`{"ok":true,"launchId":…,"pid":…,"port":…}` when it does — and in that case it wants the launch-id
header too (see "The gates on every request").

## Secrets: the stdin bootstrap line

Launch secrets are **not** passed in the environment, because any process of the same user can
read a child's starting environment. They ride the first stdin line:

```json
{"shellLifetimeToken":"…","launchId":"…","cdpBridgeToken":null,"mcpConsentToken":null}
```

A bare token string is also accepted as the lifetime token alone.

## Lifetime: how a dead shell takes its server down

The server is told to be shell-managed via `FREEBUFF_SHELL_LIFETIME_PORT`; when set, the server
shuts down once the socket closes — a killed shell cannot orphan a server. To keep a foreign
process from holding the server hostage, the socket is challenged:

1. server writes `challenge\n` (32 random bytes, base64url);
2. client answers `clientChallenge:HMAC-SHA256(token, "client:"+challenge+":"+clientChallenge)`;
3. server replies `HMAC-SHA256(token, "server:"+challenge+":"+clientChallenge)`;
4. then the client pings with `ping\n` every 3 s; the server tolerates 10 s of silence.

## The gates on every request

Three checks run before a route does, and each one has its own answer, so a client that gets a `403`
can tell which gate it hit. All three body shapes are `{"error": …}`.

**1. Host.** The `Host` header must name a loopback host — `127.0.0.1`, `localhost` or `::1` — *and*
carry the server's port, since `isAllowedLoopbackHost` compares the port it parsed (default 80) with
its own. Otherwise:

```
403 {"error":"forbidden host"}
```

This applies to `/healthz` as well, so a client that connects to `127.0.0.1:<port>` and sends
`Host: 127.0.0.1` without the port is refused even though the socket is right.

**2. Origin.** `/api/*` also checks the browser's provenance. A **missing** `Origin` is allowed —
which is what a native client sends — but a present one must be exactly
`http://127.0.0.1:<port>` or `http://localhost:<port>`, or a loopback dev-UI origin the shell named in
`FREEBUFF_DESKTOP_UI_ORIGIN`. A present `Sec-Fetch-Site` must be `same-origin` or `none`, and an
`Origin` carrying credentials is refused. Otherwise:

```
403 {"error":"forbidden origin"}
```

So a native client should not send `Origin` to the local server at all. (The hosted cloud API is the
opposite: it *requires* its own `Origin`.)

**3. Launch id.** Every `/api/*` path is refused with `401 {"error":"invalid launch id"}` unless the
request carries `x-freebuff-launch-id: <launchId>` (the value from the bootstrap line) or the
`freebuff_launch_<port>` cookie. A server started with no launch id admits everything.

`/healthz` sits between the two: it takes the Host gate, and when a launch id exists it also wants the
header (401 otherwise); when the id matches it answers
`{"ok":true,"launchId":…,"pid":…,"port":…}`, and a server started with no launch id answers plain
`ok`. A health check that works without the header is a signed-out server, not a healthy one.

## Hot bundles: which server a launch runs

A packaged app can run a downloaded `orchestrator.js` instead of the shipped one, and it does so
without an app update. The rules matter to any shell that wants to run what the user's app runs:

- The shell downloads a bundle into `<userData>/orchestrator-bundles/<version>/` and offers that
folder by setting `FREEBUFF_ORCHESTRATOR_BUNDLE_DIR` on the launch. The launch entry then becomes
`resources/orchestrator/orchestrator-loader.mjs`, not `orchestrator.js`.
- The bundle carries its own `ui/` as well as its `orchestrator.js`, because the server serves its
own renderer: a new server beside an old `ui/` is a pairing no release tested.
- Nothing from a bundle is used unverified. The loader rewrites the *shipped* entry path to the
bundle's verified bytes through a Bun runtime plugin, so `import.meta.dir` and everything resolved
relative to it (`wasm/`, `vendor/ripgrep`) still come from the signed app. `orchestrator.js` is
hashed over the bytes that run and every `ui/` file over the bytes served.
- The bundle's `ui/` and its hashes reach the server through a global (`Symbol.for(
'freebuff.orchestrator-bundle')`), never the environment, which every child would inherit.
- The loader removes `FREEBUFF_ORCHESTRATOR_BUNDLE_DIR` before the orchestrator starts, and logs one
line saying which it ran:

```
[orchestrator-bundle] running <version>
[orchestrator-bundle] rejected <dir> (<reason>); running the shipped orchestrator
```

- The shell reads a refusal from that line and drops the bundle; a bundle whose launch fails is
dropped too, and a dropped bundle is never offered again. Bundles are also re-checked on an
interval (`FREEBUFF_BUNDLE_CHECK_MS`, default every 2 hours, minimum 30 s).
- A bundle declares which shell ABI it expects: `ORCHESTRATOR_SHELL_ABI` is `1` today. A bundle
built for a different value is rejected rather than half-run.

A client that ignores all of this still has a working server — the shipped one. It just will not be
the same server, or the same behaviour, as the Electron shell on a machine that received a bundle.
That is worth logging: `build-info.json` says which commit the shipped server is, and the
`[orchestrator-bundle]` line says whether that server is the one that ran.

## Environment

| Variable | Meaning |
|---|---|
| `PORT` | loopback port to bind |
| `FREEBUFF_DESKTOP_STATE_PATH` | profile path, default `~/.config/freebuff-desktop/state.json` |
| `FREEBUFF_PROFILE_LOCK_WAIT_MS` | wait on the profile lock before failing (exit 75 + a stderr explanation if another orchestrator holds it) |
| `FREEBUFF_SHELL_LIFETIME_PORT` | lifetime server port (see above) |
| `FREEBUFF_UI_DIR` | where `ui/` lives, served at `/` |
| `FREEBUFF_APP_VERSION` | the installed app version, so telemetry groups by release |
| `FREEBUFF_ORCHESTRATOR_BUNDLE_DIR` | the hot bundle to run; read and removed by the loader |
| `FREEBUFF_BUNDLE_CHECK_MS` | how often the shell looks for a new bundle (default 2 h, floor 30 s) |
| `CODEBUFF_WASM_DIR`, `CODEBUFF_TREE_SITTER_WASM_PATH` | tree-sitter wasm used by code features |
| `FREEBUFF_BUN_PATH` | override the bundled Bun |

## Scope

This documents a boundary that exists today, and it is useful whether or not a native shell is ever
built: a test harness, a diagnostics client or an automation script needs the same facts, and none
of them needs the direction question answered first. Nothing here argues for a particular shell.

A reference implementation of all of the above is ~500 lines of dependency-light Rust: it spawns the
same server, keeps it alive and reports its state in a sidebar. It is deliberately not part of this
document. Neither the shell code nor the server code is required to use this contract; only the
words above.
Loading