fix(app): give plugin startup an explicit gate that always opens (#61580)

This commit is contained in:
Luke Parker
2026-11-04 10:53:59 -06:00
committed by GitHub
Unverified
parent 7ebb13eda3
commit 605e912fda
13 changed files with 761 additions and 199 deletions
@@ -38,8 +38,7 @@ import { Persist, persisted } from "@/runtime/persistence/storage"
import { ServerScope } from "@/runtime/server/scope"
import { PluginHostProvider, usePluginHost, type HostApiFactories } from "../src/runtime/plugin/host"
import { createHostApis } from "../src/runtime/plugin/host-apis"
import { createInstalled } from "../src/runtime/plugin/installed"
import { pluginEnabled, type Entry } from "@opencode/plugin/gui/host"
import type { Bridge, Entry } from "@opencode/plugin/gui/host"
import { createRegion, RegionContent } from "../src/runtime/plugin/panels"
import { createSessionScreenLayout } from "../src/session/screen-layout"
import type { SessionModel } from "../src/session/model"
@@ -232,7 +231,7 @@ export function mountPluginHost() {
export function mountPlugins(input: {
definitions: readonly Entry[]
disabled?: readonly string[]
bridge?: Parameters<typeof createInstalled>[0]
bridge?: Bridge
stored?: Readonly<Record<string, Json>>
/** Shows the production Extensions › Plugins rows of the desktop app's own server, which lists these plugins. */
plugins?: readonly PluginInfo[]
@@ -282,36 +281,6 @@ export function mountPlugins(input: {
remove() {},
})
function MountedHost() {
const installed = input.bridge ? createInstalled(input.bridge) : undefined
const disabledState = createMemo(() => {
if (!installed) return disabled()
const state = installed.enableState()
if (!state) return undefined
return new Set(
definitions().flatMap((definition) =>
pluginEnabled({ id: definition.id, builtin: false }, state) ? [] : [definition.id],
),
)
})
return (
<PluginHostProvider
definitions={definitions}
disabled={disabledState}
apis={fakeApis(storage)}
whenMounted={mounted}
ipc={input.ipc}
>
<Capture />
</PluginHostProvider>
)
}
function Capture() {
const host = usePluginHost()
hosts.push(host)
@@ -335,7 +304,17 @@ export function mountPlugins(input: {
<PlatformProvider value={platform}>
<LanguageProvider locale="en">
<DialogProvider>
<MountedHost />
{/* With a bridge, main's plugin manager holds the enable settings, as in a desktop window. */}
<PluginHostProvider
definitions={definitions}
disabled={input.bridge ? undefined : disabled}
bridge={input.bridge}
apis={fakeApis(storage)}
whenMounted={mounted}
ipc={input.ipc}
>
<Capture />
</PluginHostProvider>
</DialogProvider>
</LanguageProvider>
</PlatformProvider>
@@ -13,7 +13,6 @@ import { showToast } from "@/shell/notifications/toast"
import "@/settings/settings.css"
import { builtins } from "./builtins"
import { usePluginHost } from "./host"
import { createInstalled } from "./installed"
import { useReservedPlugins } from "./root"
/**
@@ -55,14 +54,13 @@ function OwnServerPlugins(props: { plugins: readonly PluginInfo[] }) {
const language = useLanguage()
const host = usePluginHost()
const bridge = usePlatform().plugins
const installed = createInstalled(bridge)
const reserved = useReservedPlugins()
const builtin = (id: string) => builtins.some((definition) => definition.id === id)
// A server plugin's id can be a built-in's (a reserved id), so each row looks up its own kind of item.
const itemOf = (id: string, kind: "builtin" | "config") =>
installed.list().find((item) => item.id === id && item.builtin === (kind === "builtin"))
host.installed().find((item) => item.id === id && item.builtin === (kind === "builtin"))
const defined = (id: string) => !builtin(id) && host.definitions().some((definition) => definition.id === id)
@@ -90,7 +88,7 @@ function OwnServerPlugins(props: { plugins: readonly PluginInfo[] }) {
return [
...new Set([
...host.definitions().flatMap((definition) => (builtin(definition.id) ? [] : [definition.id])),
...installed.list().flatMap((item) => (item.builtin ? [] : [item.id])),
...host.installed().flatMap((item) => (item.builtin ? [] : [item.id])),
...reserved(),
]),
].filter((id) => !named.has(id))
@@ -212,7 +210,7 @@ function OwnServerPlugins(props: { plugins: readonly PluginInfo[] }) {
<For each={unnamed()}>{(id) => row({ id, name: id })}</For>
<For each={failedBuiltins()}>{(id) => row({ id, name: id, builtin: true })}</For>
</SettingsList>
<Show when={installed.list().some((item) => !item.builtin)}>
<Show when={host.installed().some((item) => !item.builtin)}>
<p class="text-11-regular text-v2-text-text-muted">{language.t("settings.plugins.parts.note")}</p>
</Show>
</>
+62 -31
View File
@@ -21,7 +21,7 @@ import {
type ParentProps,
} from "solid-js"
import { createStore } from "solid-js/store"
import { LifetimeContext, liveAccessor, PluginContext, type Entry } from "@opencode/plugin/gui/host"
import { LifetimeContext, liveAccessor, PluginContext, type Bridge, type Entry } from "@opencode/plugin/gui/host"
import type { BuiltinCatalog, BuiltinContext } from "@opencode/plugin/gui/builtin"
import { Predicate } from "effect"
import { useDialog } from "@opencode/ui/context/dialog"
@@ -52,6 +52,8 @@ import {
import { OpenCode, type OpenCodeClient } from "@opencode/client/promise"
import { useLanguage } from "@/runtime/i18n/language"
import { PluginAlertDialog, PluginConfirmDialog, PluginPromptDialog, PluginSelectDialog } from "./dialogs"
import { selectDisabled, selectHostReady, selectInstalled, selectMainFailed, selectServersReady } from "./machine"
import { createStartupGate } from "./startup"
import { createSessionStore, whenLoaded } from "./stores"
type Contribution = { key: string; registry: string; plugin: string; value: Accessor<unknown> }
@@ -134,7 +136,14 @@ export function usePluginHost() {
type HostInput = {
definitions: Accessor<readonly Entry[]>
disabled: Accessor<ReadonlySet<string> | undefined>
/** The plugins that stay off. Omitted with a bridge, whose plugin manager holds the user's settings. */
disabled?: Accessor<ReadonlySet<string>>
/** Main's side of a desktop window: its plugin manager lists the plugins and their enable settings. */
bridge?: Bridge
/** The ids of the plugins that ship with the app, which always run. */
builtins?: ReadonlySet<string>
/** Startup also waits for the servers plugins contribute (`PluginServersProvider`). */
servers?: boolean
apis: HostApiFactories
/**
* Runs `run` once the app interface has mounted, behind the HostApis writes made before it, or now when it has.
@@ -147,8 +156,6 @@ type HostInput = {
plugin?: (id: string) => PluginInput | undefined
/** How many times an Ipc became available. Reactive. */
generation?: (token: Ipc) => number
/** A plugin's main entry failed. Reactive. */
failed?: (id: string) => boolean
}
export function PluginHostProvider(props: ParentProps<HostInput>) {
@@ -180,6 +187,26 @@ function createHost(input: HostInput) {
const all = input.definitions
// The definitions the host starts with (the built-ins) hold the gate; plugins that join later never do.
const startup = createStartupGate({
bridge: input.bridge,
plugins: untrack(all).flatMap((definition) => (definition.windowEntry ? [definition.id] : [])),
servers: input.servers ?? false,
})
// Undefined while startup waits for the enable settings: nothing activates before then.
const disabled = createMemo(
() =>
input.disabled?.() ??
selectDisabled(
startup.state(),
all().map((definition) => definition.id),
input.builtins ?? new Set<string>(),
),
undefined,
{ equals: (a, b) => a === b || (!!a && !!b && a.size === b.size && [...a].every((id) => b.has(id))) },
)
const providerOf = (id: string) => {
const current = providers.get(id)
@@ -201,9 +228,9 @@ function createHost(input: HostInput) {
if (!plugin) return inactive.disabled
if (main ? input.disabled()?.has(plugin) : state.status[plugin] === "disabled") return inactive.disabled
if (main ? disabled()?.has(plugin) : state.status[plugin] === "disabled") return inactive.disabled
if (main ? input.failed?.(plugin) : state.status[plugin] === "failed") return inactive.failed
if (main ? selectMainFailed(startup.state(), plugin) : state.status[plugin] === "failed") return inactive.failed
// A renderer provider that is up but does not provide the token (e.g. on this platform) is not coming.
if (!main && state.status[plugin] === "active") return inactive.disabled
@@ -397,7 +424,7 @@ function createHost(input: HostInput) {
// A disabled plugin, e.g. one reloaded from settings, stays disabled: marking it loading would make the
// enable watcher skip it later. Before the list loads nothing activates; the watcher starts each entry then.
if (!load || input.disabled()?.has(definition.id) !== false) return
if (!load || disabled()?.has(definition.id) !== false) return
setState("status", definition.id, "loading")
@@ -875,25 +902,6 @@ function createHost(input: HostInput) {
const replaced = new Map<string, Entry>()
const latest = (definition: Entry) => replaced.get(definition.id) ?? definition
// The definitions the host starts with: the built-ins. Definitions that join later (plugins) never hold the gate.
const initial = new Set(untrack(all))
// The startup gate: once every entry settled it stays open, so enabling or reloading a plugin later
// never unmounts the app.
const ready = createMemo<boolean>(
(settled) =>
settled ||
(!!input.disabled() &&
[...initial].every((definition) => {
if (!definition.windowEntry) return true
const status = state.status[definition.id]
return status === "active" || status === "failed" || status === "disabled"
})),
false,
)
// The definition object each id was last listed with; a new object for a listed id replaces it.
const listed = new Map<string, Entry>()
@@ -910,10 +918,10 @@ function createHost(input: HostInput) {
// Publish every disabled status before starting enabled entries.
createMemo(() => {
const disabled = input.disabled()
const off = disabled()
const definitions = all()
if (!disabled) return
if (!off) return
untrack(() =>
batch(() => {
@@ -930,7 +938,7 @@ function createHost(input: HostInput) {
if (before && before !== definition) forget(definition.id)
})
definitions
.filter((definition) => disabled.has(definition.id))
.filter((definition) => off.has(definition.id))
.forEach((definition) => {
deactivate(definition.id)
setState("status", definition.id, "disabled")
@@ -938,7 +946,7 @@ function createHost(input: HostInput) {
setState("failures", definition.id, undefined)
})
definitions
.filter((definition) => !disabled.has(definition.id))
.filter((definition) => !off.has(definition.id))
.forEach((definition) => {
// A failed plugin waits for Reload or a new revision, as in main.
if (instances.has(definition.id)) return
@@ -951,6 +959,20 @@ function createHost(input: HostInput) {
)
})
// Tells the startup gate as each plugin it waits for settles.
createRenderEffect(() => {
const gate = startup.state()
if (gate.status !== "activating") return
gate.pending.forEach((id) => {
const status = state.status[id]
if (status === "active" || status === "failed" || status === "disabled")
startup.dispatch({ type: "plugin.settled", id })
})
})
onCleanup(() => {
lifetime.disposed = true
loads.clear()
@@ -959,7 +981,16 @@ function createHost(input: HostInput) {
return {
state,
ready,
/** The app interface renders. Once open it stays open, so enabling or reloading a plugin never unmounts it. */
ready: createMemo(() => selectHostReady(startup.state())),
/** The contributed servers are known too, which the desktop app waits for. */
serversReady: createMemo(() => selectServersReady(startup.state())),
/** The plugins main lists; empty on the web and until main answers. */
installed: createMemo(() => selectInstalled(startup.state())),
/** A plugin's main entry cannot answer. Reactive. */
mainFailed: (id: string) => selectMainFailed(startup.state(), id),
/** Reports what the startup gate waits for. */
gate: startup.dispatch,
list,
items,
links,
@@ -1,43 +0,0 @@
import { createMemo, createResource, onCleanup } from "solid-js"
import { createStore, reconcile } from "solid-js/store"
import type { Bridge, Installed } from "@opencode/plugin/gui/host"
/** Saved enable preferences and the plugins main lists; activation status belongs to the host. */
export function createInstalled(bridge: Bridge | undefined) {
const [state, setState] = createStore<{ list?: readonly Installed[] }>({})
// A pushed list is newer than the initial reply, so a reply that arrives after one is dropped.
const pushed = { count: 0 }
const [initial] = createResource(async () => (bridge ? bridge.manager.initial?.catch(() => undefined) : []))
// Metadata still loads for settings and failure reporting. Activation can use known preload rows before it arrives.
createResource(async () => {
if (!bridge) return
const seen = pushed.count
const list = await bridge.manager.list()
if (pushed.count === seen) setState("list", reconcile([...list]))
})
if (bridge)
onCleanup(
bridge.on((message) => {
if (message.type !== "installed") return
pushed.count++
setState("list", reconcile([...message.list]))
}),
)
return {
// Main lists a plugin only once it read it from the app's own server, so until then the preload rows hold its
// saved setting.
enableState: createMemo(() => {
const list = state.list
if (!list) return initial.latest
return [...(initial.latest ?? []).filter((row) => !list.some((item) => item.id === row.id)), ...list]
}),
list: () => state.list ?? [],
}
}
@@ -0,0 +1,222 @@
import { expect, test } from "bun:test"
import type { Installed } from "@opencode/plugin/gui/host"
import {
createStartupGateState,
selectDisabled,
selectHostReady,
selectInstalled,
selectMainFailed,
selectServersReady,
transitionStartupGate,
type StartupGateEffect,
type StartupGateEvent,
type StartupGateState,
} from "./machine"
const desktop = { bridge: true, preload: true, plugins: ["review", "terminal"], servers: true }
const ids = ["review", "terminal", "notes"]
const builtins = new Set(["review", "terminal"])
const notesOff: Installed[] = [{ id: "notes", builtin: false, enabled: false }]
const settled: StartupGateEvent[] = [
{ type: "plugin.settled", id: "review" },
{ type: "plugin.settled", id: "terminal" },
]
/** Folds events through the machine from the initial state, collecting every effect in order. */
function replay(input: Parameters<typeof createStartupGateState>[0], events: readonly StartupGateEvent[]) {
const initial = createStartupGateState(input)
return events.reduce<{ state: StartupGateState; effects: StartupGateEffect[] }>(
(current, event) => {
const next = transitionStartupGate(current.state, event)
return { state: next.state, effects: [...current.effects, ...next.effects] }
},
{ state: initial.state, effects: [...initial.effects] },
)
}
function view(state: StartupGateState) {
return {
status: state.status,
host: selectHostReady(state),
servers: selectServersReady(state),
disabled: selectDisabled(state, ids, builtins),
mainFailed: selectMainFailed(state, "notes"),
}
}
test.each<{ name: string; preload: boolean; events: StartupGateEvent[] }>([
{ name: "no preload snapshot, then list() rejects", preload: false, events: [] },
{
name: "the preload snapshot is unknown, then list() rejects",
preload: true,
events: [{ type: "preload.unavailable" }],
},
])("startup reaches ready when main never answers: $name", (input) => {
const replayed = replay({ ...desktop, preload: input.preload }, [
...input.events,
{ type: "list.failed", error: "ipc down" },
])
// Before the fix the window waited here forever, with nothing activated.
expect(view(replayed.state)).toEqual({
status: "activating",
host: false,
servers: false,
disabled: new Set(["notes"]),
mainFailed: true,
})
const done = replay({ ...desktop, preload: input.preload }, [
...input.events,
{ type: "list.failed", error: "ipc down" },
...settled,
{ type: "inventory.settled" },
{ type: "sources.settled" },
])
expect(view(done.state)).toEqual({
status: "ready",
host: true,
servers: true,
disabled: new Set(["notes"]),
mainFailed: true,
})
expect(done.effects.at(-1)).toEqual({ type: "timer.stop" })
})
test("startup does not activate on a failed preload while list() can still answer", () => {
const replayed = replay({ ...desktop, preload: true }, [{ type: "preload.unavailable" }])
expect(view(replayed.state)).toEqual({
status: "preferences",
host: false,
servers: false,
disabled: undefined,
mainFailed: false,
})
})
test("a list() failure waits for the preload snapshot, whose rows then apply", () => {
const waiting = replay(desktop, [{ type: "list.failed", error: "boom" }])
expect(waiting.state).toMatchObject({ status: "preferences", pending: { kind: "preload", error: "boom" } })
const replayed = replay(desktop, [
{ type: "list.failed", error: "boom" },
{ type: "preload.resolved", rows: [{ id: "notes", enabled: true }] },
])
expect(view(replayed.state)).toMatchObject({ status: "activating", disabled: new Set(), mainFailed: true })
})
test("preferences that never arrive time out to built-ins only, and a late list still applies", () => {
const timedOut = replay(desktop, [{ type: "timeout", timer: "preferences" }])
expect(view(timedOut.state)).toMatchObject({ status: "activating", disabled: new Set(["notes"]), mainFailed: false })
expect(timedOut.effects.at(-1)).toEqual({ type: "timer.start", timer: "activation" })
const answered = replay(desktop, [
{ type: "timeout", timer: "preferences" },
{ type: "list.resolved", list: [{ id: "notes", builtin: false, enabled: true }] },
])
expect(view(answered.state)).toMatchObject({ status: "activating", disabled: new Set() })
})
test("a built-in whose load or store read never settles stops holding the window when activation times out", () => {
const replayed = replay({ ...desktop, servers: false }, [
{ type: "preload.resolved", rows: [] },
{ type: "plugin.settled", id: "review" },
])
expect(replayed.state).toMatchObject({ status: "activating", pending: ["terminal"] })
const done = transitionStartupGate(replayed.state, { type: "timeout", timer: "activation" })
expect(view(done.state)).toMatchObject({ status: "ready", host: true, servers: true })
})
test("the servers phase opens on its timeout when a source never reports", () => {
const replayed = replay(desktop, [{ type: "preload.resolved", rows: [] }, ...settled, { type: "inventory.settled" }])
expect(view(replayed.state)).toMatchObject({ status: "servers", host: true, servers: false })
const done = transitionStartupGate(replayed.state, { type: "timeout", timer: "servers" })
expect(view(done.state)).toMatchObject({ status: "ready", servers: true })
})
test("an inventory that settles before the servers phase is remembered", () => {
const replayed = replay(desktop, [{ type: "inventory.settled" }, { type: "preload.resolved", rows: [] }, ...settled])
expect(replayed.state).toMatchObject({ status: "servers", pending: "sources" })
expect(transitionStartupGate(replayed.state, { type: "sources.settled" }).state.status).toBe("ready")
})
test("the preload snapshot opens the gate without waiting for list(), whose reply then keeps unlisted rows", () => {
const replayed = replay({ ...desktop, servers: false }, [
{ type: "preload.resolved", rows: [{ id: "notes", enabled: false }] },
...settled,
])
expect(view(replayed.state)).toMatchObject({ status: "ready", disabled: new Set(["notes"]) })
const listed = transitionStartupGate(replayed.state, {
type: "list.resolved",
list: [{ id: "review", builtin: true, enabled: true }],
})
expect(selectDisabled(listed.state, ids, builtins)).toEqual(new Set(["notes"]))
expect(selectInstalled(listed.state)).toEqual([{ id: "review", builtin: true, enabled: true }])
})
test("a list main pushes wins over the older list() reply", () => {
const replayed = replay(desktop, [
{ type: "installed.pushed", list: notesOff },
{ type: "list.resolved", list: [{ id: "notes", builtin: false, enabled: true }] },
])
expect(selectInstalled(replayed.state)).toEqual(notesOff)
expect(selectDisabled(replayed.state, ids, builtins)).toEqual(new Set(["notes"]))
})
test("a pushed list recovers a window whose manager failed at startup", () => {
const replayed = replay({ ...desktop, preload: false, servers: false }, [
{ type: "list.failed", error: "ipc down" },
...settled,
{ type: "installed.pushed", list: [{ id: "notes", builtin: false, enabled: true }] },
])
expect(view(replayed.state)).toMatchObject({ status: "ready", disabled: new Set(), mainFailed: false })
})
test("ready is terminal: late phase events and timers change nothing", () => {
const ready = replay({ ...desktop, servers: false }, [{ type: "preload.resolved", rows: [] }, ...settled]).state
const late: StartupGateEvent[] = [
{ type: "plugin.settled", id: "review" },
{ type: "preload.unavailable" },
{ type: "inventory.settled" },
{ type: "sources.settled" },
{ type: "timeout", timer: "preferences" },
{ type: "timeout", timer: "activation" },
{ type: "timeout", timer: "servers" },
{ type: "preload.resolved", rows: notesOff },
]
late.forEach((event) => expect(transitionStartupGate(ready, event)).toEqual({ state: ready, effects: [] }))
late.forEach((event) => expect(transitionStartupGate(ready, event).state).toBe(ready))
})
test("a window without a bridge starts ready when nothing holds it", () => {
expect(createStartupGateState({ bridge: false, preload: false, plugins: [], servers: false })).toEqual({
state: { status: "ready", preferences: { status: "loaded", preload: [], list: [] } },
effects: [{ type: "timer.stop" }],
})
})
+318
View File
@@ -0,0 +1,318 @@
import { pluginEnabled, type EnableState, type Installed } from "@opencode/plugin/gui/host"
/** Main's reply to the one installed-list request, while it has not answered or after it failed. */
export type ListRequest = { readonly status: "loading" } | { readonly status: "failed"; readonly error: string }
/** What the window knows of main's enable settings once startup stops waiting for them. */
export type Preferences =
| { readonly status: "loaded"; readonly preload: readonly EnableState[]; readonly list: readonly Installed[] }
| { readonly status: "preload"; readonly rows: readonly EnableState[]; readonly list: ListRequest }
/** Neither source answered, or not in time: only built-ins run until main answers. */
| { readonly status: "unknown"; readonly list: ListRequest }
/** What startup still waits for: the preload snapshot and the list, the list, or the snapshot once the list failed. */
export type PendingPreferences =
| { readonly kind: "both" }
| { readonly kind: "list" }
| { readonly kind: "preload"; readonly error: string }
/** The contributed servers' stored inventory before the servers phase: not awaited, still loading, or settled. */
export type Inventory = "none" | "loading" | "settled"
export type StartupGateState =
| {
readonly status: "preferences"
readonly pending: PendingPreferences
/** The plugins activation will wait for. */
readonly plugins: readonly string[]
readonly inventory: Inventory
}
| {
readonly status: "activating"
readonly pending: readonly string[]
readonly preferences: Preferences
readonly inventory: Inventory
}
| {
readonly status: "servers"
readonly pending: "both" | "inventory" | "sources"
readonly preferences: Preferences
}
| { readonly status: "ready"; readonly preferences: Preferences }
export type StartupGateTimer = "preferences" | "activation" | "servers"
export type StartupGateEvent =
| { readonly type: "preload.resolved"; readonly rows: readonly EnableState[] }
| { readonly type: "preload.unavailable" }
| { readonly type: "list.resolved"; readonly list: readonly Installed[] }
| { readonly type: "list.failed"; readonly error: string }
| { readonly type: "installed.pushed"; readonly list: readonly Installed[] }
| { readonly type: "plugin.settled"; readonly id: string }
| { readonly type: "inventory.settled" }
| { readonly type: "sources.settled" }
| { readonly type: "timeout"; readonly timer: StartupGateTimer }
export type StartupGateEffect =
| { readonly type: "preload.read" }
| { readonly type: "list.fetch" }
/** Replaces the running timer. */
| { readonly type: "timer.start"; readonly timer: StartupGateTimer }
| { readonly type: "timer.stop" }
export type StartupGateTransition = {
readonly state: StartupGateState
readonly effects: readonly StartupGateEffect[]
}
type PreferenceEvent = Extract<
StartupGateEvent,
{ type: "preload.resolved" | "list.resolved" | "list.failed" | "installed.pushed" }
>
const loading: ListRequest = { status: "loading" }
/**
* The gate a window starts with. With a bridge it asks main for the enable settings; without one (the web) nothing is
* saved, so it starts activating at once.
*/
export function createStartupGateState(input: {
readonly bridge: boolean
readonly preload: boolean
readonly plugins: readonly string[]
readonly servers: boolean
}): StartupGateTransition {
const state: Extract<StartupGateState, { status: "preferences" }> = {
status: "preferences",
pending: input.preload ? { kind: "both" } : { kind: "list" },
plugins: Array.from(new Set(input.plugins)),
inventory: input.servers ? "loading" : "none",
}
if (!input.bridge) return advance(state, { status: "loaded", preload: [], list: [] })
return step(state, [
...(input.preload ? [{ type: "preload.read" } as const] : []),
{ type: "list.fetch" },
{ type: "timer.start", timer: "preferences" },
])
}
export function transitionStartupGate(state: StartupGateState, event: StartupGateEvent): StartupGateTransition {
if (state.status === "preferences") return preferences(state, event)
if (
event.type === "preload.resolved" ||
event.type === "list.resolved" ||
event.type === "list.failed" ||
event.type === "installed.pushed"
) {
const next = updatePreferences(state.preferences, event)
return step(next === state.preferences ? state : { ...state, preferences: next })
}
if (state.status === "activating") return activating(state, event)
if (state.status === "servers") return servers(state, event)
return step(state)
}
/** The app interface renders: every plugin startup waited for settled, or its time ran out. */
export function selectHostReady(state: StartupGateState) {
return state.status === "servers" || state.status === "ready"
}
/** The contributed servers' inventory loaded and every source reported, or their time ran out. */
export function selectServersReady(state: StartupGateState) {
return state.status === "ready"
}
/** The plugins main lists; empty until it answers. */
export function selectInstalled(state: StartupGateState): readonly Installed[] {
if (state.status === "preferences" || state.preferences.status !== "loaded") return []
return state.preferences.list
}
/** A plugin's main entry cannot answer: it failed, or main's plugin manager did not answer. */
export function selectMainFailed(state: StartupGateState, id: string) {
if (state.status === "preferences") return false
if (state.preferences.status !== "loaded") return state.preferences.list.status === "failed"
return state.preferences.list.some((item) => item.id === id && item.error !== undefined)
}
/** The plugins that stay off; undefined while startup waits for the settings, when nothing may start. */
export function selectDisabled(state: StartupGateState, ids: readonly string[], builtins: ReadonlySet<string>) {
if (state.status === "preferences") return undefined
const rows = enableRows(state.preferences)
return new Set(
ids.filter((id) => {
const builtin = builtins.has(id)
// Without settings only built-ins run: a plugin the user turned off must never start.
return !(rows ? pluginEnabled({ id, builtin }, rows) : builtin)
}),
)
}
function preferences(
state: Extract<StartupGateState, { status: "preferences" }>,
event: StartupGateEvent,
): StartupGateTransition {
const pending = state.pending
if (event.type === "installed.pushed") return advance(state, { status: "loaded", preload: [], list: event.list })
if (event.type === "preload.resolved") {
if (pending.kind === "list") return step(state)
return advance(state, {
status: "preload",
rows: event.rows,
list: pending.kind === "both" ? loading : { status: "failed", error: pending.error },
})
}
if (event.type === "preload.unavailable") {
if (pending.kind === "both") return step({ ...state, pending: { kind: "list" } })
if (pending.kind === "preload")
return advance(state, { status: "unknown", list: { status: "failed", error: pending.error } })
return step(state)
}
if (event.type === "list.resolved") {
if (pending.kind === "preload") return step(state)
return advance(state, { status: "loaded", preload: [], list: event.list })
}
if (event.type === "list.failed") {
if (pending.kind === "both") return step({ ...state, pending: { kind: "preload", error: event.error } })
if (pending.kind === "list")
return advance(state, { status: "unknown", list: { status: "failed", error: event.error } })
return step(state)
}
if (event.type === "timeout" && event.timer === "preferences")
return advance(state, {
status: "unknown",
list: pending.kind === "preload" ? { status: "failed", error: pending.error } : loading,
})
if (event.type === "inventory.settled" && state.inventory === "loading")
return step({ ...state, inventory: "settled" })
return step(state)
}
function activating(
state: Extract<StartupGateState, { status: "activating" }>,
event: StartupGateEvent,
): StartupGateTransition {
if (event.type === "plugin.settled") {
if (!state.pending.includes(event.id)) return step(state)
const pending = state.pending.filter((id) => id !== event.id)
if (pending.length > 0) return step({ ...state, pending })
return activated(state.preferences, state.inventory)
}
// A plugin whose load or store read never settles keeps loading, but no longer holds the window.
if (event.type === "timeout" && event.timer === "activation") return activated(state.preferences, state.inventory)
if (event.type === "inventory.settled" && state.inventory === "loading")
return step({ ...state, inventory: "settled" })
return step(state)
}
function servers(state: Extract<StartupGateState, { status: "servers" }>, event: StartupGateEvent) {
if (event.type === "timeout" && event.timer === "servers") return ready(state.preferences)
if (event.type === "inventory.settled") {
if (state.pending === "both") return step({ ...state, pending: "sources" })
if (state.pending === "inventory") return ready(state.preferences)
}
if (event.type === "sources.settled") {
if (state.pending === "both") return step({ ...state, pending: "inventory" })
if (state.pending === "sources") return ready(state.preferences)
}
return step(state)
}
function advance(state: Extract<StartupGateState, { status: "preferences" }>, preferences: Preferences) {
if (state.plugins.length === 0) return activated(preferences, state.inventory)
return step({ status: "activating", pending: state.plugins, preferences, inventory: state.inventory }, [
{ type: "timer.start", timer: "activation" },
])
}
function activated(preferences: Preferences, inventory: Inventory) {
if (inventory === "none") return ready(preferences)
return step({ status: "servers", pending: inventory === "settled" ? "sources" : "both", preferences }, [
{ type: "timer.start", timer: "servers" },
])
}
function ready(preferences: Preferences) {
return step({ status: "ready", preferences }, [{ type: "timer.stop" }])
}
// Main answers the one list request, then pushes every change; a push is newer than any reply still on its way.
function updatePreferences(preferences: Preferences, event: PreferenceEvent): Preferences {
if (event.type === "installed.pushed")
return { status: "loaded", preload: preloadRows(preferences), list: event.list }
if (event.type === "preload.resolved")
return preferences.status === "unknown"
? { status: "preload", rows: event.rows, list: preferences.list }
: preferences
if (preferences.status === "loaded" || preferences.list.status !== "loading") return preferences
if (event.type === "list.resolved") return { status: "loaded", preload: preloadRows(preferences), list: event.list }
return { ...preferences, list: { status: "failed", error: event.error } }
}
function preloadRows(preferences: Preferences) {
if (preferences.status === "preload") return preferences.rows
if (preferences.status === "loaded") return preferences.preload
return []
}
// Main lists a plugin only once it read it from the app's own server, so until then the preload rows hold its setting.
function enableRows(preferences: Preferences) {
if (preferences.status === "unknown") return undefined
if (preferences.status === "preload") return preferences.rows
return [
...preferences.preload.filter((row) => !preferences.list.some((item) => item.id === row.id)),
...preferences.list,
]
}
function step(state: StartupGateState, effects: readonly StartupGateEffect[] = []): StartupGateTransition {
return { state, effects }
}
+6 -22
View File
@@ -1,7 +1,6 @@
import { batch, createMemo, createSignal, lazy, onCleanup, Show, Suspense, type ParentProps } from "solid-js"
import { pluginEnabled, runsOn, type Bridge, type Entry } from "@opencode/plugin/gui/host"
import { runsOn, type Bridge, type Entry } from "@opencode/plugin/gui/host"
import { builtins } from "./builtins"
import { createInstalled } from "./installed"
import { PluginGuiLoader, type PluginGui } from "./plugins"
import { createMenubarItems, MenubarItemsProvider } from "./menubar-items"
import { usePlatform } from "@/runtime/platform/platform"
@@ -48,7 +47,6 @@ export function PluginRoot(props: ParentProps) {
const menubar = createMenubarItems(bridge)
const ipcs = createIpcClients(bridge)
onCleanup(ipcs.dispose)
const installed = createInstalled(bridge)
const os = platform.platform === "desktop" ? platform.os : undefined
@@ -70,22 +68,7 @@ export function PluginRoot(props: ParentProps) {
},
)
// Only enable preferences cross this boundary.
const disabled = createMemo(() => {
const state = installed.enableState()
if (!state) return undefined
return new Set(
definitions().flatMap((definition) =>
pluginEnabled({ id: definition.id, builtin: builtins.some((builtin) => builtin.id === definition.id) }, state)
? []
: [definition.id],
),
)
})
const failed = (id: string) => installed.list().some((item) => item.id === id && item.error !== undefined)
const builtinIds = new Set(builtins.map((builtin) => builtin.id))
return (
<HostApisContext.Provider value={apis}>
@@ -104,13 +87,14 @@ export function PluginRoot(props: ParentProps) {
>
<PluginHostProvider
definitions={definitions}
disabled={disabled}
bridge={bridge}
builtins={builtinIds}
servers
apis={apis.apis}
whenMounted={apis.whenMounted}
ipc={bridge ? (token) => ipcs.client(token) : undefined}
plugin={(id) => plugins()?.find((plugin) => plugin.definition.id === id)}
generation={ipcs.generation}
failed={failed}
>
<PluginStyles />
<PluginThemes loaded={() => plugins() !== undefined} />
@@ -120,7 +104,7 @@ export function PluginRoot(props: ParentProps) {
</Suspense>
)}
<MenubarItemsProvider value={menubar}>
<PluginServersProvider failed={failed}>{props.children}</PluginServersProvider>
<PluginServersProvider>{props.children}</PluginServersProvider>
</MenubarItemsProvider>
</PluginHostProvider>
</PluginsContext.Provider>
+26 -13
View File
@@ -1,4 +1,12 @@
import { createContext, createEffect, createMemo, createSignal, useContext, type ParentProps } from "solid-js"
import {
createContext,
createEffect,
createMemo,
createRenderEffect,
createSignal,
useContext,
type ParentProps,
} from "solid-js"
import { reconcile } from "solid-js/store"
import { Schema } from "effect"
import { MenuItem, Server, type ServerEntry } from "@opencode/plugin/gui"
@@ -42,12 +50,12 @@ export function usePluginServers() {
return value
}
/** Collects Server contributions. `failed` reports plugins whose main entry failed, so startup stops waiting for them. */
export function PluginServersProvider(props: ParentProps<{ failed: (plugin: string) => boolean }>) {
return <ServersContext.Provider value={createPluginServers(props.failed)}>{props.children}</ServersContext.Provider>
/** Collects Server contributions, and reports to the host's startup gate once they are known. */
export function PluginServersProvider(props: ParentProps) {
return <ServersContext.Provider value={createPluginServers()}>{props.children}</ServersContext.Provider>
}
function createPluginServers(failed: (plugin: string) => boolean) {
function createPluginServers() {
const host = usePluginHost()
const [known, setKnown, , knownReady] = persisted(
@@ -56,7 +64,19 @@ function createPluginServers(failed: (plugin: string) => boolean) {
{},
)
// A failed read settles the inventory too: startup then shows only the servers that report.
const settled = () => host.gate({ type: "inventory.settled" })
void Promise.resolve(knownReady.promise).then(settled, settled)
const sources = createMemo(() => host.items(Server).toSorted((a, b) => (a.value.order ?? 0) - (b.value.order ?? 0)))
// Startup waits once for every source to report or for its main entry to fail; one that reloads later does not hide
// the app again.
createRenderEffect(() => {
if (host.ready() && sources().every((item) => item.value.ready || host.mainFailed(item.plugin)))
host.gate({ type: "sources.settled" })
})
// Only a ready source reports its complete inventory. One that reloads, fails or has not started keeps its last
// inventory as stopped entries, so its servers' tabs, drafts and routes outlive the outage.
const available = createMemo(() => sources().filter((item) => item.value.ready))
@@ -125,15 +145,8 @@ function createPluginServers(failed: (plugin: string) => boolean) {
})
})
// Startup waits for every source once; a source that reloads later does not hide the app again.
const ready = createMemo<boolean>(
(previous) =>
previous || (knownReady() && host.ready() && sources().every((item) => item.value.ready || failed(item.plugin))),
false,
)
return {
ready,
ready: host.serversReady,
/** Contributed servers the app lists, as stable connections. */
list,
/**
+107
View File
@@ -0,0 +1,107 @@
import { createSignal, onCleanup, untrack } from "solid-js"
import type { Bridge } from "@opencode/plugin/gui/host"
import {
createStartupGateState,
transitionStartupGate,
type StartupGateEffect,
type StartupGateEvent,
type StartupGateTimer,
} from "./machine"
// How long the window waits for each phase before it shows anyway. Servers wait longest: listing WSL distributions
// can take many seconds.
const timeouts: Record<StartupGateTimer, number> = { preferences: 5_000, activation: 10_000, servers: 20_000 }
/**
* Runs the startup gate for the owner's lifetime: asks main for the enable settings, keeps them current as main pushes
* changes, and runs the gate's timers. Callers report what the gate waits for through `dispatch`.
*/
export function createStartupGate(input: {
readonly bridge: Bridge | undefined
/** The plugins activation waits for. */
readonly plugins: readonly string[]
/** Startup also waits for the contributed servers. */
readonly servers: boolean
}) {
const bridge = input.bridge
const initial = createStartupGateState({
bridge: !!bridge,
preload: !!bridge?.manager.initial,
plugins: input.plugins,
servers: input.servers,
})
const [state, setState] = createSignal(initial.state)
// Replies and timers that land after the owner is gone change nothing.
const lifetime = { disposed: false }
// The running phase timer; there is at most one.
const timers = new Set<ReturnType<typeof setTimeout>>()
// Events a transition's own state change raises (a plugin settling as the gate opens) wait behind its effects.
const queue: StartupGateEvent[] = []
const drain = () => {
const event = queue[0]
if (!event) return
const next = transitionStartupGate(untrack(state), event)
setState(next.state)
next.effects.forEach(run)
queue.shift()
drain()
}
const dispatch = (event: StartupGateEvent) => {
if (lifetime.disposed) return
queue.push(event)
if (queue.length === 1) drain()
}
const run = (effect: StartupGateEffect) => {
if (effect.type === "preload.read")
return void bridge?.manager.initial?.then(
(rows) => dispatch(rows ? { type: "preload.resolved", rows } : { type: "preload.unavailable" }),
() => dispatch({ type: "preload.unavailable" }),
)
if (effect.type === "list.fetch")
return void Promise.try(() => bridge?.manager.list() ?? []).then(
(list) => dispatch({ type: "list.resolved", list }),
(cause: unknown) => {
console.error("[plugin] failed to load installed plugin list", cause)
dispatch({ type: "list.failed", error: cause instanceof Error ? cause.message : String(cause) })
},
)
stopTimers()
if (effect.type === "timer.start")
timers.add(setTimeout(() => dispatch({ type: "timeout", timer: effect.timer }), timeouts[effect.timer]))
}
const stopTimers = () => {
timers.forEach(clearTimeout)
timers.clear()
}
if (bridge)
onCleanup(
bridge.on((message) => {
if (message.type === "installed") dispatch({ type: "installed.pushed", list: message.list })
}),
)
onCleanup(() => {
lifetime.disposed = true
stopTimers()
queue.length = 0
})
initial.effects.forEach(run)
return { state, dispatch }
}
@@ -1,48 +0,0 @@
import { expect, test } from "bun:test"
import { createRoot } from "solid-js"
import type { Bridge, BridgeMessage, Installed } from "@opencode/plugin/gui/host"
import { createInstalled } from "../src/runtime/plugin/installed"
test("a list main pushes while the initial list is pending wins over the older reply", async () => {
const listeners = new Set<(message: BridgeMessage) => void>()
const reply = Promise.withResolvers<readonly Installed[]>()
const bridge: Bridge = {
packaged: false,
call: () => Promise.reject(new Error("no calls in this test")),
subscribe: async () => ({ available: false }),
on: (listener) => {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
},
embed: () => {},
capture: async () => undefined,
runMenubarItem: () => {},
configure: () => {},
pluginGuis: async () => ({ plugins: [], reserved: [] }),
manager: {
list: () => reply.promise,
enable: async () => {},
disable: async () => {},
reload: async () => {},
},
}
const plugin = { id: "fixture", builtin: false }
const root = createRoot((dispose) => ({ installed: createInstalled(bridge), dispose }))
// Another window disabled the plugin before this window's initial list arrived.
listeners.forEach((listener) => listener({ type: "installed", list: [{ ...plugin, enabled: false }] }))
reply.resolve([{ ...plugin, enabled: true }])
await Bun.sleep(0)
expect({
known: root.installed.enableState() !== undefined,
enabled: root.installed.list().map((item) => item.enabled),
}).toEqual({
known: true,
enabled: [false],
})
root.dispose()
})
@@ -659,7 +659,7 @@ type RegionHost = {
PluginHostProvider: Component<
ParentProps<{
definitions: Accessor<readonly Entry[]>
disabled: Accessor<ReadonlySet<string> | undefined>
disabled: Accessor<ReadonlySet<string>>
/** The HostApis the fixture provides, by context property; the host provides links and dialogs itself. */
apis: { readonly [api: string]: (plugin: string) => object | undefined }
/** Runs once the app interface mounts; the fixture's is always mounted. */
+2 -1
View File
@@ -571,7 +571,8 @@ export interface Bridge {
/**
* Explicit enable-state rows from the existing preload startup reply. Undefined (or an omitted promise) means
* unknown: activation waits for `list()` or a live list, never assumes all are enabled. An empty list is
* authoritative: no saved settings. A rejected promise also falls back to the manager list.
* authoritative: no saved settings. A rejected promise also falls back to the manager list. When `list()` fails
* too, or neither answers in time, only built-ins run until main answers or pushes a live list.
*/
readonly initial?: Promise<readonly EnableState[] | undefined>
/** The installed plugins, built-ins included. */
+1 -1
View File
@@ -114,7 +114,7 @@ export function SshProvider(props: ParentProps) {
function SshHost(props: ParentProps) {
const host = usePluginHost()
return (
<PluginServersProvider failed={(id) => host.state.status[id] === "failed"}>
<PluginServersProvider>
<PluginStyles />
<Show when={host.state.status[plugin.id] === "active"}>{props.children}</Show>
</PluginServersProvider>