Skip to content

Commit 76450ed

Browse files
PJ-Zetierclaude
andcommitted
fix: do not gate TUI/server readiness on plugin installs
On airgapped or degraded networks a cold plugin install can hang in npm's retry ladder for minutes, and both the TUI first frame and the server plugin-activation latch waited on it without a bound. Stop gating TUI readiness on the first reconcile after 10 seconds while it keeps running in the background, so plugins still activate when it finishes. Bound each plugin setup at 15 seconds through the existing failed-slot path so activation always settles, and bound the per-package install await at 30 seconds so an unreachable registry fails that plugin and the rest of the generation proceeds. Config changes and the periodic re-check retry failed installs as before, and hung setups and installs are covered by deterministic tests. Refs anomalyco#2224 Refs anomalyco#19197 Co-Authored-By: Claude Mythos 5 <[email protected]>
1 parent aede901 commit 76450ed

6 files changed

Lines changed: 110 additions & 7 deletions

File tree

‎packages/core/src/plugin.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { Plugin } from "@opencode/schema/plugin"
55
import { Node } from "@opencode/util/effect/app-node"
66
import { LayerNode } from "@opencode/util/effect/layer-node"
77
import type { PersistentPty } from "./persistent-pty.js"
8-
import { Cause, Context, Effect, Exit, Latch, Layer, Logger, Queue, References, Scope, Semaphore } from "effect"
8+
import { Cause, Context, Duration, Effect, Exit, Latch, Layer, Logger, Queue, References, Scope, Semaphore } from "effect"
99
import { Bus } from "./bus.js"
1010
import { KV } from "./kv.js"
1111
import { PluginHost } from "./plugin/host.js"
@@ -14,6 +14,13 @@ import { State } from "./state.js"
1414

1515
export { awaitActivation, type Generation, type Interface, Service } from "./plugin/service.js"
1616

