diff --git a/packages/desktop/src/main/plugin/index.ts b/packages/desktop/src/main/plugin/index.ts index 737977e19a0..a68b44596a2 100644 --- a/packages/desktop/src/main/plugin/index.ts +++ b/packages/desktop/src/main/plugin/index.ts @@ -11,12 +11,10 @@ const LEVELS = { debug: "Debug", info: "Info", warn: "Warn", error: "Error" } as import { DesktopCli } from "../service/desktop-cli" import { DesktopStorage } from "../storage" import type { PluginHost } from "./host" - -/** The host once it loaded, and its load while one is in flight. */ -type LoadedHost = { host?: PluginHost; loading?: Promise } +import { createDriver, loadedHost } from "./machine" export interface Interface { - /** Loads the host on first use. Main plugins activate only through `start`. */ + /** Loads the host on first use, and again after a load failed. Main plugins activate only through `start`. */ readonly host: () => Promise /** The host when something already loaded it. */ readonly loaded: () => PluginHost | undefined @@ -42,53 +40,51 @@ export const layer = Layer.effect( // Renderers subscribe and push servers while they boot, which can be before the host loads. const subscriptions = new Map>() const servers = new Map() - const current: LoadedHost = {} - const host = () => { - current.loading ??= Promise.all([import("./host"), runPromise(desktopCli.resolve)]).then(([module, cli]) => { - current.host = module.createHost({ - db: storage.db, - state: storage.state, - cli: { - version: cli.version, - command: cli.command, - binary: cli.binary, - development: !app.isPackaged && !cli.binary, - }, - subscriptions, - servers, - appState: lifecycle.state, - restart: lifecycle.restart, - log: (message, data) => runFork(Effect.logError(message, data)), - write: (level, message, data) => runFork(Effect.logWithLevel(LEVELS[level])(message, data)), - }) + const driver = createDriver({ + load: async () => { + const [module, cli] = await Promise.all([import("./host"), runPromise(desktopCli.resolve)]) - return current.host - }) - - return current.loading - } - - // Plugins run only once the host loaded; until then there is nothing to stop or resume. - const remove = yield* shutdown.add({ - stop: Effect.promise(async () => { - if (current.loading) - await current.loading.then( - (loaded) => loaded.stop(), - () => undefined, - ) - }), - resume: Effect.tryPromise(async () => { - if (current.loading) await current.loading.then((loaded) => loaded.resume()) - }).pipe(Effect.catch((error) => Effect.logError("plugins failed to resume", { error }))), + return () => + module.createHost({ + db: storage.db, + state: storage.state, + cli: { + version: cli.version, + command: cli.command, + binary: cli.binary, + development: !app.isPackaged && !cli.binary, + }, + subscriptions, + servers, + appState: lifecycle.state, + restart: lifecycle.restart, + log: (message, data) => runFork(Effect.logError(message, data)), + write: (level, message, data) => runFork(Effect.logWithLevel(LEVELS[level])(message, data)), + }) + }, + subscribed: () => [...subscriptions].flatMap((entry) => (entry[1].size ? [entry[0]] : [])), + log: (message, data) => runFork(Effect.logError(message, data)), }) - yield* Effect.addFinalizer(() => Effect.sync(remove)) + const remove = yield* shutdown.add({ + stop: Effect.promise(driver.stop), + resume: Effect.tryPromise(driver.resume).pipe( + Effect.catch((error) => Effect.logError("plugins failed to resume", { error })), + ), + }) + + yield* Effect.addFinalizer(() => + Effect.sync(() => { + remove() + driver.dispose() + }), + ) return Service.of({ - host, - loaded: () => current.host, - start: Effect.tryPromise(() => host().then((loaded) => loaded.start())).pipe( + host: driver.host, + loaded: () => loadedHost(driver.state()), + start: Effect.tryPromise(driver.start).pipe( Effect.catch((error) => Effect.logError("plugins failed to start", { error })), ), subscribe(ipc, window) { @@ -97,12 +93,9 @@ export const layer = Layer.effect( subscriptions.set(ipc, ids) // A booting window waits on some Ipcs (e.g. server sources) before its first paint, so the // plugin that provides one starts now instead of with the deferred rest. - void host().then( - (loaded) => loaded.demand(ipc), - () => undefined, - ) + driver.demand(ipc) - return current.host?.snapshot(ipc, window) ?? { available: false } + return loadedHost(driver.state())?.snapshot(ipc, window) ?? { available: false } }, configure(window, list) { // Re-inserting keeps the most recent window last, which resolution prefers. diff --git a/packages/desktop/src/main/plugin/machine.test.ts b/packages/desktop/src/main/plugin/machine.test.ts new file mode 100644 index 00000000000..0b6fcf7b438 --- /dev/null +++ b/packages/desktop/src/main/plugin/machine.test.ts @@ -0,0 +1,221 @@ +import { afterEach, beforeEach, describe, expect, jest, test } from "bun:test" +import { PluginError } from "./error" +import { createDriver, initialState, LOAD_TIMEOUT_MS, loadedHost, transition, type Event, type State } from "./machine" + +type Host = { readonly name: string } + +const host: Host = { name: "host" } + +const reply = () => ({ resolve: () => {}, reject: () => {} }) + +/** Applies the events in order and returns the last state. */ +const replay = (events: readonly Event[], from: State = initialState()) => + events.reduce((state, event) => transition(state, event).state, from) + +const eperm = Object.assign(new Error("EPERM: operation not permitted, copyfile"), { code: "EPERM" }) + +describe("plugin host machine", () => { + test.each([ + { + name: "a newer load is in flight", + state: replay([ + { type: "host.requested", reply: reply() }, + { type: "load.failed", attempt: 1, error: eperm }, + { type: "host.requested", reply: reply() }, + ]), + }, + { + name: "a stop dropped the load", + state: replay([ + { type: "host.requested", reply: reply() }, + { type: "stop.requested", reply: reply() }, + ]), + }, + { + name: "the app disposed the host", + state: replay([{ type: "host.requested", reply: reply() }, { type: "disposed" }]), + }, + ])("drops a late result for load 1 when $name", (row) => { + const late = [ + { type: "load.succeeded", attempt: 1, host }, + { type: "load.failed", attempt: 1, error: eperm }, + { type: "load.timed-out", attempt: 1 }, + ] satisfies Event[] + + late.forEach((event) => expect(transition(row.state, event)).toEqual({ state: row.state, commands: [] })) + }) + + test("a loaded host stays reachable through a stop, for the plugin a restart handoff keeps", () => { + const ready = replay([ + { type: "host.requested", reply: reply() }, + { type: "load.succeeded", attempt: 1, host }, + ]) + + const stopped = transition(ready, { type: "stop.requested", reply: reply() }) + + expect(stopped.state).toBe(ready) + expect(loadedHost(stopped.state)).toBe(host) + expect(stopped.commands.map((command) => command.type)).toEqual(["stop"]) + }) + + test("disposal hides the host and refuses later loads", () => { + const disposed = replay([ + { type: "host.requested", reply: reply() }, + { type: "load.succeeded", attempt: 1, host }, + { type: "disposed" }, + ]) + + expect(loadedHost(disposed)).toBeUndefined() + expect(transition(disposed, { type: "host.requested", reply: reply() }).commands).toEqual([ + expect.objectContaining({ type: "reject", reason: { kind: "unavailable" } }), + ]) + }) +}) + +/** A host that counts how often main plugins started, which Ipcs it was asked for, and how often a load built one. */ +const fixture = () => { + const built = { count: 0 } + const demanded: string[] = [] + const calls = { start: 0, demand: demanded } + + const fake = { + start: async () => void calls.start++, + stop: async () => {}, + resume: async () => {}, + demand: (ipc: string) => void calls.demand.push(ipc), + } + + const loads: PromiseWithResolvers<() => typeof fake>[] = [] + + const build = () => { + built.count++ + + return fake + } + + const driver = createDriver({ + load: () => { + const load = Promise.withResolvers<() => typeof fake>() + loads.push(load) + + return load.promise + }, + subscribed: () => ["opencode.servers.list"], + log: () => {}, + }) + + return { driver, loads, built, calls, build, fake } +} + +// Fake timers leave setImmediate real: one turn drains every pending microtask. +const flush = () => new Promise((resolve) => setImmediate(resolve)) + +describe("plugin host driver", () => { + beforeEach(() => jest.useFakeTimers()) + + afterEach(() => { + jest.clearAllTimers() + jest.useRealTimers() + }) + + test("a boot start that failed to load activates main plugins once a later use loads the host", async () => { + const plugins = fixture() + const boot = plugins.driver.start() + await flush() + plugins.loads[0].reject(eperm) + await expect(boot).rejects.toBe(eperm) + + // On dev the rejected load was kept, so every later use failed until the app relaunched. + plugins.driver.demand("opencode.servers.list") + await flush() + plugins.loads[1].resolve(plugins.build) + await flush() + + expect(plugins.calls.start).toBe(1) + expect(plugins.driver.state()).toEqual({ status: "ready", host: plugins.fake, started: true }) + }) + + test("a subscription made while the load failed activates its plugin once a later load succeeds", async () => { + const plugins = fixture() + plugins.driver.demand("opencode.servers.list") + await flush() + plugins.loads[0].reject(eperm) + await flush() + + const list = plugins.driver.host() + await flush() + plugins.loads[1].resolve(plugins.build) + await list + + expect(plugins.calls.demand).toEqual(["opencode.servers.list"]) + expect(plugins.calls.start).toBe(0) + }) + + test("a boot load that times out still activates main plugins when the CLI lookup finishes late", async () => { + const plugins = fixture() + const boot = plugins.driver.start() + await flush() + + jest.advanceTimersByTime(LOAD_TIMEOUT_MS) + await expect(boot).rejects.toMatchObject({ code: "failed", message: "plugin host load timed out" }) + + plugins.loads[0].resolve(plugins.build) + await flush() + + expect(plugins.calls.start).toBe(1) + expect(plugins.driver.state()).toEqual({ status: "ready", host: plugins.fake, started: true }) + }) + + test("a hung load times out, and the next use loads again without building the hung one", async () => { + const plugins = fixture() + const first = plugins.driver.host() + await flush() + + jest.advanceTimersByTime(LOAD_TIMEOUT_MS) + await expect(first).rejects.toMatchObject({ code: "failed" }) + + const second = plugins.driver.host() + await flush() + plugins.loads[1].resolve(plugins.build) + expect(await second).toBe(plugins.fake) + + plugins.loads[0].resolve(plugins.build) + await flush() + expect(plugins.built.count).toBe(1) + }) + + test("a quit during the load never builds the host and does not wait for the load", async () => { + const plugins = fixture() + const list = plugins.driver.host() + await flush() + + // On dev the stop waited for the CLI copy, then built a host against closing storage only to stop it. + await plugins.driver.stop() + await expect(list).rejects.toBeInstanceOf(PluginError) + await expect(list).rejects.toMatchObject({ code: "unavailable" }) + + plugins.loads[0].resolve(plugins.build) + await flush() + + expect(plugins.built.count).toBe(0) + expect(plugins.driver.state().status).toBe("stopped") + }) + + test("a quit before any load refuses later uses until the plugins resume, then starts what boot asked for", async () => { + const plugins = fixture() + await plugins.driver.stop() + + // On dev a window's request during the quit built a host that nothing stopped. + await expect(plugins.driver.host()).rejects.toMatchObject({ code: "unavailable" }) + await plugins.driver.start() + expect(plugins.loads).toHaveLength(0) + + // A failed restart handoff resumes the app. + const resumed = plugins.driver.resume() + await flush() + plugins.loads[0].resolve(plugins.build) + await resumed + + expect(plugins.calls.start).toBe(1) + }) +}) diff --git a/packages/desktop/src/main/plugin/machine.ts b/packages/desktop/src/main/plugin/machine.ts new file mode 100644 index 00000000000..7206790fe80 --- /dev/null +++ b/packages/desktop/src/main/plugin/machine.ts @@ -0,0 +1,374 @@ +import { PluginError } from "./error" +import type { ErrorLog } from "./lifecycle" + +/** Bounds one load of the host module and the CLI, so no caller waits on a hung load forever. */ +export const LOAD_TIMEOUT_MS = 30_000 + +/** Settles a caller's promise. */ +export type Reply = { readonly resolve: (value: Value) => void; readonly reject: (cause: unknown) => void } + +/** + * Where the main-process plugin host stands. `attempt` names the load in flight, so a load that a stop, a timeout or + * disposal superseded is dropped without building its host. `started` records that the app asked for main plugins, + * so a load that succeeds after a failed one still activates them. + */ +export type State = + /** No host yet: the next use loads it, also after a failed or timed-out load. A timed-out load that finishes later still counts. */ + | { readonly status: "idle"; readonly attempt: number; readonly started: boolean } + | { + readonly status: "loading" + readonly attempt: number + readonly started: boolean + readonly hosts: readonly Reply[] + readonly starts: readonly Reply[] + } + /** Stays ready through a stop: the plugin a restart handoff keeps still runs, and the host gates activation itself. */ + | { readonly status: "ready"; readonly host: Host; readonly started: boolean } + /** The app stopped its plugins before a host loaded: nothing loads until it resumes them. */ + | { readonly status: "stopped"; readonly attempt: number; readonly started: boolean } + | { readonly status: "disposed" } + +export type Event = + | { readonly type: "host.requested"; readonly reply: Reply } + /** A window subscribed to an Ipc and waits on the plugin that provides it. */ + | { readonly type: "demand.requested"; readonly ipc: string } + | { readonly type: "start.requested"; readonly reply: Reply } + | { readonly type: "load.succeeded"; readonly attempt: number; readonly host: Host } + | { readonly type: "load.failed"; readonly attempt: number; readonly error: unknown } + | { readonly type: "load.timed-out"; readonly attempt: number } + | { readonly type: "stop.requested"; readonly reply: Reply } + | { readonly type: "resume.requested"; readonly reply: Reply } + | { readonly type: "disposed" } + +export type RejectReason = + | { readonly kind: "failed"; readonly error: unknown } + | { readonly kind: "timed-out" } + | { readonly kind: "unavailable" } + +export type Command = + | { readonly type: "load"; readonly attempt: number } + | { readonly type: "start"; readonly host: Host; readonly replies: readonly Reply[] } + | { readonly type: "demand"; readonly host: Host; readonly ipc: string } + /** Demands every Ipc a window subscribed to while no host was loaded. */ + | { readonly type: "demand-subscribed"; readonly host: Host } + | { readonly type: "stop"; readonly host: Host; readonly reply: Reply } + | { readonly type: "resume"; readonly host: Host; readonly reply: Reply } + | { readonly type: "resolve-host"; readonly host: Host; readonly replies: readonly Reply[] } + | { readonly type: "resolve"; readonly replies: readonly Reply[] } + | { + readonly type: "reject" + readonly replies: readonly Pick, "reject">[] + readonly reason: RejectReason + } + +export type Transition = { readonly state: State; readonly commands: readonly Command[] } + +export function initialState(): State { + return { status: "idle", attempt: 0, started: false } +} + +export function transition(state: State, event: Event): Transition { + if (state.status === "disposed") return disposed(state, event) + + if (event.type === "disposed") return dispose(state) + + if (event.type === "stop.requested") return stop(state, event.reply) + + if (event.type === "resume.requested") return resume(state, event.reply) + + if (state.status === "ready") return ready(state, event) + + if (state.status === "loading") return loading(state, event) + + // The CLI lookup a timed-out load waited on keeps running. When it finishes and nothing replaced that load, its host + // still serves the start and the subscriptions it was for. + if (event.type === "load.succeeded" && state.status === "idle" && event.attempt === state.attempt) + return loaded(event.host, state.started, [], []) + + if (event.type === "host.requested") { + if (state.status === "stopped") return unchanged(state, [reject([event.reply], { kind: "unavailable" })]) + + return load(state, { hosts: [event.reply] }) + } + + if (event.type === "start.requested") { + if (state.status === "stopped") + return { state: { ...state, started: true }, commands: [{ type: "resolve", replies: [event.reply] }] } + + return load(state, { started: true, starts: [event.reply] }) + } + + if (event.type === "demand.requested" && state.status === "idle") return load(state, {}) + + return unchanged(state) +} + +/** The host once it loaded, until the app disposed it. */ +export const loadedHost = (state: State) => (state.status === "ready" ? state.host : undefined) + +/** Whether the machine still takes the load `attempt`: the one in flight, or one that timed out and nothing replaced. */ +export const isCurrentLoad = (state: State, attempt: number) => + (state.status === "loading" || state.status === "idle") && state.attempt === attempt + +/** Claims the next load in the same event that asked for it. */ +function load( + state: Extract, { status: "idle" | "stopped" }>, + input: { readonly started?: boolean; readonly hosts?: Reply[]; readonly starts?: Reply[] }, +): Transition { + const attempt = state.attempt + 1 + + return { + state: { + status: "loading", + attempt, + started: state.started || !!input.started, + hosts: input.hosts ?? [], + starts: input.starts ?? [], + }, + commands: [{ type: "load", attempt }], + } +} + +function loading(state: Extract, { status: "loading" }>, event: Event): Transition { + if (event.type === "host.requested") + return { state: { ...state, hosts: [...state.hosts, event.reply] }, commands: [] } + + if (event.type === "start.requested") + return { state: { ...state, started: true, starts: [...state.starts, event.reply] }, commands: [] } + + if (event.type !== "load.succeeded" && event.type !== "load.failed" && event.type !== "load.timed-out") + return unchanged(state) + + if (event.attempt !== state.attempt) return unchanged(state) + + if (event.type === "load.succeeded") return loaded(event.host, state.started, state.hosts, state.starts) + + return { + state: { status: "idle", attempt: state.attempt, started: state.started }, + commands: waiters( + state, + event.type === "load.failed" ? { kind: "failed", error: event.error } : { kind: "timed-out" }, + ), + } +} + +function loaded( + host: Host, + started: boolean, + hosts: readonly Reply[], + starts: readonly Reply[], +): Transition { + return { + state: { status: "ready", host, started }, + commands: [ + ...(hosts.length ? [{ type: "resolve-host" as const, host, replies: hosts }] : []), + started ? { type: "start", host, replies: starts } : { type: "demand-subscribed", host }, + ], + } +} + +function ready(state: Extract, { status: "ready" }>, event: Event): Transition { + if (event.type === "host.requested") + return unchanged(state, [{ type: "resolve-host", host: state.host, replies: [event.reply] }]) + + if (event.type === "demand.requested") + return unchanged(state, [{ type: "demand", host: state.host, ipc: event.ipc }]) + + if (event.type === "start.requested") { + if (state.started) return unchanged(state, [{ type: "resolve", replies: [event.reply] }]) + + return { + state: { ...state, started: true }, + commands: [{ type: "start", host: state.host, replies: [event.reply] }], + } + } + + return unchanged(state) +} + +function stop(state: Exclude, { status: "disposed" }>, reply: Reply): Transition { + // A second stop (a quit during a restart handoff) also stops the plugin the handoff kept. + if (state.status === "ready") return unchanged(state, [{ type: "stop", host: state.host, reply }]) + + if (state.status === "stopped") return unchanged(state, [{ type: "resolve", replies: [reply] }]) + + // A load in flight is dropped: its host is never built against storage that is about to close. + if (state.status === "loading") + return { + state: { status: "stopped", attempt: state.attempt, started: state.started }, + commands: [ + ...(state.hosts.length ? [reject(state.hosts, { kind: "unavailable" })] : []), + { type: "resolve" as const, replies: [...state.starts, reply] }, + ], + } + + return { + state: { status: "stopped", attempt: state.attempt, started: state.started }, + commands: [{ type: "resolve", replies: [reply] }], + } +} + +function resume(state: Exclude, { status: "disposed" }>, reply: Reply): Transition { + if (state.status === "ready") return unchanged(state, [{ type: "resume", host: state.host, reply }]) + + if (state.status !== "stopped") return unchanged(state, [{ type: "resolve", replies: [reply] }]) + + // Main plugins the stop kept from starting start now, and the resume settles once they did. + if (state.started) return load(state, { starts: [reply] }) + + return { + state: { status: "idle", attempt: state.attempt, started: false }, + commands: [{ type: "resolve", replies: [reply] }], + } +} + +function dispose(state: Exclude, { status: "disposed" }>): Transition { + if (state.status !== "loading") return { state: { status: "disposed" }, commands: [] } + + return { + state: { status: "disposed" }, + commands: [ + ...(state.hosts.length ? [reject(state.hosts, { kind: "unavailable" })] : []), + ...(state.starts.length ? [{ type: "resolve" as const, replies: state.starts }] : []), + ], + } +} + +function disposed(state: Extract, { status: "disposed" }>, event: Event): Transition { + if (event.type === "host.requested") return unchanged(state, [reject([event.reply], { kind: "unavailable" })]) + + if (event.type === "start.requested" || event.type === "stop.requested" || event.type === "resume.requested") + return unchanged(state, [{ type: "resolve", replies: [event.reply] }]) + + return unchanged(state) +} + +function waiters(state: Extract, { status: "loading" }>, reason: RejectReason): Command[] { + const replies = [...state.hosts, ...state.starts] + + return replies.length ? [reject(replies, reason)] : [] +} + +function reject(replies: readonly Pick, "reject">[], reason: RejectReason): Command { + return { type: "reject", replies, reason } +} + +function unchanged(state: State, commands: Command[] = []): Transition { + return { state, commands } +} + +/** + * Runs the machine: it applies each event, then performs the commands, each of which reports back through a later + * event. Besides the load timers it holds no other state. + */ +export function createDriver< + Host extends { + start(): Promise + stop(): Promise + resume(): Promise + demand(ipc: string): void + }, +>(input: { + /** Loads the host module and the CLI, and returns how to build the host from them. */ + readonly load: () => Promise<() => Host> + /** The Ipcs windows subscribed to. */ + readonly subscribed: () => readonly string[] + readonly log: ErrorLog +}) { + const current = { state: initialState() } + + const timers = new Map>() + + const dispatch = (event: Event) => { + const previous = current.state + const next = transition(previous, event) + current.state = next.state + + if (previous.status === "loading" && next.state.status !== "loading") { + clearTimeout(timers.get(previous.attempt)) + timers.delete(previous.attempt) + } + + next.commands.forEach(perform) + } + + const perform = (command: Command) => { + if (command.type === "load") { + timers.set( + command.attempt, + setTimeout(() => dispatch({ type: "load.timed-out", attempt: command.attempt }), LOAD_TIMEOUT_MS), + ) + + return void Promise.resolve() + .then(input.load) + // Building the host reads storage and follows windows, the locale and the menubar, so a load that something + // superseded while it ran builds nothing. + .then((build) => (isCurrentLoad(current.state, command.attempt) ? build() : undefined)) + .then( + (host) => { + if (host) dispatch({ type: "load.succeeded", attempt: command.attempt, host }) + }, + (cause: unknown) => dispatch({ type: "load.failed", attempt: command.attempt, error: cause }), + ) + } + + if (command.type === "start") + return void Promise.resolve() + .then(() => command.host.start()) + .then( + () => command.replies.forEach((reply) => reply.resolve()), + (cause: unknown) => { + // Nobody waits on a start a later load carried over from a failed one. + if (!command.replies.length) return input.log("plugins failed to start", { error: cause }) + + command.replies.forEach((reply) => reply.reject(cause)) + }, + ) + + if (command.type === "demand") return command.host.demand(command.ipc) + + if (command.type === "demand-subscribed") return input.subscribed().forEach((ipc) => command.host.demand(ipc)) + + // The app quits whether or not every plugin stopped cleanly. + if (command.type === "stop") + return void Promise.resolve() + .then(() => command.host.stop()) + .catch((cause: unknown) => input.log("plugins failed to stop", { error: cause })) + .then(() => command.reply.resolve()) + + if (command.type === "resume") + return void Promise.resolve() + .then(() => command.host.resume()) + .then(command.reply.resolve, command.reply.reject) + + if (command.type === "resolve-host") return command.replies.forEach((reply) => reply.resolve(command.host)) + + if (command.type === "resolve") return command.replies.forEach((reply) => reply.resolve()) + + const cause = rejection(command.reason) + command.replies.forEach((reply) => reply.reject(cause)) + } + + const ask = (event: (reply: Reply) => Event) => + new Promise((resolve, reject) => dispatch(event({ resolve, reject }))) + + return { + state: () => current.state, + /** Loads the host on first use, and again after a load failed. */ + host: () => ask((reply) => ({ type: "host.requested", reply })), + /** Loads the host and activates main plugins; a later load activates them when this one fails. */ + start: () => ask((reply) => ({ type: "start.requested", reply })), + demand: (ipc: string) => dispatch({ type: "demand.requested", ipc }), + stop: () => ask((reply) => ({ type: "stop.requested", reply })), + resume: () => ask((reply) => ({ type: "resume.requested", reply })), + dispose: () => dispatch({ type: "disposed" }), + } +} + +function rejection(reason: RejectReason) { + if (reason.kind === "failed") return reason.error + + if (reason.kind === "timed-out") return new PluginError("failed", { message: "plugin host load timed out" }) + + return new PluginError("unavailable") +} diff --git a/packages/desktop/src/main/service/desktop-cli-state.test.ts b/packages/desktop/src/main/service/desktop-cli-state.test.ts new file mode 100644 index 00000000000..93b37dfc2d6 --- /dev/null +++ b/packages/desktop/src/main/service/desktop-cli-state.test.ts @@ -0,0 +1,86 @@ +import { expect, test } from "bun:test" +import { Deferred, Effect, Exit, Fiber, Scope } from "effect" +import { DesktopCliState } from "./desktop-cli-state" + +const cli = { version: "2.0.0", command: ["opencode-cli"], binary: "opencode-cli" } + +const eperm = new Error("EPERM: operation not permitted, copyfile") + +test.each([ + { name: "fails", failure: Effect.fail(eperm) }, + { name: "dies", failure: Effect.die(eperm) }, +])("a lookup that $name is looked up again by the next caller, and a success is kept", async (row) => { + const calls = await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const calls = { count: 0 } + const gate = yield* Deferred.make() + + const resolve = yield* DesktopCliState.make( + Effect.suspend(() => { + calls.count++ + + return calls.count === 1 ? Deferred.await(gate).pipe(Effect.andThen(row.failure)) : Effect.succeed(cli) + }), + ) + + // The background service and the plugin host both ask at boot; on dev the shared failure stuck for both. + const first = yield* Effect.forkChild(Effect.exit(resolve), { startImmediately: true }) + const second = yield* Effect.forkChild(Effect.exit(resolve), { startImmediately: true }) + yield* Deferred.succeed(gate, undefined) + expect(Exit.isFailure(yield* Fiber.join(first))).toBe(true) + expect(Exit.isFailure(yield* Fiber.join(second))).toBe(true) + + expect(yield* resolve).toEqual(cli) + expect(yield* resolve).toEqual(cli) + + return calls.count + }), + ), + ) + + expect(calls).toBe(2) +}) + +test("a caller that gives up does not interrupt the lookup another caller waits on", async () => { + const result = await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const gate = yield* Deferred.make() + const resolve = yield* DesktopCliState.make(Deferred.await(gate).pipe(Effect.as(cli))) + const leaving = yield* Effect.forkChild(resolve, { startImmediately: true }) + const staying = yield* Effect.forkChild(resolve, { startImmediately: true }) + + yield* Fiber.interrupt(leaving) + yield* Deferred.succeed(gate, undefined) + + return yield* Fiber.join(staying) + }), + ), + ) + + expect(result).toEqual(cli) +}) + +test("closing the scope interrupts the lookup in flight and starts none after", async () => { + const calls = { count: 0 } + const scope = Scope.makeUnsafe() + + const resolve = await Effect.runPromise( + DesktopCliState.make( + Effect.suspend(() => { + calls.count++ + + return Effect.never + }), + ).pipe(Scope.provide(scope)), + ) + + const waiting = Effect.runFork(resolve) + await Effect.runPromise(Effect.yieldNow) + await Effect.runPromise(Scope.close(scope, Exit.void)) + + expect(Exit.hasInterrupts(await Effect.runPromise(Fiber.await(waiting)))).toBe(true) + expect(Exit.hasInterrupts(await Effect.runPromise(Effect.exit(resolve)))).toBe(true) + expect(calls.count).toBe(1) +}) diff --git a/packages/desktop/src/main/service/desktop-cli-state.ts b/packages/desktop/src/main/service/desktop-cli-state.ts new file mode 100644 index 00000000000..3b179d2f8a6 --- /dev/null +++ b/packages/desktop/src/main/service/desktop-cli-state.ts @@ -0,0 +1,47 @@ +export * as DesktopCliState from "./desktop-cli-state" + +import { Deferred, Effect, Exit } from "effect" + +/** Where the lookup stands. A failed one returns to `idle`, so the next caller looks again. */ +type State = + | { readonly status: "idle" } + | { readonly status: "resolving"; readonly deferred: Deferred.Deferred } + | { readonly status: "resolved"; readonly value: A } + +function idle(): State { + return { status: "idle" } +} + +/** + * Runs `load` once for every caller that arrives while it runs, and keeps only a success. It runs in the layer's + * scope, so a caller that gives up does not interrupt it for the others, and closing the scope interrupts it. + */ +export const make = Effect.fnUntraced(function* (load: Effect.Effect) { + const scope = yield* Effect.scope + const current = { state: idle() } + + // The claim and the fork are one uninterruptible step, so a caller interrupted between them cannot leave a + // `resolving` state that nothing settles. + return Effect.uninterruptibleMask((restore) => + Effect.suspend(() => { + const state = current.state + + if (state.status === "resolved") return Effect.succeed(state.value) + + if (state.status === "resolving") return restore(Deferred.await(state.deferred)) + const deferred = Deferred.makeUnsafe() + current.state = { status: "resolving", deferred } + + return Effect.forkIn(load, scope).pipe( + Effect.map((fiber) => + // An observer also runs for a fiber that a closed scope interrupted before it started. + fiber.addObserver((exit) => { + current.state = Exit.isSuccess(exit) ? { status: "resolved", value: exit.value } : idle() + Deferred.doneUnsafe(deferred, exit) + }), + ), + Effect.andThen(restore(Deferred.await(deferred))), + ) + }), + ) +}) diff --git a/packages/desktop/src/main/service/desktop-cli.ts b/packages/desktop/src/main/service/desktop-cli.ts index 6f154f33d10..84cd85c4ef1 100644 --- a/packages/desktop/src/main/service/desktop-cli.ts +++ b/packages/desktop/src/main/service/desktop-cli.ts @@ -10,9 +10,13 @@ import { DesktopPaths } from "../paths" import { BUNDLED_CLI_VERSION_KEY } from "../storage/keys" import { getStore } from "../storage/store" import { parseCliVersion, stageName } from "./cli-version" +import { DesktopCliState } from "./desktop-cli-state" const execFileAsync = promisify(execFile) +// The first `--version` after an update can take several seconds while antivirus scans the executable. +const RUN_TIMEOUT_MS = 30_000 + export interface Resolved { readonly version: string readonly command: readonly string[] @@ -31,7 +35,8 @@ export const layer = Layer.effect( Effect.gen(function* () { const path = yield* Path.Path - const resolve = yield* Effect.cached( + // A failed lookup (for example a stage copy that antivirus held open) runs again on the next use. + const resolve = yield* DesktopCliState.make( make().pipe(Effect.provide(yield* Effect.context()), Effect.orDie), ) @@ -166,7 +171,9 @@ const installCli = Effect.fn("DesktopCli.install")(function* (source: string, ve const run = Effect.fn("DesktopCli.run")(function* (binary: string, args: string[]) { yield* Effect.logInfo("v2 CLI command started", { binary, args }) - const result = yield* Effect.tryPromise(() => execFileAsync(binary, args, { windowsHide: true })).pipe( + const result = yield* Effect.tryPromise(() => + execFileAsync(binary, args, { windowsHide: true, timeout: RUN_TIMEOUT_MS }), + ).pipe( Effect.tapError((error) => { const output = Option.getOrUndefined(Schema.decodeUnknownOption(ExecFailure)(error.cause))