Skip to content

Commit 50aa00b

Browse files
committed
fix(tui): share runtime with compiled plugin consumers
1 parent dd17d68 commit 50aa00b

13 files changed

Lines changed: 578 additions & 43 deletions

File tree

‎docs/compiled-tui-runtime.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Compiled TUI plugin runtime ownership
2+
3+
The compiled host uses OpenTUI 0.5.17. A normal NPM consumer can physically install newer peers, including 0.6.6. Those files must remain installed without creating a second renderer, Solid owner tree, or environment registry.
4+
5+
Two loading paths bypassed shared import rewriting:
6+
7+
- A local default re-export bridge could make Bun native-load its NPM target as a nested dependency. That also bypassed the target's reactive JSX compilation.
8+
- The OpenTUI prescan uses URL-style resolution for extensionless imports. `./player` can remain an extensionless URL while Bun actually loads `player.ts`. That transitive native import can reach physical peer modules.
9+
10+
The SDK now accepts additional host-owned exports through its canonical runtime provider. The TUI supplies its bundled OpenTUI/Solid namespaces before loading external plugins. Existing owners cannot be replaced. Pure default re-export bridges first load their dependency through the normal SDK entry loader, then evaluate the bridge normally. No source files are relocated or copied, peer versions are unchanged, and import errors remain visible.
11+
12+
The built-in prompt footer also read `useConfig()` during asynchronous plugin setup, outside its Solid owner. It now reads configuration in the slot render function.
13+
14+
## Verification
15+
16+
The compiled regression uses the same SDK runtime-map build plugin as the production CLI. A tarball is installed with real physical OpenTUI 0.6.6 peers and no source symlinks. It checks constructor/function identity, late SDK initialization, plugin context, reactive painting, the native footer, and both dual `/tui` and dedicated `/v2` entries through direct NPM and local-wrapper paths.
17+
18+
From `packages/tui`, run the self-contained compiled regression through the shared heavy-job wrapper:
19+
20+
```bash
21+
python3 ~/.claude/scripts/heavy-job.py --wait -- \
22+
bun test --timeout 120000 test/compiled-runtime.test.ts
23+
```
24+
25+
The production regression uses an actual compiled CLI, its normal default command, a real PTY, a headless native terminal decoder, and an isolated HTTP/SSE fixture. It installs the selected profile's exact five archives normally, retains physical 0.6.6 peers, and checks the actual Todo sidebar, prompt footer, and raw Ctrl+S speech action. Speech stays idle with no answer, so it does not synthesize audio or launch a media helper. Profile launch scripts are rejected because they can override isolation.
26+
27+
Set `OPENCODE_COMPILED_CLI` to the native executable built by `packages/cli/script/build.ts`, not a profile launcher. Set `OPENCODE_COMPILED_PROFILE_PACKAGES` to the source profile's read-only `package.json` with archive dependencies:
28+
29+
```bash
30+
python3 ~/.claude/scripts/heavy-job.py --wait -- \
31+
env OPENCODE_COMPILED_CLI="$OPENCODE_COMPILED_CLI" \
32+
OPENCODE_COMPILED_PROFILE_PACKAGES="$OPENCODE_COMPILED_PROFILE_PACKAGES" \
33+
bun test test/compiled-cli-runtime.test.ts --rerun-each 10
34+
```
35+
36+
The original migration binary, SHA-256 `243bf3ea1e506799b0e3ba97ae48be78283c8e114482e69632803d53ec30820c`, reproduced both duplicate environment registration and missing ConfigProvider failures under this isolated production harness. The corrected CLI passed repeated startup and keyboard checks using the unchanged archives and physical peer versions.

