Skip to content

Commit f94428c

Browse files
authored
fix(workbot): keep cloud desktops connecting across unrelated runner updates (#6323)
The runner's desktop identity hashed the whole lockfile and every file in packages/computer-use, so dependency bumps and Mac-only changes made the bridge in existing computers refuse the new runner. Hash only what the guest bundles (from esbuild's metafile), the versions of packages it bundles, and the files the image installs. When the bridge does refuse, the runner now logs its reason and reports desktop_outdated, and Workbot tells the person their computer needs an update instead of asking them to reconnect. The Computer tab's Browser and Computer views get their own paths (/browser, /computer). Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent 5e56640 commit f94428c

16 files changed

Lines changed: 220 additions & 53 deletions

File tree

‎docs/computer-use/workbot.md‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ branch also includes Documents; its `workbotDocuments` rollout remains independe
77

88
The two views use one conversation computer:
99

10-
- **Browser** streams the Chromium window, including its tabs and address bar.
11-
- **Computer** streams the entire Linux desktop.
10+
- **Browser** (`/browser`) streams the Chromium window, including its tabs and address bar.
11+
- **Computer** (`/computer`) streams the entire Linux desktop.
1212
- **Take control** interrupts Workbot's current turn, pauses both browser and
1313
computer tools, and enables native mouse/keyboard input through noVNC.
1414
- **Return to Workbot** ends the manual connection and releases the tools.
@@ -75,11 +75,15 @@ runner workflow and wait for every node to adopt the bundle. Keep its compatibil
7575
and real-turn checks enabled.
7676

7777
The headless computer build embeds the same guest identity in the image and
78-
runner bundle, so celld needs no local package asset files. Build both from the
79-
same desktop sources and locked dependencies. The root-owned bridge is already
80-
installed in the snapshot; it rejects incompatible runners. Existing computers
81-
and their files are not replaced automatically, so snapshot upgrades need an
82-
explicit migration plan for computers already in use.
78+
runner bundle, so celld needs no local package asset files. The identity covers
79+
the files esbuild bundles into the guest, the versions of the packages it
80+
bundles, and the files the image installs (`scripts/desktop-identity.mjs`). The
81+
rest of the lockfile, Mac-only code and tests do not change it. The root-owned
82+
bridge is already installed in the snapshot; it rejects incompatible runners.
83+
The runner then logs the bridge's reason and Workbot tells the person their
84+
computer needs an update (`desktop_outdated`) instead of asking them to
85+
reconnect. Existing computers and their files are not replaced automatically,
86+
so snapshot upgrades need an explicit migration plan for computers already in use.
8387

8488
## Transport and rollout
8589

‎ee/apps/headless-runner/src/app.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,12 @@ export function createApp(input: {
238238
return c.json(await input.computer.desktopAction(session.id, body.data.action))
239239
}
240240
return c.json({ error: "desktop_not_configured" }, 409)
241-
} catch { return c.json({ error: "desktop_unavailable" }, 409) }
241+
} catch (error) {
242+
// The page only gets a stable code; the reason goes to the runner's log, where an operator can act on it.
243+
const code = typeof error === "object" && error !== null && "desktopCode" in error && (error.desktopCode === "desktop_outdated" || error.desktopCode === "desktop_unresponsive") ? error.desktopCode : "desktop_unavailable"
244+
console.error("[headless-runner] desktop failed", { sessionId: session.id, operation: c.req.param("operation"), code, error: error instanceof Error ? error.message : "unknown" })
245+
return c.json({ error: code }, 409)
246+
}
242247
})
243248

