mirror of
https://github.com/anomalyco/opencode.git
synced 2026-07-31 07:26:47 -04:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8fe47cefbd | |||
| dbd29054ed | |||
| 53632dfcc1 | |||
| 3f9945b98d | |||
| 7ca3fc44b8 | |||
| 7a9cc15296 |
@@ -136,6 +136,9 @@ export interface SlotMap {
|
||||
readonly sessionID?: string
|
||||
readonly mode: "normal" | "shell"
|
||||
}
|
||||
readonly "session.composer.top": {
|
||||
readonly sessionID: string
|
||||
}
|
||||
readonly "sidebar.content": {
|
||||
readonly sessionID: string
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
createContext,
|
||||
createEffect,
|
||||
createMemo,
|
||||
ErrorBoundary,
|
||||
For,
|
||||
on,
|
||||
onCleanup,
|
||||
@@ -13,10 +14,12 @@ import {
|
||||
type ParentProps,
|
||||
} from "solid-js"
|
||||
import path from "path"
|
||||
import { watch } from "fs"
|
||||
import { stat } from "fs/promises"
|
||||
import { fileURLToPath, pathToFileURL } from "url"
|
||||
import type { Context, Dialog, Page, Slot, SlotMap, SlotName, Toast } from "@opencode-ai/plugin/tui/context"
|
||||
import { createStore, produce, reconcile as reconcileStore } from "solid-js/store"
|
||||
import { isDeepEqual } from "remeda"
|
||||
import { useRenderer } from "@opentui/solid"
|
||||
import "#runtime-plugin-support"
|
||||
import { useConfig } from "../config"
|
||||
@@ -38,14 +41,13 @@ import { useStorage } from "../context/storage"
|
||||
import { useSessionTabs } from "../context/session-tabs"
|
||||
import { abbreviateHome } from "../util/path-format"
|
||||
import { builtins } from "./builtins"
|
||||
import { discoverTuiPlugins } from "./discovery"
|
||||
import { discoverTuiPlugins, freshSpecifier, localSource, tuiPluginDirectory } from "./discovery"
|
||||
|
||||
export interface PackageResolver {
|
||||
readonly resolve: (spec: string) => Promise<string | undefined>
|
||||
}
|
||||
|
||||
type State =
|
||||
| { readonly target: string; readonly status: "loading" }
|
||||
| { readonly target: string; readonly id: string; readonly status: "active" | "inactive" }
|
||||
| { readonly target: string; readonly status: "unsupported" }
|
||||
| { readonly target: string; readonly status: "failed"; readonly error: string }
|
||||
@@ -61,7 +63,7 @@ type Value = {
|
||||
readonly list: () => ReadonlyArray<State>
|
||||
readonly registered: () => ReadonlyArray<RegisteredPlugin>
|
||||
readonly route: (id: string, name: string) => Page["render"] | undefined
|
||||
readonly slot: <Name extends SlotName>(name: Name) => ReadonlyArray<Slot<Name>>
|
||||
readonly slot: <Name extends SlotName>(name: Name) => ReadonlyArray<{ readonly id: string; readonly render: Slot<Name> }>
|
||||
readonly activate: (id: string) => Promise<boolean>
|
||||
readonly deactivate: (id: string) => Promise<boolean>
|
||||
}
|
||||
@@ -70,6 +72,8 @@ type Dispose = () => Promise<void>
|
||||
type Registration = {
|
||||
plugin: Plugin.Definition
|
||||
source: RegisteredPlugin["source"]
|
||||
target?: string
|
||||
version: string
|
||||
options?: Readonly<Record<string, any>>
|
||||
active: boolean
|
||||
routes: Record<string, Page>
|
||||
@@ -77,6 +81,9 @@ type Registration = {
|
||||
cleanups: Dispose[]
|
||||
}
|
||||
|
||||
// One entry of the desired plugin generation produced by the resolve phase.
|
||||
type Desired = Pick<Registration, "plugin" | "source" | "target" | "version" | "options"> & { enabled: boolean }
|
||||
|
||||
const PluginContext = createContext<Value>()
|
||||
|
||||
export function PluginProvider(props: ParentProps<{ packages: PackageResolver }>) {
|
||||
@@ -374,85 +381,199 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver }>
|
||||
return true
|
||||
}
|
||||
|
||||
const reconcile = async (configured = config.data.plugins ?? []) => {
|
||||
await Promise.all(
|
||||
Object.entries(store.registrations)
|
||||
.filter(([, registration]) => registration.active)
|
||||
.map(([id]) => deactivate(id)),
|
||||
)
|
||||
const entries = [...(await discoverTuiPlugins(paths.cwd)), ...configured]
|
||||
batch(() => {
|
||||
setStore("registrations", reconcileStore({}))
|
||||
setStore("states", [])
|
||||
})
|
||||
|
||||
for (const plugin of builtins) {
|
||||
setStore("registrations", plugin.id, {
|
||||
plugin,
|
||||
source: "builtin",
|
||||
active: false,
|
||||
routes: {},
|
||||
slots: {},
|
||||
cleanups: [],
|
||||
// Hot-reload local plugin sources: watch the discovery directory and any
|
||||
// local entrypoints, then rebuild the plugin generation when one changes.
|
||||
// Watches are deduped by path and never torn down individually (a stale
|
||||
// watch costs one fs handle and a no-op reconcile); all die with this
|
||||
// provider. Failed watches leave the set so a later reconcile can retry
|
||||
// once the path exists.
|
||||
const watchers: ReturnType<typeof watch>[] = []
|
||||
const watched = new Set<string>()
|
||||
let disposed = false
|
||||
let pending: ReturnType<typeof setTimeout> | undefined
|
||||
const scheduleReconcile = () => {
|
||||
clearTimeout(pending)
|
||||
pending = setTimeout(() => {
|
||||
loading = loading.catch(() => undefined).then(() => reconcile())
|
||||
// Observe failures immediately: a plugin cleanup that throws would
|
||||
// otherwise surface as an unhandled rejection until the next trigger.
|
||||
void loading.catch(() => undefined)
|
||||
}, 100)
|
||||
}
|
||||
const watchSource = (target: string) => {
|
||||
if (watched.has(target)) return
|
||||
watched.add(target)
|
||||
stat(target)
|
||||
.then((info) => {
|
||||
if (disposed) return
|
||||
// Watch the parent for files: editors that save by rename replace the
|
||||
// inode, which silently kills a direct file watch after the first save.
|
||||
const dir = info.isDirectory() ? target : path.dirname(target)
|
||||
if (dir !== target && watched.has(dir)) return
|
||||
watched.add(dir)
|
||||
const watcher = watch(dir, scheduleReconcile)
|
||||
// A watched directory can disappear out from under us; without a
|
||||
// listener the error event would crash the process. Forget the paths
|
||||
// so a later reconcile can re-arm once they exist again.
|
||||
watcher.on("error", () => {
|
||||
watcher.close()
|
||||
watched.delete(dir)
|
||||
watched.delete(target)
|
||||
})
|
||||
watchers.push(watcher)
|
||||
})
|
||||
await activate(plugin.id)
|
||||
}
|
||||
.catch(() => watched.delete(target))
|
||||
}
|
||||
onCleanup(() => {
|
||||
disposed = true
|
||||
clearTimeout(pending)
|
||||
for (const watcher of watchers) watcher.close()
|
||||
})
|
||||
|
||||
// Rebuild the plugin generation as resolve → compare → swap, mirroring the
|
||||
// core plugin registry: fold the ordered entries into a desired end state
|
||||
// (importing only new or changed sources, before anything running is
|
||||
// touched), no-op when the generation is unchanged, and restart only the
|
||||
// plugins that differ. Membership or order changes rebuild the whole
|
||||
// generation to preserve slot-order semantics.
|
||||
// Package resolution failures would otherwise retry a full npm install on
|
||||
// every watch event; remember them until the configuration changes.
|
||||
const npmFailures = new Map<string, string>()
|
||||
const reconcile = async (configured?: NonNullable<typeof config.data.plugins>) => {
|
||||
if (configured) npmFailures.clear()
|
||||
const entries = [...(await discoverTuiPlugins(paths.cwd)), ...(configured ?? config.data.plugins ?? [])]
|
||||
watchSource(tuiPluginDirectory(paths.cwd))
|
||||
|
||||
// Resolve: fold entries into one desired generation. A source that fails
|
||||
// to import keeps its running previous version and only reports failure.
|
||||
const desired = new Map<string, Desired>()
|
||||
for (const plugin of builtins) desired.set(plugin.id, { plugin, source: "builtin", version: "builtin", enabled: true })
|
||||
const failures: State[] = []
|
||||
for (const entry of entries) {
|
||||
const target = typeof entry === "string" ? entry : entry.package
|
||||
if (target.startsWith("-")) {
|
||||
for (const id of Object.keys(store.registrations).filter((id) => matches(target.slice(1), id)))
|
||||
await deactivate(id)
|
||||
for (const item of desired.values()) if (matches(target.slice(1), item.plugin.id)) item.enabled = false
|
||||
continue
|
||||
}
|
||||
|
||||
const selected = Object.keys(store.registrations).filter((id) => matches(target, id))
|
||||
const selected = [...desired.values()].filter((item) => matches(target, item.plugin.id))
|
||||
if (selected.length || target === "*" || target.endsWith(".*") || target.startsWith("opencode.")) {
|
||||
for (const id of selected) await activate(id)
|
||||
for (const item of selected) item.enabled = true
|
||||
continue
|
||||
}
|
||||
|
||||
const options = typeof entry === "string" ? undefined : entry.options
|
||||
setStore("states", (items) => [...items, { target, status: "loading" }])
|
||||
const plugin = await loadPlugin(target, directory, props.packages).catch((error) => {
|
||||
setStore("states", (items) =>
|
||||
items.map((state) =>
|
||||
state.target === target
|
||||
? { target, status: "failed", error: error instanceof Error ? error.message : String(error) }
|
||||
: state,
|
||||
),
|
||||
)
|
||||
return undefined
|
||||
})
|
||||
if (!plugin) {
|
||||
setStore("states", (items) =>
|
||||
items.map((state) =>
|
||||
state.target === target && state.status !== "failed" ? { target, status: "unsupported" } : state,
|
||||
),
|
||||
)
|
||||
// Watch even when the resolve below fails so fixing a broken plugin reloads it.
|
||||
const local = localSource(target, directory)
|
||||
if (local) watchSource(fileURLToPath(local))
|
||||
const previous = Object.values(store.registrations).find((registration) => registration.target === target)
|
||||
const memo = local ? undefined : npmFailures.get(target)
|
||||
const resolved = memo
|
||||
? { status: "failed" as const, error: memo }
|
||||
: await resolvePlugin(target, local, options, previous, props.packages).catch((error) => ({
|
||||
status: "failed" as const,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}))
|
||||
if (resolved.status === "unsupported") {
|
||||
failures.push({ target, status: "unsupported" })
|
||||
continue
|
||||
}
|
||||
|
||||
setStore("registrations", plugin.id, {
|
||||
plugin,
|
||||
if (resolved.status === "failed") {
|
||||
if (!local && !previous) npmFailures.set(target, resolved.error)
|
||||
failures.push({
|
||||
target,
|
||||
status: "failed",
|
||||
error: previous ? `${resolved.error} (previous version still active)` : resolved.error,
|
||||
})
|
||||
if (previous)
|
||||
desired.set(previous.plugin.id, {
|
||||
plugin: previous.plugin,
|
||||
source: "external",
|
||||
target,
|
||||
version: previous.version,
|
||||
options: previous.options,
|
||||
enabled: true,
|
||||
})
|
||||
continue
|
||||
}
|
||||
desired.set(resolved.plugin.id, {
|
||||
plugin: resolved.plugin,
|
||||
source: "external",
|
||||
target,
|
||||
version: resolved.version,
|
||||
options,
|
||||
active: false,
|
||||
routes: {},
|
||||
slots: {},
|
||||
cleanups: [],
|
||||
enabled: true,
|
||||
})
|
||||
const error = await activate(plugin.id).then(
|
||||
}
|
||||
|
||||
// Compare: unchanged plugins are never touched, and a fully unchanged
|
||||
// generation is a no-op, so spurious watch events cost nothing.
|
||||
const currentIds = Object.keys(store.registrations)
|
||||
const desiredIds = [...desired.keys()]
|
||||
const structural = currentIds.length !== desiredIds.length || currentIds.some((id, index) => desiredIds[index] !== id)
|
||||
if (structural) {
|
||||
await Promise.all(
|
||||
Object.entries(store.registrations)
|
||||
.filter(([, registration]) => registration.active)
|
||||
.map(([id]) => deactivate(id).catch(() => undefined)),
|
||||
)
|
||||
setStore("registrations", reconcileStore({}))
|
||||
}
|
||||
const changed = structural
|
||||
? desiredIds
|
||||
: desiredIds.filter((id) => {
|
||||
const registration = store.registrations[id]!
|
||||
const item = desired.get(id)!
|
||||
return (
|
||||
registration.version !== item.version ||
|
||||
!sameOptions(registration.options, item.options) ||
|
||||
registration.active !== item.enabled
|
||||
)
|
||||
})
|
||||
|
||||
// Swap: cleanup failures are logged into states, never propagated, so one
|
||||
// broken plugin cannot take the rest of the generation down.
|
||||
const errors = new Map<string, string>()
|
||||
for (const id of changed) {
|
||||
const item = desired.get(id)!
|
||||
const registration = store.registrations[id]
|
||||
if (!registration || registration.version !== item.version || !sameOptions(registration.options, item.options)) {
|
||||
if (registration) await deactivate(id).catch(() => undefined)
|
||||
// In-place replacement keeps the registration's key position, which
|
||||
// slot ordering (mode "replace" takes the last one) depends on.
|
||||
setStore("registrations", id, toRegistration(item))
|
||||
}
|
||||
if (!item.enabled) {
|
||||
await deactivate(id).catch(() => undefined)
|
||||
continue
|
||||
}
|
||||
const error = await activate(id).then(
|
||||
() => undefined,
|
||||
(error) => (error instanceof Error ? error.message : String(error)),
|
||||
)
|
||||
setStore("states", (items) => [
|
||||
...items.filter((state) => state.target !== target && (!("id" in state) || state.id !== plugin.id)),
|
||||
error
|
||||
? { target, status: "failed", error }
|
||||
: { target, id: plugin.id, status: "active" },
|
||||
])
|
||||
if (error) errors.set(id, error)
|
||||
}
|
||||
|
||||
const states: State[] = [
|
||||
...[...desired.values()].flatMap((item): State[] => {
|
||||
if (item.target === undefined) return []
|
||||
// A failed reload keeps this item running; the failure entry covers it.
|
||||
if (failures.some((failure) => failure.target === item.target)) return []
|
||||
const error = errors.get(item.plugin.id)
|
||||
if (error) return [{ target: item.target, status: "failed", error }]
|
||||
const status = store.registrations[item.plugin.id]?.active ? "active" : "inactive"
|
||||
return [{ target: item.target, id: item.plugin.id, status }]
|
||||
}),
|
||||
...failures,
|
||||
]
|
||||
// Surface newly failing plugins; repeated reconciles stay silent.
|
||||
for (const state of states)
|
||||
if (
|
||||
state.status === "failed" &&
|
||||
!store.states.some((prev) => prev.status === "failed" && prev.target === state.target && prev.error === state.error)
|
||||
)
|
||||
toast.show({ variant: "error", title: "Plugin", message: `${state.target}: ${state.error}` })
|
||||
setStore("states", reconcileStore(states))
|
||||
}
|
||||
let loading = Promise.resolve()
|
||||
createEffect(
|
||||
@@ -478,7 +599,7 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver }>
|
||||
Promise.all(
|
||||
Object.entries(store.registrations)
|
||||
.filter(([, registration]) => registration.active)
|
||||
.map(([id]) => deactivate(id)),
|
||||
.map(([id]) => deactivate(id).catch(() => undefined)),
|
||||
),
|
||||
)
|
||||
.then(() => setStore("registrations", reconcileStore({})))
|
||||
@@ -500,8 +621,8 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver }>
|
||||
Object.entries(store.registrations).map(([id, plugin]) => ({ id, source: plugin.source, active: plugin.active })),
|
||||
route: (id, name) => store.registrations[id]?.routes[name]?.render,
|
||||
slot: (name) =>
|
||||
Object.values(store.registrations).flatMap((registration) =>
|
||||
registration.active && registration.slots[name] ? [registration.slots[name]] : [],
|
||||
Object.entries(store.registrations).flatMap(([id, registration]) =>
|
||||
registration.active && registration.slots[name] ? [{ id, render: registration.slots[name] }] : [],
|
||||
),
|
||||
activate,
|
||||
deactivate,
|
||||
@@ -531,17 +652,45 @@ function matches(selector: string, id: string) {
|
||||
return selector === "*" || selector === id || (selector.endsWith(".*") && id.startsWith(selector.slice(0, -1)))
|
||||
}
|
||||
|
||||
async function loadPlugin(spec: string, directory: string, packages: PackageResolver) {
|
||||
const local = spec.startsWith("file://")
|
||||
? new URL(spec)
|
||||
: spec.startsWith("./") || spec.startsWith("../") || path.isAbsolute(spec)
|
||||
? pathToFileURL(path.resolve(directory, spec))
|
||||
: undefined
|
||||
async function resolvePlugin(
|
||||
spec: string,
|
||||
local: URL | undefined,
|
||||
options: Readonly<Record<string, any>> | undefined,
|
||||
previous: Registration | undefined,
|
||||
packages: PackageResolver,
|
||||
) {
|
||||
// Package entrypoints never change within a session, so a loaded previous
|
||||
// version needs no re-resolution (which could otherwise hit npm).
|
||||
if (!local && previous && sameOptions(previous.options, options))
|
||||
return { status: "unchanged" as const, plugin: previous.plugin, version: previous.version }
|
||||
const entrypoint = local ? await resolveLocal(local) : await packages.resolve(spec)
|
||||
if (!entrypoint) return
|
||||
const mod: { readonly default?: unknown } = await import(entrypoint)
|
||||
if (!entrypoint) return { status: "unsupported" as const }
|
||||
// The cache-busted specifier doubles as the version: unique per entrypoint
|
||||
// and mtime, so equal versions mean an identical module.
|
||||
const version = local ? freshSpecifier(entrypoint, (await stat(new URL(entrypoint))).mtimeMs) : entrypoint
|
||||
if (previous && previous.version === version && sameOptions(previous.options, options))
|
||||
return { status: "unchanged" as const, plugin: previous.plugin, version }
|
||||
const mod: { readonly default?: unknown } = await import(version)
|
||||
if (!isPlugin(mod.default)) throw new Error(`Invalid V2 TUI plugin module: ${spec}`)
|
||||
return mod.default
|
||||
return { status: "loaded" as const, plugin: mod.default, version }
|
||||
}
|
||||
|
||||
function toRegistration(item: Desired): Registration {
|
||||
return {
|
||||
plugin: item.plugin,
|
||||
source: item.source,
|
||||
target: item.target,
|
||||
version: item.version,
|
||||
options: item.options,
|
||||
active: false,
|
||||
routes: {},
|
||||
slots: {},
|
||||
cleanups: [],
|
||||
}
|
||||
}
|
||||
|
||||
function sameOptions(a: Registration["options"], b: Registration["options"]) {
|
||||
return isDeepEqual(a ?? null, b ?? null)
|
||||
}
|
||||
|
||||
async function resolveLocal(url: URL) {
|
||||
@@ -577,16 +726,43 @@ export function usePlugin() {
|
||||
return value
|
||||
}
|
||||
|
||||
// Contain render-time plugin crashes: a throwing slot or route must not take
|
||||
// down the app or the other plugins. The crash surfaces as one error toast.
|
||||
function PluginBoundary(props: ParentProps<{ id: string; where: string }>) {
|
||||
const toast = useToast()
|
||||
return (
|
||||
<ErrorBoundary
|
||||
fallback={(error) => {
|
||||
createEffect(() =>
|
||||
toast.show({
|
||||
variant: "error",
|
||||
title: "Plugin",
|
||||
message: `${props.id} crashed in ${props.where}: ${error instanceof Error ? error.message : String(error)}`,
|
||||
}),
|
||||
)
|
||||
return null
|
||||
}}
|
||||
>
|
||||
{props.children}
|
||||
</ErrorBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
export function PluginRoute(props: { readonly fallback: (id: string, name: string) => JSX.Element }) {
|
||||
const plugins = usePlugin()
|
||||
const route = useRoute()
|
||||
const id = createMemo(() => (route.data.type === "plugin" ? route.data.id : ""))
|
||||
const content = createMemo(() => {
|
||||
if (route.data.type !== "plugin") return
|
||||
const render = plugins.route(route.data.id, route.data.name)
|
||||
if (!render) return props.fallback(route.data.id, route.data.name)
|
||||
return render({ data: route.data.data })
|
||||
})
|
||||
return <>{content()}</>
|
||||
return (
|
||||
<PluginBoundary id={id()} where="route">
|
||||
{content()}
|
||||
</PluginBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
export function PluginSlot<Name extends SlotName>(props: {
|
||||
@@ -600,5 +776,13 @@ export function PluginSlot<Name extends SlotName>(props: {
|
||||
if (props.mode === "replace") return items.slice(-1)
|
||||
return items
|
||||
})
|
||||
return <For each={renderers()}>{(render) => render(props.input)}</For>
|
||||
return (
|
||||
<For each={renderers()}>
|
||||
{(item) => (
|
||||
<PluginBoundary id={item.id} where={`slot ${props.name}`}>
|
||||
{item.render(props.input)}
|
||||
</PluginBoundary>
|
||||
)}
|
||||
</For>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { readdir } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { fileURLToPath, pathToFileURL } from "node:url"
|
||||
|
||||
const extensions = new Set([".cjs", ".cts", ".js", ".jsx", ".mjs", ".mts", ".ts", ".tsx"])
|
||||
|
||||
export function tuiPluginDirectory(cwd: string) {
|
||||
return path.join(cwd, ".opencode", "plugins", "tui")
|
||||
}
|
||||
|
||||
export async function discoverTuiPlugins(cwd: string) {
|
||||
const directory = path.join(cwd, ".opencode", "plugins", "tui")
|
||||
const directory = tuiPluginDirectory(cwd)
|
||||
const entries = await readdir(directory, { withFileTypes: true }).catch((error: unknown) => {
|
||||
if (error && typeof error === "object" && Reflect.get(error, "code") === "ENOENT") return []
|
||||
return Promise.reject(error)
|
||||
@@ -14,3 +19,19 @@ export async function discoverTuiPlugins(cwd: string) {
|
||||
.map((entry) => path.join(directory, entry.name))
|
||||
.sort()
|
||||
}
|
||||
|
||||
export function localSource(spec: string, directory: string) {
|
||||
if (spec.startsWith("file://")) return new URL(spec)
|
||||
if (spec.startsWith("./") || spec.startsWith("../") || path.isAbsolute(spec))
|
||||
return pathToFileURL(path.resolve(directory, spec))
|
||||
return undefined
|
||||
}
|
||||
|
||||
// Key local plugin imports by mtime so edited sources re-import fresh instead
|
||||
// of hitting the ESM cache. Bun ignores query params when caching file:// URL
|
||||
// imports, so bust with a plain path there; Node keys its cache on the full
|
||||
// URL. Mirrors the core plugin supervisor's loader.
|
||||
export function freshSpecifier(entrypoint: string, mtime: number) {
|
||||
if (typeof Bun !== "undefined") return `${fileURLToPath(entrypoint).replaceAll("\\", "/")}?mtime=${mtime}`
|
||||
return `${entrypoint}?mtime=${mtime}`
|
||||
}
|
||||
|
||||
@@ -80,6 +80,7 @@ import { collapseToolOutput } from "../../util/collapse-tool-output"
|
||||
import { Keymap, type KeymapCommand } from "../../context/keymap"
|
||||
import { usePathFormatter } from "../../context/path-format"
|
||||
import { useLocation } from "../../context/location"
|
||||
import { PluginSlot } from "../../plugin/context"
|
||||
import {
|
||||
cacheReuseDrop,
|
||||
createSessionRows,
|
||||
@@ -1029,6 +1030,7 @@ export function Session() {
|
||||
</Show>
|
||||
</scrollbox>
|
||||
<box flexShrink={0}>
|
||||
<PluginSlot name="session.composer.top" input={{ sessionID: route.sessionID }} mode="all" />
|
||||
<Composer
|
||||
sessionID={route.sessionID}
|
||||
open={composer.open || (!!session()?.parentID && forms().length === 0)}
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import { expect, mock, test } from "bun:test"
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
import { Effect, FileSystem } from "effect"
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
import { Global } from "@opencode-ai/util/global"
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { createEventStream, createFetch } from "./fixture/tui-client"
|
||||
import { tmpdir } from "./fixture/fixture"
|
||||
|
||||
function lifecycleSource(marker: string, id: string, version: string) {
|
||||
return `
|
||||
import { appendFile } from "node:fs/promises"
|
||||
export default {
|
||||
id: ${JSON.stringify(id)},
|
||||
setup: async () => {
|
||||
await appendFile(${JSON.stringify(marker)}, "${version}:setup\\n")
|
||||
return () => appendFile(${JSON.stringify(marker)}, "${version}:cleanup\\n")
|
||||
},
|
||||
}
|
||||
`
|
||||
}
|
||||
|
||||
async function until(read: () => Promise<string>, expected: (value: string | undefined) => boolean) {
|
||||
let value: string | undefined
|
||||
for (let attempt = 0; attempt < 200; attempt++) {
|
||||
value = await read().catch(() => undefined)
|
||||
if (expected(value)) return value
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
async function bootApp(directory: string) {
|
||||
const setup = await createTestRenderer({ width: 80, height: 24, useThread: false })
|
||||
const core = await import("@opentui/core")
|
||||
mock.module("@opentui/core", () => ({ ...core, createCliRenderer: async () => setup.renderer }))
|
||||
const events = createEventStream()
|
||||
const calls = createFetch(undefined, events)
|
||||
const server = Bun.serve({ port: 0, fetch: (request) => calls.fetch(request) })
|
||||
const cwd = process.cwd()
|
||||
process.chdir(directory)
|
||||
const { run } = await import("../src/app")
|
||||
const task = Effect.runPromise(
|
||||
run({
|
||||
app: { name: "test", version: "test", channel: "test" },
|
||||
server: { endpoint: { url: server.url.toString() } },
|
||||
config: { get: async () => ({}), update: async () => ({}) },
|
||||
packages: { resolve: async () => undefined },
|
||||
args: {},
|
||||
log: () => {},
|
||||
}).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))),
|
||||
)
|
||||
return {
|
||||
task,
|
||||
async [Symbol.asyncDispose]() {
|
||||
process.chdir(cwd)
|
||||
if (!setup.renderer.isDestroyed) setup.renderer.destroy()
|
||||
await server.stop()
|
||||
mock.restore()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
test("editing a discovered TUI plugin hot-reloads its fresh module", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const directory = path.join(tmp.path, ".opencode", "plugins", "tui")
|
||||
await mkdir(directory, { recursive: true })
|
||||
const marker = path.join(tmp.path, "marker.txt")
|
||||
const source = path.join(directory, "hot.ts")
|
||||
await writeFile(source, lifecycleSource(marker, "test.hot", "v1"))
|
||||
|
||||
await using app = await bootApp(tmp.path)
|
||||
const read = () => readFile(marker, "utf8")
|
||||
expect(await until(read, (value) => value === "v1:setup\n")).toBe("v1:setup\n")
|
||||
|
||||
await writeFile(source, lifecycleSource(marker, "test.hot", "v2"))
|
||||
expect(await until(read, (value) => value?.includes("v2:setup") ?? false)).toBe("v1:setup\nv1:cleanup\nv2:setup\n")
|
||||
|
||||
process.emit("SIGHUP")
|
||||
await app.task
|
||||
})
|
||||
|
||||
test("a plugin whose slot render throws does not take down the TUI", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const directory = path.join(tmp.path, ".opencode", "plugins", "tui")
|
||||
await mkdir(directory, { recursive: true })
|
||||
const markerA = path.join(tmp.path, "a.txt")
|
||||
const markerCrash = path.join(tmp.path, "crash.txt")
|
||||
const sourceA = path.join(directory, "a.ts")
|
||||
await writeFile(sourceA, lifecycleSource(markerA, "test.a", "a1"))
|
||||
await writeFile(
|
||||
path.join(directory, "crash.ts"),
|
||||
`
|
||||
import { appendFile } from "node:fs/promises"
|
||||
export default {
|
||||
id: "test.crash",
|
||||
setup: async (context: any) => {
|
||||
context.ui.slot("home.footer", () => {
|
||||
throw new Error("boom")
|
||||
})
|
||||
await appendFile(${JSON.stringify(markerCrash)}, "setup\\n")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
await using app = await bootApp(tmp.path)
|
||||
const readA = () => readFile(markerA, "utf8")
|
||||
await until(readA, (value) => value === "a1:setup\n")
|
||||
await until(() => readFile(markerCrash, "utf8"), (value) => value === "setup\n")
|
||||
|
||||
// The app survives the crashing slot: hot reload still works for others.
|
||||
await writeFile(sourceA, lifecycleSource(markerA, "test.a", "a2"))
|
||||
expect(await until(readA, (value) => value?.includes("a2:setup") ?? false)).toBe("a1:setup\na1:cleanup\na2:setup\n")
|
||||
|
||||
process.emit("SIGHUP")
|
||||
await app.task
|
||||
})
|
||||
|
||||
test("editing one plugin leaves others untouched and a broken save keeps the last good version", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const directory = path.join(tmp.path, ".opencode", "plugins", "tui")
|
||||
await mkdir(directory, { recursive: true })
|
||||
const markerA = path.join(tmp.path, "a.txt")
|
||||
const markerB = path.join(tmp.path, "b.txt")
|
||||
const sourceB = path.join(directory, "b.ts")
|
||||
await writeFile(path.join(directory, "a.ts"), lifecycleSource(markerA, "test.a", "a1"))
|
||||
await writeFile(sourceB, lifecycleSource(markerB, "test.b", "b1"))
|
||||
|
||||
await using app = await bootApp(tmp.path)
|
||||
const readA = () => readFile(markerA, "utf8")
|
||||
const readB = () => readFile(markerB, "utf8")
|
||||
await until(readA, (value) => value === "a1:setup\n")
|
||||
await until(readB, (value) => value === "b1:setup\n")
|
||||
|
||||
// Editing B restarts only B: A sees no cleanup and no second setup.
|
||||
await writeFile(sourceB, lifecycleSource(markerB, "test.b", "b2"))
|
||||
expect(await until(readB, (value) => value?.includes("b2:setup") ?? false)).toBe("b1:setup\nb1:cleanup\nb2:setup\n")
|
||||
expect(await readA()).toBe("a1:setup\n")
|
||||
|
||||
// A broken save keeps the last good version running: b2 is never cleaned up.
|
||||
await writeFile(sourceB, "export default {")
|
||||
await new Promise((resolve) => setTimeout(resolve, 800))
|
||||
expect(await readB()).toBe("b1:setup\nb1:cleanup\nb2:setup\n")
|
||||
expect(await readA()).toBe("a1:setup\n")
|
||||
|
||||
// Fixing the file replaces the kept version.
|
||||
await writeFile(sourceB, lifecycleSource(markerB, "test.b", "b3"))
|
||||
expect(await until(readB, (value) => value?.includes("b3:setup") ?? false)).toBe(
|
||||
"b1:setup\nb1:cleanup\nb2:setup\nb2:cleanup\nb3:setup\n",
|
||||
)
|
||||
expect(await readA()).toBe("a1:setup\n")
|
||||
|
||||
process.emit("SIGHUP")
|
||||
await app.task
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import { writeFile } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { expect, test } from "bun:test"
|
||||
import { freshSpecifier, localSource } from "../src/plugin/discovery"
|
||||
import { tmpdir } from "./fixture/fixture"
|
||||
|
||||
test("localSource resolves file URLs and local paths but not package specs", () => {
|
||||
const base = process.cwd()
|
||||
const absolute = path.resolve(base, "abs", "plugin.ts")
|
||||
expect(localSource("file:///tmp/plugin.ts", base)?.href).toBe("file:///tmp/plugin.ts")
|
||||
expect(localSource("./plugin.ts", base)?.href).toBe(pathToFileURL(path.join(base, "plugin.ts")).href)
|
||||
expect(localSource("../plugin.ts", path.join(base, "nested"))?.href).toBe(
|
||||
pathToFileURL(path.join(base, "plugin.ts")).href,
|
||||
)
|
||||
expect(localSource(absolute, base)?.href).toBe(pathToFileURL(absolute).href)
|
||||
expect(localSource("some-package", base)).toBeUndefined()
|
||||
expect(localSource("@scope/some-package", base)).toBeUndefined()
|
||||
})
|
||||
|
||||
test("freshSpecifier re-imports a plugin source after it changes", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const file = path.join(tmp.path, "plugin.ts")
|
||||
await writeFile(file, "export default 1")
|
||||
const first: { readonly default?: unknown } = await import(freshSpecifier(pathToFileURL(file).href, 1))
|
||||
await writeFile(file, "export default 2")
|
||||
const second: { readonly default?: unknown } = await import(freshSpecifier(pathToFileURL(file).href, 2))
|
||||
expect(first.default).toBe(1)
|
||||
expect(second.default).toBe(2)
|
||||
})
|
||||
Reference in New Issue
Block a user