fix(desktop): settle renderer storage, plugin menubar and fullscreen seeds against live events (#62090)

This commit is contained in:
Luke Parker 2026-11-05 09:15:14 -06:00 • committed by GitHub
parent 6bd47192ac
commit d8cb7c73d0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 804 additions and 64 deletions

View file

@ -1,5 +1,6 @@
import type { DesktopMenuAction, DesktopZoomLevel } from "@opencode/app/desktop-menu"
import type { DesktopNativeBundle } from "@opencode/app/i18n/desktop-native"
import type { StorageSnapshot } from "../shared/ipc-transport"
import type { WindowBootstrap } from "../shared/window-bootstrap"
import type {
ClipboardImage,
@ -22,6 +23,8 @@ export type ElectronAPI = {
finishFirstLaunchOnboarding(createDefaultProject: boolean): Promise<string | null>
checkAppExists(appName: string): Promise<boolean>
resolveAppPath(appName: string): Promise<string | null>
/** The namespaces the preload read before the page ran; `createDesktopStorage` serves each first read from it. */
getStorageSnapshot(): Promise<StorageSnapshot>
storeItems(name: string): Promise<{ items: Record<string, string>; revision: number }>
storeUpdate(name: string, insert: Record<string, string>, remove: string[]): Promise<number>
storeClear(name: string): Promise<void>

View file

@ -17,9 +17,6 @@ const mutable = <Value>(value: Value) => value as Mutable<Value>
const toArrayBuffer = (value: Uint8Array) =>
value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength) as ArrayBuffer
// One renderer-side copy: the bridge clones on every crossing, so consumption is tracked here.
const seeded = window.electron.storageSnapshot.then((snapshot) => new Map(Object.entries(snapshot)))
export const api: ElectronAPI = {
awaitInitialization: () => invoke("AppAwaitInitialization"),
reconnectService: (signal) => cancellable("AppReconnectService", undefined, signal),
@ -31,17 +28,8 @@ export const api: ElectronAPI = {
invoke("AppFinishFirstLaunchOnboarding", { createDefaultProject }),
checkAppExists: (appName) => invoke("AppCheckAppExists", { appName }),
resolveAppPath: (appName) => invoke("AppResolveAppPath", { appName }),
// The first read of a namespace the preload already fetched is served from that snapshot; later
// reads (a window re-opening a namespace) go to the main process as usual.
storeItems: (name) =>
seeded.then((snapshot) => {
const item = snapshot.get(name)
if (!item) return invoke("StorageItems", { name }).then(mutable)
snapshot.delete(name)
return item
}),
getStorageSnapshot: () => window.electron.storageSnapshot,
storeItems: (name) => invoke("StorageItems", { name }).then(mutable),
storeUpdate: (name, insert, remove) => invoke("StorageUpdate", { name, insert, remove }),
storeClear: (name) => invoke("StorageClear", { name }),
onStoreChanged: (cb) =>

View file

@ -0,0 +1,132 @@
import { describe, expect, test } from "bun:test"
import {
createDesktopStorageState,
transitionDesktopStorage,
type DesktopStorageEffect,
type DesktopStorageEvent,
type DesktopStorageState,
type StorageItems,
} from "./storage-machine"
type Namespace = { readonly name: string }
const reply = () => Promise.withResolvers<StorageItems>()
function replay(events: readonly DesktopStorageEvent<Namespace>[], from = createDesktopStorageState<Namespace>()) {
return events.reduce<{ state: DesktopStorageState<Namespace>; effects: DesktopStorageEffect<Namespace>[] }>(
(run, event) => {
const next = transitionDesktopStorage(run.state, event)
return { state: next.state, effects: [...run.effects, ...next.effects] }
},
{ state: from, effects: [] },
)
}
// What each read was answered with: the seed it was served, or a trip to main.
function answers(effects: readonly DesktopStorageEffect<Namespace>[]) {
return effects.flatMap((effect): (StorageItems | string)[] => {
if (effect.type === "resolve-items") return [effect.value]
if (effect.type === "fetch-items") return [`fetch ${effect.name}`]
if (effect.type === "reject-items") return ["rejected"]
return []
})
}
const windowFile = "opencode.window.1.dat"
describe("preload snapshot seed", () => {
test("a change made before the window opened its namespace reaches the first read", () => {
const run = replay([
{ type: "snapshot.settled", snapshot: { [windowFile]: { items: { tabs: "old", stale: "x" }, revision: 3 } } },
{ type: "store.changed", name: windowFile, insert: { tabs: "new" }, remove: ["stale"], revision: 4 },
{ type: "items.requested", name: windowFile, reply: reply() },
{ type: "items.requested", name: windowFile, reply: reply() },
])
// On dev the change was dropped and the read got `{ tabs: "old", stale: "x" }` at revision 3.
expect(answers(run.effects)).toEqual([{ items: { tabs: "new" }, revision: 4 }, `fetch ${windowFile}`])
})
test("changes that arrive before the snapshot fold in only when newer than it", () => {
const run = replay([
{ type: "items.requested", name: "opencode.global.dat", reply: reply() },
{ type: "store.changed", name: "default.dat", insert: { theme: "older" }, remove: [], revision: 2 },
{ type: "store.changed", name: "default.dat", insert: { theme: "dark" }, remove: [], revision: 3 },
{
type: "snapshot.settled",
snapshot: {
"opencode.global.dat": { items: { a: "1" }, revision: 2 },
"default.dat": { items: { theme: "light", font: "mono" }, revision: 2 },
},
},
{ type: "items.requested", name: "default.dat", reply: reply() },
])
expect(answers(run.effects)).toEqual([
{ items: { a: "1" }, revision: 2 },
{ items: { theme: "dark", font: "mono" }, revision: 3 },
])
})
test("a change older than the seed leaves it alone", () => {
const run = replay([
{ type: "snapshot.settled", snapshot: { "default.dat": { items: { theme: "dark" }, revision: 5 } } },
{ type: "store.changed", name: "default.dat", insert: { theme: "light" }, remove: [], revision: 4 },
{ type: "items.requested", name: "default.dat", reply: reply() },
])
expect(answers(run.effects)).toEqual([{ items: { theme: "dark" }, revision: 5 }])
})
test("a namespace the snapshot lacks is read from main, never from its changes alone", () => {
const run = replay([
{ type: "store.changed", name: "other.dat", insert: { a: "1" }, remove: [], revision: 1 },
{ type: "snapshot.settled", snapshot: {} },
{ type: "store.changed", name: "other.dat", insert: { b: "2" }, remove: [], revision: 2 },
{ type: "items.requested", name: "other.dat", reply: reply() },
])
expect(answers(run.effects)).toEqual(["fetch other.dat"])
})
test("an opened namespace hears every change, before and after the snapshot", () => {
const namespace = { name: "default.dat" }
const run = replay([
{ type: "namespace.opened", name: "default.dat", namespace },
{ type: "store.changed", name: "default.dat", insert: { a: "1" }, remove: [], revision: 1 },
{ type: "snapshot.settled", snapshot: {} },
{ type: "store.changed", name: "default.dat", insert: {}, remove: ["a"], revision: 2 },
{ type: "store.changed", name: "other.dat", insert: { b: "2" }, remove: [], revision: 3 },
])
expect(run.effects).toEqual([
{ type: "accept-remote", namespace, insert: { a: "1" }, remove: [], revision: 1 },
{ type: "accept-remote", namespace, insert: {}, remove: ["a"], revision: 2 },
])
})
})
describe("disposal", () => {
test("rejects the reads still waiting for the snapshot and every later one", () => {
const namespace = { name: "default.dat" }
const run = replay([
{ type: "namespace.opened", name: "default.dat", namespace },
{ type: "items.requested", name: "default.dat", reply: reply() },
{ type: "disposed" },
{ type: "snapshot.settled", snapshot: { "default.dat": { items: {}, revision: 1 } } },
{ type: "store.changed", name: "default.dat", insert: { a: "1" }, remove: [], revision: 2 },
{ type: "items.requested", name: "default.dat", reply: reply() },
])
expect(answers(run.effects)).toEqual(["rejected", "rejected"])
expect(run.effects.some((effect) => effect.type === "accept-remote")).toBe(false)
// Queued writes still flush on pagehide through the namespaces opened before.
expect(run.state.opened.get("default.dat")).toBe(namespace)
})
})

View file

@ -0,0 +1,157 @@
import type { StorageSnapshot } from "../../shared/ipc-transport"
export type StorageItems = { items: Record<string, string>; revision: number }
/** Settles a namespace's `items(name)` read. */
export type StorageItemsReply = PromiseWithResolvers<StorageItems>
export type StorageChange = {
readonly name: string
readonly insert: Record<string, string>
readonly remove: string[]
readonly revision: number
}
// The preload asks main for the namespaces the shell reads first. Each namespace's first read is served from that
// snapshot, which follows main's changes until then, so a change another window made while this one booted is not lost.
// `seeding` holds the reads and changes that arrive before the snapshot does; `ready` holds the seeds not read yet.
// `opened` is every namespace this window opened, which hears main's changes directly.
export type DesktopStorageState<Namespace> =
| {
readonly status: "seeding"
readonly opened: ReadonlyMap<string, Namespace>
readonly reads: readonly { readonly name: string; readonly reply: StorageItemsReply }[]
readonly changes: readonly StorageChange[]
}
| {
readonly status: "ready"
readonly opened: ReadonlyMap<string, Namespace>
readonly seeds: ReadonlyMap<string, StorageItems>
}
| { readonly status: "disposed"; readonly opened: ReadonlyMap<string, Namespace> }
export type DesktopStorageEvent<Namespace> =
| { readonly type: "snapshot.settled"; readonly snapshot: StorageSnapshot }
| { readonly type: "namespace.opened"; readonly name: string; readonly namespace: Namespace }
| { readonly type: "items.requested"; readonly name: string; readonly reply: StorageItemsReply }
| ({ readonly type: "store.changed" } & StorageChange)
| { readonly type: "disposed" }
export type DesktopStorageEffect<Namespace> =
| { readonly type: "resolve-items"; readonly reply: StorageItemsReply; readonly value: StorageItems }
| { readonly type: "fetch-items"; readonly name: string; readonly reply: StorageItemsReply }
| { readonly type: "reject-items"; readonly reply: StorageItemsReply }
| ({ readonly type: "accept-remote"; readonly namespace: Namespace } & Omit<StorageChange, "name">)
export type DesktopStorageTransition<Namespace> = {
readonly state: DesktopStorageState<Namespace>
readonly effects: readonly DesktopStorageEffect<Namespace>[]
}
export function createDesktopStorageState<Namespace>(): DesktopStorageState<Namespace> {
return { status: "seeding", opened: new Map(), reads: [], changes: [] }
}
export function transitionDesktopStorage<Namespace>(
state: DesktopStorageState<Namespace>,
event: DesktopStorageEvent<Namespace>,
): DesktopStorageTransition<Namespace> {
if (event.type === "namespace.opened") {
if (state.opened.get(event.name) === event.namespace) return unchanged(state)
return { state: { ...state, opened: new Map(state.opened).set(event.name, event.namespace) }, effects: [] }
}
if (event.type === "disposed") {
if (state.status === "disposed") return unchanged(state)
return {
state: { status: "disposed", opened: state.opened },
effects:
state.status === "seeding" ? state.reads.map((read) => ({ type: "reject-items", reply: read.reply })) : [],
}
}
if (state.status === "disposed") {
if (event.type !== "items.requested") return unchanged(state)
return { state, effects: [{ type: "reject-items", reply: event.reply }] }
}
if (event.type === "store.changed") {
const namespace = state.opened.get(event.name)
const effects: DesktopStorageEffect<Namespace>[] = namespace
? [{ type: "accept-remote", namespace, insert: event.insert, remove: event.remove, revision: event.revision }]
: []
if (state.status === "seeding") return { state: { ...state, changes: [...state.changes, event] }, effects }
const seed = state.seeds.get(event.name)
if (!seed || event.revision <= seed.revision) return { state, effects }
return { state: { ...state, seeds: new Map(state.seeds).set(event.name, apply(seed, event)) }, effects }
}
if (event.type === "items.requested") {
if (state.status === "seeding") {
return { state: { ...state, reads: [...state.reads, { name: event.name, reply: event.reply }] }, effects: [] }
}
const seed = state.seeds.get(event.name)
if (!seed) return { state, effects: [{ type: "fetch-items", name: event.name, reply: event.reply }] }
const seeds = new Map(state.seeds)
seeds.delete(event.name)
return { state: { ...state, seeds }, effects: [{ type: "resolve-items", reply: event.reply, value: seed }] }
}
if (state.status === "ready") return unchanged(state)
// Changes main made after the snapshot was read are folded in; older ones are already part of it.
const seeds = new Map(
Object.entries(event.snapshot).map(([name, snapshot]): [string, StorageItems] => [
name,
state.changes.reduce(
(seed, change) => (change.name === name && change.revision > seed.revision ? apply(seed, change) : seed),
snapshot,
),
]),
)
// Reads that waited take their seed in order; a second read of the same namespace asks main.
const effects = state.reads.map((read): DesktopStorageEffect<Namespace> => {
const seed = seeds.get(read.name)
if (!seed) return { type: "fetch-items", name: read.name, reply: read.reply }
seeds.delete(read.name)
return { type: "resolve-items", reply: read.reply, value: seed }
})
return { state: { status: "ready", opened: state.opened, seeds }, effects }
}
export function selectOpenedNamespace<Namespace>(state: DesktopStorageState<Namespace>, name: string) {
return state.opened.get(name)
}
export function selectOpenedNamespaces<Namespace>(state: DesktopStorageState<Namespace>) {
return [...state.opened.values()]
}
function apply(seed: StorageItems, change: StorageChange): StorageItems {
const removed = new Set(change.remove)
return {
items: Object.fromEntries(
Object.entries({ ...seed.items, ...change.insert }).filter((entry) => !removed.has(entry[0])),
),
revision: change.revision,
}
}
function unchanged<Namespace>(state: DesktopStorageState<Namespace>): DesktopStorageTransition<Namespace> {
return { state, effects: [] }
}

View file

@ -5,19 +5,54 @@ import {
type NamespaceStorage,
type Platform,
} from "@opencode/app/desktop"
import { getOwner, onCleanup } from "solid-js"
import type { ElectronAPI } from "../api-types"
import { onBeforeDispose } from "../ipc-client"
import {
createDesktopStorageState,
selectOpenedNamespace,
selectOpenedNamespaces,
transitionDesktopStorage,
type DesktopStorageEffect,
type DesktopStorageEvent,
type StorageItems,
} from "./storage-machine"
export function createDesktopStorage(api: ElectronAPI) {
const namespaces = new Map<string, NamespaceStorage>()
const driver = { items: api.storeItems, update: api.storeUpdate, clear: api.storeClear }
let state = createDesktopStorageState<NamespaceStorage>()
const dispatch = (event: DesktopStorageEvent<NamespaceStorage>) => {
const next = transitionDesktopStorage(state, event)
state = next.state
next.effects.forEach(run)
}
const run = (effect: DesktopStorageEffect<NamespaceStorage>) => {
if (effect.type === "resolve-items") return effect.reply.resolve(effect.value)
if (effect.type === "fetch-items") return effect.reply.resolve(api.storeItems(effect.name))
if (effect.type === "reject-items") return effect.reply.reject(new Error("Desktop storage disposed"))
effect.namespace.accept(effect.insert, effect.remove, effect.revision)
}
const driver = {
items: (name: string) => {
const reply = Promise.withResolvers<StorageItems>()
dispatch({ type: "items.requested", name, reply })
return reply.promise
},
update: api.storeUpdate,
clear: api.storeClear,
}
const storage: NonNullable<Platform["storage"]> = (name = "default.dat") => {
const cached = namespaces.get(name)
const cached = selectOpenedNamespace(state, name)
if (cached) return cached
const next = createNamespaceStorage(driver, name)
namespaces.set(name, next)
dispatch({ type: "namespace.opened", name, namespace: next })
return next
}
@ -27,10 +62,26 @@ export function createDesktopStorage(api: ElectronAPI) {
const flush = () => {
flushPersisted()
return Promise.all([...namespaces.values()].map((namespace) => namespace.flush()))
return Promise.all(selectOpenedNamespaces(state).map((namespace) => namespace.flush()))
}
const stopStoreChanged = api.onStoreChanged((name, insert, remove, revision) =>
dispatch({ type: "store.changed", name, insert, remove, revision }),
)
void api.getStorageSnapshot().then(
(snapshot) => dispatch({ type: "snapshot.settled", snapshot }),
() => dispatch({ type: "snapshot.settled", snapshot: {} }),
)
// The flush hooks stay: writes already queued in the namespaces must still reach main.
if (getOwner()) {
onCleanup(() => {
stopStoreChanged()
dispatch({ type: "disposed" })
})
}
api.onStoreChanged((name, insert, remove, revision) => namespaces.get(name)?.accept(insert, remove, revision))
// Durability boundaries: the window going away, and it leaving the foreground.
onBeforeDispose(flush)
document.addEventListener("visibilitychange", () => {

View file

@ -0,0 +1,143 @@
import { describe, expect, test } from "bun:test"
import type { BridgeMenubarItem } from "@opencode/plugin/gui/host"
import {
createPluginBridgeState,
selectPluginSubscriptions,
transitionPluginBridge,
type PluginBridgeEffect,
type PluginBridgeEvent,
type PluginBridgeSubscription,
} from "./plugins-machine"
const subscribe = (): PluginBridgeSubscription => ({ listener: () => undefined })
const item = (id: string): BridgeMenubarItem => ({ menu: "file", id, label: id, enabled: true })
function replay(events: readonly PluginBridgeEvent[]) {
return events.reduce<{ state: ReturnType<typeof createPluginBridgeState>; effects: PluginBridgeEffect[] }>(
(run, event) => {
const next = transitionPluginBridge(run.state, event)
return { state: next.state, effects: [...run.effects, ...next.effects] }
},
{ state: createPluginBridgeState(), effects: [] },
)
}
// Who received which menubar items, in order.
function delivered(effects: readonly PluginBridgeEffect[], subscriptions: readonly PluginBridgeSubscription[]) {
return effects.flatMap((effect) =>
effect.type === "notify"
? [...effect.subscriptions].map((subscription) => [
subscriptions.indexOf(subscription),
effect.items.map((value) => value.id),
])
: [],
)
}
describe("menubar seed", () => {
test("a reply to an earlier attachment cannot overwrite the items a reattached window was given", () => {
const first = subscribe()
const second = subscribe()
const run = replay([
{ type: "listener.added", subscription: first },
{ type: "listener.removed", subscription: first },
{ type: "listener.added", subscription: second },
{ type: "menubar.seeded", attempt: 2, items: [item("b")] },
{ type: "menubar.seeded", attempt: 1, items: [item("a")] },
])
expect(delivered(run.effects, [first, second])).toEqual([[1, ["b"]]])
})
test("a subscriber that registers after the seed gets the current items", () => {
const first = subscribe()
const late = subscribe()
const run = replay([
{ type: "listener.added", subscription: first },
{ type: "menubar.seeded", attempt: 1, items: [item("a")] },
{ type: "listener.added", subscription: late },
])
expect(delivered(run.effects, [first, late])).toEqual([
[0, ["a"]],
[1, ["a"]],
])
expect(run.effects.filter((effect) => effect.type === "seed-menubar")).toHaveLength(1)
})
test("main's push wins over the seed still on its way", () => {
const first = subscribe()
const run = replay([
{ type: "listener.added", subscription: first },
{ type: "menubar.changed", items: [item("b")] },
{ type: "menubar.seeded", attempt: 1, items: [item("a")] },
])
expect(delivered(run.effects, [first])).toEqual([[0, ["b"]]])
})
test("a failed seed is asked again when the next subscriber registers, without attaching twice", () => {
const first = subscribe()
const second = subscribe()
const run = replay([
{ type: "listener.added", subscription: first },
{ type: "menubar.seed-failed", attempt: 1, cause: new Error("closed") },
{ type: "listener.added", subscription: second },
{ type: "menubar.seeded", attempt: 2, items: [item("a")] },
])
expect(run.effects.map((effect) => effect.type)).toEqual([
"attach",
"seed-menubar",
"log-seed-error",
"seed-menubar",
"notify",
])
expect(delivered(run.effects, [first, second])).toEqual([
[0, ["a"]],
[1, ["a"]],
])
})
})
describe("attachment", () => {
test("the same callback registered twice stays attached until both registrations stop", () => {
const listener = () => undefined
const first = { listener }
const second = { listener }
const one = replay([
{ type: "listener.added", subscription: first },
{ type: "listener.added", subscription: second },
{ type: "listener.removed", subscription: first },
])
expect([...selectPluginSubscriptions(one.state)]).toEqual([second])
expect(one.effects.some((effect) => effect.type === "detach")).toBe(false)
const none = transitionPluginBridge(one.state, { type: "listener.removed", subscription: second })
expect(none.state.status).toBe("detached")
expect(none.effects).toEqual([{ type: "detach" }])
})
test("disposal detaches and ignores everything after it", () => {
const first = subscribe()
const run = replay([
{ type: "listener.added", subscription: first },
{ type: "disposed" },
{ type: "menubar.seeded", attempt: 1, items: [item("a")] },
{ type: "listener.added", subscription: subscribe() },
])
expect(run.state.status).toBe("disposed")
expect(run.effects.map((effect) => effect.type)).toEqual(["attach", "seed-menubar", "detach"])
})
})

View file

@ -0,0 +1,129 @@
import type { BridgeMenubarItem, BridgeMessage } from "@opencode/plugin/gui/host"
/** One `bridge.on` call, so registering the same callback twice removes independently. */
export type PluginBridgeSubscription = { readonly listener: (message: BridgeMessage) => void }
type Subscriptions = ReadonlySet<PluginBridgeSubscription>
// The renderer listens to main's plugin events while any subscriber is registered. MenubarItem contributions change
// through events, so each attachment asks main once for the current items. `attempt` is the last ask; only the
// `seeding` one is current. A failed ask is retried when the next subscriber registers.
export type PluginBridgeState =
| { readonly status: "detached"; readonly attempt: number }
| { readonly status: "seeding"; readonly attempt: number; readonly subscriptions: Subscriptions }
| { readonly status: "unseeded"; readonly attempt: number; readonly subscriptions: Subscriptions }
| {
readonly status: "synced"
readonly attempt: number
readonly subscriptions: Subscriptions
readonly items: readonly BridgeMenubarItem[]
}
| { readonly status: "disposed" }
export type PluginBridgeEvent =
| { readonly type: "listener.added"; readonly subscription: PluginBridgeSubscription }
| { readonly type: "listener.removed"; readonly subscription: PluginBridgeSubscription }
| { readonly type: "menubar.changed"; readonly items: readonly BridgeMenubarItem[] }
| { readonly type: "menubar.seeded"; readonly attempt: number; readonly items: readonly BridgeMenubarItem[] }
| { readonly type: "menubar.seed-failed"; readonly attempt: number; readonly cause: unknown }
| { readonly type: "disposed" }
export type PluginBridgeEffect =
| { readonly type: "attach" }
| { readonly type: "detach" }
| { readonly type: "seed-menubar"; readonly attempt: number }
| { readonly type: "notify"; readonly subscriptions: Subscriptions; readonly items: readonly BridgeMenubarItem[] }
| { readonly type: "log-seed-error"; readonly cause: unknown }
export type PluginBridgeTransition = {
readonly state: PluginBridgeState
readonly effects: readonly PluginBridgeEffect[]
}
export function createPluginBridgeState(): PluginBridgeState {
return { status: "detached", attempt: 0 }
}
export function transitionPluginBridge(state: PluginBridgeState, event: PluginBridgeEvent): PluginBridgeTransition {
if (state.status === "disposed") return unchanged(state)
if (event.type === "disposed") {
return { state: { status: "disposed" }, effects: state.status === "detached" ? [] : [{ type: "detach" }] }
}
if (state.status === "detached") {
if (event.type !== "listener.added") return unchanged(state)
const attempt = state.attempt + 1
return {
state: { status: "seeding", attempt, subscriptions: new Set([event.subscription]) },
effects: [{ type: "attach" }, { type: "seed-menubar", attempt }],
}
}
if (event.type === "listener.added") {
if (state.subscriptions.has(event.subscription)) return unchanged(state)
const subscriptions = new Set(state.subscriptions).add(event.subscription)
if (state.status === "seeding") return { state: { ...state, subscriptions }, effects: [] }
// A late subscriber gets the items the others already have.
if (state.status === "synced") {
return {
state: { ...state, subscriptions },
effects: [{ type: "notify", subscriptions: new Set([event.subscription]), items: state.items }],
}
}
const attempt = state.attempt + 1
return { state: { status: "seeding", attempt, subscriptions }, effects: [{ type: "seed-menubar", attempt }] }
}
if (event.type === "listener.removed") {
if (!state.subscriptions.has(event.subscription)) return unchanged(state)
const subscriptions = new Set(state.subscriptions)
subscriptions.delete(event.subscription)
if (subscriptions.size === 0) {
return { state: { status: "detached", attempt: state.attempt }, effects: [{ type: "detach" }] }
}
return { state: { ...state, subscriptions }, effects: [] }
}
// Main's push is newer than any ask still on its way.
if (event.type === "menubar.changed") return synced(state, event.items)
if (state.status !== "seeding" || event.attempt !== state.attempt) return unchanged(state)
if (event.type === "menubar.seed-failed") {
return {
state: { status: "unseeded", attempt: state.attempt, subscriptions: state.subscriptions },
effects: [{ type: "log-seed-error", cause: event.cause }],
}
}
return synced(state, event.items)
}
/** Who hears main's other plugin events, which pass straight through. */
export function selectPluginSubscriptions(state: PluginBridgeState): Subscriptions {
return state.status === "detached" || state.status === "disposed" ? NO_SUBSCRIPTIONS : state.subscriptions
}
const NO_SUBSCRIPTIONS: Subscriptions = new Set()
function synced(
state: Extract<PluginBridgeState, { subscriptions: Subscriptions }>,
items: readonly BridgeMenubarItem[],
): PluginBridgeTransition {
return {
state: { status: "synced", attempt: state.attempt, subscriptions: state.subscriptions, items },
effects: [{ type: "notify", subscriptions: state.subscriptions, items }],
}
}
function unchanged(state: PluginBridgeState): PluginBridgeTransition {
return { state, effects: [] }
}

View file

@ -1,46 +1,82 @@
import { Predicate } from "effect"
import type { Bridge, BridgeMessage } from "@opencode/plugin/gui/host"
import type { PluginFailure } from "../shared/ipc-rpc/plugins"
import { getOwner, onCleanup } from "solid-js"
import { api } from "./api"
import { cancellable, invoke, listen, send } from "./ipc-client"
/** The listeners' attachment to main's plugin events, while any listener is registered. */
type Attachment = { stop?: () => void }
import {
createPluginBridgeState,
selectPluginSubscriptions,
transitionPluginBridge,
type PluginBridgeEffect,
type PluginBridgeEvent,
type PluginBridgeSubscription,
} from "./plugins-machine"
/** The renderer end of the GUI plugin bridge; main hosts every Ipc and embed. */
export function createPluginBridge(): Bridge {
const listeners = new Set<(message: BridgeMessage) => void>()
const dispatch = (message: BridgeMessage) => listeners.forEach((listener) => listener(message))
const attached: Attachment = {}
// MenubarItem contributions change through events; a window that starts listening late asks once.
const menubar = { revision: 0 }
let state = createPluginBridgeState()
// Edge handles only: the unsubscribers of main's plugin events while attached.
let stops: (() => void)[] = []
const attach = () => {
const stops = [
listen("PluginState", (event) => dispatch({ type: "state", ipc: event.ipc, state: event.state })),
listen("PluginEvent", (event) => dispatch({ type: "event", ipc: event.ipc, name: event.name, data: event.data })),
listen("PluginAvailable", (event) => dispatch({ type: "available", ipc: event.ipc, available: event.available })),
listen("PluginsChanged", (event) => dispatch({ type: "installed", list: event.list })),
listen("WindowFocusChanged", (event) => dispatch({ type: "focus", focused: event.focused })),
listen("PluginGuisChanged", (event) =>
dispatch({ type: "pluginGuis", plugins: event.plugins, reserved: event.reserved }),
),
listen("PluginMenubarItemsChanged", (event) => {
menubar.revision++
dispatch({ type: "menubarItems", items: event.items })
}),
]
const revision = menubar.revision
void invoke("PluginMenubarItems")
.then((items) => {
if (attached.stop && menubar.revision === revision) dispatch({ type: "menubarItems", items })
})
.catch((cause: unknown) => console.error("[plugin] menubar items failed", cause))
return () => stops.forEach((stop) => stop())
const dispatch = (event: PluginBridgeEvent) => {
const next = transitionPluginBridge(state, event)
state = next.state
next.effects.forEach(run)
}
const receive = (message: BridgeMessage) =>
selectPluginSubscriptions(state).forEach((subscription) => subscription.listener(message))
const run = (effect: PluginBridgeEffect) => {
if (effect.type === "attach") {
stops = [
listen("PluginState", (event) => receive({ type: "state", ipc: event.ipc, state: event.state })),
listen("PluginEvent", (event) =>
receive({ type: "event", ipc: event.ipc, name: event.name, data: event.data }),
),
listen("PluginAvailable", (event) =>
receive({ type: "available", ipc: event.ipc, available: event.available }),
),
listen("PluginsChanged", (event) => receive({ type: "installed", list: event.list })),
listen("WindowFocusChanged", (event) => receive({ type: "focus", focused: event.focused })),
listen("PluginGuisChanged", (event) =>
receive({ type: "pluginGuis", plugins: event.plugins, reserved: event.reserved }),
),
listen("PluginMenubarItemsChanged", (event) => dispatch({ type: "menubar.changed", items: event.items })),
]
return
}
if (effect.type === "detach") {
stops.forEach((stop) => stop())
stops = []
return
}
if (effect.type === "seed-menubar") {
void invoke("PluginMenubarItems").then(
(items) => dispatch({ type: "menubar.seeded", attempt: effect.attempt, items }),
(cause: unknown) => dispatch({ type: "menubar.seed-failed", attempt: effect.attempt, cause }),
)
return
}
if (effect.type === "log-seed-error") {
console.error("[plugin] menubar items failed", effect.cause)
return
}
const message: BridgeMessage = { type: "menubarItems", items: effect.items }
effect.subscriptions.forEach((subscription) => subscription.listener(message))
}
if (getOwner()) onCleanup(() => dispatch({ type: "disposed" }))
return {
packaged: api.getWindowBootstrap().packaged ?? false,
call: (input, signal) =>
@ -49,16 +85,10 @@ export function createPluginBridge(): Bridge {
}),
subscribe: (ipc) => invoke("PluginSubscribe", { ipc }),
on(listener) {
listeners.add(listener)
attached.stop ??= attach()
const subscription: PluginBridgeSubscription = { listener }
dispatch({ type: "listener.added", subscription })
return () => {
listeners.delete(listener)
if (listeners.size > 0) return
attached.stop?.()
attached.stop = undefined
}
return () => dispatch({ type: "listener.removed", subscription })
},
embed: (id, layout) => send("PluginEmbed", { id, layout }),
capture: (id) => invoke("PluginCapture", { id }).then((data) => data ?? undefined),

View file

@ -0,0 +1,54 @@
import { expect, test } from "bun:test"
import {
createFullscreenState,
selectWindowFullscreen,
transitionFullscreen,
type FullscreenEvent,
} from "./fullscreen-machine"
function replay(events: readonly FullscreenEvent[]) {
return events.reduce(transitionFullscreen, createFullscreenState())
}
test.each([
{
name: "a late boot read cannot undo leaving fullscreen",
events: [
{ type: "fullscreen.changed", fullscreen: false },
{ type: "fullscreen.seeded", fullscreen: true },
],
fullscreen: false,
},
{
name: "a late boot read cannot undo entering fullscreen",
events: [
{ type: "fullscreen.changed", fullscreen: true },
{ type: "fullscreen.seeded", fullscreen: false },
],
fullscreen: true,
},
{
name: "the boot read seeds the window",
events: [{ type: "fullscreen.seeded", fullscreen: true }],
fullscreen: true,
},
{
name: "a failed boot read draws the window windowed until main reports a change",
events: [{ type: "fullscreen.seed-failed" }],
fullscreen: false,
},
{
name: "events after a failed boot read still apply",
events: [{ type: "fullscreen.seed-failed" }, { type: "fullscreen.changed", fullscreen: true }],
fullscreen: true,
},
] satisfies { name: string; events: FullscreenEvent[]; fullscreen: boolean }[])("$name", (item) => {
expect(selectWindowFullscreen(replay(item.events))).toBe(item.fullscreen)
})
test("a repeated value keeps the same state so the signal is not written", () => {
const state = replay([{ type: "fullscreen.changed", fullscreen: true }])
expect(transitionFullscreen(state, { type: "fullscreen.changed", fullscreen: true })).toBe(state)
expect(transitionFullscreen(state, { type: "fullscreen.seeded", fullscreen: true })).toBe(state)
})

View file

@ -0,0 +1,34 @@
// `seeded` turns on with the first answer or main event, so a late boot read cannot overwrite a newer event.
export type FullscreenState =
| { readonly status: "unseeded" }
| { readonly status: "seeded"; readonly fullscreen: boolean }
export type FullscreenEvent =
| { readonly type: "fullscreen.seeded"; readonly fullscreen: boolean }
| { readonly type: "fullscreen.seed-failed" }
| { readonly type: "fullscreen.changed"; readonly fullscreen: boolean }
const UNSEEDED: FullscreenState = Object.freeze({ status: "unseeded" })
const WINDOWED: FullscreenState = Object.freeze({ status: "seeded", fullscreen: false })
const FULLSCREEN: FullscreenState = Object.freeze({ status: "seeded", fullscreen: true })
export function createFullscreenState() {
return UNSEEDED
}
export function transitionFullscreen(state: FullscreenState, event: FullscreenEvent): FullscreenState {
if (event.type === "fullscreen.changed") return event.fullscreen ? FULLSCREEN : WINDOWED
if (state.status === "seeded") return state
// A window whose state main could not report is drawn windowed, as before the first answer.
if (event.type === "fullscreen.seed-failed") return WINDOWED
return event.fullscreen ? FULLSCREEN : WINDOWED
}
export function selectWindowFullscreen(state: FullscreenState) {
return state.status === "seeded" && state.fullscreen
}

View file

@ -1,10 +1,29 @@
import { createSignal } from "solid-js"
import { api } from "../api"
import {
createFullscreenState,
selectWindowFullscreen,
transitionFullscreen,
type FullscreenEvent,
} from "./fullscreen-machine"
const [windowFullscreen, setWindowFullscreen] = createSignal(false)
let state = createFullscreenState()
api.onWindowFullscreenChanged(setWindowFullscreen)
const [windowFullscreen, setWindowFullscreen] = createSignal(selectWindowFullscreen(state))
void api.getWindowFullscreen().then(setWindowFullscreen)
const dispatch = (event: FullscreenEvent) => {
const next = transitionFullscreen(state, event)
if (next === state) return
state = next
setWindowFullscreen(selectWindowFullscreen(state))
}
api.onWindowFullscreenChanged((fullscreen) => dispatch({ type: "fullscreen.changed", fullscreen }))
void api.getWindowFullscreen().then(
(fullscreen) => dispatch({ type: "fullscreen.seeded", fullscreen }),
() => dispatch({ type: "fullscreen.seed-failed" }),
)
export { windowFullscreen }