244249
app.post("/v1/sessions", async (c) => {

‎ee/apps/headless-runner/src/types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ export type SessionComputer = {
125125
image: string
126126
desktopTools?: ToolSpec[]
127127
desktopRun?(sessionId: string, input: Record<string, unknown>, signal?: AbortSignal): Promise<ToolResult>
128+
/** Desktop failures may carry `desktopCode` (`desktop_outdated`, `desktop_unresponsive`), which the runner reports as its error code. */
128129
desktopViewer?(sessionId: string, input: { view: "browser" | "computer"; control: boolean; origin: string }): Promise<{ state: "paused" } | { state: "connected"; url: string; expiresAt: number; paused: boolean }>
129130
browserDemonstration?(sessionId: string, command: import("@openwork/types/browser-demonstration").DemonstrationCommand): Promise<import("@openwork/types/browser-demonstration").DemonstrationReply>
130131
desktopAction?(sessionId: string, action: "continue" | "pause" | "resume"): Promise<{ ok: boolean }>

‎ee/apps/workbot/scripts/computer.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,27 @@ test("Computer follows the member's existing session cell after chat storage mig
124124
assert.ok(calls.includes(`/v1/sessions/${sessionId}/desktop/viewer`))
125125
assert.ok(!calls.some(path => path.includes(workbotSessionId("org", "cell_member"))))
126126
})
127+
128+
test("Computer says when its image is out of date instead of asking to reconnect", async t => {
129+
const signed = member("outdated")
130+
let viewer: { status: number; body: unknown } = { status: 409, body: { error: "desktop_outdated" } }
131+
t.mock.method(globalThis, "fetch", async (url: string | URL | Request, init?: RequestInit) => {
132+
const parsed = new URL(url instanceof Request ? url.url : url)
133+
if (parsed.pathname.endsWith("/desktop/viewer")) return new Response(JSON.stringify(viewer.body), { status: viewer.status, headers: { "content-type": "application/json" } })
134+
if (init?.method === "PUT") return Response.json({ id: parsed.pathname.split("/").at(-1) })
135+
return Response.json({ turns: [], messages: [], finalAssistantText: "" })
136+
})
137+
t.mock.method(console, "error", () => {})
138+
const app = new Hono<AppEnv>()
139+
registerWorkbotRoutes(app, {
140+
config, den: { ...createDen({ apiUrl: config.denApiUrl, publicUrl: config.publicUrl }), session: async () => signed.den },
141+
member: async (c, next) => { c.set("member", signed); await next() }, sameOrigin: async (_c, next) => next(),
142+
})
143+
const open = () => app.request("/v1/workbot/computer/viewer", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ view: "browser" }) })
144+
const outdated = await open()
145+
assert.equal(outdated.status, 409)
146+
assert.deepEqual(await outdated.json(), { error: "desktop_outdated", message: "Your computer needs an update before it can connect. Ask your workspace admin to update Workbot's computer." })
147+
// Other runner codes, including ones this Workbot doesn't know, keep the reconnect message.
148+
viewer = { status: 409, body: { error: "desktop_unresponsive" } }
149+
assert.deepEqual(await (await open()).json(), { error: "desktop_unavailable", message: "Your computer is unavailable. Try reconnecting." })
150+
})

‎ee/apps/workbot/src/server/routes.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,13 @@ export function registerWorkbotRoutes(app: Hono<AppEnv>, input: { config: Config
224224
})
225225
})
226226

