fix(app): track plugin Ipc subscriptions in one state machine (#61802)

This commit is contained in:
Luke Parker
2026-11-04 16:33:41 -06:00
committed by GitHub
Unverified
parent 9a3f03e5c5
commit 2e56427f0e
8 changed files with 587 additions and 83 deletions
@@ -237,6 +237,8 @@ export function mountPlugins(input: {
plugins?: readonly PluginInfo[]
/** The client of an Ipc while main provides it, as a desktop window's bridge reports it. Omitted: the web. */
ipc?: (token: Ipc) => IpcClient<IpcSpec> | undefined
/** Whether main failed to answer the window's subscribe to an Ipc. */
ipcFailed?: (token: Ipc) => boolean
}) {
const held = Promise.withResolvers<void>()
const saved = { ...input.stored }
@@ -312,6 +314,7 @@ export function mountPlugins(input: {
apis={fakeApis(storage)}
whenMounted={mounted}
ipc={input.ipc}
ipcFailed={input.ipcFailed}
>
<Capture />
</PluginHostProvider>
@@ -1066,6 +1066,7 @@ story(
const Other = Ipc.define({ id: "other.ipc", methods: {} })
const [available, setAvailable] = createSignal(false)
const [awake, setAwake] = createSignal(false)
const [failed, setFailed] = createSignal(false)
const kept: Kept = {}
const client = {
@@ -1076,6 +1077,7 @@ story(
const host = mountPlugins({
ipc: (token: { readonly id: string }) => (token.id === Awake.id && available() ? client : undefined),
ipcFailed: (token: { readonly id: string }) => token.id === Awake.id && failed(),
definitions: [{ id: "acme", windowEntry: async () => ({ default: (ctx: Context) => void (kept.ctx = ctx) }) }],
})
@@ -1085,6 +1087,16 @@ story(
if (!ctx) throw new Error("the plugin never set up")
const main = ctx.main(Awake)
// A call that waits rejects once main fails to answer the window's subscribe, instead of waiting forever.
const stuck = main.get()
setFailed(true)
const unanswered = await stuck.then(
() => false,
(cause: unknown) => String(cause).includes("unavailable: failed"),
)
setFailed(false)
const waiting = main.get()
const before = main.state()
setAwake(true)
@@ -1111,10 +1123,11 @@ story(
host.unmount()
return { before, answered, state, foreign, rejected, same: ctx.main(Awake) === main }
return { unanswered, before, answered, state, foreign, rejected, same: ctx.main(Awake) === main }
}, fixture)
expect(result).toEqual({
unanswered: true,
before: undefined,
answered: true,
state: { awake: true },
+8 -1
View File
@@ -156,6 +156,8 @@ type HostInput = {
plugin?: (id: string) => PluginInput | undefined
/** How many times an Ipc became available. Reactive. */
generation?: (token: Ipc) => number
/** Main did not answer the window's subscribe to an Ipc. Reactive. */
ipcFailed?: (token: Ipc) => boolean
}
export function PluginHostProvider(props: ParentProps<HostInput>) {
@@ -573,7 +575,12 @@ function createHost(input: HostInput) {
const client = input.ipc(token)
if (!client) return absent(token.id, true)
if (!client) {
const reason = absent(token.id, true)
// A provider that may still start, but whose subscribe failed, is not coming until main provides it again.
return reason === pending && input.ipcFailed?.(token) ? inactive.failed : reason
}
const generation = input.generation?.(token) ?? 1
const cached = clients.get(token.id)
@@ -0,0 +1,172 @@
import { expect, test } from "bun:test"
import {
createIpcState,
selectIpcAvailable,
selectIpcFailed,
selectIpcGeneration,
selectIpcNeedsSubscribe,
selectIpcValue,
transitionIpc,
type IpcEffect,
type IpcEvent,
type IpcState,
} from "./ipc-machine"
/** Folds events through the machine, collecting every effect in order. */
function replay(events: readonly IpcEvent[], from = createIpcState()) {
return events.reduce<{ state: IpcState; effects: IpcEffect[] }>(
(current, event) => {
const next = transitionIpc(current.state, event)
return { state: next.state, effects: [...current.effects, ...next.effects] }
},
{ state: from, effects: [] },
)
}
function view(state: IpcState, id = "acme.awake") {
return {
available: selectIpcAvailable(state, id),
value: selectIpcValue(state, id),
generation: selectIpcGeneration(state, id),
failed: selectIpcFailed(state, id),
subscribe: selectIpcNeedsSubscribe(state, id),
}
}
const subscribe: IpcEvent = { type: "subscribe", id: "acme.awake" }
// Before, a subscribe that rejected or never answered left the Ipc looking like it was still subscribing, so every
// `ctx.main()` call waited forever.
test.each<{ name: string; event: IpcEvent }>([
{ name: "rejects", event: { type: "failed", id: "acme.awake", attempt: 1, cause: new Error("boom") } },
{ name: "never answers", event: { type: "timeout", id: "acme.awake", attempt: 1 } },
])("a subscribe that $name fails the Ipc without retrying on every read", (input) => {
const run = replay([subscribe, input.event, subscribe])
expect(run.effects.map((effect) => effect.type)).toEqual(["subscribe", "timer.start", "timer.stop", "log"])
expect(view(run.state)).toEqual({ available: false, value: undefined, generation: 0, failed: true, subscribe: false })
})
test("a failed Ipc subscribes again once main provides it again, keeping its generation count", () => {
const run = replay([
subscribe,
{ type: "failed", id: "acme.awake", attempt: 1, cause: "boom" },
{ type: "available", id: "acme.awake", available: false },
{ type: "available", id: "acme.awake", available: true },
])
expect(run.effects.slice(-2)).toEqual([
{ type: "subscribe", id: "acme.awake", attempt: 2 },
{ type: "timer.start", id: "acme.awake", attempt: 2 },
])
// The reply's own availability is older than the broadcast that started it.
const answered = transitionIpc(run.state, {
type: "subscribed",
id: "acme.awake",
attempt: 2,
available: false,
state: { awake: true },
})
expect(view(answered.state)).toEqual({
available: true,
value: { awake: true },
generation: 1,
failed: false,
subscribe: false,
})
})
test("results of an older subscribe change nothing", () => {
const run = replay([
subscribe,
{ type: "timeout", id: "acme.awake", attempt: 1 },
{ type: "available", id: "acme.awake", available: true },
])
const stale: IpcEvent[] = [
{ type: "subscribed", id: "acme.awake", attempt: 1, available: true, state: 1 },
{ type: "failed", id: "acme.awake", attempt: 1, cause: "late" },
{ type: "timeout", id: "acme.awake", attempt: 1 },
]
stale.forEach((event) => expect(transitionIpc(run.state, event)).toEqual({ state: run.state, effects: [] }))
})
// Before, a state push or reply while the Ipc was unavailable stored a value its readers then saw.
test("an unavailable Ipc holds no state", () => {
const reply = replay([
subscribe,
{ type: "subscribed", id: "acme.awake", attempt: 1, available: false, state: { awake: true } },
])
expect(view(reply.state).value).toBeUndefined()
expect(transitionIpc(reply.state, { type: "state", id: "acme.awake", value: 1 }).state).toBe(reply.state)
const gone = replay([
subscribe,
{ type: "state", id: "acme.awake", value: { awake: true } },
{ type: "available", id: "acme.awake", available: false },
{ type: "available", id: "acme.awake", available: true },
{ type: "subscribed", id: "acme.awake", attempt: 1, available: true, state: { awake: false } },
])
// Going away cleared both the push and the reply's older state.
expect(view(gone.state)).toMatchObject({ available: true, value: undefined, generation: 1 })
})
test.each<{ name: string; event: IpcEvent; reply: { available: boolean; state: unknown }; expected: object }>([
{
name: "the Ipc appearing",
event: { type: "available", id: "acme.awake", available: true },
reply: { available: false, state: undefined },
expected: { available: true, value: undefined, generation: 1 },
},
{
name: "the Ipc going away",
event: { type: "available", id: "acme.awake", available: false },
reply: { available: true, state: { count: 1 } },
expected: { available: false, value: undefined, generation: 0 },
},
{
name: "a state push",
event: { type: "state", id: "acme.awake", value: { count: 2 } },
reply: { available: true, state: { count: 1 } },
expected: { available: true, value: { count: 2 }, generation: 1 },
},
])("a subscribe reply older than $name keeps the event's data", (input) => {
const run = replay([subscribe, input.event, { type: "subscribed", id: "acme.awake", attempt: 1, ...input.reply }])
expect(view(run.state)).toMatchObject(input.expected)
})
test("availability broadcast before any read counts a generation once", () => {
const run = replay([
{ type: "available", id: "acme.awake", available: true },
subscribe,
{ type: "subscribed", id: "acme.awake", attempt: 1, available: true, state: undefined },
{ type: "available", id: "acme.awake", available: false },
{ type: "available", id: "acme.awake", available: true },
])
expect(view(run.state)).toMatchObject({ available: true, generation: 2 })
})
test("disposing stops pending timers and ignores late replies", () => {
const run = replay([subscribe, { type: "disposed" }])
expect(run.effects.at(-1)).toEqual({ type: "timer.stop", id: "acme.awake" })
const late = transitionIpc(run.state, {
type: "subscribed",
id: "acme.awake",
attempt: 1,
available: true,
state: undefined,
})
expect(late.state).toBe(run.state)
expect(selectIpcNeedsSubscribe(run.state, "acme.awake")).toBe(false)
})
@@ -0,0 +1,213 @@
export type IpcChannel =
/** Only main's availability broadcasts arrived; no window code asked for a client yet. */
| { readonly status: "unsubscribed"; readonly available: boolean; readonly generation: number }
/**
* `subscribe` is in flight. `available` is the last availability known; `moved` is true once a broadcast arrived
* during the flight, which is newer than the reply. `pushed` is state main pushed during the flight.
*/
| {
readonly status: "subscribing"
readonly attempt: number
readonly generation: number
readonly available: boolean
readonly moved: boolean
readonly pushed: { readonly value: unknown } | undefined
}
| { readonly status: "available"; readonly generation: number; readonly value: unknown }
| { readonly status: "unavailable"; readonly generation: number }
/** The subscribe request failed or timed out; the next availability broadcast subscribes again. */
| { readonly status: "failed"; readonly generation: number }
export type IpcState = {
readonly status: "running" | "disposed"
readonly issued: number
readonly channels: Readonly<Record<string, IpcChannel>>
}
export type IpcEvent =
/** Window code asked for the Ipc's client. */
| { readonly type: "subscribe"; readonly id: string }
| {
readonly type: "subscribed"
readonly id: string
readonly attempt: number
readonly available: boolean
/** The decoded state main sent with the reply, if any. */
readonly state: unknown
}
| { readonly type: "failed"; readonly id: string; readonly attempt: number; readonly cause: unknown }
| { readonly type: "timeout"; readonly id: string; readonly attempt: number }
| { readonly type: "available"; readonly id: string; readonly available: boolean }
/** Decoded state main pushed. */
| { readonly type: "state"; readonly id: string; readonly value: unknown }
| { readonly type: "disposed" }
export type IpcEffect =
| { readonly type: "subscribe"; readonly id: string; readonly attempt: number }
| { readonly type: "timer.start"; readonly id: string; readonly attempt: number }
| { readonly type: "timer.stop"; readonly id: string }
| { readonly type: "log"; readonly id: string; readonly cause: unknown }
export type IpcTransition = { readonly state: IpcState; readonly effects: readonly IpcEffect[] }
export function createIpcState(): IpcState {
return { status: "running", issued: 0, channels: {} }
}
export function transitionIpc(state: IpcState, event: IpcEvent): IpcTransition {
if (state.status === "disposed") return step(state)
if (event.type === "disposed")
return step(
{ status: "disposed", issued: state.issued, channels: {} },
Object.entries(state.channels).flatMap(([id, channel]) =>
channel.status === "subscribing" ? [{ type: "timer.stop", id } as const] : [],
),
)
const channel = state.channels[event.id]
if (event.type === "subscribe") {
if (channel && channel.status !== "unsubscribed") return step(state)
return subscribe(state, event.id, {
generation: channel?.generation ?? 0,
available: channel?.available ?? false,
moved: false,
})
}
if (event.type === "available") return available(state, event.id, channel, event.available)
if (event.type === "state") {
if (channel?.status === "subscribing")
return step(put(state, event.id, { ...channel, pushed: { value: event.value } }))
if (channel?.status === "available") return step(put(state, event.id, { ...channel, value: event.value }))
// Main pushes state only while it provides the Ipc.
return step(state)
}
if (channel?.status !== "subscribing" || channel.attempt !== event.attempt) return step(state)
if (event.type === "subscribed") {
// A broadcast during the flight is newer than the reply's availability, and a push newer than its state.
const live = channel.moved ? channel.available : event.available
const generation = live && !channel.available ? channel.generation + 1 : channel.generation
const stop = [{ type: "timer.stop", id: event.id } as const]
if (!live) return step(put(state, event.id, { status: "unavailable", generation }), stop)
return step(
put(state, event.id, {
status: "available",
generation,
value: channel.pushed ? channel.pushed.value : event.state,
}),
stop,
)
}
const cause = event.type === "failed" ? event.cause : new Error(`Ipc "${event.id}" did not answer the subscribe`)
return step(put(state, event.id, { status: "failed", generation: channel.generation }), [
{ type: "timer.stop", id: event.id },
{ type: "log", id: event.id, cause },
])
}
/** Window code reading the client asks main for it: never yet asked, and the clients still run. */
export function selectIpcNeedsSubscribe(state: IpcState, id: string) {
const channel = state.channels[id]
return state.status === "running" && (!channel || channel.status === "unsubscribed")
}
/** Main provides the Ipc, as far as the window knows. */
export function selectIpcAvailable(state: IpcState, id: string) {
const channel = state.channels[id]
return channel?.status === "available" || (channel?.status === "subscribing" && channel.available)
}
export function selectIpcValue(state: IpcState, id: string) {
const channel = state.channels[id]
if (channel?.status === "available") return channel.value
if (channel?.status === "subscribing" && channel.available) return channel.pushed?.value
return undefined
}
/** How many times the Ipc became available; 0 until it first is. */
export function selectIpcGeneration(state: IpcState, id: string) {
return state.channels[id]?.generation ?? 0
}
export function selectIpcFailed(state: IpcState, id: string) {
return state.channels[id]?.status === "failed"
}
function available(state: IpcState, id: string, channel: IpcChannel | undefined, next: boolean): IpcTransition {
if (!channel) return step(put(state, id, { status: "unsubscribed", available: next, generation: next ? 1 : 0 }))
const generation = next ? channel.generation + 1 : channel.generation
if (channel.status === "unsubscribed") {
if (channel.available === next) return step(state)
return step(put(state, id, { status: "unsubscribed", available: next, generation }))
}
if (channel.status === "subscribing")
return step(
put(state, id, {
...channel,
available: next,
moved: true,
generation: next && !channel.available ? generation : channel.generation,
// Going away clears the state too, so the reply's older state never shows.
pushed: next ? channel.pushed : { value: undefined },
}),
)
if (channel.status === "available") {
if (next) return step(state)
return step(put(state, id, { status: "unavailable", generation: channel.generation }))
}
if (channel.status === "unavailable") {
if (!next) return step(state)
return step(put(state, id, { status: "available", generation, value: undefined }))
}
// A provider that comes back may answer a subscribe that failed before.
if (!next) return step(state)
return subscribe(state, id, { generation, available: true, moved: true })
}
function subscribe(
state: IpcState,
id: string,
input: { readonly generation: number; readonly available: boolean; readonly moved: boolean },
) {
const attempt = state.issued + 1
return step(put({ ...state, issued: attempt }, id, { status: "subscribing", attempt, pushed: undefined, ...input }), [
{ type: "subscribe", id, attempt },
{ type: "timer.start", id, attempt },
])
}
function put(state: IpcState, id: string, channel: IpcChannel): IpcState {
return { ...state, channels: { ...state.channels, [id]: channel } }
}
function step(state: IpcState, effects: readonly IpcEffect[] = []): IpcTransition {
return { state, effects }
}
+61 -3
View File
@@ -72,14 +72,69 @@ test("no-input methods pass their first argument's abort signal to the bridge",
ipcs.dispose()
})
test("a subscribe main rejects fails the Ipc until main provides it again", async () => {
const bridge = fakeBridge()
const ipcs = createIpcClients(bridge.value)
ipcs.client(token)
bridge.fail(new Error("main is busy"))
await Bun.sleep(0)
const failed = { failed: ipcs.failed(token), client: ipcs.client(token), subscribes: bridge.subscribes() }
bridge.emit({ type: "available", ipc: "fixture", available: true })
bridge.reply({ available: true, state: { count: 1 } })
await Bun.sleep(0)
expect(failed).toEqual({ failed: true, client: undefined, subscribes: 1 })
expect({ failed: ipcs.failed(token), state: ipcs.client(token)?.state(), subscribes: bridge.subscribes() }).toEqual({
failed: false,
state: { count: 1 },
subscribes: 2,
})
ipcs.dispose()
})
test("a payload its codec rejects reaches no reader and does not stop the bridge's other listeners", async () => {
const bridge = fakeBridge()
const Counter = Ipc.define({ id: "fixture", methods: {}, state: Schema.Struct({ count: Schema.Number }) })
const ipcs = createIpcClients(bridge.value)
const seen: string[] = []
ipcs.typed(Counter)
bridge.value.on((message) => void seen.push(message.type))
bridge.reply({ available: true, state: { count: 1 } })
await Bun.sleep(0)
bridge.emit({ type: "state", ipc: "fixture", state: { count: "many" } })
expect({ seen, state: ipcs.typed(Counter)?.state() }).toEqual({ seen: ["state"], state: { count: 1 } })
ipcs.dispose()
})
test("a subscribe reply that lands after dispose changes nothing", async () => {
const bridge = fakeBridge()
const ipcs = createIpcClients(bridge.value)
ipcs.client(token)
ipcs.dispose()
bridge.reply({ available: true })
await Bun.sleep(0)
expect({ client: ipcs.client(token), generation: ipcs.generation(token) }).toEqual({
client: undefined,
generation: 0,
})
})
function fakeBridge() {
const listeners = new Set<(message: BridgeMessage) => void>()
const pending = Promise.withResolvers<Reply>()
// One reply per subscribe, answered in order.
const replies: PromiseWithResolvers<Reply>[] = []
const value: Bridge = {
packaged: false,
call: () => Promise.reject(new Error("no calls in this test")),
subscribe: () => pending.promise,
subscribe: () => {
const reply = Promise.withResolvers<Reply>()
replies.push(reply)
return reply.promise
},
on: (listener) => {
listeners.add(listener)
@@ -103,6 +158,9 @@ function fakeBridge() {
return {
value,
emit: (message: BridgeMessage) => listeners.forEach((listener) => listener(message)),
reply: (reply: Reply) => pending.resolve(reply),
/** Answers the latest subscribe. */
reply: (reply: Reply) => replies.at(-1)?.resolve(reply),
fail: (cause: unknown) => replies.at(-1)?.reject(cause),
subscribes: () => replies.length,
}
}
+115 -78
View File
@@ -1,8 +1,19 @@
import { batch } from "solid-js"
import { untrack } from "solid-js"
import { createStore, reconcile } from "solid-js/store"
import { Schema } from "effect"
import { Exit, Schema } from "effect"
import type { Ipc, IpcCallOptions, IpcClient, IpcSpec } from "@opencode/plugin/gui"
import type { Bridge } from "@opencode/plugin/gui/host"
import {
createIpcState,
selectIpcAvailable,
selectIpcFailed,
selectIpcGeneration,
selectIpcNeedsSubscribe,
selectIpcValue,
transitionIpc,
type IpcEffect,
type IpcEvent,
} from "./ipc-machine"
type Codec = NonNullable<IpcSpec["state"]>
@@ -12,107 +23,128 @@ type Decoded = Codec["Type"]
/** A value as it crosses the bridge, encoded by an Ipc's codec. */
type Encoded = Codec["Encoded"]
type IpcState = {
available: Record<string, boolean | undefined>
values: Record<string, Decoded>
// Counts each time an Ipc becomes available, so users can tell a returning provider from the one they had.
generations: Record<string, number | undefined>
}
type View = { available: boolean; generation: number; failed: boolean; value: Decoded }
// How long main may take to answer a subscribe before the Ipc counts as failed.
const subscribeTimeout = 10_000
/** Renderer-side clients for the Ipcs that plugins provide in the main process. */
export function createIpcClients(bridge: Bridge | undefined) {
const [state, setState] = createStore<IpcState>({ available: {}, values: {}, generations: {} })
const setAvailable = (id: string, available: boolean) => {
if (available && !state.available[id]) setState("generations", id, (value = 0) => value + 1)
setState("available", id, available)
}
const machine = { state: createIpcState() }
// What readers see of each Ipc, projected from the machine and reconciled, so a change wakes only its own readers.
const [views, setViews] = createStore<Record<string, View | undefined>>({})
// Events an effect raises synchronously wait behind that effect.
const queue: IpcEvent[] = []
const timers = new Map<string, ReturnType<typeof setTimeout>>()
const specs = new Map<string, IpcSpec>()
const clients = new Map<string, IpcClient<IpcSpec>>()
const listeners = new Map<string, Set<(name: string, data: Decoded) => void>>()
const subscribed = new Set<string>()
// How many availability and state events reached each Ipc. Events are newer than any snapshot, so a
// subscribe reply only fills in what no event changed while it was in flight.
const changes = new Map<string, { available: number; state: number }>()
const changesOf = (id: string) => {
const existing = changes.get(id)
const dispatch = (event: IpcEvent) => {
queue.push(event)
if (existing) return existing
const created = { available: 0, state: 0 }
changes.set(id, created)
return created
if (queue.length === 1) untrack(drain)
}
const decodeState = (id: string, value: Encoded): Decoded => {
const schema = specs.get(id)?.state
const drain = () => {
const event = queue[0]
return schema ? Schema.decodeUnknownSync(schema)(value) : value
if (!event) return
const next = transitionIpc(machine.state, event)
if (next.state !== machine.state && event.type !== "disposed")
setViews(
event.id,
reconcile({
available: selectIpcAvailable(next.state, event.id),
generation: selectIpcGeneration(next.state, event.id),
failed: selectIpcFailed(next.state, event.id),
value: selectIpcValue(next.state, event.id),
}),
)
machine.state = next.state
next.effects.forEach(run)
queue.shift()
drain()
}
const stop = bridge?.on((message) => {
if (message.type === "state") {
if (!specs.has(message.ipc)) return
const run = (effect: IpcEffect) => {
if (effect.type === "subscribe") {
if (!bridge) return
changesOf(message.ipc).state++
setState("values", message.ipc, reconcile(decodeState(message.ipc, message.state)))
return void Promise.try(() => bridge.subscribe(effect.id)).then(
(result) => {
const state = result.state === undefined ? Exit.succeed(undefined) : decodeState(effect.id, result.state)
if (Exit.isFailure(state))
return dispatch({ type: "failed", id: effect.id, attempt: effect.attempt, cause: state.cause })
dispatch({
type: "subscribed",
id: effect.id,
attempt: effect.attempt,
available: result.available,
state: state.value,
})
},
(cause: unknown) => dispatch({ type: "failed", id: effect.id, attempt: effect.attempt, cause }),
)
}
if (effect.type === "timer.start") {
clearTimeout(timers.get(effect.id))
timers.set(
effect.id,
setTimeout(() => dispatch({ type: "timeout", id: effect.id, attempt: effect.attempt }), subscribeTimeout),
)
return
}
if (message.type === "available") {
const changed = changesOf(message.ipc)
changed.available++
// Going away clears the state too.
if (!message.available) changed.state++
batch(() => {
setAvailable(message.ipc, message.available)
if (!message.available) setState("values", message.ipc, undefined)
})
if (effect.type === "timer.stop") {
clearTimeout(timers.get(effect.id))
timers.delete(effect.id)
return
}
console.error(`[plugin] ${effect.id}`, effect.cause)
}
const decodeState = (id: string, value: Encoded) => {
const schema = specs.get(id)?.state
return schema ? Schema.decodeUnknownExit(schema)(value) : Exit.succeed(value)
}
// A payload its codec rejects is dropped here, so it never throws into the bridge's other listeners.
const stop = bridge?.on((message) => {
if (message.type === "available")
return dispatch({ type: "available", id: message.ipc, available: message.available })
if (message.type === "state") {
if (!specs.has(message.ipc)) return
const state = decodeState(message.ipc, message.state)
if (Exit.isFailure(state)) return console.error(`[plugin] ${message.ipc}`, state.cause)
return dispatch({ type: "state", id: message.ipc, value: state.value })
}
if (message.type !== "event") return
const schema = specs.get(message.ipc)?.events?.[message.name]
const data = schema ? Schema.decodeUnknownSync(schema)(message.data) : message.data
const data = schema ? Schema.decodeUnknownExit(schema)(message.data) : Exit.succeed(message.data)
listeners.get(message.ipc)?.forEach((listener) => listener(message.name, data))
if (Exit.isFailure(data)) return console.error(`[plugin] ${message.ipc}`, data.cause)
listeners.get(message.ipc)?.forEach((listener) => listener(message.name, data.value))
})
const subscribe = (connected: Bridge, token: Ipc) => {
if (subscribed.has(token.id)) return
subscribed.add(token.id)
specs.set(token.id, token.spec)
const before = { ...changesOf(token.id) }
void connected
.subscribe(token.id)
.then((result) => {
const after = changesOf(token.id)
batch(() => {
if (after.available === before.available) setAvailable(token.id, result.available)
if (after.state === before.state && result.state !== undefined)
setState("values", token.id, decodeState(token.id, result.state))
})
})
.catch((cause: unknown) => console.error(`[plugin] ${token.id}`, cause))
}
const create = (connected: Bridge, token: Ipc): IpcClient<IpcSpec> => {
const methods = Object.fromEntries(
Object.entries(token.spec.methods).map(([name, method]) => {
@@ -128,7 +160,7 @@ export function createIpcClients(bridge: Bridge | undefined) {
)
const client = Object.assign(methods, {
state: () => state.values[token.id],
state: () => (views[token.id]?.available ? views[token.id]?.value : undefined),
on(name: string, listener: (data: Decoded) => void) {
const set = listeners.get(token.id) ?? new Set()
@@ -152,9 +184,11 @@ export function createIpcClients(bridge: Bridge | undefined) {
const client = (token: Ipc) => {
if (!bridge) return undefined
subscribe(bridge, token)
specs.set(token.id, token.spec)
if (!state.available[token.id]) return undefined
if (selectIpcNeedsSubscribe(machine.state, token.id)) dispatch({ type: "subscribe", id: token.id })
if (!views[token.id]?.available) return undefined
const existing = clients.get(token.id)
@@ -170,7 +204,9 @@ export function createIpcClients(bridge: Bridge | undefined) {
return {
client,
/** How many times the Ipc became available; 0 until it first is. Reactive. */
generation: (token: Ipc) => state.generations[token.id] ?? 0,
generation: (token: Ipc) => views[token.id]?.generation ?? 0,
/** Main did not answer the Ipc's subscribe; the next time main provides it, the window asks again. Reactive. */
failed: (token: Ipc) => views[token.id]?.failed ?? false,
/** A client typed by its token, for host code that uses one Ipc directly. */
typed: <S extends IpcSpec>(token: Ipc<S>) =>
// SAFETY: the client was built from this token's spec, so its methods, state and events are those of `S`.
@@ -178,6 +214,7 @@ export function createIpcClients(bridge: Bridge | undefined) {
/** Stops listening to the bridge. Call it when the owner of these clients goes away. */
dispose() {
stop?.()
dispatch({ type: "disposed" })
},
}
}
+1
View File
@@ -95,6 +95,7 @@ export function PluginRoot(props: ParentProps) {
ipc={bridge ? (token) => ipcs.client(token) : undefined}
plugin={(id) => plugins()?.find((plugin) => plugin.definition.id === id)}
generation={ipcs.generation}
ipcFailed={ipcs.failed}
>
<PluginStyles />
<PluginThemes loaded={() => plugins() !== undefined} />