From b6a5a10044cc8ad339eb3853339fbf1c735f9396 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Thu, 5 Nov 2026 01:18:31 -0600 Subject: [PATCH] fix(app): keep the Office worker queue moving and bound What's New (#62000) --- .../src/microsoft-office/office-worker.ts | 9 +- .../worker-rpc-machine.test.ts | 340 ++++++++++++++++++ .../microsoft-office/worker-rpc-machine.ts | 336 +++++++++++++++++ .../src/microsoft-office/worker-rpc.test.ts | 19 +- .../src/microsoft-office/worker-rpc.ts | 326 +++++++++-------- .../gui-plugins/src/updater/beta-dialog.tsx | 49 ++- packages/gui-plugins/src/updater/renderer.tsx | 119 ++++-- .../src/updater/whats-new-machine.test.ts | 134 +++++++ .../src/updater/whats-new-machine.ts | 117 ++++++ .../gui-plugins/src/updater/whats-new.tsx | 53 +-- 10 files changed, 1263 insertions(+), 239 deletions(-) create mode 100644 packages/gui-plugins/src/microsoft-office/worker-rpc-machine.test.ts create mode 100644 packages/gui-plugins/src/microsoft-office/worker-rpc-machine.ts create mode 100644 packages/gui-plugins/src/updater/whats-new-machine.test.ts create mode 100644 packages/gui-plugins/src/updater/whats-new-machine.ts diff --git a/packages/gui-plugins/src/microsoft-office/office-worker.ts b/packages/gui-plugins/src/microsoft-office/office-worker.ts index c867be2ecad..b3259764603 100644 --- a/packages/gui-plugins/src/microsoft-office/office-worker.ts +++ b/packages/gui-plugins/src/microsoft-office/office-worker.ts @@ -79,11 +79,8 @@ export function createOfficeWorker(options: { const start = (attempt: number, bytes: Uint8Array, timeoutMs: number) => { const controller = new AbortController() const worker = options.createWorker() - const client = createWorkerClient(worker) - const crashed = () => dispatch({ type: "worker.crashed", attempt }) + const client = createWorkerClient(worker, { onCrash: () => dispatch({ type: "worker.crashed", attempt }) }) - worker.addEventListener("error", crashed) - worker.addEventListener("messageerror", crashed) runs.set(attempt, { controller, close: () => client.close(), @@ -109,8 +106,10 @@ export function createOfficeWorker(options: { runs.delete(attempt) clearTimeout(entry.timer) - entry.controller.abort() + // Closing first rejects the pending calls and detaches their abort listeners, so the abort posts no cancel to the + // terminated worker. entry.close() + entry.controller.abort() } createKeyed(options.bytes, (bytes) => dispatch({ type: "bytes.changed", bytes })) diff --git a/packages/gui-plugins/src/microsoft-office/worker-rpc-machine.test.ts b/packages/gui-plugins/src/microsoft-office/worker-rpc-machine.test.ts new file mode 100644 index 00000000000..ff5ea0e7d7e --- /dev/null +++ b/packages/gui-plugins/src/microsoft-office/worker-rpc-machine.test.ts @@ -0,0 +1,340 @@ +import { describe, expect, test } from "bun:test" +import { + transitionWorkerRpcClient, + transitionWorkerRpcServer, + type RpcRequest, + type WorkerRpcClientEvent, + type WorkerRpcClientState, + type WorkerRpcClientTransition, + type WorkerRpcServerEvent, + type WorkerRpcServerState, + type WorkerRpcServerTransition, +} from "./worker-rpc-machine" + +const live: WorkerRpcClientState = { status: "live", pending: new Set() } + +const idle: WorkerRpcServerState = { status: "idle", attempt: 0 } + +const request = (id: number, method = "echo", key?: string): RpcRequest => ({ id, method, key, input: id }) + +const requested = (id: number, aborted = false): WorkerRpcClientEvent => ({ + type: "call.requested", + request: request(id), + transfer: [], + aborted, +}) + +// Folds the events in order and returns the last transition. +const client = (events: readonly WorkerRpcClientEvent[], state: WorkerRpcClientState = live) => + events.reduce((last, event) => transitionWorkerRpcClient(last.state, event), { + state, + effects: [], + }) + +const server = (events: readonly WorkerRpcServerEvent[], state: WorkerRpcServerState = idle) => + events.reduce((last, event) => transitionWorkerRpcServer(last.state, event), { + state, + effects: [], + }) + +describe("transitionWorkerRpcServer", () => { + test("a reply that cannot be posted still answers the caller and the queue runs the next call", () => { + const running = server([ + { type: "request.received", request: request(1, "paint") }, + { type: "request.received", request: request(2) }, + { type: "turn.ready", attempt: 1 }, + ]) + + const bitmap = new ArrayBuffer(8) + + const replied = transitionWorkerRpcServer(running.state, { + type: "handler.succeeded", + attempt: 2, + value: bitmap, + transfer: [bitmap], + }) + + expect(replied).toEqual({ + state: { status: "yielding", attempt: 3, queue: [request(2)] }, + effects: [ + { type: "reply", response: { id: 1, ok: true, value: bitmap, transferred: [bitmap] }, transfer: [bitmap] }, + { type: "schedule-turn", attempt: 3 }, + ], + }) + + const failed = transitionWorkerRpcServer(replied.state, { + type: "reply.failed", + id: 1, + message: "DataCloneError", + transferred: [bitmap], + }) + + expect(failed).toEqual({ + state: replied.state, + effects: [ + { type: "close-bitmaps", transferred: [bitmap] }, + { type: "reply", response: { id: 1, ok: false, superseded: false, message: "DataCloneError" }, transfer: [] }, + ], + }) + expect(transitionWorkerRpcServer(failed.state, { type: "turn.ready", attempt: 3 }).effects).toEqual([ + { type: "run-handler", attempt: 4, request: request(2) }, + ]) + }) + + test("an unknown method answers with an error and leaves no call running while the next one yields", () => { + const running = server([ + { type: "request.received", request: request(1, "missing") }, + { type: "request.received", request: request(2) }, + { type: "turn.ready", attempt: 1 }, + ]) + + expect(running.effects).toEqual([{ type: "run-handler", attempt: 2, request: request(1, "missing") }]) + + const failed = transitionWorkerRpcServer(running.state, { + type: "handler.failed", + attempt: 2, + message: "Unknown method missing", + }) + + expect(failed).toEqual({ + state: { status: "yielding", attempt: 3, queue: [request(2)] }, + effects: [ + { + type: "reply", + response: { id: 1, ok: false, superseded: false, message: "Unknown method missing" }, + transfer: [], + }, + { type: "schedule-turn", attempt: 3 }, + ], + }) + + // The finished call's late cancel aborts nothing. + const cancelled = transitionWorkerRpcServer(failed.state, { type: "cancel.received", id: 1 }) + + expect(cancelled.state).toBe(failed.state) + expect(cancelled.effects).toEqual([]) + expect(server([{ type: "handler.failed", attempt: 3, message: "late" }], failed.state).state).toBe(failed.state) + }) + + test("the last call to finish leaves the worker idle", () => { + const done = server([ + { type: "request.received", request: request(1) }, + { type: "turn.ready", attempt: 1 }, + { type: "handler.succeeded", attempt: 2, value: 1, transfer: [] }, + ]) + + expect(done).toEqual({ + state: { status: "idle", attempt: 2 }, + effects: [{ type: "reply", response: { id: 1, ok: true, value: 1, transferred: [] }, transfer: [] }], + }) + }) + + test("a newer call with the same key replaces a queued one but never the one that runs", () => { + const yielding = server([ + { type: "request.received", request: request(1, "echo", "a") }, + { type: "request.received", request: request(2, "echo", "a") }, + ]) + + expect(yielding).toEqual({ + state: { status: "yielding", attempt: 1, queue: [request(2, "echo", "a")] }, + effects: [ + { + type: "reply", + response: { id: 1, ok: false, superseded: true, message: "Replaced by a newer call" }, + transfer: [], + }, + ], + }) + + const running = server( + [ + { type: "turn.ready", attempt: 1 }, + { type: "request.received", request: request(3, "echo", "a") }, + ], + yielding.state, + ) + + expect(running).toEqual({ + state: { + status: "running", + attempt: 2, + request: request(2, "echo", "a"), + cancelled: false, + queue: [request(3, "echo", "a")], + }, + effects: [], + }) + }) + + test("cancelling the only queued call goes idle, and its turn no longer runs anything", () => { + const cancelled = server([ + { type: "request.received", request: request(1) }, + { type: "cancel.received", id: 1 }, + ]) + + expect(cancelled).toEqual({ state: { status: "idle", attempt: 1 }, effects: [] }) + + const stale = transitionWorkerRpcServer(cancelled.state, { type: "turn.ready", attempt: 1 }) + + expect(stale.state).toBe(cancelled.state) + expect(stale.effects).toEqual([]) + + // A new call claims a new turn; the old timer stays stale. + const next = server( + [ + { type: "request.received", request: request(2) }, + { type: "turn.ready", attempt: 1 }, + ], + cancelled.state, + ) + + expect(next.state).toEqual({ status: "yielding", attempt: 2, queue: [request(2)] }) + }) + + test("a cancelled running call aborts once, closes its bitmaps instead of replying, and the queue moves on", () => { + const running = server([ + { type: "request.received", request: request(1, "paint") }, + { type: "turn.ready", attempt: 1 }, + { type: "request.received", request: request(2) }, + ]) + + const aborted = transitionWorkerRpcServer(running.state, { type: "cancel.received", id: 1 }) + + expect(aborted.effects).toEqual([{ type: "abort-handler", attempt: 2 }]) + expect(transitionWorkerRpcServer(aborted.state, { type: "cancel.received", id: 1 }).state).toBe(aborted.state) + + const bitmap = new ArrayBuffer(8) + + expect( + transitionWorkerRpcServer(aborted.state, { + type: "handler.succeeded", + attempt: 2, + value: bitmap, + transfer: [bitmap], + }), + ).toEqual({ + state: { status: "yielding", attempt: 3, queue: [request(2)] }, + effects: [ + { type: "close-bitmaps", transferred: [bitmap] }, + { type: "schedule-turn", attempt: 3 }, + ], + }) + expect( + transitionWorkerRpcServer(aborted.state, { type: "handler.failed", attempt: 2, message: "aborted" }), + ).toEqual({ + state: { status: "yielding", attempt: 3, queue: [request(2)] }, + effects: [{ type: "schedule-turn", attempt: 3 }], + }) + }) + + test("a cancel withdraws a queued call behind the running one", () => { + const running = server([ + { type: "request.received", request: request(1) }, + { type: "turn.ready", attempt: 1 }, + { type: "request.received", request: request(2) }, + { type: "cancel.received", id: 2 }, + ]) + + expect(running.state).toEqual({ status: "running", attempt: 2, request: request(1), cancelled: false, queue: [] }) + expect(running.effects).toEqual([]) + }) +}) + +describe("transitionWorkerRpcClient", () => { + test("a caller's abort rejects as aborted and cancels the call; a close rejects as closed", () => { + const aborted = client([requested(1), requested(2), { type: "call.aborted", id: 1 }]) + + expect(aborted).toEqual({ + state: { status: "live", pending: new Set([2]) }, + effects: [ + { type: "reject-calls", ids: [1], reason: { kind: "aborted" } }, + { type: "post-cancel", id: 1 }, + ], + }) + + const closed = transitionWorkerRpcClient(aborted.state, { type: "closed" }) + + expect(closed).toEqual({ + state: { status: "closed", failure: { kind: "closed", message: "The Office engine was closed" } }, + effects: [ + { type: "terminate-worker" }, + { type: "reject-calls", ids: [2], reason: { kind: "closed", message: "The Office engine was closed" } }, + ], + }) + + // Cleanup that aborts after the close posts nothing to the terminated worker. + const late = transitionWorkerRpcClient(closed.state, { type: "call.aborted", id: 2 }) + + expect(late.state).toBe(closed.state) + expect(late.effects).toEqual([]) + }) + + test("a crash rejects the pending calls as crashed, tells the viewer once, and fails later calls", () => { + const crashed = client([requested(1), { type: "worker.crashed", message: "boom" }]) + + expect(crashed).toEqual({ + state: { status: "closed", failure: { kind: "crashed", message: "boom" } }, + effects: [ + { type: "terminate-worker" }, + { type: "reject-calls", ids: [1], reason: { kind: "crashed", message: "boom" } }, + { type: "notify-crash" }, + ], + }) + expect(transitionWorkerRpcClient(crashed.state, { type: "worker.crashed", message: "again" }).effects).toEqual([]) + expect(transitionWorkerRpcClient(crashed.state, requested(2)).effects).toEqual([ + { type: "reject-calls", ids: [2], reason: { kind: "crashed", message: "boom" } }, + ]) + }) + + test("a request that cannot be posted rejects that call alone and keeps the worker", () => { + const failed = client([requested(1), requested(2), { type: "call.post-failed", id: 2, message: "detached" }]) + + expect(failed).toEqual({ + state: { status: "live", pending: new Set([1]) }, + effects: [{ type: "reject-calls", ids: [2], reason: { kind: "error", message: "detached" } }], + }) + expect(transitionWorkerRpcClient(failed.state, requested(3)).effects).toEqual([ + { type: "post-request", request: request(3), transfer: [] }, + ]) + }) + + test("a signal that already aborted rejects without posting", () => { + expect(client([requested(1, true)])).toEqual({ + state: live, + effects: [{ type: "reject-calls", ids: [1], reason: { kind: "aborted" } }], + }) + }) + + test("replies settle their own call, and a reply nobody waits for closes its bitmaps", () => { + const bitmap = new ArrayBuffer(8) + + const resolved = client([ + requested(1), + requested(2), + { type: "reply.received", response: { id: 1, ok: true, value: "one", transferred: [] } }, + { type: "reply.received", response: { id: 2, ok: false, superseded: true, message: "Replaced" } }, + ]) + + expect(resolved).toEqual({ + state: { status: "live", pending: new Set() }, + effects: [{ type: "reject-calls", ids: [2], reason: { kind: "superseded", message: "Replaced" } }], + }) + + const crossed = transitionWorkerRpcClient(resolved.state, { + type: "reply.received", + response: { id: 1, ok: true, value: bitmap, transferred: [bitmap] }, + }) + + expect(crossed.state).toBe(resolved.state) + expect(crossed.effects).toEqual([{ type: "close-bitmaps", transferred: [bitmap] }]) + + const closed = client([{ type: "closed" }]) + + expect( + transitionWorkerRpcClient(closed.state, { + type: "reply.received", + response: { id: 1, ok: true, value: bitmap, transferred: [bitmap] }, + }).effects, + ).toEqual([{ type: "close-bitmaps", transferred: [bitmap] }]) + }) +}) diff --git a/packages/gui-plugins/src/microsoft-office/worker-rpc-machine.ts b/packages/gui-plugins/src/microsoft-office/worker-rpc-machine.ts new file mode 100644 index 00000000000..6e47f653a2e --- /dev/null +++ b/packages/gui-plugins/src/microsoft-office/worker-rpc-machine.ts @@ -0,0 +1,336 @@ +// Both ends of an Office worker's call protocol as pure machines: the window's calls waiting for replies, and the +// worker's queue, which runs one call at a time. `worker-rpc.ts` drives them: it posts the messages and runs handlers. + +export type RpcRequest = { + readonly id: number + readonly method: string + readonly key?: string + readonly input: unknown +} + +/** Withdraws a call whose caller aborted it. */ +export type RpcCancel = { readonly cancel: number } + +export type RpcResponse = + /** `transferred` lists the objects the reply moved, so a reply nobody waits for can close its bitmaps. */ + | { readonly id: number; readonly ok: true; readonly value: unknown; readonly transferred: readonly Transferable[] } + | { readonly id: number; readonly ok: false; readonly superseded: boolean; readonly message: string } + +/** Why the worker stopped answering: the window closed it, or it crashed. */ +export type WorkerClientFailure = { readonly kind: "closed" | "crashed"; readonly message: string } + +/** Why a call rejects; the driver turns each kind into its error class. */ +export type WorkerRejectReason = + | { readonly kind: "aborted" } + /** A newer call with the same key replaced it, or its handler failed. */ + | { readonly kind: "superseded" | "error"; readonly message: string } + | WorkerClientFailure + +export type WorkerRpcClientState = + /** The worker answers; `pending` holds the ids of the calls waiting for a reply. */ + | { readonly status: "live"; readonly pending: ReadonlySet } + /** The worker is gone: every call, pending or later, rejects with `failure`. */ + | { readonly status: "closed"; readonly failure: WorkerClientFailure } + +export type WorkerRpcClientEvent = + /** `aborted` when the caller's signal aborted before the call. */ + | { + readonly type: "call.requested" + readonly request: RpcRequest + readonly transfer: readonly Transferable[] + readonly aborted: boolean + } + /** Posting the request threw, as it does for a detached buffer. */ + | { readonly type: "call.post-failed"; readonly id: number; readonly message: string } + | { readonly type: "call.aborted"; readonly id: number } + | { readonly type: "reply.received"; readonly response: RpcResponse } + /** The worker raised `error` or `messageerror`. */ + | { readonly type: "worker.crashed"; readonly message: string } + | { readonly type: "closed" } + +export type WorkerRpcClientEffect = + | { readonly type: "post-request"; readonly request: RpcRequest; readonly transfer: readonly Transferable[] } + | { readonly type: "post-cancel"; readonly id: number } + | { readonly type: "resolve-call"; readonly id: number; readonly value: unknown } + /** Rejects the calls and detaches their abort listeners. */ + | { readonly type: "reject-calls"; readonly ids: readonly number[]; readonly reason: WorkerRejectReason } + | { readonly type: "close-bitmaps"; readonly transferred: readonly Transferable[] } + | { readonly type: "terminate-worker" } + /** Tells the viewer its worker crashed. */ + | { readonly type: "notify-crash" } + +export type WorkerRpcClientTransition = { + readonly state: WorkerRpcClientState + readonly effects: readonly WorkerRpcClientEffect[] +} + +export type WorkerRpcServerState = + /** No call runs or waits. `attempt` is the last one claimed, so a timer of an earlier phase is stale. */ + | { readonly status: "idle"; readonly attempt: number } + /** + * Calls wait one macrotask (`attempt`) before the head runs, so calls that arrive meanwhile can replace or cancel + * it. No handler runs. + */ + | { readonly status: "yielding"; readonly attempt: number; readonly queue: readonly RpcRequest[] } + /** `request`'s handler runs under `attempt`; `cancelled` once its caller aborted it. */ + | { + readonly status: "running" + readonly attempt: number + readonly request: RpcRequest + readonly cancelled: boolean + readonly queue: readonly RpcRequest[] + } + +export type WorkerRpcServerEvent = + | { readonly type: "request.received"; readonly request: RpcRequest } + | { readonly type: "cancel.received"; readonly id: number } + | { readonly type: "turn.ready"; readonly attempt: number } + | { + readonly type: "handler.succeeded" + readonly attempt: number + readonly value: unknown + readonly transfer: readonly Transferable[] + } + /** The handler threw or rejected, or no handler has the method. */ + | { readonly type: "handler.failed"; readonly attempt: number; readonly message: string } + /** Posting a successful reply threw, as it does for a value that cannot be cloned. */ + | { + readonly type: "reply.failed" + readonly id: number + readonly message: string + readonly transferred: readonly Transferable[] + } + +export type WorkerRpcServerEffect = + | { readonly type: "schedule-turn"; readonly attempt: number } + | { readonly type: "run-handler"; readonly attempt: number; readonly request: RpcRequest } + | { readonly type: "abort-handler"; readonly attempt: number } + | { readonly type: "reply"; readonly response: RpcResponse; readonly transfer: readonly Transferable[] } + | { readonly type: "close-bitmaps"; readonly transferred: readonly Transferable[] } + +export type WorkerRpcServerTransition = { + readonly state: WorkerRpcServerState + readonly effects: readonly WorkerRpcServerEffect[] +} + +const NONE: readonly never[] = [] + +const ABORTED: WorkerRejectReason = { kind: "aborted" } + +const CLOSED: WorkerClientFailure = { kind: "closed", message: "The Office engine was closed" } + +export function transitionWorkerRpcClient( + state: WorkerRpcClientState, + event: WorkerRpcClientEvent, +): WorkerRpcClientTransition { + if (event.type === "call.requested") { + const id = event.request.id + + if (state.status === "closed") + return { state, effects: [{ type: "reject-calls", ids: [id], reason: state.failure }] } + + if (event.aborted) return { state, effects: [{ type: "reject-calls", ids: [id], reason: ABORTED }] } + + return { + state: { status: "live", pending: new Set(state.pending).add(id) }, + effects: [{ type: "post-request", request: event.request, transfer: event.transfer }], + } + } + + if (event.type === "reply.received") { + const response = event.response + + // A reply that crossed its call's cancel, or came after the close: its bitmaps would hold memory until collected. + if (state.status === "closed" || !state.pending.has(response.id)) + return { + state, + effects: + response.ok && response.transferred.length > 0 + ? [{ type: "close-bitmaps", transferred: response.transferred }] + : NONE, + } + + return { + state: settle(state.pending, response.id), + effects: [ + response.ok + ? { type: "resolve-call", id: response.id, value: response.value } + : { + type: "reject-calls", + ids: [response.id], + reason: { kind: response.superseded ? "superseded" : "error", message: response.message }, + }, + ], + } + } + + // A dead worker gets no cancel, and its calls already rejected. + if (state.status === "closed") return { state, effects: NONE } + + if (event.type === "call.aborted") { + if (!state.pending.has(event.id)) return { state, effects: NONE } + + return { + state: settle(state.pending, event.id), + effects: [ + { type: "reject-calls", ids: [event.id], reason: ABORTED }, + { type: "post-cancel", id: event.id }, + ], + } + } + + if (event.type === "call.post-failed") { + if (!state.pending.has(event.id)) return { state, effects: NONE } + + return { + state: settle(state.pending, event.id), + effects: [{ type: "reject-calls", ids: [event.id], reason: { kind: "error", message: event.message } }], + } + } + + const failure: WorkerClientFailure = + event.type === "worker.crashed" ? { kind: "crashed", message: event.message } : CLOSED + + return { + state: { status: "closed", failure }, + effects: [ + { type: "terminate-worker" }, + ...(state.pending.size > 0 ? [{ type: "reject-calls" as const, ids: [...state.pending], reason: failure }] : []), + ...(event.type === "worker.crashed" ? [{ type: "notify-crash" as const }] : []), + ], + } +} + +export function transitionWorkerRpcServer( + state: WorkerRpcServerState, + event: WorkerRpcServerEvent, +): WorkerRpcServerTransition { + if (event.type === "request.received") { + if (state.status === "idle") { + const attempt = state.attempt + 1 + + return { + state: { status: "yielding", attempt, queue: [event.request] }, + effects: [{ type: "schedule-turn", attempt }], + } + } + + // A newer call with the same key replaces a queued one, never the one that runs. + const key = event.request.key + const replaced = key === undefined ? undefined : state.queue.find((request) => request.key === key) + + return { + state: { ...state, queue: [...state.queue.filter((request) => request !== replaced), event.request] }, + effects: replaced + ? [ + { + type: "reply", + response: { id: replaced.id, ok: false, superseded: true, message: "Replaced by a newer call" }, + transfer: NONE, + }, + ] + : NONE, + } + } + + // The caller already settled a cancelled call, so it gets no reply. + if (event.type === "cancel.received") { + if (state.status === "running" && state.request.id === event.id) { + if (state.cancelled) return { state, effects: NONE } + + return { state: { ...state, cancelled: true }, effects: [{ type: "abort-handler", attempt: state.attempt }] } + } + + if (state.status === "idle" || !state.queue.some((request) => request.id === event.id)) + return { state, effects: NONE } + + const queue = state.queue.filter((request) => request.id !== event.id) + + if (state.status === "yielding" && queue.length === 0) + return { state: { status: "idle", attempt: state.attempt }, effects: NONE } + + return { state: { ...state, queue }, effects: NONE } + } + + if (event.type === "turn.ready") { + if (state.status !== "yielding" || event.attempt !== state.attempt) return { state, effects: NONE } + + const [request, ...queue] = state.queue + + if (!request) return { state: { status: "idle", attempt: state.attempt }, effects: NONE } + + const attempt = state.attempt + 1 + + return { + state: { status: "running", attempt, request, cancelled: false, queue }, + effects: [{ type: "run-handler", attempt, request }], + } + } + + // The reply could not be posted, so its bitmaps stay here; the caller still gets an answer. + if (event.type === "reply.failed") + return { + state, + effects: [ + ...closeBitmaps(event.transferred), + { + type: "reply", + response: { id: event.id, ok: false, superseded: false, message: event.message }, + transfer: NONE, + }, + ], + } + + const transferred = event.type === "handler.succeeded" ? event.transfer : NONE + + if (state.status !== "running" || event.attempt !== state.attempt) + return { state, effects: closeBitmaps(transferred) } + + // The caller already settled a call it aborted, so nothing would take the reply or its bitmaps. + if (state.cancelled) return next(state, closeBitmaps(transferred)) + + if (event.type === "handler.failed") + return next(state, [ + { + type: "reply", + response: { id: state.request.id, ok: false, superseded: false, message: event.message }, + transfer: NONE, + }, + ]) + + return next(state, [ + { + type: "reply", + response: { id: state.request.id, ok: true, value: event.value, transferred }, + transfer: transferred, + }, + ]) +} + +/** The client's state without one call that has settled. */ +function settle(pending: ReadonlySet, id: number): WorkerRpcClientState { + const next = new Set(pending) + + next.delete(id) + + return { status: "live", pending: next } +} + +/** Leaves the finished call behind: the queue yields once before its head runs, or the worker goes idle. */ +function next( + state: Extract, + effects: readonly WorkerRpcServerEffect[], +): WorkerRpcServerTransition { + if (state.queue.length === 0) return { state: { status: "idle", attempt: state.attempt }, effects } + + const attempt = state.attempt + 1 + + return { + state: { status: "yielding", attempt, queue: state.queue }, + effects: [...effects, { type: "schedule-turn", attempt }], + } +} + +function closeBitmaps(transferred: readonly Transferable[]): readonly WorkerRpcServerEffect[] { + return transferred.length > 0 ? [{ type: "close-bitmaps", transferred }] : NONE +} diff --git a/packages/gui-plugins/src/microsoft-office/worker-rpc.test.ts b/packages/gui-plugins/src/microsoft-office/worker-rpc.test.ts index f7865a09e7f..faf64dfd5e9 100644 --- a/packages/gui-plugins/src/microsoft-office/worker-rpc.test.ts +++ b/packages/gui-plugins/src/microsoft-office/worker-rpc.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, test } from "bun:test" import type { FixtureMethods } from "./worker-rpc.fixture" -import { createWorkerClient, SupersededError, WorkerClosedError } from "./worker-rpc" +import { AbortedError, createWorkerClient, SupersededError, WorkerClosedError } from "./worker-rpc" const clients: ReturnType>[] = [] @@ -26,7 +26,7 @@ describe("worker rpc", () => { const call = client.call("echo", "aborted", { signal: controller.signal }) controller.abort() - await expect(call).rejects.toBeInstanceOf(WorkerClosedError) + await expect(call).rejects.toBeInstanceOf(AbortedError) await busy expect(await client.call("echo", "next")).toBe("next") expect((await client.call("log", undefined)).ran).toEqual(["sleep", "echo:next"]) @@ -40,7 +40,7 @@ describe("worker rpc", () => { await running controller.abort() - await expect(call).rejects.toBeInstanceOf(WorkerClosedError) + await expect(call).rejects.toBeInstanceOf(AbortedError) expect(await client.call("log", undefined)).toEqual({ ran: ["hold"], aborted: ["hold"], closed: 0 }) }) @@ -52,7 +52,7 @@ describe("worker rpc", () => { await running controller.abort() - await expect(call).rejects.toBeInstanceOf(WorkerClosedError) + await expect(call).rejects.toBeInstanceOf(AbortedError) // The stand-in bitmap cannot be posted, so a reply would fail in the worker before it counted a close. expect(await client.call("log", undefined)).toEqual({ ran: ["paint"], aborted: [], closed: 1 }) }) @@ -65,12 +65,21 @@ describe("worker rpc", () => { await running controller.abort() - await expect(call).rejects.toBeInstanceOf(WorkerClosedError) + await expect(call).rejects.toBeInstanceOf(AbortedError) // The worker replied before it read the cancel, and the window's next calls still settle with their own replies. expect(await client.call("echo", "after")).toBe("after") expect((await client.call("log", undefined)).ran).toEqual(["spin", "echo:after"]) }) + test("a reply that cannot be posted rejects its call, frees its bitmaps, and the next call still runs", async () => { + const client = start() + + // The stand-in bitmap cannot be posted, as a detached or uncloneable reply cannot. + await expect(client.call("paint", 0)).rejects.toThrow() + expect(await client.call("echo", "after")).toBe("after") + expect(await client.call("log", undefined)).toEqual({ ran: ["paint", "echo:after"], aborted: [], closed: 1 }) + }) + test("close rejects the pending calls and every later one", async () => { const client = start() const pending = client.call("sleep", 1000) diff --git a/packages/gui-plugins/src/microsoft-office/worker-rpc.ts b/packages/gui-plugins/src/microsoft-office/worker-rpc.ts index 52a9a6e5754..3fc0e47af64 100644 --- a/packages/gui-plugins/src/microsoft-office/worker-rpc.ts +++ b/packages/gui-plugins/src/microsoft-office/worker-rpc.ts @@ -1,6 +1,22 @@ // The engines run in a worker per open file, so no layout, recalculation or painting holds the window. These are the // two ends of that worker's protocol: typed calls by method name, a key that lets a newer call replace a queued one // (as the markdown worker's queue does), transferable payloads, and a worker that fails every pending call when it dies. +// The machines in `worker-rpc-machine.ts` decide; these drivers post the messages and run the handlers. + +import { + transitionWorkerRpcClient, + transitionWorkerRpcServer, + type RpcCancel, + type RpcRequest, + type RpcResponse, + type WorkerRejectReason, + type WorkerRpcClientEffect, + type WorkerRpcClientEvent, + type WorkerRpcClientState, + type WorkerRpcServerEffect, + type WorkerRpcServerEvent, + type WorkerRpcServerState, +} from "./worker-rpc-machine" /** What one method takes and returns. */ export type Method = { readonly input: Input; readonly output: Output } @@ -8,16 +24,6 @@ export type Method = { readonly input: Input; readonly output: Ou /** A worker's methods by name. */ export type Methods = { readonly [name: string]: Method } -type Request = { readonly id: number; readonly method: string; readonly key?: string; readonly input: unknown } - -/** Withdraws a call whose caller aborted it. */ -type Cancel = { readonly cancel: number } - -type Response = - /** `transferred` lists the objects the reply moved, so a reply nobody waits for can close its bitmaps. */ - | { readonly id: number; readonly ok: true; readonly value: unknown; readonly transferred: readonly Transferable[] } - | { readonly id: number; readonly ok: false; readonly superseded: boolean; readonly message: string } - /** A value a method returns with the buffers to move to the caller rather than copy. */ export class Transfer { constructor( @@ -44,6 +50,12 @@ export class SupersededError extends Error {} /** A call made after the worker failed or was closed, or pending when that happened. */ export class WorkerClosedError extends Error {} +/** + * A call its caller aborted. It extends `WorkerClosedError`, so a caller that ignores a closed worker also ignores its + * own aborts; check this class first to tell them apart. + */ +export class AbortedError extends WorkerClosedError {} + type CallOptions = { /** A newer call with the same key replaces this one while it waits to run. */ readonly key?: string @@ -53,40 +65,63 @@ type CallOptions = { readonly signal?: AbortSignal } -/** A call waiting for its reply. */ -type Pending = { readonly settle: (response: Response) => void; readonly reject: (error: Error) => void } +/** A call waiting for its reply, and the abort listener to detach once it settles. */ +type Call = { + readonly resolve: (effect: Extract) => void + readonly reject: (error: Error) => void + readonly detach: () => void +} -/** The next call id, and why the worker stopped answering once it has. */ -type ClientState = { next: number; failure: Error | undefined } +/** The window's end: starts the worker and calls its methods. `onCrash` runs once if the worker dies on its own. */ +export function createWorkerClient(worker: Worker, options: { readonly onCrash?: () => void } = {}) { + const calls = new Map() + let clientState: WorkerRpcClientState = { status: "live", pending: new Set() } + let ids = 0 -/** The window's end: starts the worker and calls its methods. */ -export function createWorkerClient(worker: Worker) { - const pending = new Map() - const state: ClientState = { next: 0, failure: undefined } + const take = (id: number) => { + const call = calls.get(id) - const fail = (error: Error) => { - state.failure ??= error - pending.forEach((call) => call.reject(error)) - pending.clear() - worker.terminate() + calls.delete(id) + call?.detach() + + return call } - worker.onmessage = (event: MessageEvent) => { - const call = pending.get(event.data.id) + const dispatch = createDispatch({ + read: () => clientState, + write: (next) => { + clientState = next + }, + transition: transitionWorkerRpcClient, + run: (effect) => { + if (effect.type === "post-request") return worker.postMessage(effect.request, [...effect.transfer]) - // A reply that crossed its call's cancel on the way: its bitmaps would hold their memory until collected. - if (!call) { - if (event.data.ok) closeBitmaps(event.data.transferred) + if (effect.type === "post-cancel") return worker.postMessage({ cancel: effect.id } satisfies RpcCancel) - return - } + if (effect.type === "resolve-call") return take(effect.id)?.resolve(effect) - pending.delete(event.data.id) - call.settle(event.data) - } + if (effect.type === "reject-calls") return effect.ids.forEach((id) => take(id)?.reject(rejection(effect.reason))) - worker.onerror = (event) => fail(new WorkerClosedError(event.message || "The Office engine stopped")) - worker.onmessageerror = () => fail(new WorkerClosedError("The Office engine sent an unreadable reply")) + if (effect.type === "close-bitmaps") return closeBitmaps(effect.transferred) + + if (effect.type === "notify-crash") return options.onCrash?.() + + worker.onmessage = null + worker.onerror = null + worker.onmessageerror = null + worker.terminate() + }, + failed: (effect, cause) => + effect.type === "post-request" + ? { type: "call.post-failed", id: effect.request.id, message: message(cause) } + : undefined, + }) + + worker.onmessage = (event: MessageEvent) => dispatch({ type: "reply.received", response: event.data }) + worker.onerror = (event) => + dispatch({ type: "worker.crashed", message: event.message || "The Office engine stopped" }) + worker.onmessageerror = () => + dispatch({ type: "worker.crashed", message: "The Office engine sent an unreadable reply" }) return { call( @@ -94,48 +129,36 @@ export function createWorkerClient(worker: Worker) { input: M[K]["input"], options: CallOptions = {}, ): Promise { - if (state.failure) return Promise.reject(state.failure) - - if (options.signal?.aborted) return Promise.reject(new WorkerClosedError("The call was aborted")) - - const id = ++state.next + const id = ++ids + const signal = options.signal return new Promise((resolve, reject) => { - const abort = () => { - pending.delete(id) - reject(new WorkerClosedError("The call was aborted")) - worker.postMessage({ cancel: id } satisfies Cancel) - } + const abort = () => dispatch({ type: "call.aborted", id }) - options.signal?.addEventListener("abort", abort, { once: true }) - pending.set(id, { - settle: (response) => { - options.signal?.removeEventListener("abort", abort) - - if (!response.ok) - return reject(response.superseded ? new SupersededError(response.message) : new Error(response.message)) - - // SAFETY: the worker answers each id with the output of the method that id called (see `serveWorker`). - resolve(response.value as M[K]["output"]) - }, + calls.set(id, { + // SAFETY: the worker answers each id with the output of the method that id called (see `serveWorker`). + resolve: (effect) => resolve(effect.value as M[K]["output"]), reject, + detach: () => signal?.removeEventListener("abort", abort), + }) + + if (signal && !signal.aborted) signal.addEventListener("abort", abort, { once: true }) + + dispatch({ + type: "call.requested", + request: { id, method, key: options.key, input }, + transfer: options.transfer ?? [], + aborted: signal?.aborted ?? false, }) - worker.postMessage({ id, method, key: options.key, input } satisfies Request, [...(options.transfer ?? [])]) }) }, /** Stops the worker, which frees its engine's memory, and fails every pending call. */ close() { - fail(new WorkerClosedError("The Office engine was closed")) + dispatch({ type: "closed" }) }, } } -/** Whether a call runs, and which call it is, so its caller can abort it. */ -type ServerState = { - running: boolean - current: { readonly id: number; readonly controller: AbortController } | undefined -} - /** * The worker's end: runs calls one at a time, in order, letting messages through between them. A handler's signal * aborts when its caller aborts the call. @@ -146,98 +169,119 @@ export function serveWorker(handlers: { signal: AbortSignal, ) => M[K]["output"] | Transfer | Promise> }) { - const queue: Request[] = [] + const controllers = new Map() + let serverState: WorkerRpcServerState = { status: "idle", attempt: 0 } - const state: ServerState = { running: false, current: undefined } + const start = (attempt: number, request: RpcRequest) => { + const handler = handlers[request.method] - const reply = (response: Response, transfer: readonly Transferable[] = []) => - self.postMessage(response, { transfer: [...transfer] }) + if (!handler) return dispatch({ type: "handler.failed", attempt, message: `Unknown method ${request.method}` }) - const run = async () => { - if (state.running) return + const controller = new AbortController() + // SAFETY: the client sends each method the input its `Methods` entry declares (see `createWorkerClient`). + const input = request.input as never - state.running = true - - // Each call returns to the event loop before it leaves the queue, so calls that arrived meanwhile can replace it. - while (queue.length > 0) { - await new Promise((resolve) => setTimeout(resolve)) - - const request = queue.shift() - - if (!request) break - - const handler = handlers[request.method] - const controller = new AbortController() - - state.current = { id: request.id, controller } - - if (!handler) { - reply({ id: request.id, ok: false, superseded: false, message: `Unknown method ${request.method}` }) - continue - } - - // SAFETY: the client sends each method the input its `Methods` entry declares (see `createWorkerClient`). - const input = request.input as never - - await Promise.try(() => handler(input, controller.signal)).then( - (result) => { - const transfer = result instanceof Transfer ? result.transfer : [] - - // The caller already settled a call it aborted, so nothing would take the reply or its bitmaps. - if (controller.signal.aborted) return closeBitmaps(transfer) - - reply( - { - id: request.id, - ok: true, - value: result instanceof Transfer ? result.value : result, - transferred: transfer, - }, - transfer, - ) - }, - (cause: unknown) => { - if (controller.signal.aborted) return - - reply({ - id: request.id, - ok: false, - superseded: false, - message: cause instanceof Error ? cause.message : String(cause), - }) - }, + controllers.set(attempt, controller) + void Promise.try(() => handler(input, controller.signal)) + .finally(() => controllers.delete(attempt)) + .then( + (result) => + dispatch( + result instanceof Transfer + ? { type: "handler.succeeded", attempt, value: result.value, transfer: result.transfer } + : { type: "handler.succeeded", attempt, value: result, transfer: [] }, + ), + (cause: unknown) => dispatch({ type: "handler.failed", attempt, message: message(cause) }), ) - } - - state.running = false - state.current = undefined } - self.onmessage = (event: MessageEvent) => { - // The caller already settled a cancelled call, so it gets no reply. - if ("cancel" in event.data) { - const id = event.data.cancel - const queued = queue.findIndex((request) => request.id === id) + const dispatch = createDispatch({ + read: () => serverState, + write: (next) => { + serverState = next + }, + transition: transitionWorkerRpcServer, + run: (effect) => { + // Each call returns to the event loop before it leaves the queue, so calls that arrived meanwhile can replace it. + if (effect.type === "schedule-turn") + return void setTimeout(() => dispatch({ type: "turn.ready", attempt: effect.attempt })) - if (queued !== -1) queue.splice(queued, 1) + if (effect.type === "abort-handler") return controllers.get(effect.attempt)?.abort() - if (state.current?.id === id) state.current.controller.abort() + if (effect.type === "reply") return self.postMessage(effect.response, { transfer: [...effect.transfer] }) - return - } + if (effect.type === "close-bitmaps") return closeBitmaps(effect.transferred) - const key = event.data.key - const replaced = key === undefined ? -1 : queue.findIndex((request) => request.key === key) + start(effect.attempt, effect.request) + }, + failed: (effect, cause) => + effect.type === "reply" && effect.response.ok + ? { type: "reply.failed", id: effect.response.id, message: message(cause), transferred: effect.transfer } + : undefined, + }) - if (replaced !== -1) { - const [old] = queue.splice(replaced, 1) + self.onmessage = (event: MessageEvent) => + dispatch( + "cancel" in event.data + ? { type: "cancel.received", id: event.data.cancel } + : { type: "request.received", request: event.data }, + ) +} - if (old) reply({ id: old.id, ok: false, superseded: true, message: "Replaced by a newer call" }) - } +/** + * Applies one event at a time and runs its effects; an effect may dispatch, and its event waits for the current one. + * A throwing effect never stalls the queue: it reports `failed(effect, cause)` back to the machine, and one without + * such an event surfaces as an unhandled rejection while later events keep applying. + */ +function createDispatch(machine: { + readonly read: () => State + readonly write: (state: State) => void + readonly transition: (state: State, event: Event) => { readonly state: State; readonly effects: readonly Effect[] } + readonly run: (effect: Effect) => void + readonly failed: (effect: Effect, cause: unknown) => Event | undefined +}) { + const queue: Event[] = [] - queue.push(event.data) - void run() + const apply = (event: Event) => { + const next = machine.transition(machine.read(), event) + + machine.write(next.state) + next.effects.forEach((effect) => { + void Promise.try(() => machine.run(effect)).catch((cause: unknown) => { + const failure = machine.failed(effect, cause) + + if (!failure) throw cause + dispatch(failure) + }) + }) } + + const dispatch = (event: Event) => { + queue.push(event) + + if (queue.length > 1) return + + while (queue.length > 0) { + void Promise.try(apply, queue[0]) + queue.shift() + } + } + + return dispatch +} + +function rejection(reason: WorkerRejectReason) { + if (reason.kind === "aborted") return new AbortedError("The call was aborted") + + if (reason.kind === "superseded") return new SupersededError(reason.message) + + if (reason.kind === "error") return new Error(reason.message) + + return new WorkerClosedError(reason.message) +} + +function message(cause: unknown) { + return cause instanceof Error ? cause.message : String(cause) } /** Frees the bitmaps among objects that were moved for a reply nobody takes. */ diff --git a/packages/gui-plugins/src/updater/beta-dialog.tsx b/packages/gui-plugins/src/updater/beta-dialog.tsx index 73ede83a35f..0120bad9c7a 100644 --- a/packages/gui-plugins/src/updater/beta-dialog.tsx +++ b/packages/gui-plugins/src/updater/beta-dialog.tsx @@ -16,38 +16,33 @@ import { import type definition from "./index" /** - * Shows the features and fixes this beta build carries since the commit of the build the user saw last, and remembers - * this build as seen. Everything comes from the build itself; only the links reach the network, when clicked. + * The features and fixes this beta build carries since the commit of the build the user saw last; undefined when there + * are none. Everything comes from the build itself; only the links reach the network, when clicked. */ -export function showBetaNotes( - ctx: SetupContext, - input: { readonly previous: string; readonly previousCommit: string | undefined; readonly markSeen: () => void }, -) { - const notes = Option.flatMap(decodeEmbeddedNotes(import.meta.env.OPENCODE_BETA_NOTES), (embedded) => - sliceBetaNotes(embedded, input.previousCommit), - ) - - input.markSeen() - - if (Option.isNone(notes)) return - - ctx.dialogs.open( - (dialog) => ( - ctx.system.openExternal(href)} - viewAll={() => { - dialog.close() - ctx.layout.settings("whats-new") - }} - /> +export function readBetaNotes(previousCommit: string | undefined) { + return Option.getOrUndefined( + Option.flatMap(decodeEmbeddedNotes(import.meta.env.OPENCODE_BETA_NOTES), (embedded) => + sliceBetaNotes(embedded, previousCommit), ), - { replace: true }, ) } +/** Opens What's new in beta above any open dialog. */ +export function openBetaNotes(ctx: SetupContext, notes: BetaNotes, previous: string) { + ctx.dialogs.open((dialog) => ( + ctx.system.openExternal(href)} + viewAll={() => { + dialog.close() + ctx.layout.settings("whats-new") + }} + /> + )) +} + /** What's new in beta: the listed features and fixes, and the What's new page when some are not listed. */ export function DialogBetaNotes(props: { notes: BetaNotes diff --git a/packages/gui-plugins/src/updater/renderer.tsx b/packages/gui-plugins/src/updater/renderer.tsx index df111a4d07a..b344dbd6ad1 100644 --- a/packages/gui-plugins/src/updater/renderer.tsx +++ b/packages/gui-plugins/src/updater/renderer.tsx @@ -1,10 +1,18 @@ import { showToast } from "@opencode/ui/toast" import { lazy, onCleanup, Suspense } from "solid-js" -import { Command, SettingsPage, TitlebarItem, type SetupContext, type Plugin } from "@opencode/plugin/gui" +import { Command, createKeyed, SettingsPage, TitlebarItem, type SetupContext, type Plugin } from "@opencode/plugin/gui" import { onIdle } from "@opencode/plugin/gui/builtin" import { Updater } from "@opencode/plugin/gui/updater" import { updaterAction } from "./action" import { webUpdates } from "./web" +import { + initWhatsNew, + transitionWhatsNew, + whatsNewLoading, + type WhatsNewContent, + type WhatsNewEffect, + type WhatsNewEvent, +} from "./whats-new-machine" import type definition from "./index" const setup: Plugin.Setup = (ctx) => { @@ -108,40 +116,97 @@ function betaNotes(ctx: SetupContext) { * features and fixes of the beta builds since then. The first run and a disabled What's New only remember the version. */ function whatsNew(ctx: SetupContext) { - const version = ctx.app.version const seen = ctx.stores.seen - const previous = seen.value.version + const controller = new AbortController() - if (!version || previous === version) return + const start = initWhatsNew({ + version: ctx.app.version, + commit: import.meta.env.OPENCODE_COMMIT, + channel: ctx.app.channel === "beta" ? "beta" : "stable", + previousVersion: seen.value.version, + previousCommit: seen.value.commit, + enabled: ctx.stores.releaseNotes.value.enabled, + }) - const commit = import.meta.env.OPENCODE_COMMIT - const previousCommit = seen.value.commit + let whatsNewState = start.state + let timer: ReturnType | undefined - const markSeen = () => - seen.update((draft) => { - draft.version = version + const dispatch = (event: WhatsNewEvent) => { + const next = transitionWhatsNew(whatsNewState, event) - // Beta remembers the build's commit even when nothing shows, so the next update lists what came after it. - if (commit) draft.commit = commit - }) - - if (!previous || !ctx.stores.releaseNotes.value.enabled) return markSeen() - - if (ctx.app.channel === "beta") { - void import("./beta-dialog").then((module) => { - if (ctx.signal.aborted) return - - module.showBetaNotes(ctx, { previous, previousCommit, markSeen }) - }) - - return + whatsNewState = next.state + next.effects.forEach(run) } - void import("./whats-new").then((module) => { - if (ctx.signal.aborted) return + const run = (effect: WhatsNewEffect) => { + if (effect.type === "mark-seen") + return seen.update((draft) => { + draft.version = effect.version - module.showWhatsNew(ctx, { previous, current: version, markSeen }) - }) + // Beta remembers the build's commit even when nothing shows, so the next update lists what came after it. + if (effect.commit) draft.commit = effect.commit + }) + + if (effect.type === "abort-load") { + clearTimeout(timer) + controller.abort() + + return + } + + if (effect.type === "open") return void open(effect.content, effect.previousVersion) + + timer = setTimeout(() => dispatch({ type: "load.timed-out" }), effect.timeoutMs) + void load(effect).then( + (content) => dispatch({ type: "loaded", content }), + () => dispatch({ type: "load.failed" }), + ) + } + + const load = async (effect: Extract): Promise => { + if (effect.channel === "beta") { + const { readBetaNotes } = await import("./beta-dialog") + const notes = readBetaNotes(effect.previousCommit) + + return notes && { channel: "beta", notes } + } + + const { loadWhatsNewHighlights } = await import("./whats-new") + + const highlights = await loadWhatsNewHighlights({ + previous: effect.previousVersion, + current: effect.version, + signal: controller.signal, + }) + + return { channel: "stable", highlights } + } + + // The chunk loaded with the notes, so this resolves at once. + const open = async (content: WhatsNewContent, previousVersion: string) => { + if (content.channel === "beta") { + const { openBetaNotes } = await import("./beta-dialog") + + if (!ctx.signal.aborted) openBetaNotes(ctx, content.notes, previousVersion) + + return + } + + const { openWhatsNew } = await import("./whats-new") + + if (!ctx.signal.aborted) openWhatsNew(ctx, content.highlights) + } + + start.effects.forEach(run) + + if (!whatsNewLoading(whatsNewState)) return + + // Turning release notes off in Settings while the notes load means they never open. + createKeyed( + () => !ctx.stores.releaseNotes.value.enabled, + () => dispatch({ type: "disabled" }), + ) + onCleanup(() => dispatch({ type: "disposed" })) } export default setup diff --git a/packages/gui-plugins/src/updater/whats-new-machine.test.ts b/packages/gui-plugins/src/updater/whats-new-machine.test.ts new file mode 100644 index 00000000000..ca4e3351835 --- /dev/null +++ b/packages/gui-plugins/src/updater/whats-new-machine.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, test } from "bun:test" +import type { BetaNotes } from "./beta-notes" +import { + initWhatsNew, + transitionWhatsNew, + whatsNewLoading, + WHATS_NEW_TIMEOUT_MS, + type WhatsNewContent, + type WhatsNewEffect, + type WhatsNewInit, +} from "./whats-new-machine" + +const upgraded: WhatsNewInit = { + version: "1.10.0", + commit: undefined, + channel: "stable", + previousVersion: "1.9.1", + previousCommit: undefined, + enabled: true, +} + +const beta: WhatsNewInit = { + ...upgraded, + version: "1.10.0-beta.2", + commit: "bbb", + channel: "beta", + previousVersion: "1.10.0-beta.1", + previousCommit: "aaa", +} + +const highlights: WhatsNewContent = { + channel: "stable", + highlights: [{ title: "Split panes", description: "Work side by side." }], +} + +const notes: WhatsNewContent = { + channel: "beta", + notes: { + added: [], + fixed: [{ sha: "bbb", type: "fix", summary: "Fixed a crash" }], + total: 1, + more: false, + } satisfies BetaNotes, +} + +const loading = (input: WhatsNewInit) => initWhatsNew(input).state + +const markSeen: WhatsNewEffect = { type: "mark-seen", version: "1.10.0", commit: undefined } + +describe("whats new", () => { + test("turning release notes off while they load remembers the release and never opens the dialog", () => { + const disabled = transitionWhatsNew(loading(upgraded), { type: "disabled" }) + + expect(disabled).toEqual({ state: { status: "done" }, effects: [{ type: "abort-load" }, markSeen] }) + + const late = transitionWhatsNew(disabled.state, { type: "loaded", content: highlights }) + + expect(late.state).toBe(disabled.state) + expect(late.effects).toEqual([]) + }) + + test("a changelog that hangs times out and leaves the release for the next start", () => { + const timedOut = transitionWhatsNew(loading(upgraded), { type: "load.timed-out" }) + + expect(timedOut).toEqual({ state: { status: "done" }, effects: [{ type: "abort-load" }] }) + expect(transitionWhatsNew(timedOut.state, { type: "loaded", content: highlights }).effects).toEqual([]) + }) + + test("both channels remember the release as they open its notes, and neither does on dispose", () => { + expect(transitionWhatsNew(loading(upgraded), { type: "loaded", content: highlights }).effects).toEqual([ + { type: "abort-load" }, + markSeen, + { type: "open", content: highlights, previousVersion: "1.9.1" }, + ]) + expect(transitionWhatsNew(loading(beta), { type: "loaded", content: notes }).effects).toEqual([ + { type: "abort-load" }, + { type: "mark-seen", version: "1.10.0-beta.2", commit: "bbb" }, + { type: "open", content: notes, previousVersion: "1.10.0-beta.1" }, + ]) + expect(transitionWhatsNew(loading(upgraded), { type: "disposed" }).effects).toEqual([{ type: "abort-load" }]) + expect(transitionWhatsNew(loading(beta), { type: "disposed" }).effects).toEqual([{ type: "abort-load" }]) + }) + + test.each([ + { name: "no version", input: { ...upgraded, version: undefined }, effects: [] }, + { name: "the version seen", input: { ...upgraded, previousVersion: "1.10.0" }, effects: [] }, + { name: "the first run", input: { ...upgraded, previousVersion: undefined }, effects: [markSeen] }, + { name: "release notes off", input: { ...upgraded, enabled: false }, effects: [markSeen] }, + { + name: "release notes off on beta", + input: { ...beta, enabled: false }, + effects: [{ type: "mark-seen", version: "1.10.0-beta.2", commit: "bbb" }], + }, + ])("$name loads nothing", (row) => { + const start = initWhatsNew(row.input) + + expect(start).toEqual({ state: { status: "done" }, effects: row.effects }) + expect(whatsNewLoading(start.state)).toBe(false) + }) + + test("an upgrade loads the channel's notes with a bounded timeout", () => { + const start = initWhatsNew(beta) + + expect(start).toEqual({ + state: { status: "loading", version: "1.10.0-beta.2", commit: "bbb", previousVersion: "1.10.0-beta.1" }, + effects: [ + { + type: "load", + channel: "beta", + previousVersion: "1.10.0-beta.1", + previousCommit: "aaa", + version: "1.10.0-beta.2", + timeoutMs: WHATS_NEW_TIMEOUT_MS, + }, + ], + }) + expect(whatsNewLoading(start.state)).toBe(true) + }) + + test("nothing to show remembers the release; a failed load does not", () => { + const empty = [undefined, { channel: "stable" as const, highlights: [] }] + + empty.forEach((content) => + expect(transitionWhatsNew(loading(upgraded), { type: "loaded", content }).effects).toEqual([ + { type: "abort-load" }, + markSeen, + ]), + ) + expect(transitionWhatsNew(loading(upgraded), { type: "load.failed" })).toEqual({ + state: { status: "done" }, + effects: [{ type: "abort-load" }], + }) + }) +}) diff --git a/packages/gui-plugins/src/updater/whats-new-machine.ts b/packages/gui-plugins/src/updater/whats-new-machine.ts new file mode 100644 index 00000000000..e1e6cf39f50 --- /dev/null +++ b/packages/gui-plugins/src/updater/whats-new-machine.ts @@ -0,0 +1,117 @@ +import type { BetaNotes } from "./beta-notes" +import type { Highlight } from "./whats-new" + +/** Bounds the dialog's chunk and the changelog request, so a stalled connection never opens a dialog mid-session. */ +export const WHATS_NEW_TIMEOUT_MS = 15_000 + +/** What the dialog shows: on beta the notes the build embeds, elsewhere the changelog's highlights. */ +export type WhatsNewContent = + | { readonly channel: "beta"; readonly notes: BetaNotes } + | { readonly channel: "stable"; readonly highlights: readonly Highlight[] } + +export type WhatsNewInit = { + readonly version: string | undefined + readonly commit: string | undefined + readonly channel: WhatsNewContent["channel"] + readonly previousVersion: string | undefined + readonly previousCommit: string | undefined + /** Release notes are on in Settings. */ + readonly enabled: boolean +} + +/** What's New after an update; it only moves forward, so results match on the phase. */ +export type WhatsNewState = + /** The dialog's chunk, and on stable the changelog, load for the release `version`. */ + | { + readonly status: "loading" + readonly version: string + readonly commit: string | undefined + readonly previousVersion: string + } + /** Nothing more happens this start: the dialog opened, there was nothing to show, or the load failed or ended. */ + | { readonly status: "done" } + +export type WhatsNewEvent = + /** `content` is undefined, or has no highlights, when nothing since the version seen is worth showing. */ + | { readonly type: "loaded"; readonly content: WhatsNewContent | undefined } + | { readonly type: "load.failed" } + | { readonly type: "load.timed-out" } + /** The user turned release notes off in Settings. */ + | { readonly type: "disabled" } + | { readonly type: "disposed" } + +export type WhatsNewEffect = + | { + readonly type: "load" + readonly channel: WhatsNewContent["channel"] + readonly previousVersion: string + readonly previousCommit: string | undefined + readonly version: string + readonly timeoutMs: number + } + /** Ends the load's timeout and request. */ + | { readonly type: "abort-load" } + /** Remembers the release, so the next start shows nothing. */ + | { readonly type: "mark-seen"; readonly version: string; readonly commit: string | undefined } + | { readonly type: "open"; readonly content: WhatsNewContent; readonly previousVersion: string } + +export type WhatsNewTransition = { readonly state: WhatsNewState; readonly effects: readonly WhatsNewEffect[] } + +const DONE: WhatsNewState = { status: "done" } + +const NONE: readonly WhatsNewEffect[] = [] + +/** + * Decides at startup: an unchanged version shows nothing; the first run and disabled release notes only remember the + * version; otherwise the channel's notes load. + */ +export function initWhatsNew(input: WhatsNewInit): WhatsNewTransition { + const version = input.version + + if (!version || input.previousVersion === version) return { state: DONE, effects: NONE } + + if (!input.previousVersion || !input.enabled) + return { state: DONE, effects: [{ type: "mark-seen", version, commit: input.commit }] } + + return { + state: { status: "loading", version, commit: input.commit, previousVersion: input.previousVersion }, + effects: [ + { + type: "load", + channel: input.channel, + previousVersion: input.previousVersion, + previousCommit: input.previousCommit, + version, + timeoutMs: WHATS_NEW_TIMEOUT_MS, + }, + ], + } +} + +export function transitionWhatsNew(state: WhatsNewState, event: WhatsNewEvent): WhatsNewTransition { + if (state.status === "done") return { state, effects: NONE } + + // A failed or abandoned load leaves the release unseen, so the next start tries again. + if (event.type === "load.failed" || event.type === "load.timed-out" || event.type === "disposed") + return { state: DONE, effects: [{ type: "abort-load" }] } + + const seen: readonly WhatsNewEffect[] = [ + { type: "abort-load" }, + { type: "mark-seen", version: state.version, commit: state.commit }, + ] + + const content = event.type === "loaded" ? event.content : undefined + + if (!content || (content.channel === "stable" && content.highlights.length === 0)) + return { state: DONE, effects: seen } + + return { + state: DONE, + effects: [...seen, { type: "open", content, previousVersion: state.previousVersion }], + } +} + +/** Whether the driver still watches the setting and owns a load to end. */ +export function whatsNewLoading(state: WhatsNewState) { + return state.status === "loading" +} diff --git a/packages/gui-plugins/src/updater/whats-new.tsx b/packages/gui-plugins/src/updater/whats-new.tsx index 7c1b7546c11..5dd691a8254 100644 --- a/packages/gui-plugins/src/updater/whats-new.tsx +++ b/packages/gui-plugins/src/updater/whats-new.tsx @@ -7,7 +7,7 @@ import type definition from "./index" const CHANGELOG_URL = "https://opencode.ai/changelog.json" -type Highlight = { +export type Highlight = { title: string description: string media?: { type: "image" | "video"; src: string; alt?: string } @@ -49,42 +49,27 @@ const Changelog = Schema.Union([Releases, Schema.Struct({ releases: Releases })] const decodeChangelog = Schema.decodeUnknownOption(Changelog) /** - * Shows the desktop highlights of the releases since `previous` once the changelog loads, and remembers the current - * version as seen. A changelog without highlights only remembers the version; a failed request leaves it for the next - * start. + * The desktop highlights of the releases since `previous`, from the changelog; none when it holds none. Rejects when the + * request fails, so the release stays unseen for the next start. */ -export function showWhatsNew( - ctx: SetupContext, - input: { readonly previous: string; readonly current: string; readonly markSeen: () => void }, -) { - const timers = new Set>() +export async function loadWhatsNewHighlights(input: { + readonly previous: string + readonly current: string + readonly signal: AbortSignal +}): Promise { + const response = await fetch(CHANGELOG_URL, { signal: input.signal, headers: { Accept: "application/json" } }) - ctx.signal.addEventListener("abort", () => timers.forEach(clearTimeout)) + if (!response.ok) throw new Error(`The changelog request failed with ${response.status}`) - fetch(CHANGELOG_URL, { signal: ctx.signal, headers: { Accept: "application/json" } }) - .then((response) => (response.ok ? response.json() : undefined)) - .then((json) => { - if (!json) return + return Option.match(decodeChangelog(await response.json()), { + onNone: () => [], + onSome: (changelog) => sliceHighlights(releases(changelog), input.current, input.previous), + }) +} - const highlights = Option.match(decodeChangelog(json), { - onNone: () => [], - onSome: (changelog) => sliceHighlights(releases(changelog), input.current, input.previous), - }) - - if (ctx.signal.aborted) return - - if (highlights.length === 0) return input.markSeen() - - timers.add( - setTimeout(() => { - input.markSeen() - ctx.dialogs.open((dialog) => , { - replace: true, - }) - }, 500), - ) - }) - .catch(() => undefined) +/** Opens What's New above any open dialog. */ +export function openWhatsNew(ctx: SetupContext, highlights: readonly Highlight[]) { + ctx.dialogs.open((dialog) => ) } function releases(changelog: typeof Changelog.Type) { @@ -182,7 +167,7 @@ function sliceHighlights(list: { tag?: string; highlights: Highlight[] }[], curr .slice(0, 5) } -function DialogReleaseNotes(props: { highlights: Highlight[]; dialog: DialogHandle }) { +function DialogReleaseNotes(props: { highlights: readonly Highlight[]; dialog: DialogHandle }) { const ctx = usePlugin() const [index, setIndex] = createSignal(0)