227+
/** The runner's desktop codes in the person's words; anything else reads as a reconnectable outage. */
228+
const desktopFailure = (c: Context<AppEnv>, operation: string, code: string) => {
229+
console.error("[workbot] desktop unavailable", { operation, code })
230+
if (code === "desktop_outdated") return c.json({ error: code, message: "Your computer needs an update before it can connect. Ask your workspace admin to update Workbot's computer." }, 409)
231+
return c.json({ error: "desktop_unavailable", message: "Your computer is unavailable. Try reconnecting." }, 409)
232+
}
233+
227234
// No sandbox ids or preview credentials are accepted from the page: the member determines the computer.
228235
app.post("/v1/workbot/computer/:operation", async (c) => {
229236
const member = c.get("member")
@@ -247,16 +254,16 @@ export function registerWorkbotRoutes(app: Hono<AppEnv>, input: { config: Config
247254
const existing = await client.readSession(sessionId, { turns: 1, limit: 1, outputs: "none" })
248255
if (!existing.ok && existing.status === 404) sessionId = await workbot.ensureComputer(actorOf(member))
249256
else {
250-
if (!existing.ok) return c.json({ error: "desktop_unavailable" }, 409)
257+
if (!existing.ok) return desktopFailure(c, operation, existing.error)
251258
const updated = await client.putSession(sessionId, { computer: true, desktop: true })
252-
if (!updated.ok) return c.json({ error: "desktop_unavailable" }, 409)
259+
if (!updated.ok) return desktopFailure(c, operation, updated.error)
253260
}
254261
if (operation === "viewer") {
255262
const body = viewer
256263
if (!body.success) return c.json({ error: "invalid_request" }, 400)
257264
if (body.data.control) await workbot.stop(actorOf(member))
258265
const result = await client.desktopViewer(sessionId, { ...body.data, origin: new URL(config.publicUrl).origin })
259-
if (!result.ok) return c.json({ error: "desktop_unavailable", message: "Your computer is unavailable. Try reconnecting." }, 409)
266+
if (!result.ok) return desktopFailure(c, operation, result.error)
260267
// A cold VM may take longer than the membership cache: verify again before sharing its stream.
261268
if (!await stillAllowed()) return c.json({ error: "feature_disabled" }, 403)
262269
return c.json(result.value)
@@ -266,8 +273,11 @@ export function registerWorkbotRoutes(app: Hono<AppEnv>, input: { config: Config
266273
if (!await stillAllowed()) return c.json({ error: "feature_disabled" }, 403)
267274
if (body.data.action === "pause") await workbot.stop(actorOf(member))
268275
const result = await client.desktopAction(sessionId, body.data.action)
269-
return result.ok ? c.json({ ok: true }) : c.json({ error: "desktop_unavailable" }, 409)
270-
} catch { return c.json({ error: "desktop_unavailable", message: "Your computer is unavailable. Try reconnecting." }, 409) }
276+
return result.ok ? c.json({ ok: true }) : desktopFailure(c, operation, result.error)
277+
} catch (error) {
278+
console.error("[workbot] desktop request failed", { operation, error: error instanceof Error ? error.message : "unknown" })
279+
return desktopFailure(c, operation, "desktop_unavailable")
280+
}
271281
})
272282

273283
app.get("/v1/workbot/model-recovery", async (c) => {
Lines changed: 11 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,25 @@
11
import { build } from "esbuild";
2-
import { copyFile, readFile, readdir, writeFile } from "node:fs/promises";
3-
import { createHash } from "node:crypto";
4-
import { join } from "node:path";
2+
import { copyFile, writeFile } from "node:fs/promises";
53
import { fileURLToPath } from "node:url";
4+
import { desktopIdentity } from "./desktop-identity.mjs";
65

7-
await build({
6+
const guest = await build({
87
absWorkingDir: fileURLToPath(new URL("..", import.meta.url)),
98
entryPoints: ["src/desktop-guest.mjs"], outfile: "dist/desktop-guest.mjs", bundle: true,
10-
platform: "node", format: "esm", target: "node22",
9+
platform: "node", format: "esm", target: "node22", metafile: true,
1110
// TypeScript's bundled CommonJS runtime also resolves its own file location.
1211
// The guest is a standalone ESM file with no installed node_modules.
1312
banner: { js: "import { createRequire } from 'node:module'; import { fileURLToPath as guestFileURLToPath } from 'node:url'; import { dirname as guestDirname } from 'node:path'; const require = createRequire(import.meta.url); const __filename = guestFileURLToPath(import.meta.url); const __dirname = guestDirname(__filename);" },
1413
});
1514
await copyFile(new URL("../../../apps/den-worker-runtime/scripts/cloud-desktop.sh", import.meta.url), new URL("../dist/cloud-desktop.sh", import.meta.url));
1615

17-
// Compatibility follows source and locked dependencies, not platform-specific
18-
// bundler output or the optional packages present in a developer's install.
19-
const root = fileURLToPath(new URL("../../../../", import.meta.url));
20-
const fingerprint = createHash("sha256");
21-
async function include(relative) {
22-
let bytes;
23-
try { bytes = await readFile(join(root, relative)); }
24-
catch (error) { if (error.code === "ENOENT") return; if (error.code !== "EISDIR") throw error; }
25-
if (bytes) { fingerprint.update(relative).update("\0").update(bytes).update("\0"); return; }
26-
for (const entry of (await readdir(join(root, relative))).sort()) await include(`${relative}/${entry}`);
27-
}
28-
for (const relative of [
29-
"packages/types/src/browser-demonstration.ts", "packages/types/package.json", "packages/types/tsup.config.ts",
30-
"pnpm-lock.yaml", "packages/computer-use/package.json", "packages/computer-use/src",
31-
"packages/codemode/package.json", "packages/codemode/src",
32-
"ee/packages/headless-computer/package.json", "ee/packages/headless-computer/Dockerfile.desktop",
33-
"ee/packages/headless-computer/src/image.ts", "ee/packages/headless-computer/requirements-desktop.lock",
34-
"ee/packages/headless-computer/src/desktop.ts", "ee/packages/headless-computer/src/desktop-apps.mjs",
35-
"ee/packages/headless-computer/src/desktop-guest.mjs", "ee/packages/headless-computer/src/viewer-tickets.mjs", "ee/packages/headless-computer/src/desktop-scripting.mjs",
36-
"ee/packages/headless-computer/src/scripting", "ee/packages/headless-computer/scripts/build-desktop.mjs",
37-
"ee/packages/headless-computer/scripts/desktop-bridge.py", "ee/packages/headless-computer/scripts/vnc-stdio.py", "ee/packages/headless-computer/scripts/configure-desktop-files.sh",
38-
"ee/packages/headless-computer/scripts/install-desktop-apps.sh",
39-
"ee/apps/den-worker-runtime/scripts/cloud-desktop.sh",
40-
]) await include(relative);
41-
for (const name of (await readdir(join(root, "packages/computer-use"))).sort()) {
42-
if ((name.endsWith(".mjs") && !name.endsWith(".test.mjs")) || name.endsWith(".py")) await include(`packages/computer-use/${name}`);
43-
}
44-
const identity = `${fingerprint.digest("hex")}\n`;
16+
// Compatibility follows what the guest bundles and the image installs, not the rest of the lockfile or code the guest
17+
// never loads (see desktop-identity.mjs).
18+
const identity = await desktopIdentity({
19+
root: fileURLToPath(new URL("../../../../", import.meta.url)),
20+
workingDirectory: fileURLToPath(new URL("..", import.meta.url)),
21+
inputs: Object.keys(guest.metafile.inputs),
22+
});
4523
await writeFile(new URL("../dist/desktop-guest.version", import.meta.url), identity);
4624
// Keep the same identity in bundled Workers, which have no package asset files.
4725
await writeFile(new URL("../dist/desktop-identity.mjs", import.meta.url), `export default ${JSON.stringify(identity)};\n`);
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export declare const IMAGE_FILES: string[]
2+
export declare function desktopIdentity(input: { root: string; workingDirectory: string; inputs: string[] }): Promise<string>
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { createHash } from "node:crypto";
2+
import { readFile, readdir } from "node:fs/promises";
3+
import { join, relative, sep } from "node:path";
4+
5+
/**
6+
* Files that reach the desktop image without passing through the guest bundle, plus the runner's half of the bridge
7+
* protocol. Paths are relative to the repository root; directories are read recursively.
8+
*/
9+
export const IMAGE_FILES = [
10+
"ee/packages/headless-computer/Dockerfile.desktop", "ee/packages/headless-computer/requirements-desktop.lock",
11+
"ee/packages/headless-computer/src/image.ts", "ee/packages/headless-computer/src/desktop.ts",
12+
"ee/packages/headless-computer/src/scripting",
13+
"ee/packages/headless-computer/scripts/build-desktop.mjs", "ee/packages/headless-computer/scripts/desktop-identity.mjs",
14+
"ee/packages/headless-computer/scripts/build-desktop-vnc.sh", "ee/packages/headless-computer/scripts/desktop-bridge.py",
15+
"ee/packages/headless-computer/scripts/vnc-stdio.py", "ee/packages/headless-computer/scripts/configure-desktop-files.sh",
16+
"ee/packages/headless-computer/scripts/install-desktop-apps.sh",
17+
"ee/packages/headless-computer/scripts/daytona-desktop-permissions.service",
18+
"ee/packages/headless-computer/scripts/daytona-desktop-permissions.conf",
19+
"ee/apps/den-worker-runtime/scripts/cloud-desktop.sh",
20+
];
21+
22+
/**
23+
* The guest's compatibility identity: the bytes of every repository file esbuild bundled into the guest (from its
24+
* metafile), the name and version of every installed package it bundled, and the image files above. Anything the guest
25+
* doesn't contain, such as the rest of the lockfile, Mac-only code or tests, leaves the identity unchanged, so it no
26+
* longer forces a snapshot rebuild.
27+
*/
28+
export async function desktopIdentity({ root, workingDirectory, inputs }) {
29+
const sources = new Set();
30+
const packages = new Set();
31+
for (const input of inputs) {
32+
const path = relative(root, join(workingDirectory, input)).split(sep).join("/");
33+
const installed = path.lastIndexOf("node_modules/");
34+
if (installed === -1) { sources.add(path); continue; }
35+
const [first, second] = path.slice(installed + "node_modules/".length).split("/");
36+
const name = first.startsWith("@") ? `${first}/${second}` : first;
37+
const manifest = JSON.parse(await readFile(join(root, path.slice(0, installed), "node_modules", name, "package.json"), "utf8"));
38+
packages.add(`${name}@${manifest.version}`);
39+
}
40+
const fingerprint = createHash("sha256");
41+
async function include(path) {
42+
let bytes;
43+
try { bytes = await readFile(join(root, path)); }
44+
catch (error) { if (error.code === "ENOENT") return; if (error.code !== "EISDIR") throw error; }
45+
if (bytes) { fingerprint.update(path).update("\0").update(bytes).update("\0"); return; }
46+
for (const entry of (await readdir(join(root, path))).sort()) await include(`${path}/${entry}`);
47+
}
48+
for (const path of [...new Set([...sources, ...IMAGE_FILES])].sort()) await include(path);
49+
for (const name of [...packages].sort()) fingerprint.update(`package:${name}`).update("\0");
50+
return `${fingerprint.digest("hex")}\n`;
51+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import assert from "node:assert/strict"
2+
import { test } from "node:test"
3+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"
4+
import { tmpdir } from "node:os"
5+
import { dirname, join } from "node:path"
6+
import { desktopIdentity } from "../scripts/desktop-identity.mjs"
7+
8+
test("only what the guest bundles or the image installs changes the desktop identity", async () => {
9+
const root = await mkdtemp(join(tmpdir(), "desktop-identity-"))
10+
const put = async (path: string, text: string) => { await mkdir(dirname(join(root, path)), { recursive: true }); await writeFile(join(root, path), text) }
11+
try {
12+
await put("pkg/src/guest.mjs", "guest")
13+
await put("node_modules/ws/package.json", JSON.stringify({ name: "ws", version: "8.0.0" }))
14+
await put("node_modules/ws/index.js", "ws")
15+
await put("ee/packages/headless-computer/scripts/desktop-bridge.py", "bridge")
16+
await put("pnpm-lock.yaml", "lock")
17+
await put("packages/computer-use/native/Sources/Mac.swift", "mac")
18+
const identity = () => desktopIdentity({ root, workingDirectory: join(root, "pkg"), inputs: ["src/guest.mjs", "../node_modules/ws/index.js"] })
19+
const original = await identity()
20+
21+
await put("pnpm-lock.yaml", "another package was added")
22+
await put("packages/computer-use/native/Sources/Mac.swift", "mac only")
23+
assert.equal(await identity(), original, "lockfile and Mac-only changes keep the snapshot compatible")
24+
25+
await put("node_modules/ws/index.js", "same version, different install")
26+
assert.equal(await identity(), original, "a bundled package counts by its version")
27+
28+
await put("node_modules/ws/package.json", JSON.stringify({ name: "ws", version: "8.1.0" }))
29+
const upgraded = await identity()
30+
assert.notEqual(upgraded, original, "a new version of a bundled package needs a new snapshot")
31+
32+
await put("pkg/src/guest.mjs", "changed guest")
33+
const guest = await identity()
34+
assert.notEqual(guest, upgraded, "bundled guest code needs a new snapshot")
35+
36+
await put("ee/packages/headless-computer/scripts/desktop-bridge.py", "changed bridge")
37+
assert.notEqual(await identity(), guest, "files installed in the image need a new snapshot")
38+
} finally { await rm(root, { recursive: true, force: true }) }
39+
})
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import assert from "node:assert/strict"
2+
import { test } from "node:test"
3+
import type { SandboxHandle, SandboxProvider } from "@openwork/sandbox"
4+
import { Desktop, DesktopError } from "./desktop.js"
5+
6+
test("a computer whose image was built for another runner reports desktop_outdated", async () => {
7+
const provider = {
8+
describe: () => ({ platform: { os: "linux" } }),
9+
blocks: { run: async (_box: SandboxHandle, input: { command: string }) => input.command.includes(" start ")
10+
? { exitCode: 1, stdout: "", stderr: "The desktop image is out of date. Rebuild its snapshot for this runner.\n" }
11+
: { exitCode: 1, stdout: "", stderr: "" } },
12+
} as unknown as SandboxProvider
13+
await assert.rejects(new Desktop(provider).start({ ref: { id: "old" } } as unknown as SandboxHandle), (error: unknown) => {
14+
assert.ok(error instanceof DesktopError)
15+
assert.equal(error.desktopCode, "desktop_outdated")
16+
assert.match(error.message, /out of date/)
17+
return true
18+
})
19+
})

0 commit comments

Comments
 (0)