Skip to content

Commit ed65c9e

Browse files
authored
fix(workbot): reconnect the computer view and rebuild outdated ones (#6432)
The desktop guest's WebSocket upgrade handler read the outer `transport` ("vnc" or "screencast") inside a callback that later declared its own `const transport`, so every viewer connection threw a ReferenceError and took the guest down. The Browser and Computer views retried until they showed "Connection lost", and rebuilding could not help because every computer runs the same guest. The VNC handle is now called `vnc`, and a test runs the bundled guest and opens both kinds of viewer socket. When the viewer finds a computer out of date, Workbot now rebuilds it and connects, instead of asking the person to press Rebuild. Concurrent viewers share one rebuild, and a running turn is never stopped by it. If a fresh computer is still out of date, Workbot no longer suggests rebuilding again. Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent 0910652 commit ed65c9e

4 files changed

Lines changed: 140 additions & 17 deletions

File tree

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

Lines changed: 49 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -150,14 +150,24 @@ test("Rebuilding the computer stops the running turn before the runner replaces
150150
assert.deepEqual(calls[rebuild]?.body, { action: "rebuild" })
151151
})
152152

153-
test("Computer says when its image is out of date instead of asking to reconnect", async t => {
153+
test("Computer rebuilds an out-of-date computer by itself, but not under a running turn", async t => {
154154
const signed = member("outdated")
155-
let viewer: { status: number; body: unknown } = { status: 409, body: { error: "desktop_outdated" } }
155+
const connected = { state: "connected", url: "wss://viewer.example.test/vnc/synthetic", expiresAt: Date.now() + 60_000, paused: false }
156+
let current = false
157+
let stillOutdated = false
158+
let busy = false
159+
const rebuilds: unknown[] = []
156160
t.mock.method(globalThis, "fetch", async (url: string | URL | Request, init?: RequestInit) => {
157161
const parsed = new URL(url instanceof Request ? url.url : url)
158-
if (parsed.pathname.endsWith("/desktop/viewer")) return new Response(JSON.stringify(viewer.body), { status: viewer.status, headers: { "content-type": "application/json" } })
162+
if (parsed.pathname.endsWith("/desktop/viewer")) return current ? Response.json(connected) : Response.json({ error: "desktop_outdated" }, { status: 409 })
163+
if (parsed.pathname.endsWith("/desktop/action")) {
164+
rebuilds.push(typeof init?.body === "string" ? JSON.parse(init.body) : null)
165+
await new Promise(resolve => setTimeout(resolve, 20))
166+
current = !stillOutdated
167+
return Response.json({ ok: true })
168+
}
159169
if (init?.method === "PUT") return Response.json({ id: parsed.pathname.split("/").at(-1) })
160-
return Response.json({ turns: [], messages: [], finalAssistantText: "" })
170+
return Response.json({ turns: [], messages: [], finalAssistantText: "", ...(busy ? { status: "busy" } : {}) })
161171
})
162172
t.mock.method(console, "error", () => {})
163173
const app = new Hono<AppEnv>()
@@ -166,10 +176,40 @@ test("Computer says when its image is out of date instead of asking to reconnect
166176
member: async (c, next) => { c.set("member", signed); await next() }, sameOrigin: async (_c, next) => next(),
167177
})
168178
const open = () => app.request("/v1/workbot/computer/viewer", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ view: "browser" }) })
169-
const outdated = await open()
170-
assert.equal(outdated.status, 409)
171-
assert.deepEqual(await outdated.json(), { error: "desktop_outdated", message: "Your computer needs an update before it can connect. Rebuild it, or ask your workspace admin if that doesn't help." })
179+
// The Browser view and the chat's live glimpse open together: one rebuild, then both connect.
180+
const opened = await Promise.all([open(), open()])
181+
assert.deepEqual(opened.map(response => response.status), [200, 200])
182+
assert.deepEqual(await opened[0]!.json(), connected)
183+
assert.deepEqual(rebuilds, [{ action: "rebuild" }])
184+
// Rebuilding stops a running turn, so while one runs the person decides.
185+
current = false
186+
busy = true
187+
const waiting = await open()
188+
assert.equal(waiting.status, 409)
189+
assert.deepEqual(await waiting.json(), { error: "desktop_outdated", message: "Your computer needs an update before it can connect. Rebuild it, or ask your workspace admin if that doesn't help." })
190+
assert.equal(rebuilds.length, 1)
191+
// A fresh computer that is still out of date needs an operator, not another rebuild.
192+
busy = false
193+
stillOutdated = true
194+
assert.deepEqual(await (await open()).json(), { error: "desktop_outdated", message: "Your computer still needs an update after rebuilding. Ask your workspace admin for help." })
195+
assert.equal(rebuilds.length, 2)
196+
})
197+
198+
test("Computer asks to reconnect for other desktop failures", async t => {
199+
const signed = member("unresponsive")
200+
t.mock.method(globalThis, "fetch", async (url: string | URL | Request, init?: RequestInit) => {
201+
const parsed = new URL(url instanceof Request ? url.url : url)
202+
if (parsed.pathname.endsWith("/desktop/viewer")) return Response.json({ error: "desktop_unresponsive" }, { status: 409 })
203+
if (init?.method === "PUT") return Response.json({ id: parsed.pathname.split("/").at(-1) })
204+
return Response.json({ turns: [], messages: [], finalAssistantText: "" })
205+
})
206+
t.mock.method(console, "error", () => {})
207+
const app = new Hono<AppEnv>()
208+
registerWorkbotRoutes(app, {
209+
config, den: { ...createDen({ apiUrl: config.denApiUrl, publicUrl: config.publicUrl }), session: async () => signed.den },
210+
member: async (c, next) => { c.set("member", signed); await next() }, sameOrigin: async (_c, next) => next(),
211+
})
212+
const response = await app.request("/v1/workbot/computer/viewer", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ view: "browser" }) })
172213
// Other runner codes, including ones this Workbot doesn't know, keep the reconnect message.
173-
viewer = { status: 409, body: { error: "desktop_unresponsive" } }
174-
assert.deepEqual(await (await open()).json(), { error: "desktop_unavailable", message: "Your computer is unavailable. Try reconnecting." })
214+
assert.deepEqual(await response.json(), { error: "desktop_unavailable", message: "Your computer is unavailable. Try reconnecting." })
175215
})

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

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -227,12 +227,17 @@ export function registerWorkbotRoutes(app: Hono<AppEnv>, input: { config: Config
227227
})
228228
})
229229

