Skip to content

Commit f8690ae

Browse files
authored
fix(workbot): resume a paused computer on open and log where its start time goes (#6557)
Opening the full Browser or Computer view of a paused computer now resumes it instead of showing a Resume button, since Freestyle restores a paused VM from memory. The chat's live glimpse still leaves it paused. The runner logs one "desktop timing" line per viewer request, desktop action, and tool call that had to wake or start the desktop, with the VM's prior state and the time spent in each step (VM lookup, start, create, health checks, desktop start, viewer, endpoint). Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent b5c965a commit f8690ae

6 files changed

Lines changed: 199 additions & 16 deletions

File tree

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,3 +228,37 @@ test("Computer asks to reconnect for other desktop failures", async t => {
228228
// Other runner codes, including ones this Workbot doesn't know, keep the reconnect message.
229229
assert.deepEqual(await response.json(), { error: "desktop_unavailable", message: "Your computer is unavailable. Try reconnecting." })
230230
})
231+
232+
test("Opening the full view resumes a paused computer, but the chat's glimpse leaves it paused", async t => {
233+
const signed = member("paused")
234+
const connected = { state: "connected", url: "wss://viewer.example.test/vnc/synthetic", expiresAt: Date.now() + 60_000, paused: false }
235+
let paused = true
236+
const viewers: unknown[] = []
237+
const actions: string[] = []
238+
t.mock.method(globalThis, "fetch", async (url: string | URL | Request, init?: RequestInit) => {
239+
const parsed = new URL(url instanceof Request ? url.url : url)
240+
if (parsed.pathname.endsWith("/desktop/viewer")) {
241+
viewers.push(JSON.parse(String(init?.body)))
242+
return Response.json(paused ? { state: "paused" } : connected)
243+
}
244+
if (parsed.pathname.endsWith("/desktop/action")) {
245+
actions.push((JSON.parse(String(init?.body)) as { action: string }).action)
246+
paused = false
247+
return Response.json({ ok: true })
248+
}
249+
if (init?.method === "PUT") return Response.json({ id: parsed.pathname.split("/").at(-1) })
250+
return Response.json({ turns: [], messages: [], finalAssistantText: "" })
251+
})
252+
const app = new Hono<AppEnv>()
253+
registerWorkbotRoutes(app, {
254+
config, den: { ...createDen({ apiUrl: config.denApiUrl, publicUrl: config.publicUrl }), session: async () => signed.den },
255+
member: async (c, next) => { c.set("member", signed); await next() }, sameOrigin: async (_c, next) => next(),
256+
})
257+
const open = (body: unknown) => app.request("/v1/workbot/computer/viewer", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })
258+
assert.deepEqual(await (await open({ view: "browser" })).json(), { state: "paused" })
259+
assert.deepEqual(actions, [])
260+
assert.deepEqual(await (await open({ view: "browser", wake: true })).json(), connected)
261+
assert.deepEqual(actions, ["resume"])
262+
// The runner gets the view it always did; waking is Workbot's step.
263+
assert.deepEqual(viewers.at(-1), { view: "browser", control: false, origin: "http://localhost:3020" })
264+
})

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

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ export function registerWorkbotRoutes(app: Hono<AppEnv>, input: { config: Config
248248
const operation = c.req.param("operation")
249249
if (operation !== "viewer" && operation !== "action") return c.json({ error: "not_found" }, 404)
250250
const raw: unknown = await c.req.json().catch(() => null)
251-
const viewer = z.object({ view: z.enum(["browser", "computer"]), control: z.boolean().default(false) }).strict().safeParse(raw)
251+
const viewer = z.object({ view: z.enum(["browser", "computer"]), control: z.boolean().default(false), wake: z.boolean().default(false) }).strict().safeParse(raw)
252252
const action = z.object({ action: z.enum(["continue", "pause", "resume", "rebuild"]) }).strict().safeParse(raw)
253253
if (operation === "viewer" ? !viewer.success : !action.success) return c.json({ error: "invalid_request" }, 400)
254254
const workbot = workbotFor(member)
@@ -282,9 +282,18 @@ export function registerWorkbotRoutes(app: Hono<AppEnv>, input: { config: Config
282282
if (operation === "viewer") {
283283
const body = viewer
284284
if (!body.success) return c.json({ error: "invalid_request" }, 400)
285-
if (body.data.control) await workbot.stop(actorOf(member))
286-
const open = () => client.desktopViewer(sessionId, { ...body.data, origin: new URL(config.publicUrl).origin })
285+
const { wake, ...view } = body.data
286+
if (view.control) await workbot.stop(actorOf(member))
287+
const open = () => client.desktopViewer(sessionId, { ...view, origin: new URL(config.publicUrl).origin })
287288
let result = await open()
289+
// Opening the full view of a paused computer resumes it: Freestyle restores its memory in about a second, so
290+
// asking the person to press Resume only adds a round trip. The chat's live glimpse never wakes it.
291+
if (wake && result.ok && result.value.state === "paused") {
292+
let resumed = await client.desktopAction(sessionId, "resume")
293+
if (!resumed.ok && resumed.error === "desktop_outdated" && canRebuild) resumed = await rebuildOutdated()
294+
if (!resumed.ok) return desktopFailure(c, operation, resumed.error)
295+
result = await open()
296+
}
288297
if (!result.ok && result.error === "desktop_outdated" && canRebuild) {
289298
const rebuilt = await rebuildOutdated()
290299
if (!rebuilt.ok) return desktopFailure(c, operation, rebuilt.error, true)

‎ee/packages/headless-computer/src/computer.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,36 @@ test("rebuilding replaces the conversation's VM and starts the desktop on the ne
9797
await computers.delete("rebuild")
9898
})
9999

100+
test("opening and resuming a desktop log one line with where the time went", async t => {
101+
let desktopUp = false
102+
const provider = createFakeProvider({ capabilities: { platform: { os: "linux", isolation: "microvm" } }, onRun(spec) {
103+
if (/ start [a-f0-9]{64}$/.test(spec.command)) desktopUp = true
104+
if (spec.command.includes("call '/health'")) return desktopUp ? { exitCode: 0, stdout: JSON.stringify({ version: "running" }), stderr: "" } : { exitCode: 1, stdout: "", stderr: "" }
105+
return { exitCode: 0, stdout: "0", stderr: "" }
106+
} })
107+
const lines: string[] = []
108+
t.mock.method(console, "log", (line: string) => { lines.push(line) })
109+
const computers = new Computers({ provider, idlePauseMs: 1000, keepDays: 1, desktop: true }, { readFile: async () => ({ text: "" }) })
110+
t.after(() => computers.delete("timed"))
111+
await provider.stop(await computers.vm("timed"), { timeoutMs: 1000 })
112+
const timings = () => lines.filter(line => line.startsWith("[headless-computer] desktop timing ")).map(line => JSON.parse(line.slice(35)) as { sessionId: string; operation: string; outcome: string; totalMs: number; before: string | null; steps: Record<string, { ms: number; count: number }> })
113+
114+
assert.deepEqual(await computers.desktopViewer("timed", { view: "browser", control: false, origin: "https://chat.example.test" }), { state: "paused" })
115+
assert.deepEqual(await computers.desktopAction("timed", "resume"), { ok: true })
116+
const [viewer, resume] = timings()
117+
assert.deepEqual([viewer?.operation, viewer?.outcome, viewer?.before], ["viewer", "paused", "stopped"])
118+
assert.deepEqual([resume?.sessionId, resume?.operation, resume?.outcome, resume?.before], ["timed", "resume", "ok", "stopped"])
119+
// The paused VM is woken, the desktop is found down, started, and polled until it answers.
120+
assert.deepEqual(Object.keys(resume?.steps ?? {}).sort(), ["desktop_start", "health", "vm_lookup", "vm_start"])
121+
assert.equal(resume?.steps.vm_start?.count, 1)
122+
assert.equal(resume?.steps.health?.count, 2)
123+
124+
// A tool call that finds the desktop ready stays out of the log.
125+
Object.assign(computers as unknown as Record<string, unknown>, { desktop: { start: async () => {}, call: async () => ({ ok: true }) } })
126+
await computers.desktopRun("timed", { view: "browser", operation: "open", args: {} })
127+
assert.equal(timings().length, 2)
128+
})
129+
100130
test("a new command waits for a pending idle pause and resumes before running", { timeout: 2000 }, async t => {
101131
let release = () => {}
102132
const gate = new Promise<void>(resolve => { release = resolve })

‎ee/packages/headless-computer/src/computer.ts‎

Lines changed: 49 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { ComputerFile, ComputerFiles, FileReader, ToolResult, ToolSpec } fr
66
import { demonstrationReplySchema, type DemonstrationCommand } from "@openwork/types/browser-demonstration"
77
import { Desktop, type DesktopView } from "./desktop.js"
88
import { DESKTOP_TOOL } from "./desktop-tool.js"
9+
import { DesktopTiming, timedProvider } from "./desktop-timing.js"
910

1011
/** One provider-neutral Linux computer per conversation. Jobs own idle policy and files; adapters own transport. */
1112
export type ComputerOptions = {
@@ -54,6 +55,8 @@ export class Computers {
5455
private readonly pausing = new Map<string, Promise<void>>()
5556
/** Saved file ids already copied into each session's VM by this process. */
5657
private readonly copied = new Map<string, Set<string>>()
58+
/** The desktop request being timed for each VM, by its slug. */
59+
private readonly timings = new Map<string, DesktopTiming>()
5760

5861
private readonly snapshot: string
5962
private readonly files?: ComputerFiles
@@ -71,7 +74,7 @@ export class Computers {
7174
* `readFile` turns a file into what the model can see (images, PDFs, text), the same way tool results are read.
7275
*/
7376
constructor(private readonly options: ComputerOptions, deps: { files?: ComputerFiles; readFile: FileReader }) {
74-
this.provider = options.provider
77+
this.provider = timedProvider(options.provider, key => this.timings.get(key))
7578
this.blocks = computerBlocks(this.provider)
7679
this.snapshot = this.provider.currentImage()?.id ?? "configured image"
7780
this.files = deps.files
@@ -86,14 +89,17 @@ export class Computers {
8689
const desktop = this.desktop
8790
if (!desktop) throw new Error("Desktop access is not configured.")
8891
signal?.throwIfAborted()
89-
const box = await this.vm(sessionId)
92+
const timing = this.track(sessionId, "tool")
93+
const box = await this.vm(sessionId).catch((error: unknown) => { this.finish(timing, "failed"); throw error })
9094
let stopping: Promise<unknown> | undefined
9195
const stop = () => {
9296
stopping ??= desktop.call(box, "/stop", {})
9397
void stopping.catch(() => {})
9498
}
9599
try {
96-
await desktop.start(box)
100+
await desktop.start(box).catch((error: unknown) => { this.finish(timing, "failed"); throw error })
101+
// A tool call that found the desktop ready is not worth a log line; one that woke or started it is.
102+
this.finish(timing, "ok", !timing.prepared)
97103
signal?.addEventListener("abort", stop, { once: true })
98104
if (signal?.aborted) { stop(); signal.throwIfAborted() }
99105
const program = parsed.operation === "computer_run"
@@ -118,12 +124,22 @@ export class Computers {
118124

119125
async desktopViewer(sessionId: string, input: { view: DesktopView; control: boolean; origin: string }) {
120126
if (!this.desktop) throw new Error("Desktop access is not configured.")
121-
const pending = this.vms.get(sessionId)
122-
const existing = pending ? await this.provider.inspect(await pending) : await this.provider.find({ idempotencyKey: this.slug(sessionId), labels: this.spec(sessionId).labels })
123-
if (existing?.state === "stopped" || existing?.state === "stopping") return { state: "paused" as const }
124-
const box = await this.vm(sessionId)
125-
try { return { state: "connected" as const, ...await this.desktop.viewer(box, input) } }
126-
finally { this.release(sessionId) }
127+
const timing = this.track(sessionId, "viewer")
128+
let outcome = "failed"
129+
try {
130+
const pending = this.vms.get(sessionId)
131+
const existing = pending ? await this.provider.inspect(await pending) : await this.provider.find({ idempotencyKey: this.slug(sessionId), labels: this.spec(sessionId).labels })
132+
if (existing?.state === "stopped" || existing?.state === "stopping") {
133+
outcome = "paused"
134+
return { state: "paused" as const }
135+
}
136+
const box = await this.vm(sessionId)
137+
try {
138+
const viewer = { state: "connected" as const, ...await this.desktop.viewer(box, input) }
139+
outcome = "ok"
140+
return viewer
141+
} finally { this.release(sessionId) }
142+
} finally { this.finish(timing, outcome) }
127143
}
128144

129145
async browserDemonstration(sessionId: string, command: DemonstrationCommand) {
@@ -141,6 +157,16 @@ export class Computers {
141157
}
142158

143159
async desktopAction(sessionId: string, action: "continue" | "pause" | "resume" | "rebuild") {
160+
const timing = this.track(sessionId, action)
161+
let outcome = "failed"
162+
try {
163+
const result = await this.changeDesktop(sessionId, action)
164+
outcome = "ok"
165+
return result
166+
} finally { this.finish(timing, outcome) }
167+
}
168+
169+
private async changeDesktop(sessionId: string, action: "continue" | "pause" | "resume" | "rebuild") {
144170
if (!this.desktop) throw new Error("Desktop access is not configured.")
145171
if (action === "rebuild") {
146172
// A fresh VM from the configured snapshot, without waking the old one first. Kept Files survive; the VM's own disk does not.
@@ -284,6 +310,20 @@ export class Computers {
284310
this.pauseTimers.delete(sessionId)
285311
}
286312

313+
/** Times one desktop request; the first one open for a VM gets its steps, a concurrent one only its total. */
314+
private track(sessionId: string, operation: string) {
315+
const timing = new DesktopTiming(sessionId, operation)
316+
const slug = this.slug(sessionId)
317+
if (!this.timings.has(slug)) this.timings.set(slug, timing)
318+
return timing
319+
}
320+
321+
private finish(timing: DesktopTiming, outcome: string, quiet = false) {
322+
const slug = this.slug(timing.sessionId)
323+
if (this.timings.get(slug) === timing) this.timings.delete(slug)
324+
if (!quiet) timing.log(outcome)
325+
}
326+
287327
/** Deletes the conversation's VM, if it has one. */
288328
async delete(sessionId: string) {
289329
this.cancelPause(sessionId)
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import type { RunSpec, SandboxHandle, SandboxProvider } from "@openwork/sandbox"
2+
3+
type Step = { ms: number; count: number }
4+
5+
/** What one bridge command asked the guest, from its command line; never the command or its payload. */
6+
function bridgeStep(command: string) {
7+
if (/openwork-desktop-bridge start /.test(command)) return "desktop_start"
8+
const path = /openwork-desktop-bridge call '?\/([a-z/]+)/.exec(command)?.[1]
9+
return path ? path.replaceAll("/", "_") : "command"
10+
}
11+
12+
/**
13+
* The steps of one desktop request (opening the view, resuming, a tool's first desktop use), written to the runner
14+
* log as one line when it ends, so a slow computer shows where the time went. Only step names, counts and durations.
15+
*/
16+
export class DesktopTiming {
17+
private readonly started = performance.now()
18+
private readonly steps: Record<string, Step> = {}
19+
/** The VM's state when the request first looked it up: `stopped` is paused, `missing` means a new computer. */
20+
before?: string
21+
22+
constructor(readonly sessionId: string, readonly operation: string) {}
23+
24+
add(name: string, ms: number) {
25+
const step = this.steps[name] ??= { ms: 0, count: 0 }
26+
step.ms += ms
27+
step.count++
28+
}
29+
30+
/** Whether the request woke, created or started anything, rather than finding the desktop ready. */
31+
get prepared() {
32+
return ["vm_start", "vm_create", "desktop_start"].some(name => name in this.steps)
33+
}
34+
35+
log(outcome: string) {
36+
const steps = Object.fromEntries(Object.entries(this.steps).map(([name, step]) => [name, { ms: Math.round(step.ms), count: step.count }]))
37+
console.log(`[headless-computer] desktop timing ${JSON.stringify({ sessionId: this.sessionId, operation: this.operation, outcome, totalMs: Math.round(performance.now() - this.started), before: this.before ?? null, steps })}`)
38+
}
39+
}
40+
41+
/**
42+
* The provider with each VM call and bridge command added to the timing open for that VM, found by the VM's slug
43+
* (every provider names its handles by it). Calls with no open timing pass straight through.
44+
*/
45+
export function timedProvider(provider: SandboxProvider, timingFor: (key: string) => DesktopTiming | undefined): SandboxProvider {
46+
const keyOf = (handle: SandboxHandle) => timingFor(handle.name ?? "")
47+
async function timed<T>(timing: DesktopTiming | undefined, name: string, fn: () => Promise<T>): Promise<T> {
48+
if (!timing) return fn()
49+
const started = performance.now()
50+
try { return await fn() }
51+
finally { timing.add(name, performance.now() - started) }
52+
}
53+
const seen = <T extends SandboxHandle | null>(timing: DesktopTiming | undefined, handle: T) => {
54+
if (timing) timing.before ??= handle?.state ?? "missing"
55+
return handle
56+
}
57+
const blocks = provider.blocks
58+
const run = blocks?.run
59+
return {
60+
...provider,
61+
describe: () => provider.describe(),
62+
currentImage: () => provider.currentImage(),
63+
find: async query => { const timing = timingFor(query.idempotencyKey ?? ""); return seen(timing, await timed(timing, "vm_lookup", () => provider.find(query))) },
64+
inspect: async handle => { const timing = keyOf(handle); return seen(timing, await timed(timing, "vm_lookup", () => provider.inspect(handle))) },
65+
create: (spec, opts) => timed(timingFor(spec.idempotencyKey), "vm_create", () => provider.create(spec, opts)),
66+
start: (handle, opts) => timed(keyOf(handle), "vm_start", () => provider.start(handle, opts)),
67+
endpoint: (handle, port, opts) => timed(keyOf(handle), "endpoint", () => provider.endpoint(handle, port, opts)),
68+
...(blocks ? { blocks: { ...blocks, ...(run ? { run: (handle: SandboxHandle, spec: RunSpec) => timed(keyOf(handle), bridgeStep(spec.command), () => run(handle, spec)) } : {}) } } : {}),
69+
}
70+
}

‎ee/packages/workbot-ui/src/computer.tsx‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ export function WorkbotComputer({ onTeachingChange, onRun, canTeach = true, page
7474
// Nobody watching a hidden tab, so stop streaming until it is shown again.
7575
if (!target || paused || away) return;
7676
setError(null); setConnected(false); setReconnecting(false); setLivePage(null);
77-
return connectDesktopViewer(target, host, { view, control, screencast: host.browserLiveView === true }, {
77+
return connectDesktopViewer(target, host, { view, control, wake: true, screencast: host.browserLiveView === true }, {
7878
paused: () => setPaused(true),
7979
agentPaused: setAgentPaused,
8080
connected: () => { setConnected(true); setReconnecting(false); setError(null); },
@@ -148,9 +148,9 @@ type ViewerEvents = {
148148
* Streams one view of the member's computer into `target`, renewing the connection before the computer closes it and
149149
* reconnecting a few times when it drops. Returns the function that closes it. With `screencast`, watching the browser
150150
* uses the computer's page stream; a computer whose image predates it refuses the stream, and the view falls back to
151-
* noVNC.
151+
* noVNC. With `wake`, a paused computer is resumed instead of reported as paused.
152152
*/
153-
export function connectDesktopViewer(target: HTMLElement, host: ReturnType<typeof workbotHost>, options: { view: ComputerView; control: boolean; screencast?: boolean }, events: ViewerEvents) {
153+
export function connectDesktopViewer(target: HTMLElement, host: ReturnType<typeof workbotHost>, options: { view: ComputerView; control: boolean; wake?: boolean; screencast?: boolean }, events: ViewerEvents) {
154154
const { view, control } = options;
155155
let disposed = false;
156156
let screencastRefused = false;
@@ -170,7 +170,7 @@ export function connectDesktopViewer(target: HTMLElement, host: ReturnType<typeo
170170
const timeout = setTimeout(abort, 195_000);
171171
try {
172172
const { response, payload } = await host.requestJson("/v1/workbot/computer/viewer", {
173-
method: "POST", body: JSON.stringify({ view, control }), signal: request.signal,
173+
method: "POST", body: JSON.stringify({ view, control, ...(options.wake ? { wake: true } : {}) }), signal: request.signal,
174174
}, 195_000);
175175
if (disposed) return;
176176
if (!response.ok) {

0 commit comments

Comments
 (0)