‎packages/cli/script/build.ts‎

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { embed } from "@opencode/script/highlights"
88
import { createSolidTransformPlugin } from "@opentui/solid/bun-plugin"
99
import type { BunPlugin } from "bun"
1010
import pkg from "../package.json"
11-
import { discoverPluginRuntimeSpecifiers, pluginRuntimeLoaderCode } from "@opencode/plugin/runtime-modules"
11+
import { createPluginRuntimePlugin } from "@opencode/plugin/runtime-build"
1212
import { buildAppArchive } from "./app-assets"
1313
import { verifyArtifact, verifySimulationGraph } from "./verify-artifact"
1414
import { resolveOpencodePty } from "./opencode-pty"
@@ -86,23 +86,10 @@ export default () => readFileSync(archive)`,
8686
}))
8787
},
8888
}
89-
const pluginRuntimeEntries = discoverPluginRuntimeSpecifiers()
90-
const pluginRuntimeModulesSource = [
91-
"export const resolveHostPackageRoots = () => []",
92-
"const modules = {",
93-
...[...pluginRuntimeEntries.keys()].map(
94-
(specifier) => ` ${JSON.stringify(specifier)}: ${pluginRuntimeLoaderCode(specifier, pluginRuntimeEntries)},`,
95-
),
96-
"}",
97-
"export const loadRuntimeModules = () => modules",
98-
].join("\n")
99-
const pluginRuntimePlugin: BunPlugin = {
100-
name: "opencode-plugin-runtime",
89+
const pluginRuntimePlugin = createPluginRuntimePlugin()
90+
const httpApiAssetsPlugin: BunPlugin = {
91+
name: "opencode-http-api-assets",
10192
setup(build) {
102-
build.onLoad({ filter: /plugin[/\\]src[/\\]runtime-modules\.ts$/ }, () => ({
103-
contents: pluginRuntimeModulesSource,
104-
loader: "ts",
105-
}))
10693
build.onLoad({ filter: /[/\\]internal[/\\]httpApi(?:Scalar|Swagger)\.js$/ }, () => ({
10794
contents:
10895
'export const css = ""; export const javascript = \'document.body.textContent = "Scalar/Swagger UI assets are not bundled in OpenCode"\'',
@@ -162,6 +149,7 @@ export default { path: file, version: ${JSON.stringify(opencodePty.version)}, sh
162149
parcelWatcherPlugin,
163150
opencodePtyPlugin,
164151
pluginRuntimePlugin,
152+
httpApiAssetsPlugin,
165153
simulationGraphPlugin,
166154
],
167155
external: ["node-gyp"],
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import type { BunPlugin } from "bun"
2+
import { discoverPluginRuntimeSpecifiers, pluginRuntimeLoaderCode } from "./runtime-modules.js"
3+
4+
/** Embed the same public SDK runtime map in CLI and compiled consumer builds. */
5+
export function createPluginRuntimePlugin(): BunPlugin {
6+
const entries = discoverPluginRuntimeSpecifiers()
7+
const contents = [
8+
"export const resolveHostPackageRoots = () => []",
9+
"const modules = {",
10+
...[...entries.keys()].map(
11+
(specifier) => ` ${JSON.stringify(specifier)}: ${pluginRuntimeLoaderCode(specifier, entries)},`,
12+
),
13+
"}",
14+
"export const loadRuntimeModules = () => modules",
15+
].join("\n")
16+
return {
17+
name: "opencode-plugin-runtime",
18+
setup(build) {
19+
build.onLoad({ filter: /plugin[/\\]src[/\\]runtime-modules\.ts$/ }, () => ({ contents, loader: "ts" }))
20+
},
21+
}
22+
}

‎packages/plugin/src/runtime.ts‎

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,32 +9,41 @@ export function provides(specifier: string) {
99
return installed !== undefined && Object.hasOwn(installed, specifier)
1010
}
1111

12-
export function ensurePluginRuntime() {
12+
/** Later host consumers may add shared modules without replacing existing owners. */
13+
export function ensurePluginRuntime(additional: Readonly<Record<string, Record<string, unknown>>> = {}) {
1314
if (typeof Bun === "undefined") return {}
14-
if (installed) return installed
15-
const modules = loadRuntimeModules()
16-
installed = modules
15+
const previous = installed
16+
const modules = previous ?? loadRuntimeModules()
17+
const added = Object.fromEntries(
18+
Object.entries(additional)
19+
.filter(([specifier]) => !Object.hasOwn(modules, specifier))
20+
.map(([specifier, exports]) => [specifier, () => exports]),
21+
)
22+
if (previous && Object.keys(added).length === 0) return previous
23+
installed = { ...modules, ...added }
24+
const pending = previous ? added : installed
1725
Bun.plugin({
1826
name: "opencode-plugin-runtime",
1927
setup(build) {
20-
for (const [specifier, load] of Object.entries(modules)) {
28+
for (const [specifier, load] of Object.entries(pending)) {
2129
build.module(specifier, () => {
2230
const exports = load()
2331
return exports instanceof Promise
2432
? exports.then((value) => ({ exports: value, loader: "object" as const }))
2533
: { exports, loader: "object" as const }
2634
})
2735
}
28-
build.onLoad({ filter: createForeignPackageFilter() }, (args) => {
29-
const match = args.path.match(foreignPkgPattern)
30-
const target = match ? `${match[2] ?? match[3]}/${match[4]}`.replaceAll("\\", "/") : args.path
31-
throw new Error(
32-
`Cannot load "${target}" from plugin node_modules: "${target}" is not provided by OpenCode; plugins must use the host's "effect" and "@opencode/plugin" modules.`,
33-
)
34-
})
36+
if (!previous)
37+
build.onLoad({ filter: createForeignPackageFilter() }, (args) => {
38+
const match = args.path.match(foreignPkgPattern)
39+
const target = match ? `${match[2] ?? match[3]}/${match[4]}`.replaceAll("\\", "/") : args.path
40+
throw new Error(
41+
`Cannot load "${target}" from plugin node_modules: "${target}" is not provided by OpenCode; plugins must use the host's "effect" and "@opencode/plugin" modules.`,
42+
)
43+
})
3544
},
3645
})
37-
return modules
46+
return installed
3847
}
3948

