From 8288ef70ec4db247ea7c0ebc1d422ae89bb5c3a0 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Wed, 4 Nov 2026 22:49:05 -0600 Subject: [PATCH] fix(app): keep HostApis writes in call order with an explicit attach machine (#61916) --- .../src/runtime/plugin/attach-machine.test.ts | 174 ++++++++++++++++++ .../app/src/runtime/plugin/attach-machine.ts | 152 +++++++++++++++ packages/app/src/runtime/plugin/host-apis.tsx | 110 ++++++----- 3 files changed, 394 insertions(+), 42 deletions(-) create mode 100644 packages/app/src/runtime/plugin/attach-machine.test.ts create mode 100644 packages/app/src/runtime/plugin/attach-machine.ts diff --git a/packages/app/src/runtime/plugin/attach-machine.test.ts b/packages/app/src/runtime/plugin/attach-machine.test.ts new file mode 100644 index 00000000000..bca60c8c5b3 --- /dev/null +++ b/packages/app/src/runtime/plugin/attach-machine.test.ts @@ -0,0 +1,174 @@ +import { expect, test } from "bun:test" +import { + createHostApiAttachState, + HOST_API_MAX_QUEUE, + selectAttached, + transitionHostApiAttach, + type HostApiAttachEvent, + type HostApiAttachState, +} from "./attach-machine" + +type Mount = { readonly name: string } + +/** + * Drives the machine as the HostApis driver does: runs `run` effects at once, so a write can make another write, and + * records which write ran against which mount. + */ +function harness() { + const log: string[] = [] + const dropped: string[] = [] + const machine = { state: createHostApiAttachState() } + + const dispatch = (event: HostApiAttachEvent) => { + const next = transitionHostApiAttach(machine.state, event) + + machine.state = next.state + next.effects.forEach((effect) => { + if (effect.type === "run") effect.run(effect.attached) + + if (effect.type === "drop") effect.items.forEach((item) => item.onDrop?.()) + }) + + return next + } + + const write = (name: string, then?: () => void) => + dispatch({ + type: "write", + run: (mount) => { + log.push(`${name}@${mount.name}`) + then?.() + }, + onDrop: () => dropped.push(name), + }).queued + + const drain = (attempt: number) => { + while (machine.state.status === "draining" && machine.state.attempt === attempt) + dispatch({ type: "drain.next", attempt }) + } + + return { machine, log, dropped, dispatch, write, drain } +} + +const one = { name: "one" } + +const two = { name: "two" } + +// Before, the flush spliced the whole queue first, so a write made by a waiting write found it empty and ran at once, +// ahead of the writes still waiting. +test("a write made by a waiting write runs after the writes that waited before it", () => { + const run = harness() + + run.write("A", () => run.write("nested")) + run.write("B") + run.dispatch({ type: "attach", attached: one }) + run.drain(1) + + expect(run.log).toEqual(["A@one", "B@one", "nested@one"]) + expect(run.machine.state.status).toBe("live") +}) + +// Before, an empty queue at attach made writes during the interface's first render run in that render, while the same +// writes behind a waiting one ran after it. +test("a write made during the first render waits for the drain even when nothing waited before it", () => { + const run = harness() + const attached = run.dispatch({ type: "attach", attached: one }) + + run.write("render") + + expect({ effects: attached.effects, log: [...run.log], attached: selectAttached(run.machine.state) }).toEqual({ + effects: [{ type: "schedule.drain", attempt: 1 }], + log: [], + attached: one, + }) + run.drain(1) + run.write("live") + expect(run.log).toEqual(["render@one", "live@one"]) +}) + +test("a waiting write cancelled by an earlier one never runs", () => { + const run = harness() + const ids: number[] = [] + + run.write("A", () => run.dispatch({ type: "cancel", id: ids[0] ?? 0 })) + ids.push(run.write("B") ?? 0) + run.write("C") + run.dispatch({ type: "attach", attached: one }) + run.drain(1) + + expect(run.log).toEqual(["A@one", "C@one"]) +}) + +test("cancelling a write that already ran, or one never queued, changes nothing", () => { + const run = harness() + + run.dispatch({ type: "attach", attached: one }) + run.drain(1) + const live = run.machine.state + + expect(run.write("now")).toBeUndefined() + expect(transitionHostApiAttach(live, { type: "cancel", id: 7 }).state).toBe(live) +}) + +test("a detached queue past its cap drops the oldest write", () => { + const run = harness() + + Array.from({ length: HOST_API_MAX_QUEUE + 1 }, (_, index) => run.write(`w${index}`)) + + expect({ + dropped: run.dropped, + size: run.machine.state.status === "detached" ? run.machine.state.queue.length : -1, + }).toEqual({ dropped: ["w0"], size: HOST_API_MAX_QUEUE }) +}) + +test("disposal drops every waiting write and every later one", () => { + const run = harness() + + run.write("A") + run.write("B") + run.dispatch({ type: "disposed" }) + run.write("late") + run.dispatch({ type: "attach", attached: one }) + run.drain(1) + + expect({ dropped: run.dropped, log: run.log, status: run.machine.state.status }).toEqual({ + dropped: ["A", "B", "late"], + log: [], + status: "disposed", + }) +}) + +test("a detach while draining keeps the writes not run yet for the next mount", () => { + const run = harness() + + run.write("A", () => run.dispatch({ type: "detach", attempt: 1 })) + run.write("B") + run.dispatch({ type: "attach", attached: one }) + run.drain(1) + run.dispatch({ type: "attach", attached: two }) + run.drain(2) + + expect(run.log).toEqual(["A@one", "B@two"]) +}) + +test("a detach or drain of an earlier mount is ignored", () => { + const run = harness() + + run.write("A") + run.dispatch({ type: "attach", attached: one }) + run.dispatch({ type: "attach", attached: two }) + + const draining: HostApiAttachState = run.machine.state + + expect(transitionHostApiAttach(draining, { type: "detach", attempt: 1 }).state).toBe(draining) + expect(transitionHostApiAttach(draining, { type: "drain.next", attempt: 1 }).state).toBe(draining) + run.drain(2) + expect(run.log).toEqual(["A@two"]) + + const live = run.machine.state + + expect(transitionHostApiAttach(live, { type: "detach", attempt: 1 }).state).toBe(live) + run.dispatch({ type: "detach", attempt: 2 }) + expect(transitionHostApiAttach(run.machine.state, { type: "drain.next", attempt: 2 }).state).toBe(run.machine.state) + expect(selectAttached(run.machine.state)).toBeUndefined() +}) diff --git a/packages/app/src/runtime/plugin/attach-machine.ts b/packages/app/src/runtime/plugin/attach-machine.ts new file mode 100644 index 00000000000..2d861c99835 --- /dev/null +++ b/packages/app/src/runtime/plugin/attach-machine.ts @@ -0,0 +1,152 @@ +/** Writes waiting for the app interface beyond this drop the oldest, so a long detach cannot grow without bound. */ +export const HOST_API_MAX_QUEUE = 1024 + +export type QueuedHostWrite = { + readonly id: number + readonly run: (attached: A) => void + /** Settles a caller that waits on the write, such as a notification, when it is dropped instead of run. */ + readonly onDrop?: () => void +} + +/** + * The app interface as HostApis see it. `attempt` counts attaches, so a detach or drain of an earlier mount is + * ignored; `writeId` is the id last given to a queued write. + */ +export type HostApiAttachState = + /** Not mounted: writes wait, in call order. */ + | { + readonly status: "detached" + readonly attempt: number + readonly writeId: number + readonly queue: readonly QueuedHostWrite[] + } + /** + * Mounted, and the waiting writes run one at a time after its first render. A write made meanwhile, even by a + * waiting write, joins the end of the queue. + */ + | { + readonly status: "draining" + readonly attempt: number + readonly writeId: number + readonly attached: A + readonly queue: readonly QueuedHostWrite[] + } + /** Mounted with nothing waiting: writes run at once. */ + | { readonly status: "live"; readonly attempt: number; readonly writeId: number; readonly attached: A } + | { readonly status: "disposed" } + +export type HostApiAttachEvent = + | { readonly type: "attach"; readonly attached: A } + | { readonly type: "detach"; readonly attempt: number } + /** Runs the next waiting write of the mount `attempt`, or ends its drain. */ + | { readonly type: "drain.next"; readonly attempt: number } + | { readonly type: "write"; readonly run: (attached: A) => void; readonly onDrop?: () => void } + | { readonly type: "cancel"; readonly id: number } + | { readonly type: "disposed" } + +export type HostApiAttachEffect = + /** After the interface's first render, so the waiting writes find its layout. */ + | { readonly type: "schedule.drain"; readonly attempt: number } + | { readonly type: "run"; readonly attached: A; readonly run: (attached: A) => void } + | { readonly type: "drop"; readonly items: readonly QueuedHostWrite[] } + +export type HostApiAttachTransition = { + readonly state: HostApiAttachState + readonly effects: readonly HostApiAttachEffect[] + /** The id of a write this event queued, which `cancel` takes. */ + readonly queued?: number +} + +export function createHostApiAttachState(): HostApiAttachState { + return { status: "detached", attempt: 0, writeId: 0, queue: [] } +} + +export function transitionHostApiAttach( + state: HostApiAttachState, + event: HostApiAttachEvent, +): HostApiAttachTransition { + if (state.status === "disposed") { + if (event.type === "write" && event.onDrop) + return step(state, [drop([{ id: 0, run: event.run, onDrop: event.onDrop }])]) + + return step(state) + } + + if (event.type === "attach") { + const attempt = state.attempt + 1 + const queue = state.status === "live" ? [] : state.queue + + return step({ status: "draining", attempt, writeId: state.writeId, attached: event.attached, queue }, [ + { type: "schedule.drain", attempt }, + ]) + } + + if (event.type === "disposed") { + if (state.status === "live" || state.queue.length === 0) return step({ status: "disposed" }) + + return step({ status: "disposed" }, [drop(state.queue)]) + } + + if (state.status === "live") { + if (event.type === "write") return step(state, [{ type: "run", attached: state.attached, run: event.run }]) + + if (event.type === "detach" && event.attempt === state.attempt) + return step({ status: "detached", attempt: state.attempt, writeId: state.writeId, queue: [] }) + + return step(state) + } + + if (event.type === "write") { + const id = state.writeId + 1 + const item = { id, run: event.run, onDrop: event.onDrop } + const overflow = state.queue.length >= HOST_API_MAX_QUEUE ? state.queue.slice(0, 1) : [] + const queue = [...state.queue.slice(overflow.length), item] + + return { + state: { ...state, writeId: id, queue }, + effects: overflow.length > 0 ? [drop(overflow)] : [], + queued: id, + } + } + + if (event.type === "cancel") { + if (!state.queue.some((item) => item.id === event.id)) return step(state) + + return step({ ...state, queue: state.queue.filter((item) => item.id !== event.id) }) + } + + if (state.status === "detached" || event.attempt !== state.attempt) return step(state) + + if (event.type === "detach") + return step({ status: "detached", attempt: state.attempt, writeId: state.writeId, queue: state.queue }) + + const [head, ...rest] = state.queue + + if (!head) return step({ status: "live", attempt: state.attempt, writeId: state.writeId, attached: state.attached }) + + return step({ ...state, queue: rest }, [{ type: "run", attached: state.attached, run: head.run }]) +} + +/** The mounted interface, while draining or live. */ +export function selectAttached(state: HostApiAttachState) { + return state.status === "draining" || state.status === "live" ? state.attached : undefined +} + +export function selectAttachAttempt(state: HostApiAttachState) { + return state.status === "disposed" ? 0 : state.attempt +} + +export function selectDraining(state: HostApiAttachState, attempt: number) { + return state.status === "draining" && state.attempt === attempt +} + +function drop(items: readonly QueuedHostWrite[]): HostApiAttachEffect { + return { type: "drop", items } +} + +function step( + state: HostApiAttachState, + effects: readonly HostApiAttachEffect[] = [], +): HostApiAttachTransition { + return { state, effects } +} diff --git a/packages/app/src/runtime/plugin/host-apis.tsx b/packages/app/src/runtime/plugin/host-apis.tsx index cbe72867e1c..5139e45f124 100644 --- a/packages/app/src/runtime/plugin/host-apis.tsx +++ b/packages/app/src/runtime/plugin/host-apis.tsx @@ -6,6 +6,7 @@ import { createSignal, getOwner, on, + onCleanup, runWithOwner, untrack, type Accessor, @@ -55,6 +56,14 @@ import { formatKeybindParts, useCommand } from "@/shell/commands/command" import { createMediaQuery } from "@solid-primitives/media" import { useIsRouting, useLocation } from "@solidjs/router" import { useLanguage } from "@/runtime/i18n/language" +import { + createHostApiAttachState, + selectAttachAttempt, + selectAttached, + selectDraining, + transitionHostApiAttach, + type HostApiAttachEvent, +} from "./attach-machine" import { closedEntry, createClosedTabs } from "./closed-tabs" import { panelsMoving } from "@/shell/panel-motion" import { createEmbeds } from "./embeds" @@ -114,37 +123,51 @@ export function createHostApis() { const desktop = createMediaQuery("(min-width: 768px)") const narrow = () => !desktop() const systemDark = createMediaQuery("(prefers-color-scheme: dark)") - const [attached, setAttached] = createSignal() + // A plain signal: the interface holds live functions and SDK clients, which a store would wrap in proxies. + const [attachState, setAttachState] = createSignal(createHostApiAttachState()) + // A memo, so readers rerun when the interface mounts or detaches, not on every queued write. + const attached = createMemo(() => selectAttached(attachState())) const removed = new Set<(value: { server: string; directory: string }) => void>() const memory = new Map>() const current = () => attached() - // Writes made while the app interface is not mounted, in call order. - const early: ((value: Attached) => void)[] = [] // Removals of a session's store wait for its location, as layout writes do. const located = createLocatedWrites() - // Runs a write now when the interface is mounted and nothing waits before it; otherwise once it mounts. - const write = (run: (value: Attached) => void) => { - const value = untrack(attached) + const dispatchAttach = (event: HostApiAttachEvent) => { + const next = transitionHostApiAttach(untrack(attachState), event) - if (value && early.length === 0) return run(value) - early.push(run) + setAttachState(next.state) + next.effects.forEach((effect) => { + if (effect.type === "schedule.drain") return queueMicrotask(() => drain(effect.attempt)) + + if (effect.type === "drop") return effect.items.forEach((item) => item.onDrop?.()) + + // Promise.try runs each write synchronously and isolates a throw, such as an unlisted server, from the later ones. + void Promise.try(() => effect.run(effect.attached)).catch((cause: unknown) => console.error("[plugin]", cause)) + }) + + return next.queued } - // Promise.try runs each write synchronously and isolates a throw, such as an unlisted server, from the later ones. - const flush = () => { - const value = untrack(attached) + // Each step takes the next write off the queue before running it, so a throw cannot stall the writes behind it. + const drain = (attempt: number) => + batch(() => { + while (selectDraining(untrack(attachState), attempt)) dispatchAttach({ type: "drain.next", attempt }) + }) - if (!value) return - batch(() => - early - .splice(0) - .forEach( - (run) => void Promise.try(() => run(value)).catch((cause: unknown) => console.error("[plugin]", cause)), - ), - ) + // Runs a write now when the interface is mounted and nothing waits before it; otherwise once it mounts. Returns a + // cancel for a write that waits; `onDrop` runs instead of the write when it is dropped. + const write = (run: (value: Attached) => void, onDrop?: () => void) => { + const id = dispatchAttach({ type: "write", run, onDrop }) + + return () => { + if (id !== undefined) dispatchAttach({ type: "cancel", id }) + } } + // Writes still waiting when the plugin root goes away are dropped. + if (getOwner()) onCleanup(() => dispatchAttach({ type: "disposed" })) + const embeds = createEmbeds({ bridge: platform.plugins, zoom: () => platform.webviewZoom?.() ?? 1, @@ -381,15 +404,30 @@ export function createHostApis() { return { dismiss: runWithOwner(owner, () => register(dismiss)) ?? dismiss } }, }), - // The user's notification settings live in the app interface, so a notification waits for it to mount. + // The user's notification settings live in the app interface, so a notification waits for it to mount. One that + // the plugin going away or the host dropping it ends first resolves as not shown. attention: (plugin, _owner, context) => ({ notify: (options) => - new Promise((resolve) => - write((value) => { - if (context.signal.aborted) return resolve({ notification: false, sound: false }) + new Promise((resolve) => { + const skip = () => { + context.signal.removeEventListener("abort", abort) + resolve({ notification: false, sound: false }) + } + + const abort = () => { + cancel() + skip() + } + + if (context.signal.aborted) return skip() + context.signal.addEventListener("abort", abort, { once: true }) + + const cancel = write((value) => { + if (context.signal.aborted) return skip() + context.signal.removeEventListener("abort", abort) void value.notify(plugin, options).then(resolve) - }), - ), + }, skip) + }), }), // No command is registered before the interface mounts. commands: () => ({ run: (id) => untrack(attached)?.run(id) ?? false }), @@ -437,25 +475,13 @@ export function createHostApis() { * Runs `run` now while the app interface is mounted and no write waits; otherwise after the interface's first * render, behind the writes made before it. The returned function cancels a run that still waits. */ - whenMounted(run: () => void) { - const state = { cancelled: false } - - write(() => { - if (!state.cancelled) run() - }) - - return () => { - state.cancelled = true - } - }, + whenMounted: (run: () => void) => write(() => run()), + /** Writes that wait, and writes made during the interface's first render, run after that render in call order. */ attach(value: Attached) { - setAttached(() => value) - // After the interface's first render, so the waiting writes find its layout, in call order. - queueMicrotask(flush) + dispatchAttach({ type: "attach", attached: value }) + const attempt = selectAttachAttempt(untrack(attachState)) - return () => { - if (attached() === value) setAttached(undefined) - } + return () => void dispatchAttach({ type: "detach", attempt }) }, workspaceRemoved(value: { server: string; directory: string }) { removed.forEach((handler) => handler(value))