The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode. |
| 2 | // The engines run in a worker per open file, so no layout, recalculation or painting holds the window. These are the |
| 3 | // two ends of that worker's protocol: typed calls by method name, a key that lets a newer call replace a queued one |
| 4 | // (as the markdown worker's queue does), transferable payloads, and a worker that fails every pending call when it dies. |
| 5 | |
| 6 | import * as Schema from "effect/Schema"; |
| 7 | import { isPreviewError, PreviewError, type PreviewFailure } from "../previewFailure"; |
| 8 | |
| 9 | /** What one method takes and returns. */ |
| 10 | export type Method<Input, Output> = { readonly input: Input; readonly output: Output }; |
| 11 | |
| 12 | /** A worker's methods by name. */ |
| 13 | export type Methods = { readonly [name: string]: Method<unknown, unknown> }; |
| 14 | |
| 15 | type Request = { |
| 16 | readonly id: number; |
| 17 | readonly method: string; |
| 18 | readonly key?: string | undefined; |
| 19 | readonly input: unknown; |
| 20 | }; |
| 21 | |
| 22 | /** Withdraws a call whose caller aborted it. */ |
| 23 | type Cancel = { readonly cancel: number }; |
| 24 | |
| 25 | type Response = |
| 26 | /** `transferred` lists the objects the reply moved, so a reply nobody waits for can close its bitmaps. */ |
| 27 | | { |
| 28 | readonly id: number; |
| 29 | readonly ok: true; |
| 30 | readonly value: unknown; |
| 31 | readonly transferred: readonly Transferable[]; |
| 32 | } |
| 33 | | ({ |
| 34 | readonly id: number; |
| 35 | readonly ok: false; |
| 36 | readonly superseded: boolean; |
| 37 | } & PreviewFailure); |
| 38 | |
| 39 | /** A value a method returns with the buffers to move to the caller rather than copy. */ |
| 40 | export class Transfer<T> { |
| 41 | constructor( |
| 42 | readonly value: T, |
| 43 | readonly transfer: readonly Transferable[], |
| 44 | ) {} |
| 45 | } |
| 46 | |
| 47 | /** A call that a newer call with the same key replaced before it ran. */ |
| 48 | export class SupersededError extends Schema.TaggedError<SupersededError>()("SupersededError", { |
| 49 | message: Schema.String, |
| 50 | }) {} |
| 51 | |
| 52 | /** A call made after the worker failed or was closed, or pending when that happened. */ |
| 53 | class WorkerClosedError extends Schema.TaggedError<WorkerClosedError>()("WorkerClosedError", { |
| 54 | message: Schema.String, |
| 55 | }) {} |
| 56 | |
| 57 | type CallOptions = { |
| 58 | /** A newer call with the same key replaces this one while it waits to run. */ |
| 59 | readonly key?: string; |
| 60 | /** Buffers to move to the worker rather than copy, such as the file's bytes or a transferred canvas. */ |
| 61 | readonly transfer?: readonly Transferable[]; |
| 62 | /** Drops the reply and a call still queued; a call that has started sees its handler's signal abort. */ |
| 63 | readonly signal?: AbortSignal; |
| 64 | }; |
| 65 | |
| 66 | /** A call waiting for its reply. */ |
| 67 | type Pending = { |
| 68 | readonly settle: (response: Response) => void; |
| 69 | readonly reject: (error: Error) => void; |
| 70 | }; |
| 71 | |
| 72 | /** The next call id, and why the worker stopped answering once it has. */ |
| 73 | type ClientState = { next: number; failure: Error | undefined }; |
| 74 | |
| 75 | /** The window's end: starts the worker and calls its methods. */ |
| 76 | export function createWorkerClient<M extends Methods>(worker: Worker) { |
| 77 | const pending = new Map<number, Pending>(); |
| 78 | const state: ClientState = { next: 0, failure: undefined }; |
| 79 | |
| 80 | const fail = (error: Error) => { |
| 81 | state.failure ??= error; |
| 82 | pending.forEach((call) => call.reject(error)); |
| 83 | pending.clear(); |
| 84 | worker.terminate(); |
| 85 | }; |
| 86 | |
| 87 | worker.addEventListener("message", (event: MessageEvent<Response>) => { |
| 88 | const call = pending.get(event.data.id); |
| 89 | |
| 90 | // A reply that crossed its call's cancel on the way: its bitmaps would hold their memory until collected. |
| 91 | if (!call) { |
| 92 | if (event.data.ok) closeBitmaps(event.data.transferred); |
| 93 | |
| 94 | return; |
| 95 | } |
| 96 | |
| 97 | pending.delete(event.data.id); |
| 98 | call.settle(event.data); |
| 99 | }); |
| 100 | |
| 101 | worker.addEventListener("error", (event) => |
| 102 | fail( |
| 103 | event.message |
| 104 | ? new WorkerClosedError({ message: event.message }) |
| 105 | : new PreviewError({ code: "office-engine-stopped" }), |
| 106 | ), |
| 107 | ); |
| 108 | worker.addEventListener("messageerror", () => |
| 109 | fail(new PreviewError({ code: "office-engine-unreadable" })), |
| 110 | ); |
| 111 | |
| 112 | return { |
| 113 | call<K extends keyof M & string>( |
| 114 | method: K, |
| 115 | input: M[K]["input"], |
| 116 | options: CallOptions = {}, |
| 117 | ): Promise<M[K]["output"]> { |
| 118 | if (state.failure) return Promise.reject(state.failure); |
| 119 | |
| 120 | if (options.signal?.aborted) |
| 121 | return Promise.reject(new WorkerClosedError({ message: "The call was aborted" })); |
| 122 | |
| 123 | const id = ++state.next; |
| 124 | |
| 125 | return new Promise<M[K]["output"]>((resolve, reject) => { |
| 126 | const timeout = setTimeout( |
| 127 | () => fail(new PreviewError({ code: "office-timeout" })), |
| 128 | 30_000, |
| 129 | ); |
| 130 | const abort = () => { |
| 131 | clearTimeout(timeout); |
| 132 | pending.delete(id); |
| 133 | reject(new WorkerClosedError({ message: "The call was aborted" })); |
| 134 | worker.postMessage({ cancel: id } satisfies Cancel, []); |
| 135 | }; |
| 136 | |
| 137 | options.signal?.addEventListener("abort", abort, { once: true }); |
| 138 | pending.set(id, { |
| 139 | settle: (response) => { |
| 140 | clearTimeout(timeout); |
| 141 | options.signal?.removeEventListener("abort", abort); |
| 142 | |
| 143 | if (!response.ok) |
| 144 | return reject( |
| 145 | response.superseded |
| 146 | ? new SupersededError({ message: response.message }) |
| 147 | : response.code |
| 148 | ? new PreviewError({ code: response.code }) |
| 149 | : new Error(response.message), |
| 150 | ); |
| 151 | |
| 152 | // SAFETY: the worker answers each id with the output of the method that id called (see `serveWorker`). |
| 153 | resolve(response.value as M[K]["output"]); |
| 154 | }, |
| 155 | reject: (error) => { |
| 156 | clearTimeout(timeout); |
| 157 | options.signal?.removeEventListener("abort", abort); |
| 158 | reject(error); |
| 159 | }, |
| 160 | }); |
| 161 | worker.postMessage({ id, method, key: options.key, input } satisfies Request, [ |
| 162 | ...(options.transfer ?? []), |
| 163 | ]); |
| 164 | }); |
| 165 | }, |
| 166 | /** Stops the worker, which frees its engine's memory, and fails every pending call. */ |
| 167 | close() { |
| 168 | fail(new WorkerClosedError({ message: "The Office engine was closed" })); |
| 169 | }, |
| 170 | }; |
| 171 | } |
| 172 | |
| 173 | /** Whether a call runs, and which call it is, so its caller can abort it. */ |
| 174 | type ServerState = { |
| 175 | running: boolean; |
| 176 | current: { readonly id: number; readonly controller: AbortController } | undefined; |
| 177 | }; |
| 178 | |
| 179 | /** |
| 180 | * The worker's end: runs calls one at a time, in order, letting messages through between them. A handler's signal |
| 181 | * aborts when its caller aborts the call. |
| 182 | */ |
| 183 | export function serveWorker<M extends Methods>(handlers: { |
| 184 | readonly [K in keyof M]: ( |
| 185 | input: M[K]["input"], |
| 186 | signal: AbortSignal, |
| 187 | ) => |
| 188 | | M[K]["output"] |
| 189 | | Transfer<M[K]["output"]> |
| 190 | | Promise<M[K]["output"] | Transfer<M[K]["output"]>>; |
| 191 | }) { |
| 192 | const queue: Request[] = []; |
| 193 | |
| 194 | const state: ServerState = { running: false, current: undefined }; |
| 195 | |
| 196 | const reply = (response: Response, transfer: readonly Transferable[] = []) => |
| 197 | self.postMessage(response, { transfer: [...transfer] }); |
| 198 | |
| 199 | const run = async () => { |
| 200 | if (state.running) return; |
| 201 | |
| 202 | state.running = true; |
| 203 | |
| 204 | // Each call returns to the event loop before it leaves the queue, so calls that arrived meanwhile can replace it. |
| 205 | while (queue.length > 0) { |
| 206 | await new Promise((resolve) => setTimeout(resolve)); |
| 207 | |
| 208 | const request = queue.shift(); |
| 209 | |
| 210 | if (!request) break; |
| 211 | |
| 212 | const handler = handlers[request.method]; |
| 213 | const controller = new AbortController(); |
| 214 | |
| 215 | state.current = { id: request.id, controller }; |
| 216 | |
| 217 | if (!handler) { |
| 218 | reply({ |
| 219 | id: request.id, |
| 220 | ok: false, |
| 221 | superseded: false, |
| 222 | // oxlint-disable-next-line t3code/no-untranslated-copy -- internal worker RPC error, never shown |
| 223 | message: `Unknown method ${request.method}`, |
| 224 | }); |
| 225 | continue; |
| 226 | } |
| 227 | |
| 228 | // SAFETY: the client sends each method the input its `Methods` entry declares (see `createWorkerClient`). |
| 229 | const input = request.input as never; |
| 230 | |
| 231 | await Promise.resolve() |
| 232 | .then(() => handler(input, controller.signal)) |
| 233 | .then( |
| 234 | (result) => { |
| 235 | const transfer = result instanceof Transfer ? result.transfer : []; |
| 236 | |
| 237 | // The caller already settled a call it aborted, so nothing would take the reply or its bitmaps. |
| 238 | if (controller.signal.aborted) return closeBitmaps(transfer); |
| 239 | |
| 240 | reply( |
| 241 | { |
| 242 | id: request.id, |
| 243 | ok: true, |
| 244 | value: result instanceof Transfer ? result.value : result, |
| 245 | transferred: transfer, |
| 246 | }, |
| 247 | transfer, |
| 248 | ); |
| 249 | }, |
| 250 | (cause: unknown) => { |
| 251 | if (controller.signal.aborted) return; |
| 252 | |
| 253 | reply({ |
| 254 | id: request.id, |
| 255 | ok: false, |
| 256 | superseded: false, |
| 257 | ...(isPreviewError(cause) |
| 258 | ? { code: cause.code, message: cause.code } |
| 259 | : { message: cause instanceof Error ? cause.message : String(cause) }), |
| 260 | }); |
| 261 | }, |
| 262 | ); |
| 263 | } |
| 264 | |
| 265 | state.running = false; |
| 266 | state.current = undefined; |
| 267 | }; |
| 268 | |
| 269 | self.addEventListener("message", (event: MessageEvent<Request | Cancel>) => { |
| 270 | // The caller already settled a cancelled call, so it gets no reply. |
| 271 | if ("cancel" in event.data) { |
| 272 | const id = event.data.cancel; |
| 273 | const queued = queue.findIndex((request) => request.id === id); |
| 274 | |
| 275 | if (queued !== -1) queue.splice(queued, 1); |
| 276 | |
| 277 | if (state.current?.id === id) state.current.controller.abort(); |
| 278 | |
| 279 | return; |
| 280 | } |
| 281 | |
| 282 | const key = event.data.key; |
| 283 | const replaced = key === undefined ? -1 : queue.findIndex((request) => request.key === key); |
| 284 | |
| 285 | if (replaced !== -1) { |
| 286 | const [old] = queue.splice(replaced, 1); |
| 287 | |
| 288 | if (old) |
| 289 | // oxlint-disable-next-line t3code/no-untranslated-copy -- superseded calls are dropped, never shown |
| 290 | reply({ id: old.id, ok: false, superseded: true, message: "Replaced by a newer call" }); |
| 291 | } |
| 292 | |
| 293 | queue.push(event.data); |
| 294 | void run(); |
| 295 | }); |
| 296 | } |
| 297 | |
| 298 | /** Frees the bitmaps among objects that were moved for a reply nobody takes. */ |
| 299 | function closeBitmaps(transfer: readonly Transferable[]) { |
| 300 | transfer.forEach((item) => { |
| 301 | if (item instanceof ImageBitmap) item.close(); |
| 302 | }); |
| 303 | } |