4049
export function createForeignPackageFilter(rootsInput: Iterable<string> = resolveHostPackageRoots()) {

‎packages/plugin/src/source.bun.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,5 +67,22 @@ export async function prepareSource(entrypoint: string, track: (file: string, di
6767
}
6868
}
6969
visit(root)
70-
return { version: String(++generation), load: () => Host.load(entrypoint) }
70+
// A source bridge must not make Bun native-load its NPM target as a nested
71+
// dependency before the host's shared-runtime/JSX loaders see that entry.
72+
// Load a pure default re-export's dependency as an SDK entry first, preserving
73+
// normal ESM evaluation order and the bridge's actual namespace afterwards.
74+
const trivia = String.raw`(?:\s|//[^\n]*(?:\n|$)|/\*[\s\S]*?\*/)*`
75+
const forwarding = new RegExp(
76+
String.raw`^${trivia}export\s*\{\s*default\s*\}\s*from\s*(["'])([^"']+)\1\s*;?${trivia}$`,
77+
).exec(readFileSync(root, "utf8"))
78+
return {
79+
version: String(++generation),
80+
load: async () => {
81+
if (forwarding && !provides(forwarding[2])) {
82+
const dependency = Bun.resolveSync(forwarding[2], path.dirname(root))
83+
if (dependency.split(path.sep).includes("node_modules")) await Host.load(pathToFileURL(dependency).href)
84+
}
85+
return Host.load(entrypoint)
86+
},
87+
}
7188
}

‎packages/tui/src/feature-plugins/prompt/footer.tsx‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -137,18 +137,20 @@ export function PromptFooter(props: {
137137
export default Plugin.define({
138138
id: "opencode.prompt.footer",
139139
setup(context) {
140-
const config = useConfig()
141140
context.ui.slot({
142141
append: "prompt.footer",
143-
render: (props) => (
144-
<PromptFooter
145-
context={context}
146-
sessionID={props.sessionID}
147-
mode={props.mode}
148-
showDetails={props.showDetails}
149-
hints={config.data.prompt?.hints}
150-
/>
151-
),
142+
render(props) {
143+
const config = useConfig()
144+
return (
145+
<PromptFooter
146+
context={context}
147+
sessionID={props.sessionID}
148+
mode={props.mode}
149+
showDetails={props.showDetails}
150+
hints={config.data.prompt?.hints}
151+
/>
152+
)
153+
},
152154
})
153155
},
154156
})

‎packages/tui/src/plugin/runtime-plugin-support.bun.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,19 @@ import { ensurePluginRuntime, provides } from "@opencode/plugin/runtime"
22
import { Plugin, PluginContextProvider, usePlugin } from "@opencode/plugin/tui"
33
import { ensureRuntimePluginSupport } from "@opentui/solid/runtime-plugin-support/configure"
44

5-
ensurePluginRuntime()
5+
// Capture the host namespaces before registering bare module providers. Bun can
6+
// native-load extensionless NPM dependencies without hitting OpenTUI's prescan;
7+
// those imports must still resolve to the compiled host, not physical peers.
8+
ensurePluginRuntime({
9+
"@opentui/core": await import("@opentui/core"),
10+
"@opentui/core/testing": await import("@opentui/core/testing"),
11+
"@opentui/solid": await import("@opentui/solid"),
12+
"@opentui/solid/components": await import("@opentui/solid/components"),
13+
"@opentui/solid/jsx-runtime": await import("@opentui/solid/jsx-runtime"),
14+
"@opentui/solid/jsx-dev-runtime": await import("@opentui/solid/jsx-dev-runtime"),
15+
"solid-js": await import("solid-js"),
16+
"solid-js/store": await import("solid-js/store"),
17+
})
618
ensureRuntimePluginSupport({
719
additional: {
820
"@opencode/plugin/tui": { Plugin, PluginContextProvider, usePlugin },

0 commit comments

Comments
 (0)