17+
// Activation (and readiness gated on it) awaits every setup, and a plugin's setup may wait on
18+
// the network with no deadline of its own. A timed-out setup takes the same failed-slot path
19+
// as a thrown one, so the rest of the generation still activates.
20+
export const SetupTimeout = Context.Reference<Duration.Duration>("@opencode/Plugin/SetupTimeout", {
21+
defaultValue: () => Duration.seconds(30),
22+
})
23+
1724
const layer = Layer.effect(
1825
Service,
1926
Effect.gen(function* () {
@@ -45,6 +52,7 @@ const layer = Layer.effect(
4552
})
4653
const host = yield* PluginHost.make({ list })
4754
const load = Effect.fnUntraced(function* (plugin: Generation) {
55+
const timeout = yield* SetupTimeout
4856
const activation: Activation = { plugin, scope: yield* Scope.fork(scope) }
4957
const inherit = yield* State.inherit()
5058
const grouped = State.group((failure, refresh) => {
@@ -73,6 +81,10 @@ const layer = Layer.effect(
7381
),
7482
),
7583
Effect.withSpan("Plugin.load", { attributes: { "plugin.id": plugin.id } }),
84+
Effect.timeoutOrElse({
85+
duration: timeout,
86+
orElse: () => Effect.fail(new Error(`Plugin setup did not finish within ${Duration.format(timeout)}`)),
87+
}),
7688
Effect.onExit((exit) =>
7789
Exit.isFailure(exit) && !activation.failure ? Scope.close(activation.scope, exit) : Effect.void,
7890
),

‎packages/core/src/plugin/module.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import type { Plugin } from "@opencode/plugin/effect/plugin"
44
import { Host } from "@opencode/plugin/host"
55
import { createPluginSources } from "@opencode/plugin/source"
66
import { Npm } from "@opencode/util/npm"
7-
import { Deferred, Effect, FiberSet, PubSub, Schema, Stream } from "effect"
7+
import { Deferred, Duration, Effect, FiberSet, PubSub, Schema, Stream } from "effect"
88
import path from "path"
99
import { stat } from "node:fs/promises"
1010
import { fileURLToPath, pathToFileURL } from "url"
@@ -95,6 +95,11 @@ export class LoadError extends Schema.TaggedError<LoadError>()("PluginModule.Loa
9595
cause: Schema.optional(Schema.Defect()),
9696
}) {}
9797

98+
// On offline hosts a cold install hangs in npm's retry ladder while the activation generation
99+
// awaits it. Bound the wait so the plugin reports failed and the rest of the generation
100+
// proceeds; a config change or the periodic refresh retries the install.
101+
const installTimeout = Duration.seconds(30)
102+
98103
const load = Effect.fn("PluginModule.load")(function* (
99104
operation: Extract<ConfigPluginSource.Operation, { type: "add" }>,
100105
sources: ReturnType<typeof createPluginSources>,
@@ -106,7 +111,17 @@ const load = Effect.fn("PluginModule.load")(function* (
106111
? undefined
107112
: options?.install === false
108113
? yield* npm.resolve(operation.target)
109-
: yield* npm.add(operation.target)
114+
: yield* npm.add(operation.target).pipe(
115+
Effect.timeoutOrElse({
116+
duration: installTimeout,
117+
orElse: () =>
118+
Effect.fail(
119+
new LoadError({
120+
message: `Plugin install did not finish within ${Duration.format(installTimeout)}; check network connectivity or npm offline configuration`,
121+
}),
122+
),
123+
}),
124+
)
110125
// Legacy auto-discovery still admits standalone server sources. Configured
111126
// local plugins always arrive here as directories.
112127
const entrypoints: Host.Entrypoints =

‎packages/core/test/plugin-failure.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,50 @@ import { Bus } from "@opencode/core/bus"
44
import { Command } from "@opencode/core/command"
55
import { Plugin } from "@opencode/core/plugin"
66
import { PluginHooks } from "@opencode/core/plugin/hooks"
7+
import { PluginPromise } from "@opencode/core/plugin/promise"
78
import { Rpc } from "@opencode/core/rpc"
9+
import { advance } from "./lib/clock"
810
import { testEffect } from "./lib/effect"
911
import { PluginTestLayer } from "./plugin/fixture"
1012

1113
const it = testEffect(PluginTestLayer)
1214

15+
// Both setup shapes must respect the bound: an Effect setup suspends interruptibly on its own,
16+
// while an npm plugin's setup crosses the promise adapter bridge, which must not pin the fiber.
17+
const stuckSetups: Record<string, Plugin.Generation["effect"]> = {
18+
effect: () => Effect.never,
19+
promise: (ctx) => PluginPromise.fromPromise({ id: "stuck", setup: () => new Promise<void>(() => {}) }).effect(ctx),
20+
}
21+
22+
Object.entries(stuckSetups).forEach(([shape, effect]) =>
23+
it.effect(`bounds a ${shape} setup that never settles and keeps activating the rest of the generation`, () =>
24+
Effect.gen(function* () {
25+
const plugins = yield* Plugin.Service
26+
const commands = yield* Command.Service
27+
const activation = yield* plugins
28+
.activate([
29+
{ id: "stuck", revision: "1", effect },
30+
{
31+
id: "healthy",
32+
revision: "1",
33+
effect: (ctx) =>
34+
ctx.command
35+
.transform((editor) => editor.add({ name: "healthy", execute: () => Effect.void }))
36+
.pipe(Effect.asVoid),
37+
},
38+
])
39+
.pipe(Effect.forkChild({ startImmediately: true }))
40+
yield* advance(() => activation.pollUnsafe() !== undefined)
41+
yield* Fiber.join(activation)
42+
yield* plugins.awaitActivation
43+
const inventory = yield* plugins.list()
44+
expect(inventory.map((plugin) => plugin.state.status)).toEqual(["failed", "active"])
45+
expect(inventory[0]?.state).toMatchObject({ error: expect.stringContaining("did not finish") })
46+
expect(yield* commands.get("healthy")).toBeDefined()
47+
}),
48+
),
49+
)
50+
1351
it.live("removes a failed plugin's hooks and RPC handlers without affecting healthy plugins", () =>
1452
Effect.gen(function* () {
1553
const plugins = yield* Plugin.Service

‎packages/core/test/plugin/module.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { createForeignPackageFilter, ensurePluginRuntime } from "@opencode/plugi
1919
import { createLoader, discoverPluginRuntimeSpecifiers, pluginRuntimeLoaderCode } from "@opencode/plugin/runtime-modules"
2020
import { tempGlobalLayer } from "../fixture/global"
2121
import { tmpdirScoped } from "../fixture/tmpdir"
22+
import { advance } from "../lib/clock"
2223
import { testEffect } from "../lib/effect"
2324
import { PluginTestLayer } from "./fixture"
2425

@@ -425,6 +426,33 @@ it.live("blocks a local plugin before module initialization and honors replaceme
425426
}),
426427
)
427428

429+
it.effect("bounds a package install that never finishes and fails the load", () =>
430+
Effect.gen(function* () {
431+
const modules = yield* PluginModule.make()
432+
const fiber = yield* modules
433+
.load({ type: "add", target: "fixture-pkg", options: {} }, { install: true })
434+
.pipe(
435+
Effect.provideService(
436+
Npm.Service,
437+
Npm.Service.of({
438+
// A black-holed registry: the install never settles on its own.
439+
add: () => Effect.never,
440+
resolve: (name) => Effect.succeed({ directory: "", name }),
441+
check: () => Effect.succeed(false),
442+
update: (name) => Effect.succeed({ directory: "", name }),
443+
which: () => Effect.undefined,
444+
}),
445+
),
446+
Effect.flip,
447+
Effect.forkChild({ startImmediately: true }),
448+
)
449+
yield* advance(() => fiber.pollUnsafe() !== undefined)
450+
const error = yield* Fiber.join(fiber)
451+
expect(error).toBeInstanceOf(PluginModule.LoadError)
452+
if (error instanceof PluginModule.LoadError) expect(error.message).toContain("did not finish")
453+
}),
454+
)
455+
428456
for (const target of ["[email protected]", "@scope/[email protected]"]) {
429457
it.live(`blocks versioned package ${target} before npm resolution or installation`, () =>
430458
Effect.gen(function* () {

‎packages/plugin/src/promise/adapter.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -616,9 +616,13 @@ export function fromPromise(plugin: Plugin) {
616616
},
617617
}
618618

619+
// Interruptible, or the registry's setup bound can never abandon a hung setup promise:
620+
// an uninterruptible acquire makes the timeout wait for the promise it is bounding.
621+
// Cleanup registers only once setup resolves, and an abandoned setup never returned one.
619622
yield* Effect.acquireRelease(
620623
Effect.promise(() => Promise.resolve(plugin.setup(context2))),
621624
(cleanup) => (cleanup ? Effect.promise(() => Promise.resolve(cleanup())) : Effect.void),
625+
{ interruptible: true },
622626
)
623627
}),
624628
})

‎packages/tui/src/plugin/context.tsx‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -529,10 +529,16 @@ export function PluginProvider(props: ParentProps<{ packages: PackageSource; dir
529529
() => JSON.stringify([serverTuiPlugins(), config.data.plugins ?? []]),
530530
() => {
531531
npmFailures.clear()
532-
void enqueue(reconcile).then(
533-
() => setStore("ready", true),
534-
() => setStore("ready", true),
535-
)
532+
// Cold package installs can hold the first reconcile for minutes on an offline host;
533+
// stop gating readiness after a bound while the reconcile keeps running, so plugins
534+
// still activate when it finishes.
535+
const deadline = setTimeout(() => setStore("ready", true), 10_000)
536+
void enqueue(reconcile)
537+
.then(
538+
() => setStore("ready", true),
539+
() => setStore("ready", true),
540+
)
541+
.finally(() => clearTimeout(deadline))
536542
},
537543
),
538544
)

0 commit comments

Comments
 (0)