Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Merge origin/main into feat/harness-grid

Kelvin7b763bcc5482
diff --cc cli/src/backendSocket.ts
index 58f903b0f,ca2d756ee..cc02156c1
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@@ -1201,23 -1228,15 +1287,35 @@@ export class BackendSocket
this.send({ type: resultType, payload: { requestId, ...payload } })
}
- private async dispatchDown(frame: Frame, connId: string, transport: 'relay' | 'p2p' = 'relay'): Promise<void> {
+ private async dispatchDown(frame: Frame, connId: string, transport: DownTransport = 'relay'): Promise<void> {
const type = frame.type as string | undefined
if (!type) return
- // Whether this frame came from a process on THIS machine — the trust boundary four gates below
++ // Whether this frame came from a process on THIS machine — the trust boundary the gates below
+ // turn on. The membership half is a dispatch-time question about a connection that may already
+ // be gone: frames run through a per-connId queue, so a local client that disconnects between
+ // sending and being dispatched used to leave `localClients.has()` false, and its already-queued
+ // frames were then read as the BACKEND's. The transport half closes that, because it is stamped
+ // at enqueue by the caller that had just verified membership. Either one being true is local.
+ const local = transport === 'local' || this.localClients.has(connId)
+ // ⚠️ The backend's own instructions, refused from anywhere else. See BACKEND_ONLY_DOWN_TYPES.
+ // `transport === 'relay'` rather than `!local`, so this keeps holding if the p2p allowlist
+ // (`TERMINAL_P2P_DOWN_TYPES`) ever widens; "not local" would quietly start admitting p2p.
++ //
++ // Deliberately ABOVE the observer hand-off below. A genuine observer frame is `relay`, so this
++ // never intercepts one; but placed after it, a forged `observer:` connId on a local or p2p frame
++ // would be swallowed by `harnessSharing.receive` and returned without ever reaching this line —
++ // silently, with no warning — and the invariant would then rest on three facts in other files
++ // (the `local:` prefix rule, `registerLocalClient`'s check, the p2p-signal ordering) instead of
++ // on this one. The grid-name incident was exactly a bypass nobody could see.
+ if (transport !== 'relay' && BACKEND_ONLY_DOWN_TYPES.has(type)) {
+ console.warn(`[backend] ignoring ${type} from ${transport} (${connId}) — only the backend may send it`)
+ return
+ }
+ if (connId.startsWith('observer:')) {
+ await this.harnessSharing?.receive(connId, type, (frame.payload ?? {}) as Record<string, unknown>)
+ return
+ }
+ if (type.startsWith('observer_')) return
- const local = this.localClients.has(connId)
// E2EE control frames (pairing/handshake) are handled by the manager, never as node RPCs.
if (type.startsWith('e2e_')) {
if (local) {
diff --cc cli/src/cli.ts
index dccc81eef,b6bdb3f7c..c73a8284e
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@@ -1603,68 -1555,10 +1610,69 @@@ async function runForeground(session: A
void fullReconcile(true).catch((err) => {
console.error('[runtime-profile] connect reconcile failed:', err instanceof Error ? err.message : err)
})
+ onBackendConnected()
}, computerId())
backendRef = backend
+ backend.viewerTargetProvider = (agentId) => dshViewers.forwardingUrl(agentId)
+ // Bring this machine's grid sign-in into line with its harness sign-in, in the background.
+ // This is what makes a machine that signed in to the harness BEFORE grid existed usable after an
+ // update: it has the `grid` binary now (above), but no grid credentials and no grid to point at
+ // until something signs it in — and the login *event* that used to do that never fires again for
+ // an already-signed-in account. Reconciling on daemon start (the path every update takes) removes
+ // the `harness logout` / `harness login` a person would otherwise have to run by hand.
+ //
+ // Best-effort and non-blocking: it awaits the managed grid, mints/reads the account's name, and
+ // signs in + creates the grid only when the machine is not already there. The RPCs that need the
+ // name wait briefly for it through `gridReadyProbe`.
+ //
+ // ⚠️ Retried on backend RECONNECT, not just at start, and this is not belt-and-braces: the daemon
+ // OUTLIVES the desktop app (it must keep running after the window closes), and `harness start`
+ // against a live daemon returns without starting a new one. So "start" can be days ago, and a
+ // single attempt that lost to a control plane which was not reachable yet — the ordinary shape of
+ // a daemon coming up with the network — would leave the account with no grid until the next real
+ // restart. A connect is the evidence the control plane is reachable, so it is when to try again.
+ // How long the RPCs gate on an attempt, and how many attempts there are, live in the runner —
+ // `lib/gridAttach.ts`, beside the reconcile itself, so the coordination has a unit test rather
+ // than only a comment. Everything below is the daemon-shaped half: what one attempt actually does.
+ const gridAttach = createGridAttachRunner({
+ maxAttempts: GRID_ATTACH_MAX_ATTEMPTS,
+ minIntervalMs: GRID_ATTACH_MIN_INTERVAL_MS,
+ ceilingMs: GRID_ATTACH_CEILING_MS,
+ log: (line) => console.log(`[grid-attach] ${line}`),
+ attempt: () => reconcileGridAttach({
+ managedGridReady,
+ gridAvailable: () => gridAvailable(),
+ // The backend mints and remembers the name; this CLI holds neither the account's email nor its
+ // id. An older backend (no route) answers nothing, which the reconcile treats as "no grid yet".
+ // Bounded so a stalled control-plane connection cannot hold the attempt open indefinitely.
+ mintName: async () => {
+ const { headers } = await controlPlaneAuth()
+ return (await postJson<{ gridName?: string }>('/api/grid/name', {}, headers, AbortSignal.timeout(GRID_MINT_TIMEOUT_MS))).gridName ?? null
+ },
+ accessToken: () => new AuthSessionManager(backendHttpBase()).accessToken(),
+ signedInEmail: () => signedInGridEmail(),
+ gridNames: () => gridNamesLocal(),
+ handoff: (token) => handOffToGrid(token, { json: true }),
+ ensure: (name) => ensureHarnessGrid(name),
+ onName: (name) => {
+ // Answer the picker with this account's grid at once, and drop the memos a stale or absent
+ // sign-in may have filled — the model list, the derived name, and the web-tools URL.
+ backend.setHarnessGridName(name)
+ forgetGridModels()
+ resetGridDeriveMemo()
+ clearGridMcpUrlCache()
+ },
+ log: (line) => console.log(`[grid-attach] ${line}`),
+ }),
+ })
+
+ // While an attempt is running AND within its ceiling, the RPCs that need the grid name wait
+ // briefly on it; otherwise they read the name directly.
+ backend.gridReadyProbe = () => gridAttach.probe()
+ onBackendConnected = () => gridAttach.run()
+ gridAttach.run()
+
/**
* Is ANY device surface watching this machine?
*