From 9dc81059eeb30652ee79477533c6d71c9fc992a8 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:17:13 -0600 Subject: [PATCH] refactor(gui-plugins): never share machine state objects that reach a Solid store (#61874) --- packages/app/AGENTS.md | 2 +- .../src/file/link-open-machine.test.ts | 12 +++++---- .../gui-plugins/src/file/link-open-machine.ts | 6 ++++- .../src/file/picker-machine.test.ts | 4 +-- .../gui-plugins/src/file/picker-machine.ts | 21 ++++++++++----- packages/gui-plugins/src/file/renderer.tsx | 6 ++--- packages/gui-plugins/src/wsl/machine.test.ts | 18 +++++++++++++ packages/gui-plugins/src/wsl/machine.ts | 27 ++++++++++++------- 8 files changed, 68 insertions(+), 28 deletions(-) diff --git a/packages/app/AGENTS.md b/packages/app/AGENTS.md index 739c03d615b..412d1898e9c 100644 --- a/packages/app/AGENTS.md +++ b/packages/app/AGENTS.md @@ -41,7 +41,7 @@ This section is the single source for lifecycle state across `app`, `ui`, `sessi - A result that arrives late can still have side effects. When the user went back but the server already saved the change (a key, a credential), keep the state and emit only the refresh effect. When a timeout cuts a batch short, report the real outcome of the parts that finished and time out only the rest. - Serialize operations that touch the same data through one queue in the machine (`active` plus `pending`), including actions that look independent (steer, remove, reorder, undo). A side path that skips the queue can resurrect what another operation removed. - On an identity change (another session, server, window or credential), move to a new target with a new attempt instead of carrying the previous target's error, controller or result forward. -- On hot paths (scroll, pointer, resize, streaming), keep the machine allocation-free: return the same object when nothing changes, reuse event objects, and keep frozen singleton states. Benchmark with strobe as the Priorities section requires. +- On hot paths (scroll, pointer, resize, streaming), keep the machine allocation-free: return the same object when nothing changes, reuse event objects, and keep frozen singleton states. Benchmark with strobe as the Priorities section requires. Shared or frozen singleton states are safe only in signals and plain variables. Solid store writes (`setStore(path, obj)`, `reconcile`) merge into the object already in the store, so state written into a store never shares an object between two entries or with a module constant: replace it whole (`produce` replacement, or a signal), or build fresh objects with a factory (`createFileTreeState()`), and test through the real store with two entries. - Test the pure transition. Replay the bug's event sequence as a regression that fails on the old logic, then cover stale attempts and every exit (success, failure, timeout, cancel, dispose). Build events the way production builds them (through the real decoder, without fields the wire never carries), or the test passes on routes production never takes. These tests need no DOM, timers or mocks. - Name new driver inputs so they cannot collide with existing ones (`appState`, not a second `state`), and wire Solid reads of machine state into `` and `` with keyed matches or memos so a branch never reads a value another branch already narrowed. diff --git a/packages/gui-plugins/src/file/link-open-machine.test.ts b/packages/gui-plugins/src/file/link-open-machine.test.ts index bae7af8a640..22d90d6ba20 100644 --- a/packages/gui-plugins/src/file/link-open-machine.test.ts +++ b/packages/gui-plugins/src/file/link-open-machine.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test" import { LINK_OPEN_TIMEOUT_MS, - initialLinkOpenState, + createLinkOpenState, transitionLinkOpen, type LinkOpenEvent, type LinkOpenState, @@ -37,7 +37,7 @@ const synced = (attempt: number, fields: Partial +const replay = (events: readonly LinkOpenEvent[], state: LinkOpenState = createLinkOpenState()) => events.reduce((last, event) => transitionLinkOpen(last.state, event), { state, effects: [] }) describe("transitionLinkOpen", () => { @@ -92,7 +92,7 @@ describe("transitionLinkOpen", () => { }) test("a click claims an attempt and starts resolving before any await", () => { - expect(transitionLinkOpen(initialLinkOpenState, { ...click, base: "docs" })).toEqual({ + expect(transitionLinkOpen(createLinkOpenState(), { ...click, base: "docs" })).toEqual({ state: { status: "resolving", attempt: 1, @@ -245,7 +245,9 @@ describe("transitionLinkOpen", () => { const loading = replay([click, resolvedFile(1)]) expect(transitionLinkOpen(loading.state, resolvedFile(1)).state).toBe(loading.state) - expect(transitionLinkOpen(initialLinkOpenState, resolvedFile(0)).state).toBe(initialLinkOpenState) + const idle = createLinkOpenState() + + expect(transitionLinkOpen(idle, resolvedFile(0)).state).toBe(idle) }) test("disposal aborts the click in flight and ignores everything after it", () => { @@ -254,6 +256,6 @@ describe("transitionLinkOpen", () => { expect(disposed).toEqual({ state: { status: "disposed" }, effects: [{ type: "abort", attempt: 1 }] }) expect(transitionLinkOpen(disposed.state, click).state).toBe(disposed.state) expect(transitionLinkOpen(disposed.state, resolvedFile(1)).effects).toEqual([]) - expect(transitionLinkOpen(initialLinkOpenState, { type: "disposed" }).effects).toEqual([]) + expect(transitionLinkOpen(createLinkOpenState(), { type: "disposed" }).effects).toEqual([]) }) }) diff --git a/packages/gui-plugins/src/file/link-open-machine.ts b/packages/gui-plugins/src/file/link-open-machine.ts index ac27168949a..3b5fc3b56f9 100644 --- a/packages/gui-plugins/src/file/link-open-machine.ts +++ b/packages/gui-plugins/src/file/link-open-machine.ts @@ -112,7 +112,11 @@ export type LinkOpenEffect = export type LinkOpenTransition = { readonly state: LinkOpenState; readonly effects: readonly LinkOpenEffect[] } -export const initialLinkOpenState: LinkOpenState = { status: "idle", issued: 0 } +// A fresh object, never a shared constant: the renderer keeps this state in a Solid store, which writes into the +// objects it holds. +export function createLinkOpenState(): LinkOpenState { + return { status: "idle", issued: 0 } +} const NONE: readonly LinkOpenEffect[] = [] diff --git a/packages/gui-plugins/src/file/picker-machine.test.ts b/packages/gui-plugins/src/file/picker-machine.test.ts index 3d41f70943f..666bc1de704 100644 --- a/packages/gui-plugins/src/file/picker-machine.test.ts +++ b/packages/gui-plugins/src/file/picker-machine.test.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test" import { PICKER_FOCUS_TIMEOUT_MS, PICKER_MAX_SESSIONS, - initialPickerState, + createPickerState, pickerBrowsing, pickerFilterText, pickerFocusRequest, @@ -29,7 +29,7 @@ const openedMobile: PickerEvent = { } // Folds the events in order and returns the last transition. -const replay = (events: readonly PickerEvent[], state: PickerState = initialPickerState) => +const replay = (events: readonly PickerEvent[], state: PickerState = createPickerState()) => events.reduce((last, event) => transitionPicker(last.state, event), { state, effects: [] }) describe("transitionPicker", () => { diff --git a/packages/gui-plugins/src/file/picker-machine.ts b/packages/gui-plugins/src/file/picker-machine.ts index 297808e6553..2a10b3b175a 100644 --- a/packages/gui-plugins/src/file/picker-machine.ts +++ b/packages/gui-plugins/src/file/picker-machine.ts @@ -69,9 +69,15 @@ const NONE: readonly PickerEffect[] = [] const CANCEL: readonly PickerEffect[] = [{ type: "cancel-focus-timer" }] -const NO_FOCUS: PickerFocus = { status: "none" } +// Fresh objects, never shared constants: the renderer keeps this state in a Solid store, which writes into the +// objects it holds. +export function createPickerState(): PickerState { + return { status: "active", issued: 0, filters: {}, focus: noFocus() } +} -export const initialPickerState: PickerState = { status: "active", issued: 0, filters: {}, focus: NO_FOCUS } +function noFocus(): PickerFocus { + return { status: "none" } +} export function transitionPicker(state: PickerState, event: PickerEvent): PickerTransition { if (state.status === "disposed") return { state, effects: NONE } @@ -82,7 +88,8 @@ export function transitionPicker(state: PickerState, event: PickerEvent): Picker if (event.type === "picker.opened") { const filters = patch(state.filters, event.sessionKey, { text: event.query, browsing: true }) - if (event.background) return update(state, filters, ownedBy(state.focus, event.sessionKey) ? NO_FOCUS : state.focus) + if (event.background) + return update(state, filters, ownedBy(state.focus, event.sessionKey) ? noFocus() : state.focus) const request = state.issued + 1 @@ -106,7 +113,7 @@ export function transitionPicker(state: PickerState, event: PickerEvent): Picker return update( state, patch(state.filters, event.sessionKey, { browsing: event.browsing }), - cancel ? NO_FOCUS : state.focus, + cancel ? noFocus() : state.focus, ) } @@ -114,7 +121,7 @@ export function transitionPicker(state: PickerState, event: PickerEvent): Picker return update( state, patch(state.filters, event.sessionKey, { browsing: false }), - ownedBy(state.focus, event.sessionKey) ? NO_FOCUS : state.focus, + ownedBy(state.focus, event.sessionKey) ? noFocus() : state.focus, ) if (event.type === "launcher.closed") { @@ -123,12 +130,12 @@ export function transitionPicker(state: PickerState, event: PickerEvent): Picker state.focus.target.kind === "launcher" && state.focus.target.tabId === event.tabId - return update(state, state.filters, cancel ? NO_FOCUS : state.focus) + return update(state, state.filters, cancel ? noFocus() : state.focus) } const ended = state.focus.status === "requested" && state.focus.request === event.request - return update(state, state.filters, ended ? NO_FOCUS : state.focus) + return update(state, state.filters, ended ? noFocus() : state.focus) } export function pickerFilterText(state: PickerState, sessionKey: string) { diff --git a/packages/gui-plugins/src/file/renderer.tsx b/packages/gui-plugins/src/file/renderer.tsx index faeb8223547..913c69fecda 100644 --- a/packages/gui-plugins/src/file/renderer.tsx +++ b/packages/gui-plugins/src/file/renderer.tsx @@ -54,7 +54,7 @@ import { type LinkExistsState, } from "./link-exists-machine" import { - initialLinkOpenState, + createLinkOpenState, transitionLinkOpen, type LinkOpenEffect, type LinkOpenEvent, @@ -63,7 +63,7 @@ import { } from "./link-open-machine" import { fileTabId, fileTabPath, isFileTab, workspaceFileUrl } from "./path" import { - initialPickerState, + createPickerState, pickerBrowsing, pickerFilterText, pickerFocusRequest, @@ -117,7 +117,7 @@ const setup: Plugin.Setup = (ctx) => { const preference = desktop ? ctx.stores.app : undefined const [request, setRequest] = createStore<{ app?: OpenApp }>({}) - const [machines, setMachines] = createStore({ linkOpen: initialLinkOpenState, picker: initialPickerState }) + const [machines, setMachines] = createStore({ linkOpen: createLinkOpenState(), picker: createPickerState() }) const revealListeners = new Map void>>() const linkAttempts = new Map() diff --git a/packages/gui-plugins/src/wsl/machine.test.ts b/packages/gui-plugins/src/wsl/machine.test.ts index 0636a7faefc..6af4b7ebd92 100644 --- a/packages/gui-plugins/src/wsl/machine.test.ts +++ b/packages/gui-plugins/src/wsl/machine.test.ts @@ -312,3 +312,21 @@ describe("host jobs", () => { expect(toServersState(settled.state)).toMatchObject({ hostJob: "idle", runtime }) }) }) + +describe("servers state", () => { + // Windows reconcile this state into a Solid store, which writes into the objects it holds: a shared runtime + // object would let starting one server rewrite another's row. + test("stopped servers never share a runtime object, open or closed", () => { + const open = createWslMachineState([ubuntu, { id: "wsl:Debian", distro: "Debian" }]) + const closed = transitionWslMachine(open, { type: "close" }).state + + const runtimes = [open, closed].map((state) => toServersState(state).servers.map((server) => server.runtime)) + + expect(runtimes).toEqual([ + [{ kind: "stopped" }, { kind: "stopped" }], + [{ kind: "stopped" }, { kind: "stopped" }], + ]) + expect(runtimes[0]?.[0]).not.toBe(runtimes[0]?.[1]) + expect(runtimes[1]?.[0]).not.toBe(runtimes[1]?.[1]) + }) +}) diff --git a/packages/gui-plugins/src/wsl/machine.ts b/packages/gui-plugins/src/wsl/machine.ts index 0f4584bd9a7..a7cde1a53e4 100644 --- a/packages/gui-plugins/src/wsl/machine.ts +++ b/packages/gui-plugins/src/wsl/machine.ts @@ -155,9 +155,15 @@ export type WslMachineTransition = { readonly effects: readonly WslMachineEffect[] } -const STOPPED: WslServer = { kind: "stopped" } +// Fresh objects, never shared constants: windows reconcile `toServersState` into a Solid store, which writes into +// the objects it holds, so two servers must never share one runtime object. +function stoppedServer(): WslServer { + return { kind: "stopped" } +} -const IDLE: WslDistro = { status: "idle", server: STOPPED } +function idleDistro(): WslDistro { + return { status: "idle", server: stoppedServer() } +} export function createWslMachineState(configured: readonly WslServerConfig[]): WslMachineState { return { @@ -244,7 +250,7 @@ export function toServersState(state: WslMachineState): WslServersState { pendingRestart: state.pendingRestart, servers: state.configured.map((config) => ({ config, - runtime: open ? serverRuntime(distroOf(open, config.distro)) : STOPPED, + runtime: open ? serverRuntime(distroOf(open, config.distro)) : stoppedServer(), })), hostJob: open?.host.status ?? "idle", distroJobs: Object.fromEntries( @@ -383,7 +389,7 @@ function distroInstalled( distroProbes: { ...state.distroProbes, [event.distro]: event.probe }, } - return next(put(installed, event.distro, IDLE), [resolve(event.attempt)]) + return next(put(installed, event.distro, idleDistro()), [resolve(event.attempt)]) } // Updating stops the distro's server first, even one still starting, and starts it again once the CLI matches. @@ -416,7 +422,8 @@ function cliInstalled(state: OpenState, event: { distro: string; attempt: string if (current.status !== "updating" || current.attempt !== event.attempt) return next(state) const checked = withCheck(state, event.distro, event.check) - if (!configuredDistro(state, event.distro)) return next(put(checked, event.distro, IDLE), [resolve(event.attempt)]) + if (!configuredDistro(state, event.distro)) + return next(put(checked, event.distro, idleDistro()), [resolve(event.attempt)]) return next(put(checked, event.distro, { status: "starting", attempt: event.attempt }), [ { type: "spawn", distro: event.distro, attempt: event.attempt }, @@ -438,7 +445,7 @@ function jobFailed( } const checked = event.check ? withCheck(state, event.distro, event.check) : state - const idle: WslDistro = current.status === "probing" ? { status: "idle", server: current.server } : IDLE + const idle: WslDistro = current.status === "probing" ? { status: "idle", server: current.server } : idleDistro() return next(put(checked, event.distro, idle), [reject(event.attempt, { kind: "error", message: event.message })]) } @@ -590,16 +597,18 @@ function cliChecked(state: OpenState, distro: string, check: WslOpencodeCheck) { function serverRuntime(job: WslDistro): WslServerRuntime { if (job.status === "starting") return { kind: "starting" } - if (job.status !== "idle" && job.status !== "probing") return STOPPED + if (job.status !== "idle" && job.status !== "probing") return stoppedServer() if (job.server.kind === "ready") return { kind: "ready", url: job.server.url, password: job.server.password } - return job.server + if (job.server.kind === "failed") return { kind: "failed", message: job.server.message } + + return stoppedServer() } // A distro without a job is idle with no server. function distroOf(state: OpenState, distro: string): WslDistro { - return state.distros[distro] ?? IDLE + return state.distros[distro] ?? idleDistro() } function needsCliCheck(state: OpenState, distro: string) {