230-
/** The runner's desktop codes in the person's words; anything else reads as a reconnectable outage. */
231-
const desktopFailure = (c: Context<AppEnv>, operation: string, code: string) => {
232-
console.error("[workbot] desktop unavailable", { operation, code })
233-
if (code === "desktop_outdated") return c.json({ error: code, message: "Your computer needs an update before it can connect. Rebuild it, or ask your workspace admin if that doesn't help." }, 409)
230+
/**
231+
* The runner's desktop codes in the person's words; anything else reads as a reconnectable outage. `rebuilt`: Workbot
232+
* already rebuilt the computer, so rebuilding again won't help.
233+
*/
234+
const desktopFailure = (c: Context<AppEnv>, operation: string, code: string, rebuilt = false) => {
235+
console.error("[workbot] desktop unavailable", { operation, code, rebuilt })
236+
if (code === "desktop_outdated") return c.json({ error: code, message: rebuilt ? "Your computer still needs an update after rebuilding. Ask your workspace admin for help." : "Your computer needs an update before it can connect. Rebuild it, or ask your workspace admin if that doesn't help." }, 409)
234237
return c.json({ error: "desktop_unavailable", message: "Your computer is unavailable. Try reconnecting." }, 409)
235238
}
239+
/** One automatic rebuild per computer at a time: the Browser view and the chat's live glimpse can both find it outdated. */
240+
const autoRebuilds = new Map<string, Promise<{ ok: boolean; error: string }>>()
236241

237242
// No sandbox ids or preview credentials are accepted from the page: the member determines the computer.
238243
app.post("/v1/workbot/computer/:operation", async (c) => {
@@ -265,7 +270,22 @@ export function registerWorkbotRoutes(app: Hono<AppEnv>, input: { config: Config
265270
const body = viewer
266271
if (!body.success) return c.json({ error: "invalid_request" }, 400)
267272
if (body.data.control) await workbot.stop(actorOf(member))
268-
const result = await client.desktopViewer(sessionId, { ...body.data, origin: new URL(config.publicUrl).origin })
273+
const open = () => client.desktopViewer(sessionId, { ...body.data, origin: new URL(config.publicUrl).origin })
274+
let result = await open()
275+
// An outdated computer never connects and rebuilding is the only fix, so do it now instead of asking. Not under
276+
// a running turn, though: rebuilding stops it, so that stays the person's Rebuild.
277+
if (!result.ok && result.error === "desktop_outdated" && (!existing.ok || existing.value.status !== "busy")) {
278+
let rebuilding = autoRebuilds.get(sessionId)
279+
if (!rebuilding) {
280+
console.error("[workbot] rebuilding an outdated computer")
281+
rebuilding = client.desktopAction(sessionId, "rebuild").finally(() => autoRebuilds.delete(sessionId))
282+
autoRebuilds.set(sessionId, rebuilding)
283+
}
284+
const rebuilt = await rebuilding
285+
if (!rebuilt.ok) return desktopFailure(c, operation, rebuilt.error)
286+
result = await open()
287+
if (!result.ok) return desktopFailure(c, operation, result.error, true)
288+
}
269289
if (!result.ok) return desktopFailure(c, operation, result.error)
270290
// A cold VM may take longer than the membership cache: verify again before sharing its stream.
271291
if (!await stillAllowed()) return c.json({ error: "feature_disabled" }, 403)

‎ee/packages/headless-computer/src/desktop-guest.mjs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,11 @@ server.on("upgrade", (request, socket, head) => {
116116
// Private stdio cannot be pre-bound by the command account. The VNC
117117
// process itself enforces view-only, independently of noVNC's controls.
118118
const viewer = spawn("/usr/bin/python3", ["-I", viewerScript, ticket.view, ticket.control ? "control" : "view"], { stdio: ["pipe", "pipe", "ignore"] });
119-
const transport = { destroy: () => { viewer.stdin.destroy(); viewer.stdout.destroy(); viewer.kill("SIGTERM"); } };
119+
const vnc = { destroy: () => { viewer.stdin.destroy(); viewer.stdout.destroy(); viewer.kill("SIGTERM"); } };
120120
sockets.add(ws);
121-
transports.set(ws, transport);
121+
transports.set(ws, vnc);
122122
const deadline = setTimeout(() => ws.close(1000, "Renew viewer access"), 60_000);
123-
const close = () => { clearTimeout(deadline); sockets.delete(ws); transports.delete(ws); transport.destroy(); ws.close(); };
123+
const close = () => { clearTimeout(deadline); sockets.delete(ws); transports.delete(ws); vnc.destroy(); ws.close(); };
124124
viewer.stdout.on("data", data => { if (ws.readyState === WebSocket.OPEN) ws.send(data, { binary: true }); });
125125
ws.on("message", (data, binary) => {
126126
if (!binary || Date.now() >= until || ticket.generation !== tickets.generation) return close();
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import assert from "node:assert/strict"
2+
import { spawn } from "node:child_process"
3+
import { once } from "node:events"
4+
import { mkdtemp, rm, writeFile } from "node:fs/promises"
5+
import { tmpdir } from "node:os"
6+
import { join } from "node:path"
7+
import { test } from "node:test"
8+
import { fileURLToPath } from "node:url"
9+
import { build } from "esbuild"
10+
import { WebSocket } from "ws"
11+
12+
/** The guest's server and tickets stay real; the desktop it drives is replaced by stand-ins. */
13+
const stubs: Record<string, string> = {
14+
"@openwork/computer-use/cloud": "export const createCloudComputer = async () => ({ snapshot: async () => ({ paused: false }), interact: async () => {}, close: async () => {} }); export const browserEgressStatus = async () => ({});",
15+
"@openwork/computer-use/browser-demonstration": "export const createBrowserDemonstration = () => ({ isTeaching: () => false });",
16+
"./desktop-apps.mjs": "export const createDesktopApplications = () => ({});",
17+
"./browser-screencast.mjs": "export const streamBrowser = (ws) => { ws.send('frame'); return () => {}; };",
18+
}
19+
20+
test("the desktop guest keeps serving after viewers open the page stream and VNC", async () => {
21+
const directory = await mkdtemp(join(tmpdir(), "desktop-guest-"))
22+
const outfile = join(directory, "guest.mjs")
23+
await build({
24+
entryPoints: [fileURLToPath(new URL("./desktop-guest.mjs", import.meta.url))], outfile, bundle: true, platform: "node", format: "esm", logLevel: "silent",
25+
banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },
26+
plugins: [{ name: "desktop-stubs", setup(plugin) {
27+
plugin.onResolve({ filter: /./ }, args => args.path in stubs ? { path: args.path, namespace: "desktop-stub" } : undefined)
28+
plugin.onLoad({ filter: /./, namespace: "desktop-stub" }, args => ({ contents: stubs[args.path], loader: "js" }))
29+
} }],
30+
})
31+
const secret = "test-bearer"
32+
await writeFile(join(directory, "token"), secret)
33+
const guest = spawn(process.execPath, [outfile], { env: { ...process.env, WORKBOT_DESKTOP_STATE: directory }, stdio: ["ignore", "ignore", "pipe"] })
34+
let errors = ""
35+
guest.stderr.on("data", chunk => { errors += chunk })
36+
const origin = "https://chat.example"
37+
const ticket = async () => {
38+
for (let attempt = 0; attempt < 100; attempt++) {
39+
const response = await fetch("http://127.0.0.1:6080/viewer", { method: "POST", headers: { authorization: `Bearer ${secret}` }, body: JSON.stringify({ view: "browser", origin }) }).catch(() => null)
40+
if (response?.ok) return (await response.json() as { token: string }).token
41+
await new Promise(resolve => setTimeout(resolve, 50))
42+
}
43+
throw new Error(`The guest never served a viewer ticket. ${errors}`)
44+
}
45+
try {
46+
const stream = new WebSocket(`ws://127.0.0.1:6080/screencast/${await ticket()}`, { origin })
47+
const frame = await new Promise((resolve, reject) => {
48+
stream.once("message", resolve)
49+
stream.once("close", () => reject(new Error(`The page stream closed before its first frame. ${errors}`)))
50+
})
51+
assert.equal(String(frame), "frame")
52+
stream.close()
53+
// No VNC helper exists here, so the guest closes this viewer itself; it must not take the guest down with it.
54+
const vnc = new WebSocket(`ws://127.0.0.1:6080/vnc/${await ticket()}`, { origin })
55+
await once(vnc, "open")
56+
await once(vnc, "close")
57+
assert.ok(await ticket(), "the guest still issues viewer tickets")
58+
assert.equal(guest.exitCode, null, errors)
59+
} finally {
60+
guest.kill()
61+
await rm(directory, { recursive: true, force: true })
62+
}
63+
})

0 commit comments

Comments
 (0)