tui plugins (#19347)
This commit is contained in:
90
packages/opencode/test/cli/tui/keybind-plugin.test.ts
Normal file
90
packages/opencode/test/cli/tui/keybind-plugin.test.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { ParsedKey } from "@opentui/core"
|
||||
import { createPluginKeybind } from "../../../src/cli/cmd/tui/context/plugin-keybinds"
|
||||
|
||||
describe("createPluginKeybind", () => {
|
||||
const defaults = {
|
||||
open: "ctrl+o",
|
||||
close: "escape",
|
||||
}
|
||||
|
||||
test("uses defaults when overrides are missing", () => {
|
||||
const api = {
|
||||
match: () => false,
|
||||
print: (key: string) => key,
|
||||
}
|
||||
const bind = createPluginKeybind(api, defaults)
|
||||
|
||||
expect(bind.all).toEqual(defaults)
|
||||
expect(bind.get("open")).toBe("ctrl+o")
|
||||
expect(bind.get("close")).toBe("escape")
|
||||
})
|
||||
|
||||
test("applies valid overrides", () => {
|
||||
const api = {
|
||||
match: () => false,
|
||||
print: (key: string) => key,
|
||||
}
|
||||
const bind = createPluginKeybind(api, defaults, {
|
||||
open: "ctrl+alt+o",
|
||||
close: "q",
|
||||
})
|
||||
|
||||
expect(bind.all).toEqual({
|
||||
open: "ctrl+alt+o",
|
||||
close: "q",
|
||||
})
|
||||
})
|
||||
|
||||
test("ignores invalid overrides", () => {
|
||||
const api = {
|
||||
match: () => false,
|
||||
print: (key: string) => key,
|
||||
}
|
||||
const bind = createPluginKeybind(api, defaults, {
|
||||
open: " ",
|
||||
close: 1,
|
||||
extra: "ctrl+x",
|
||||
})
|
||||
|
||||
expect(bind.all).toEqual(defaults)
|
||||
expect(bind.get("extra")).toBe("extra")
|
||||
})
|
||||
|
||||
test("resolves names for match", () => {
|
||||
const list: string[] = []
|
||||
const api = {
|
||||
match: (key: string) => {
|
||||
list.push(key)
|
||||
return true
|
||||
},
|
||||
print: (key: string) => key,
|
||||
}
|
||||
const bind = createPluginKeybind(api, defaults, {
|
||||
open: "ctrl+shift+o",
|
||||
})
|
||||
|
||||
bind.match("open", { name: "x" } as ParsedKey)
|
||||
bind.match("ctrl+k", { name: "x" } as ParsedKey)
|
||||
|
||||
expect(list).toEqual(["ctrl+shift+o", "ctrl+k"])
|
||||
})
|
||||
|
||||
test("resolves names for print", () => {
|
||||
const list: string[] = []
|
||||
const api = {
|
||||
match: () => false,
|
||||
print: (key: string) => {
|
||||
list.push(key)
|
||||
return `print:${key}`
|
||||
},
|
||||
}
|
||||
const bind = createPluginKeybind(api, defaults, {
|
||||
close: "q",
|
||||
})
|
||||
|
||||
expect(bind.print("close")).toBe("print:q")
|
||||
expect(bind.print("ctrl+p")).toBe("print:ctrl+p")
|
||||
expect(list).toEqual(["q", "ctrl+p"])
|
||||
})
|
||||
})
|
||||
61
packages/opencode/test/cli/tui/plugin-add.test.ts
Normal file
61
packages/opencode/test/cli/tui/plugin-add.test.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { expect, spyOn, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import { tmpdir } from "../../fixture/fixture"
|
||||
import { createTuiPluginApi } from "../../fixture/tui-plugin"
|
||||
import { TuiConfig } from "../../../src/config/tui"
|
||||
|
||||
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
|
||||
|
||||
test("adds tui plugin at runtime from spec", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "add-plugin.ts")
|
||||
const spec = pathToFileURL(file).href
|
||||
const marker = path.join(dir, "add.txt")
|
||||
|
||||
await Bun.write(
|
||||
file,
|
||||
`export default {
|
||||
id: "demo.add",
|
||||
tui: async () => {
|
||||
await Bun.write(${JSON.stringify(marker)}, "called")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return { spec, marker }
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
|
||||
const get = spyOn(TuiConfig, "get").mockResolvedValue({
|
||||
plugin: [],
|
||||
plugin_meta: undefined,
|
||||
})
|
||||
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
|
||||
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(createTuiPluginApi())
|
||||
|
||||
await expect(TuiPluginRuntime.addPlugin(tmp.extra.spec)).resolves.toBe(true)
|
||||
await expect(fs.readFile(tmp.extra.marker, "utf8")).resolves.toBe("called")
|
||||
expect(TuiPluginRuntime.list().find((item) => item.id === "demo.add")).toEqual({
|
||||
id: "demo.add",
|
||||
source: "file",
|
||||
spec: tmp.extra.spec,
|
||||
target: tmp.extra.spec,
|
||||
enabled: true,
|
||||
active: true,
|
||||
})
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
cwd.mockRestore()
|
||||
get.mockRestore()
|
||||
wait.mockRestore()
|
||||
delete process.env.OPENCODE_PLUGIN_META_FILE
|
||||
}
|
||||
})
|
||||
95
packages/opencode/test/cli/tui/plugin-install.test.ts
Normal file
95
packages/opencode/test/cli/tui/plugin-install.test.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { expect, spyOn, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import { tmpdir } from "../../fixture/fixture"
|
||||
import { createTuiPluginApi } from "../../fixture/tui-plugin"
|
||||
import { TuiConfig } from "../../../src/config/tui"
|
||||
|
||||
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
|
||||
|
||||
test("installs plugin without loading it", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "install-plugin.ts")
|
||||
const spec = pathToFileURL(file).href
|
||||
const marker = path.join(dir, "install.txt")
|
||||
|
||||
await Bun.write(
|
||||
path.join(dir, "package.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: "demo-install-plugin",
|
||||
type: "module",
|
||||
main: "./install-plugin.ts",
|
||||
"oc-plugin": [["tui", { marker }]],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
file,
|
||||
`export default {
|
||||
id: "demo.install",
|
||||
tui: async (_api, options) => {
|
||||
if (!options?.marker) return
|
||||
await Bun.write(options.marker, "loaded")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return { spec, marker }
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
|
||||
let cfg: Awaited<ReturnType<typeof TuiConfig.get>> = {
|
||||
plugin: [],
|
||||
plugin_meta: undefined,
|
||||
}
|
||||
const get = spyOn(TuiConfig, "get").mockImplementation(async () => cfg)
|
||||
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
|
||||
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
|
||||
const api = createTuiPluginApi({
|
||||
state: {
|
||||
path: {
|
||||
state: path.join(tmp.path, "state.json"),
|
||||
config: path.join(tmp.path, "tui.json"),
|
||||
worktree: tmp.path,
|
||||
directory: tmp.path,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(api)
|
||||
cfg = {
|
||||
plugin: [[tmp.extra.spec, { marker: tmp.extra.marker }]],
|
||||
plugin_meta: {
|
||||
[tmp.extra.spec]: {
|
||||
scope: "local",
|
||||
source: path.join(tmp.path, "tui.json"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const out = await TuiPluginRuntime.installPlugin(tmp.extra.spec)
|
||||
expect(out).toMatchObject({
|
||||
ok: true,
|
||||
tui: true,
|
||||
})
|
||||
|
||||
await expect(fs.readFile(tmp.extra.marker, "utf8")).rejects.toThrow()
|
||||
await expect(TuiPluginRuntime.addPlugin(tmp.extra.spec)).resolves.toBe(true)
|
||||
await expect(fs.readFile(tmp.extra.marker, "utf8")).resolves.toBe("loaded")
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
cwd.mockRestore()
|
||||
get.mockRestore()
|
||||
wait.mockRestore()
|
||||
delete process.env.OPENCODE_PLUGIN_META_FILE
|
||||
}
|
||||
})
|
||||
225
packages/opencode/test/cli/tui/plugin-lifecycle.test.ts
Normal file
225
packages/opencode/test/cli/tui/plugin-lifecycle.test.ts
Normal file
@@ -0,0 +1,225 @@
|
||||
import { expect, spyOn, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import { tmpdir } from "../../fixture/fixture"
|
||||
import { createTuiPluginApi } from "../../fixture/tui-plugin"
|
||||
import { mockTuiRuntime } from "../../fixture/tui-runtime"
|
||||
import { TuiConfig } from "../../../src/config/tui"
|
||||
|
||||
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
|
||||
|
||||
test("runs onDispose callbacks with aborted signal and is idempotent", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "plugin.ts")
|
||||
const spec = pathToFileURL(file).href
|
||||
const marker = path.join(dir, "marker.txt")
|
||||
|
||||
await Bun.write(
|
||||
file,
|
||||
`export default {
|
||||
id: "demo.lifecycle",
|
||||
tui: async (api, options) => {
|
||||
api.event.on("event.test", () => {})
|
||||
api.route.register([{ name: "lifecycle.route", render: () => null }])
|
||||
api.lifecycle.onDispose(async () => {
|
||||
const prev = await Bun.file(options.marker).text().catch(() => "")
|
||||
await Bun.write(options.marker, prev + "custom\\n")
|
||||
})
|
||||
api.lifecycle.onDispose(async () => {
|
||||
const prev = await Bun.file(options.marker).text().catch(() => "")
|
||||
await Bun.write(options.marker, prev + "aborted:" + String(api.lifecycle.signal.aborted) + "\\n")
|
||||
})
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return { spec, marker }
|
||||
},
|
||||
})
|
||||
|
||||
const restore = mockTuiRuntime(tmp.path, [[tmp.extra.spec, { marker: tmp.extra.marker }]])
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(createTuiPluginApi())
|
||||
await TuiPluginRuntime.dispose()
|
||||
|
||||
const marker = await fs.readFile(tmp.extra.marker, "utf8")
|
||||
expect(marker).toContain("custom")
|
||||
expect(marker).toContain("aborted:true")
|
||||
|
||||
// second dispose is a no-op
|
||||
await TuiPluginRuntime.dispose()
|
||||
const after = await fs.readFile(tmp.extra.marker, "utf8")
|
||||
expect(after).toBe(marker)
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
restore()
|
||||
}
|
||||
})
|
||||
|
||||
test("rolls back failed plugin and continues loading next", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const bad = path.join(dir, "bad-plugin.ts")
|
||||
const good = path.join(dir, "good-plugin.ts")
|
||||
const badSpec = pathToFileURL(bad).href
|
||||
const goodSpec = pathToFileURL(good).href
|
||||
const badMarker = path.join(dir, "bad-cleanup.txt")
|
||||
const goodMarker = path.join(dir, "good-called.txt")
|
||||
|
||||
await Bun.write(
|
||||
bad,
|
||||
`export default {
|
||||
id: "demo.bad",
|
||||
tui: async (api, options) => {
|
||||
api.route.register([{ name: "bad.route", render: () => null }])
|
||||
api.lifecycle.onDispose(async () => {
|
||||
await Bun.write(options.bad_marker, "cleaned")
|
||||
})
|
||||
throw new Error("bad plugin")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
good,
|
||||
`export default {
|
||||
id: "demo.good",
|
||||
tui: async (_api, options) => {
|
||||
await Bun.write(options.good_marker, "called")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return { badSpec, goodSpec, badMarker, goodMarker }
|
||||
},
|
||||
})
|
||||
|
||||
const restore = mockTuiRuntime(tmp.path, [
|
||||
[tmp.extra.badSpec, { bad_marker: tmp.extra.badMarker }],
|
||||
[tmp.extra.goodSpec, { good_marker: tmp.extra.goodMarker }],
|
||||
])
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(createTuiPluginApi())
|
||||
// bad plugin's onDispose ran during rollback
|
||||
await expect(fs.readFile(tmp.extra.badMarker, "utf8")).resolves.toBe("cleaned")
|
||||
// good plugin still loaded
|
||||
await expect(fs.readFile(tmp.extra.goodMarker, "utf8")).resolves.toBe("called")
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
restore()
|
||||
}
|
||||
})
|
||||
|
||||
test("assigns sequential slot ids scoped to plugin", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "slot-plugin.ts")
|
||||
const spec = pathToFileURL(file).href
|
||||
const marker = path.join(dir, "slot-setup.txt")
|
||||
|
||||
await Bun.write(
|
||||
file,
|
||||
`import fs from "fs"
|
||||
|
||||
const mark = (label) => {
|
||||
fs.appendFileSync(${JSON.stringify(marker)}, label + "\\n")
|
||||
}
|
||||
|
||||
export default {
|
||||
id: "demo.slot",
|
||||
tui: async (api) => {
|
||||
const one = api.slots.register({
|
||||
id: 1,
|
||||
setup: () => { mark("one") },
|
||||
slots: { home_logo() { return null } },
|
||||
})
|
||||
const two = api.slots.register({
|
||||
id: 2,
|
||||
setup: () => { mark("two") },
|
||||
slots: { home_bottom() { return null } },
|
||||
})
|
||||
mark("id:" + one)
|
||||
mark("id:" + two)
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return { spec, marker }
|
||||
},
|
||||
})
|
||||
|
||||
const restore = mockTuiRuntime(tmp.path, [tmp.extra.spec])
|
||||
const err = spyOn(console, "error").mockImplementation(() => {})
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(createTuiPluginApi())
|
||||
|
||||
const marker = await fs.readFile(tmp.extra.marker, "utf8")
|
||||
expect(marker).toContain("one")
|
||||
expect(marker).toContain("two")
|
||||
expect(marker).toContain("id:demo.slot")
|
||||
expect(marker).toContain("id:demo.slot:1")
|
||||
|
||||
// no initialization failures
|
||||
const hit = err.mock.calls.find(
|
||||
(item) => typeof item[0] === "string" && item[0].includes("failed to initialize tui plugin"),
|
||||
)
|
||||
expect(hit).toBeUndefined()
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
err.mockRestore()
|
||||
restore()
|
||||
}
|
||||
})
|
||||
|
||||
test(
|
||||
"times out hanging plugin cleanup on dispose",
|
||||
async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "timeout-plugin.ts")
|
||||
const spec = pathToFileURL(file).href
|
||||
|
||||
await Bun.write(
|
||||
file,
|
||||
`export default {
|
||||
id: "demo.timeout",
|
||||
tui: async (api) => {
|
||||
api.lifecycle.onDispose(() => new Promise(() => {}))
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return { spec }
|
||||
},
|
||||
})
|
||||
|
||||
const restore = mockTuiRuntime(tmp.path, [tmp.extra.spec])
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(createTuiPluginApi())
|
||||
|
||||
const done = await new Promise<string>((resolve) => {
|
||||
const timer = setTimeout(() => resolve("timeout"), 7000)
|
||||
TuiPluginRuntime.dispose().then(() => {
|
||||
clearTimeout(timer)
|
||||
resolve("done")
|
||||
})
|
||||
})
|
||||
expect(done).toBe("done")
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
restore()
|
||||
}
|
||||
},
|
||||
{ timeout: 15000 },
|
||||
)
|
||||
132
packages/opencode/test/cli/tui/plugin-loader-entrypoint.test.ts
Normal file
132
packages/opencode/test/cli/tui/plugin-loader-entrypoint.test.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { expect, spyOn, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { tmpdir } from "../../fixture/fixture"
|
||||
import { createTuiPluginApi } from "../../fixture/tui-plugin"
|
||||
import { TuiConfig } from "../../../src/config/tui"
|
||||
import { BunProc } from "../../../src/bun"
|
||||
|
||||
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
|
||||
|
||||
test("loads npm tui plugin from package ./tui export", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const mod = path.join(dir, "mods", "acme-plugin")
|
||||
const marker = path.join(dir, "tui-called.txt")
|
||||
await fs.mkdir(mod, { recursive: true })
|
||||
|
||||
await Bun.write(
|
||||
path.join(mod, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "acme-plugin",
|
||||
type: "module",
|
||||
exports: { ".": "./index.js", "./server": "./server.js", "./tui": "./tui.js" },
|
||||
}),
|
||||
)
|
||||
await Bun.write(path.join(mod, "index.js"), 'import "./main-throws.js"\nexport default {}\n')
|
||||
await Bun.write(path.join(mod, "main-throws.js"), 'throw new Error("main loaded")\n')
|
||||
await Bun.write(path.join(mod, "server.js"), "export default {}\n")
|
||||
await Bun.write(
|
||||
path.join(mod, "tui.js"),
|
||||
`export default {
|
||||
id: "demo.tui.export",
|
||||
tui: async (_api, options) => {
|
||||
if (!options?.marker) return
|
||||
await Bun.write(${JSON.stringify(marker)}, "called")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return { mod, marker, spec: "acme-plugin@1.0.0" }
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
|
||||
const get = spyOn(TuiConfig, "get").mockResolvedValue({
|
||||
plugin: [[tmp.extra.spec, { marker: tmp.extra.marker }]],
|
||||
plugin_meta: {
|
||||
[tmp.extra.spec]: { scope: "local", source: path.join(tmp.path, "tui.json") },
|
||||
},
|
||||
})
|
||||
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
|
||||
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
|
||||
const install = spyOn(BunProc, "install").mockResolvedValue(tmp.extra.mod)
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(createTuiPluginApi())
|
||||
await expect(fs.readFile(tmp.extra.marker, "utf8")).resolves.toBe("called")
|
||||
const hit = TuiPluginRuntime.list().find((item) => item.id === "demo.tui.export")
|
||||
expect(hit?.enabled).toBe(true)
|
||||
expect(hit?.active).toBe(true)
|
||||
expect(hit?.source).toBe("npm")
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
install.mockRestore()
|
||||
cwd.mockRestore()
|
||||
get.mockRestore()
|
||||
wait.mockRestore()
|
||||
delete process.env.OPENCODE_PLUGIN_META_FILE
|
||||
}
|
||||
})
|
||||
|
||||
test("rejects npm tui export that resolves outside plugin directory", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const mod = path.join(dir, "mods", "acme-plugin")
|
||||
const outside = path.join(dir, "outside")
|
||||
const marker = path.join(dir, "outside-called.txt")
|
||||
await fs.mkdir(mod, { recursive: true })
|
||||
await fs.mkdir(outside, { recursive: true })
|
||||
|
||||
await Bun.write(
|
||||
path.join(mod, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "acme-plugin",
|
||||
type: "module",
|
||||
exports: { ".": "./index.js", "./tui": "./escape/tui.js" },
|
||||
}),
|
||||
)
|
||||
await Bun.write(path.join(mod, "index.js"), "export default {}\n")
|
||||
await Bun.write(
|
||||
path.join(outside, "tui.js"),
|
||||
`export default {
|
||||
id: "demo.outside",
|
||||
tui: async () => {
|
||||
await Bun.write(${JSON.stringify(marker)}, "outside")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
await fs.symlink(outside, path.join(mod, "escape"), process.platform === "win32" ? "junction" : "dir")
|
||||
|
||||
return { mod, marker, spec: "acme-plugin@1.0.0" }
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
|
||||
const get = spyOn(TuiConfig, "get").mockResolvedValue({
|
||||
plugin: [tmp.extra.spec],
|
||||
plugin_meta: {
|
||||
[tmp.extra.spec]: { scope: "local", source: path.join(tmp.path, "tui.json") },
|
||||
},
|
||||
})
|
||||
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
|
||||
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
|
||||
const install = spyOn(BunProc, "install").mockResolvedValue(tmp.extra.mod)
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(createTuiPluginApi())
|
||||
// plugin code never ran
|
||||
await expect(fs.readFile(tmp.extra.marker, "utf8")).rejects.toThrow()
|
||||
// plugin not listed
|
||||
expect(TuiPluginRuntime.list().some((item) => item.spec === tmp.extra.spec)).toBe(false)
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
install.mockRestore()
|
||||
cwd.mockRestore()
|
||||
get.mockRestore()
|
||||
wait.mockRestore()
|
||||
delete process.env.OPENCODE_PLUGIN_META_FILE
|
||||
}
|
||||
})
|
||||
71
packages/opencode/test/cli/tui/plugin-loader-pure.test.ts
Normal file
71
packages/opencode/test/cli/tui/plugin-loader-pure.test.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { expect, spyOn, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import { tmpdir } from "../../fixture/fixture"
|
||||
import { createTuiPluginApi } from "../../fixture/tui-plugin"
|
||||
import { TuiConfig } from "../../../src/config/tui"
|
||||
|
||||
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
|
||||
|
||||
test("skips external tui plugins in pure mode", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "plugin.ts")
|
||||
const spec = pathToFileURL(file).href
|
||||
const marker = path.join(dir, "called.txt")
|
||||
const meta = path.join(dir, "plugin-meta.json")
|
||||
|
||||
await Bun.write(
|
||||
file,
|
||||
`export default {
|
||||
id: "demo.pure",
|
||||
tui: async (_api, options) => {
|
||||
if (!options?.marker) return
|
||||
await Bun.write(options.marker, "called")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return { spec, marker, meta }
|
||||
},
|
||||
})
|
||||
|
||||
const pure = process.env.OPENCODE_PURE
|
||||
const meta = process.env.OPENCODE_PLUGIN_META_FILE
|
||||
process.env.OPENCODE_PURE = "1"
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = tmp.extra.meta
|
||||
|
||||
const get = spyOn(TuiConfig, "get").mockResolvedValue({
|
||||
plugin: [[tmp.extra.spec, { marker: tmp.extra.marker }]],
|
||||
plugin_meta: {
|
||||
[tmp.extra.spec]: {
|
||||
scope: "local",
|
||||
source: path.join(tmp.path, "tui.json"),
|
||||
},
|
||||
},
|
||||
})
|
||||
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
|
||||
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(createTuiPluginApi())
|
||||
await expect(fs.readFile(tmp.extra.marker, "utf8")).rejects.toThrow()
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
cwd.mockRestore()
|
||||
get.mockRestore()
|
||||
wait.mockRestore()
|
||||
if (pure === undefined) {
|
||||
delete process.env.OPENCODE_PURE
|
||||
} else {
|
||||
process.env.OPENCODE_PURE = pure
|
||||
}
|
||||
if (meta === undefined) {
|
||||
delete process.env.OPENCODE_PLUGIN_META_FILE
|
||||
} else {
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = meta
|
||||
}
|
||||
}
|
||||
})
|
||||
563
packages/opencode/test/cli/tui/plugin-loader.test.ts
Normal file
563
packages/opencode/test/cli/tui/plugin-loader.test.ts
Normal file
@@ -0,0 +1,563 @@
|
||||
import { beforeAll, describe, expect, spyOn, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import { tmpdir } from "../../fixture/fixture"
|
||||
import { createTuiPluginApi } from "../../fixture/tui-plugin"
|
||||
import { Global } from "../../../src/global"
|
||||
import { TuiConfig } from "../../../src/config/tui"
|
||||
import { Config } from "../../../src/config/config"
|
||||
import { Filesystem } from "../../../src/util/filesystem"
|
||||
|
||||
const { allThemes, addTheme } = await import("../../../src/cli/cmd/tui/context/theme")
|
||||
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
|
||||
|
||||
type Row = Record<string, unknown>
|
||||
|
||||
type Data = {
|
||||
local: Row
|
||||
global: Row
|
||||
invalid: Row
|
||||
preloaded: Row
|
||||
fn_called: boolean
|
||||
local_installed: string
|
||||
global_installed: string
|
||||
preloaded_installed: string
|
||||
leaked_local_to_global: boolean
|
||||
leaked_global_to_local: boolean
|
||||
local_theme: string
|
||||
global_theme: string
|
||||
}
|
||||
|
||||
async function row(file: string): Promise<Row> {
|
||||
return Filesystem.readJson<Row>(file)
|
||||
}
|
||||
|
||||
async function load(): Promise<Data> {
|
||||
const stamp = Date.now()
|
||||
const globalConfigPath = path.join(Global.Path.config, "tui.json")
|
||||
const backup = await Bun.file(globalConfigPath)
|
||||
.text()
|
||||
.catch(() => undefined)
|
||||
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const localPluginPath = path.join(dir, "local-plugin.ts")
|
||||
const invalidPluginPath = path.join(dir, "invalid-plugin.ts")
|
||||
const preloadedPluginPath = path.join(dir, "preloaded-plugin.ts")
|
||||
const globalPluginPath = path.join(dir, "global-plugin.ts")
|
||||
const localSpec = pathToFileURL(localPluginPath).href
|
||||
const invalidSpec = pathToFileURL(invalidPluginPath).href
|
||||
const preloadedSpec = pathToFileURL(preloadedPluginPath).href
|
||||
const globalSpec = pathToFileURL(globalPluginPath).href
|
||||
const localThemeFile = `local-theme-${stamp}.json`
|
||||
const invalidThemeFile = `invalid-theme-${stamp}.json`
|
||||
const globalThemeFile = `global-theme-${stamp}.json`
|
||||
const preloadedThemeFile = `preloaded-theme-${stamp}.json`
|
||||
const localThemeName = localThemeFile.replace(/\.json$/, "")
|
||||
const invalidThemeName = invalidThemeFile.replace(/\.json$/, "")
|
||||
const globalThemeName = globalThemeFile.replace(/\.json$/, "")
|
||||
const preloadedThemeName = preloadedThemeFile.replace(/\.json$/, "")
|
||||
const localThemePath = path.join(dir, localThemeFile)
|
||||
const invalidThemePath = path.join(dir, invalidThemeFile)
|
||||
const globalThemePath = path.join(dir, globalThemeFile)
|
||||
const preloadedThemePath = path.join(dir, preloadedThemeFile)
|
||||
const localDest = path.join(dir, ".opencode", "themes", localThemeFile)
|
||||
const globalDest = path.join(Global.Path.config, "themes", globalThemeFile)
|
||||
const preloadedDest = path.join(dir, ".opencode", "themes", preloadedThemeFile)
|
||||
const fnMarker = path.join(dir, "function-called.txt")
|
||||
const localMarker = path.join(dir, "local-called.json")
|
||||
const invalidMarker = path.join(dir, "invalid-called.json")
|
||||
const globalMarker = path.join(dir, "global-called.json")
|
||||
const preloadedMarker = path.join(dir, "preloaded-called.json")
|
||||
const localConfigPath = path.join(dir, "tui.json")
|
||||
|
||||
await Bun.write(localThemePath, JSON.stringify({ theme: { primary: "#101010" } }, null, 2))
|
||||
await Bun.write(invalidThemePath, "{ invalid json }")
|
||||
await Bun.write(globalThemePath, JSON.stringify({ theme: { primary: "#202020" } }, null, 2))
|
||||
await Bun.write(preloadedThemePath, JSON.stringify({ theme: { primary: "#f0f0f0" } }, null, 2))
|
||||
await Bun.write(preloadedDest, JSON.stringify({ theme: { primary: "#303030" } }, null, 2))
|
||||
|
||||
await Bun.write(
|
||||
localPluginPath,
|
||||
`export const ignored = async (_input, options) => {
|
||||
if (!options?.fn_marker) return
|
||||
await Bun.write(options.fn_marker, "called")
|
||||
}
|
||||
|
||||
export default {
|
||||
id: "demo.local",
|
||||
tui: async (api, options) => {
|
||||
if (!options?.marker) return
|
||||
const cfg_theme = api.tuiConfig.theme
|
||||
const cfg_diff = api.tuiConfig.diff_style
|
||||
const cfg_speed = api.tuiConfig.scroll_speed
|
||||
const cfg_accel = api.tuiConfig.scroll_acceleration?.enabled
|
||||
const cfg_submit = api.tuiConfig.keybinds?.input_submit
|
||||
const key = api.keybind.create(
|
||||
{ modal: "ctrl+shift+m", screen: "ctrl+shift+o", close: "escape" },
|
||||
options.keybinds,
|
||||
)
|
||||
const kv_before = api.kv.get(options.kv_key, "missing")
|
||||
api.kv.set(options.kv_key, "stored")
|
||||
const kv_after = api.kv.get(options.kv_key, "missing")
|
||||
const diff = api.state.session.diff(options.session_id)
|
||||
const todo = api.state.session.todo(options.session_id)
|
||||
const lsp = api.state.lsp()
|
||||
const mcp = api.state.mcp()
|
||||
const depth_before = api.ui.dialog.depth
|
||||
const open_before = api.ui.dialog.open
|
||||
const size_before = api.ui.dialog.size
|
||||
api.ui.dialog.setSize("large")
|
||||
const size_after = api.ui.dialog.size
|
||||
api.ui.dialog.replace(() => null)
|
||||
const depth_after = api.ui.dialog.depth
|
||||
const open_after = api.ui.dialog.open
|
||||
api.ui.dialog.clear()
|
||||
const open_clear = api.ui.dialog.open
|
||||
const before = api.theme.has(options.theme_name)
|
||||
const set_missing = api.theme.set(options.theme_name)
|
||||
await api.theme.install(options.theme_path)
|
||||
const after = api.theme.has(options.theme_name)
|
||||
const set_installed = api.theme.set(options.theme_name)
|
||||
const first = await Bun.file(options.dest).text()
|
||||
await Bun.write(options.source, JSON.stringify({ theme: { primary: "#fefefe" } }, null, 2))
|
||||
await api.theme.install(options.theme_path)
|
||||
const second = await Bun.file(options.dest).text()
|
||||
await Bun.write(
|
||||
options.marker,
|
||||
JSON.stringify({
|
||||
before,
|
||||
set_missing,
|
||||
after,
|
||||
set_installed,
|
||||
selected: api.theme.selected,
|
||||
same: first === second,
|
||||
key_modal: key.get("modal"),
|
||||
key_close: key.get("close"),
|
||||
key_unknown: key.get("ctrl+k"),
|
||||
key_print: key.print("modal"),
|
||||
kv_before,
|
||||
kv_after,
|
||||
kv_ready: api.kv.ready,
|
||||
diff_count: diff.length,
|
||||
diff_file: diff[0]?.file,
|
||||
todo_count: todo.length,
|
||||
todo_first: todo[0]?.content,
|
||||
lsp_count: lsp.length,
|
||||
mcp_count: mcp.length,
|
||||
mcp_first: mcp[0]?.name,
|
||||
depth_before,
|
||||
open_before,
|
||||
size_before,
|
||||
size_after,
|
||||
depth_after,
|
||||
open_after,
|
||||
open_clear,
|
||||
cfg_theme,
|
||||
cfg_diff,
|
||||
cfg_speed,
|
||||
cfg_accel,
|
||||
cfg_submit,
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
invalidPluginPath,
|
||||
`export default {
|
||||
id: "demo.invalid",
|
||||
tui: async (api, options) => {
|
||||
if (!options?.marker) return
|
||||
const before = api.theme.has(options.theme_name)
|
||||
const set_missing = api.theme.set(options.theme_name)
|
||||
await api.theme.install(options.theme_path)
|
||||
const after = api.theme.has(options.theme_name)
|
||||
const set_installed = api.theme.set(options.theme_name)
|
||||
await Bun.write(
|
||||
options.marker,
|
||||
JSON.stringify({
|
||||
before,
|
||||
set_missing,
|
||||
after,
|
||||
set_installed,
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
preloadedPluginPath,
|
||||
`export default {
|
||||
id: "demo.preloaded",
|
||||
tui: async (api, options) => {
|
||||
if (!options?.marker) return
|
||||
const before = api.theme.has(options.theme_name)
|
||||
await api.theme.install(options.theme_path)
|
||||
const after = api.theme.has(options.theme_name)
|
||||
const text = await Bun.file(options.dest).text()
|
||||
await Bun.write(
|
||||
options.marker,
|
||||
JSON.stringify({
|
||||
before,
|
||||
after,
|
||||
text,
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
globalPluginPath,
|
||||
`export default {
|
||||
id: "demo.global",
|
||||
tui: async (api, options) => {
|
||||
if (!options?.marker) return
|
||||
await api.theme.install(options.theme_path)
|
||||
const has = api.theme.has(options.theme_name)
|
||||
const set_installed = api.theme.set(options.theme_name)
|
||||
await Bun.write(
|
||||
options.marker,
|
||||
JSON.stringify({
|
||||
has,
|
||||
set_installed,
|
||||
selected: api.theme.selected,
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
globalConfigPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
plugin: [
|
||||
[globalSpec, { marker: globalMarker, theme_path: `./${globalThemeFile}`, theme_name: globalThemeName }],
|
||||
],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
localConfigPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
plugin: [
|
||||
[
|
||||
localSpec,
|
||||
{
|
||||
fn_marker: fnMarker,
|
||||
marker: localMarker,
|
||||
source: localThemePath,
|
||||
dest: localDest,
|
||||
theme_path: `./${localThemeFile}`,
|
||||
theme_name: localThemeName,
|
||||
kv_key: "plugin_state_key",
|
||||
session_id: "ses_test",
|
||||
keybinds: {
|
||||
modal: "ctrl+alt+m",
|
||||
close: "q",
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
invalidSpec,
|
||||
{
|
||||
marker: invalidMarker,
|
||||
theme_path: `./${invalidThemeFile}`,
|
||||
theme_name: invalidThemeName,
|
||||
},
|
||||
],
|
||||
[
|
||||
preloadedSpec,
|
||||
{
|
||||
marker: preloadedMarker,
|
||||
dest: preloadedDest,
|
||||
theme_path: `./${preloadedThemeFile}`,
|
||||
theme_name: preloadedThemeName,
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
|
||||
return {
|
||||
localThemeFile,
|
||||
invalidThemeFile,
|
||||
globalThemeFile,
|
||||
preloadedThemeFile,
|
||||
localThemeName,
|
||||
invalidThemeName,
|
||||
globalThemeName,
|
||||
preloadedThemeName,
|
||||
localDest,
|
||||
globalDest,
|
||||
preloadedDest,
|
||||
localPluginPath,
|
||||
invalidPluginPath,
|
||||
globalPluginPath,
|
||||
preloadedPluginPath,
|
||||
localSpec,
|
||||
invalidSpec,
|
||||
globalSpec,
|
||||
preloadedSpec,
|
||||
fnMarker,
|
||||
localMarker,
|
||||
invalidMarker,
|
||||
globalMarker,
|
||||
preloadedMarker,
|
||||
}
|
||||
},
|
||||
})
|
||||
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
|
||||
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
|
||||
const install = spyOn(Config, "installDependencies").mockResolvedValue()
|
||||
|
||||
try {
|
||||
expect(addTheme(tmp.extra.preloadedThemeName, { theme: { primary: "#303030" } })).toBe(true)
|
||||
|
||||
await TuiPluginRuntime.init(
|
||||
createTuiPluginApi({
|
||||
tuiConfig: {
|
||||
theme: "smoke",
|
||||
diff_style: "stacked",
|
||||
scroll_speed: 1.5,
|
||||
scroll_acceleration: { enabled: true },
|
||||
keybinds: {
|
||||
input_submit: "ctrl+enter",
|
||||
},
|
||||
},
|
||||
keybind: {
|
||||
print: (key) => `print:${key}`,
|
||||
},
|
||||
state: {
|
||||
session: {
|
||||
diff(sessionID) {
|
||||
if (sessionID !== "ses_test") return []
|
||||
return [{ file: "src/app.ts", additions: 3, deletions: 1 }]
|
||||
},
|
||||
todo(sessionID) {
|
||||
if (sessionID !== "ses_test") return []
|
||||
return [{ content: "ship it", status: "pending" }]
|
||||
},
|
||||
},
|
||||
lsp() {
|
||||
return [{ id: "ts", root: "/tmp/project", status: "connected" }]
|
||||
},
|
||||
mcp() {
|
||||
return [{ name: "github", status: "connected" }]
|
||||
},
|
||||
},
|
||||
theme: {
|
||||
has(name) {
|
||||
return allThemes()[name] !== undefined
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
const local = await row(tmp.extra.localMarker)
|
||||
const global = await row(tmp.extra.globalMarker)
|
||||
const invalid = await row(tmp.extra.invalidMarker)
|
||||
const preloaded = await row(tmp.extra.preloadedMarker)
|
||||
const fn_called = await fs
|
||||
.readFile(tmp.extra.fnMarker, "utf8")
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
const local_installed = await fs.readFile(tmp.extra.localDest, "utf8")
|
||||
const global_installed = await fs.readFile(tmp.extra.globalDest, "utf8")
|
||||
const preloaded_installed = await fs.readFile(tmp.extra.preloadedDest, "utf8")
|
||||
const leaked_local_to_global = await fs
|
||||
.stat(path.join(Global.Path.config, "themes", tmp.extra.localThemeFile))
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
const leaked_global_to_local = await fs
|
||||
.stat(path.join(tmp.path, ".opencode", "themes", tmp.extra.globalThemeFile))
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
|
||||
return {
|
||||
local,
|
||||
global,
|
||||
invalid,
|
||||
preloaded,
|
||||
fn_called,
|
||||
local_installed,
|
||||
global_installed,
|
||||
preloaded_installed,
|
||||
leaked_local_to_global,
|
||||
leaked_global_to_local,
|
||||
local_theme: tmp.extra.localThemeName,
|
||||
global_theme: tmp.extra.globalThemeName,
|
||||
}
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
cwd.mockRestore()
|
||||
wait.mockRestore()
|
||||
install.mockRestore()
|
||||
if (backup === undefined) {
|
||||
await fs.rm(globalConfigPath, { force: true })
|
||||
} else {
|
||||
await Bun.write(globalConfigPath, backup)
|
||||
}
|
||||
await fs.rm(tmp.extra.globalDest, { force: true }).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
test("continues loading when a plugin is missing config metadata", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const bad = path.join(dir, "missing-meta-plugin.ts")
|
||||
const good = path.join(dir, "next-plugin.ts")
|
||||
const bare = path.join(dir, "plain-plugin.ts")
|
||||
const badSpec = pathToFileURL(bad).href
|
||||
const goodSpec = pathToFileURL(good).href
|
||||
const bareSpec = pathToFileURL(bare).href
|
||||
const goodMarker = path.join(dir, "next-called.txt")
|
||||
const bareMarker = path.join(dir, "plain-called.txt")
|
||||
|
||||
for (const [file, id] of [
|
||||
[bad, "demo.missing-meta"],
|
||||
[good, "demo.next"],
|
||||
] as const) {
|
||||
await Bun.write(
|
||||
file,
|
||||
`export default {
|
||||
id: "${id}",
|
||||
tui: async (_api, options) => {
|
||||
if (!options?.marker) return
|
||||
await Bun.write(options.marker, "called")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
}
|
||||
|
||||
await Bun.write(
|
||||
bare,
|
||||
`export default {
|
||||
id: "demo.plain",
|
||||
tui: async (_api, options) => {
|
||||
await Bun.write(${JSON.stringify(bareMarker)}, options === undefined ? "undefined" : "value")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return { badSpec, goodSpec, bareSpec, goodMarker, bareMarker }
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
|
||||
const get = spyOn(TuiConfig, "get").mockResolvedValue({
|
||||
plugin: [
|
||||
[tmp.extra.badSpec, { marker: path.join(tmp.path, "bad.txt") }],
|
||||
[tmp.extra.goodSpec, { marker: tmp.extra.goodMarker }],
|
||||
tmp.extra.bareSpec,
|
||||
],
|
||||
plugin_meta: {
|
||||
[tmp.extra.goodSpec]: { scope: "local", source: path.join(tmp.path, "tui.json") },
|
||||
[tmp.extra.bareSpec]: { scope: "local", source: path.join(tmp.path, "tui.json") },
|
||||
},
|
||||
})
|
||||
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
|
||||
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(createTuiPluginApi())
|
||||
// bad plugin was skipped (no metadata entry)
|
||||
await expect(fs.readFile(path.join(tmp.path, "bad.txt"), "utf8")).rejects.toThrow()
|
||||
// good plugin loaded fine
|
||||
await expect(fs.readFile(tmp.extra.goodMarker, "utf8")).resolves.toBe("called")
|
||||
// bare string spec gets undefined options
|
||||
await expect(fs.readFile(tmp.extra.bareMarker, "utf8")).resolves.toBe("undefined")
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
cwd.mockRestore()
|
||||
get.mockRestore()
|
||||
wait.mockRestore()
|
||||
delete process.env.OPENCODE_PLUGIN_META_FILE
|
||||
}
|
||||
})
|
||||
|
||||
describe("tui.plugin.loader", () => {
|
||||
let data: Data
|
||||
|
||||
beforeAll(async () => {
|
||||
data = await load()
|
||||
})
|
||||
|
||||
test("passes keybind, kv, state, and dialog APIs to v1 plugins", () => {
|
||||
expect(data.local.key_modal).toBe("ctrl+alt+m")
|
||||
expect(data.local.key_close).toBe("q")
|
||||
expect(data.local.key_unknown).toBe("ctrl+k")
|
||||
expect(data.local.key_print).toBe("print:ctrl+alt+m")
|
||||
expect(data.local.kv_before).toBe("missing")
|
||||
expect(data.local.kv_after).toBe("stored")
|
||||
expect(data.local.kv_ready).toBe(true)
|
||||
expect(data.local.diff_count).toBe(1)
|
||||
expect(data.local.diff_file).toBe("src/app.ts")
|
||||
expect(data.local.todo_count).toBe(1)
|
||||
expect(data.local.todo_first).toBe("ship it")
|
||||
expect(data.local.lsp_count).toBe(1)
|
||||
expect(data.local.mcp_count).toBe(1)
|
||||
expect(data.local.mcp_first).toBe("github")
|
||||
expect(data.local.depth_before).toBe(0)
|
||||
expect(data.local.open_before).toBe(false)
|
||||
expect(data.local.size_before).toBe("medium")
|
||||
expect(data.local.size_after).toBe("large")
|
||||
expect(data.local.depth_after).toBe(1)
|
||||
expect(data.local.open_after).toBe(true)
|
||||
expect(data.local.open_clear).toBe(false)
|
||||
expect(data.local.cfg_theme).toBe("smoke")
|
||||
expect(data.local.cfg_diff).toBe("stacked")
|
||||
expect(data.local.cfg_speed).toBe(1.5)
|
||||
expect(data.local.cfg_accel).toBe(true)
|
||||
expect(data.local.cfg_submit).toBe("ctrl+enter")
|
||||
})
|
||||
|
||||
test("installs themes in the correct scope and remains resilient", () => {
|
||||
expect(data.local.before).toBe(false)
|
||||
expect(data.local.set_missing).toBe(false)
|
||||
expect(data.local.after).toBe(true)
|
||||
expect(data.local.set_installed).toBe(true)
|
||||
expect(data.local.selected).toBe(data.local_theme)
|
||||
expect(data.local.same).toBe(true)
|
||||
|
||||
expect(data.global.has).toBe(true)
|
||||
expect(data.global.set_installed).toBe(true)
|
||||
expect(data.global.selected).toBe(data.global_theme)
|
||||
|
||||
expect(data.invalid.before).toBe(false)
|
||||
expect(data.invalid.set_missing).toBe(false)
|
||||
expect(data.invalid.after).toBe(false)
|
||||
expect(data.invalid.set_installed).toBe(false)
|
||||
|
||||
expect(data.preloaded.before).toBe(true)
|
||||
expect(data.preloaded.after).toBe(true)
|
||||
expect(data.preloaded.text).toContain("#303030")
|
||||
expect(data.preloaded.text).not.toContain("#f0f0f0")
|
||||
|
||||
expect(data.fn_called).toBe(false)
|
||||
expect(data.local_installed).toContain("#101010")
|
||||
expect(data.local_installed).not.toContain("#fefefe")
|
||||
expect(data.global_installed).toContain("#202020")
|
||||
expect(data.preloaded_installed).toContain("#303030")
|
||||
expect(data.preloaded_installed).not.toContain("#f0f0f0")
|
||||
expect(data.leaked_local_to_global).toBe(false)
|
||||
expect(data.leaked_global_to_local).toBe(false)
|
||||
})
|
||||
})
|
||||
157
packages/opencode/test/cli/tui/plugin-toggle.test.ts
Normal file
157
packages/opencode/test/cli/tui/plugin-toggle.test.ts
Normal file
@@ -0,0 +1,157 @@
|
||||
import { expect, spyOn, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import { tmpdir } from "../../fixture/fixture"
|
||||
import { createTuiPluginApi } from "../../fixture/tui-plugin"
|
||||
import { TuiConfig } from "../../../src/config/tui"
|
||||
|
||||
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
|
||||
|
||||
test("toggles plugin runtime state by exported id", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "toggle-plugin.ts")
|
||||
const spec = pathToFileURL(file).href
|
||||
const marker = path.join(dir, "toggle.txt")
|
||||
|
||||
await Bun.write(
|
||||
file,
|
||||
`export default {
|
||||
id: "demo.toggle",
|
||||
tui: async (api, options) => {
|
||||
const text = await Bun.file(options.marker).text().catch(() => "")
|
||||
await Bun.write(options.marker, text + "start\\n")
|
||||
api.lifecycle.onDispose(async () => {
|
||||
const next = await Bun.file(options.marker).text().catch(() => "")
|
||||
await Bun.write(options.marker, next + "stop\\n")
|
||||
})
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return {
|
||||
spec,
|
||||
marker,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
|
||||
const get = spyOn(TuiConfig, "get").mockResolvedValue({
|
||||
plugin: [[tmp.extra.spec, { marker: tmp.extra.marker }]],
|
||||
plugin_enabled: {
|
||||
"demo.toggle": false,
|
||||
},
|
||||
plugin_meta: {
|
||||
[tmp.extra.spec]: {
|
||||
scope: "local",
|
||||
source: path.join(tmp.path, "tui.json"),
|
||||
},
|
||||
},
|
||||
})
|
||||
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
|
||||
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
|
||||
const api = createTuiPluginApi()
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(api)
|
||||
|
||||
await expect(fs.readFile(tmp.extra.marker, "utf8")).rejects.toThrow()
|
||||
expect(TuiPluginRuntime.list().find((item) => item.id === "demo.toggle")).toEqual({
|
||||
id: "demo.toggle",
|
||||
source: "file",
|
||||
spec: tmp.extra.spec,
|
||||
target: tmp.extra.spec,
|
||||
enabled: false,
|
||||
active: false,
|
||||
})
|
||||
|
||||
await expect(TuiPluginRuntime.activatePlugin("demo.toggle")).resolves.toBe(true)
|
||||
await expect(fs.readFile(tmp.extra.marker, "utf8")).resolves.toBe("start\n")
|
||||
expect(api.kv.get("plugin_enabled", {})).toEqual({
|
||||
"demo.toggle": true,
|
||||
})
|
||||
|
||||
await expect(TuiPluginRuntime.deactivatePlugin("demo.toggle")).resolves.toBe(true)
|
||||
await expect(fs.readFile(tmp.extra.marker, "utf8")).resolves.toBe("start\nstop\n")
|
||||
expect(api.kv.get("plugin_enabled", {})).toEqual({
|
||||
"demo.toggle": false,
|
||||
})
|
||||
|
||||
await expect(TuiPluginRuntime.activatePlugin("missing.id")).resolves.toBe(false)
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
cwd.mockRestore()
|
||||
get.mockRestore()
|
||||
wait.mockRestore()
|
||||
delete process.env.OPENCODE_PLUGIN_META_FILE
|
||||
}
|
||||
})
|
||||
|
||||
test("kv plugin_enabled overrides tui config on startup", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "startup-plugin.ts")
|
||||
const spec = pathToFileURL(file).href
|
||||
const marker = path.join(dir, "startup.txt")
|
||||
|
||||
await Bun.write(
|
||||
file,
|
||||
`export default {
|
||||
id: "demo.startup",
|
||||
tui: async (_api, options) => {
|
||||
await Bun.write(options.marker, "on")
|
||||
},
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
return {
|
||||
spec,
|
||||
marker,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
|
||||
const get = spyOn(TuiConfig, "get").mockResolvedValue({
|
||||
plugin: [[tmp.extra.spec, { marker: tmp.extra.marker }]],
|
||||
plugin_enabled: {
|
||||
"demo.startup": false,
|
||||
},
|
||||
plugin_meta: {
|
||||
[tmp.extra.spec]: {
|
||||
scope: "local",
|
||||
source: path.join(tmp.path, "tui.json"),
|
||||
},
|
||||
},
|
||||
})
|
||||
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
|
||||
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
|
||||
const api = createTuiPluginApi()
|
||||
api.kv.set("plugin_enabled", {
|
||||
"demo.startup": true,
|
||||
})
|
||||
|
||||
try {
|
||||
await TuiPluginRuntime.init(api)
|
||||
|
||||
await expect(fs.readFile(tmp.extra.marker, "utf8")).resolves.toBe("on")
|
||||
expect(TuiPluginRuntime.list().find((item) => item.id === "demo.startup")).toEqual({
|
||||
id: "demo.startup",
|
||||
source: "file",
|
||||
spec: tmp.extra.spec,
|
||||
target: tmp.extra.spec,
|
||||
enabled: true,
|
||||
active: true,
|
||||
})
|
||||
} finally {
|
||||
await TuiPluginRuntime.dispose()
|
||||
cwd.mockRestore()
|
||||
get.mockRestore()
|
||||
wait.mockRestore()
|
||||
delete process.env.OPENCODE_PLUGIN_META_FILE
|
||||
}
|
||||
})
|
||||
50
packages/opencode/test/cli/tui/theme-store.test.ts
Normal file
50
packages/opencode/test/cli/tui/theme-store.test.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { expect, test } from "bun:test"
|
||||
|
||||
const { DEFAULT_THEMES, allThemes, addTheme, hasTheme, resolveTheme } =
|
||||
await import("../../../src/cli/cmd/tui/context/theme")
|
||||
|
||||
test("addTheme writes into module theme store", () => {
|
||||
const name = `plugin-theme-${Date.now()}`
|
||||
expect(addTheme(name, DEFAULT_THEMES.opencode)).toBe(true)
|
||||
|
||||
expect(allThemes()[name]).toBeDefined()
|
||||
})
|
||||
|
||||
test("addTheme keeps first theme for duplicate names", () => {
|
||||
const name = `plugin-theme-keep-${Date.now()}`
|
||||
const one = structuredClone(DEFAULT_THEMES.opencode)
|
||||
const two = structuredClone(DEFAULT_THEMES.opencode)
|
||||
one.theme.primary = "#101010"
|
||||
two.theme.primary = "#fefefe"
|
||||
|
||||
expect(addTheme(name, one)).toBe(true)
|
||||
expect(addTheme(name, two)).toBe(false)
|
||||
|
||||
expect(allThemes()[name]).toBeDefined()
|
||||
expect(allThemes()[name]!.theme.primary).toBe("#101010")
|
||||
})
|
||||
|
||||
test("addTheme ignores entries without a theme object", () => {
|
||||
const name = `plugin-theme-invalid-${Date.now()}`
|
||||
expect(addTheme(name, { defs: { a: "#ffffff" } })).toBe(false)
|
||||
expect(allThemes()[name]).toBeUndefined()
|
||||
})
|
||||
|
||||
test("hasTheme checks theme presence", () => {
|
||||
const name = `plugin-theme-has-${Date.now()}`
|
||||
expect(hasTheme(name)).toBe(false)
|
||||
expect(addTheme(name, DEFAULT_THEMES.opencode)).toBe(true)
|
||||
expect(hasTheme(name)).toBe(true)
|
||||
})
|
||||
|
||||
test("resolveTheme rejects circular color refs", () => {
|
||||
const item = structuredClone(DEFAULT_THEMES.opencode)
|
||||
item.defs = {
|
||||
...(item.defs ?? {}),
|
||||
one: "two",
|
||||
two: "one",
|
||||
}
|
||||
item.theme.primary = "one"
|
||||
|
||||
expect(() => resolveTheme(item, "dark")).toThrow("Circular color reference")
|
||||
})
|
||||
@@ -20,6 +20,7 @@ import { pathToFileURL } from "url"
|
||||
import { Global } from "../../src/global"
|
||||
import { ProjectID } from "../../src/project/schema"
|
||||
import { Filesystem } from "../../src/util/filesystem"
|
||||
import * as Network from "../../src/util/network"
|
||||
import { BunProc } from "../../src/bun"
|
||||
|
||||
const emptyAccount = Layer.mock(Account.Service)({
|
||||
@@ -765,6 +766,20 @@ test("installs dependencies in writable OPENCODE_CONFIG_DIR", async () => {
|
||||
|
||||
const prev = process.env.OPENCODE_CONFIG_DIR
|
||||
process.env.OPENCODE_CONFIG_DIR = tmp.extra
|
||||
const online = spyOn(Network, "online").mockReturnValue(false)
|
||||
const run = spyOn(BunProc, "run").mockImplementation(async (_cmd, opts) => {
|
||||
const mod = path.join(opts?.cwd ?? "", "node_modules", "@opencode-ai", "plugin")
|
||||
await fs.mkdir(mod, { recursive: true })
|
||||
await Filesystem.write(
|
||||
path.join(mod, "package.json"),
|
||||
JSON.stringify({ name: "@opencode-ai/plugin", version: "1.0.0" }),
|
||||
)
|
||||
return {
|
||||
code: 0,
|
||||
stdout: Buffer.alloc(0),
|
||||
stderr: Buffer.alloc(0),
|
||||
}
|
||||
})
|
||||
|
||||
try {
|
||||
await Instance.provide({
|
||||
@@ -778,25 +793,43 @@ test("installs dependencies in writable OPENCODE_CONFIG_DIR", async () => {
|
||||
expect(await Filesystem.exists(path.join(tmp.extra, "package.json"))).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(tmp.extra, ".gitignore"))).toBe(true)
|
||||
} finally {
|
||||
online.mockRestore()
|
||||
run.mockRestore()
|
||||
if (prev === undefined) delete process.env.OPENCODE_CONFIG_DIR
|
||||
else process.env.OPENCODE_CONFIG_DIR = prev
|
||||
}
|
||||
})
|
||||
|
||||
test("serializes concurrent config dependency installs", async () => {
|
||||
test("dedupes concurrent config dependency installs for the same dir", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const dirs = [path.join(tmp.path, "a"), path.join(tmp.path, "b")]
|
||||
await Promise.all(dirs.map((dir) => fs.mkdir(dir, { recursive: true })))
|
||||
const dir = path.join(tmp.path, "a")
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
|
||||
const seen: string[] = []
|
||||
let active = 0
|
||||
let max = 0
|
||||
const ticks: number[] = []
|
||||
let calls = 0
|
||||
let start = () => {}
|
||||
let done = () => {}
|
||||
let blocked = () => {}
|
||||
const ready = new Promise<void>((resolve) => {
|
||||
start = resolve
|
||||
})
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
done = resolve
|
||||
})
|
||||
const waiting = new Promise<void>((resolve) => {
|
||||
blocked = resolve
|
||||
})
|
||||
const online = spyOn(Network, "online").mockReturnValue(false)
|
||||
const run = spyOn(BunProc, "run").mockImplementation(async (_cmd, opts) => {
|
||||
active++
|
||||
max = Math.max(max, active)
|
||||
seen.push(opts?.cwd ?? "")
|
||||
await new Promise((resolve) => setTimeout(resolve, 25))
|
||||
active--
|
||||
calls += 1
|
||||
start()
|
||||
await gate
|
||||
const mod = path.join(opts?.cwd ?? "", "node_modules", "@opencode-ai", "plugin")
|
||||
await fs.mkdir(mod, { recursive: true })
|
||||
await Filesystem.write(
|
||||
path.join(mod, "package.json"),
|
||||
JSON.stringify({ name: "@opencode-ai/plugin", version: "1.0.0" }),
|
||||
)
|
||||
return {
|
||||
code: 0,
|
||||
stdout: Buffer.alloc(0),
|
||||
@@ -805,15 +838,85 @@ test("serializes concurrent config dependency installs", async () => {
|
||||
})
|
||||
|
||||
try {
|
||||
await Promise.all(dirs.map((dir) => Config.installDependencies(dir)))
|
||||
const first = Config.installDependencies(dir)
|
||||
await ready
|
||||
const second = Config.installDependencies(dir, {
|
||||
waitTick: (tick) => {
|
||||
ticks.push(tick.attempt)
|
||||
blocked()
|
||||
blocked = () => {}
|
||||
},
|
||||
})
|
||||
await waiting
|
||||
done()
|
||||
await Promise.all([first, second])
|
||||
} finally {
|
||||
online.mockRestore()
|
||||
run.mockRestore()
|
||||
}
|
||||
|
||||
expect(max).toBe(1)
|
||||
expect(seen.toSorted()).toEqual(dirs.toSorted())
|
||||
expect(await Filesystem.exists(path.join(dirs[0], "package.json"))).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(dirs[1], "package.json"))).toBe(true)
|
||||
expect(calls).toBe(1)
|
||||
expect(ticks.length).toBeGreaterThan(0)
|
||||
expect(await Filesystem.exists(path.join(dir, "package.json"))).toBe(true)
|
||||
})
|
||||
|
||||
test("serializes config dependency installs across dirs", async () => {
|
||||
if (process.platform !== "win32") return
|
||||
|
||||
await using tmp = await tmpdir()
|
||||
const a = path.join(tmp.path, "a")
|
||||
const b = path.join(tmp.path, "b")
|
||||
await fs.mkdir(a, { recursive: true })
|
||||
await fs.mkdir(b, { recursive: true })
|
||||
|
||||
let calls = 0
|
||||
let open = 0
|
||||
let peak = 0
|
||||
let start = () => {}
|
||||
let done = () => {}
|
||||
const ready = new Promise<void>((resolve) => {
|
||||
start = resolve
|
||||
})
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
done = resolve
|
||||
})
|
||||
|
||||
const online = spyOn(Network, "online").mockReturnValue(false)
|
||||
const run = spyOn(BunProc, "run").mockImplementation(async (_cmd, opts) => {
|
||||
calls += 1
|
||||
open += 1
|
||||
peak = Math.max(peak, open)
|
||||
if (calls === 1) {
|
||||
start()
|
||||
await gate
|
||||
}
|
||||
const mod = path.join(opts?.cwd ?? "", "node_modules", "@opencode-ai", "plugin")
|
||||
await fs.mkdir(mod, { recursive: true })
|
||||
await Filesystem.write(
|
||||
path.join(mod, "package.json"),
|
||||
JSON.stringify({ name: "@opencode-ai/plugin", version: "1.0.0" }),
|
||||
)
|
||||
open -= 1
|
||||
return {
|
||||
code: 0,
|
||||
stdout: Buffer.alloc(0),
|
||||
stderr: Buffer.alloc(0),
|
||||
}
|
||||
})
|
||||
|
||||
try {
|
||||
const first = Config.installDependencies(a)
|
||||
await ready
|
||||
const second = Config.installDependencies(b)
|
||||
done()
|
||||
await Promise.all([first, second])
|
||||
} finally {
|
||||
online.mockRestore()
|
||||
run.mockRestore()
|
||||
}
|
||||
|
||||
expect(calls).toBe(2)
|
||||
expect(peak).toBe(1)
|
||||
})
|
||||
|
||||
test("resolves scoped npm plugins in config", async () => {
|
||||
@@ -855,15 +958,7 @@ test("resolves scoped npm plugins in config", async () => {
|
||||
fn: async () => {
|
||||
const config = await Config.get()
|
||||
const pluginEntries = config.plugin ?? []
|
||||
|
||||
const baseUrl = pathToFileURL(path.join(tmp.path, "opencode.json")).href
|
||||
const expected = pathToFileURL(path.join(tmp.path, "node_modules", "@scope", "plugin", "index.js")).href
|
||||
|
||||
expect(pluginEntries.includes(expected)).toBe(true)
|
||||
|
||||
const scopedEntry = pluginEntries.find((entry) => entry === expected)
|
||||
expect(scopedEntry).toBeDefined()
|
||||
expect(scopedEntry?.includes("/node_modules/@scope/plugin/")).toBe(true)
|
||||
expect(pluginEntries).toContain("@scope/plugin")
|
||||
},
|
||||
})
|
||||
})
|
||||
@@ -1710,27 +1805,43 @@ test("wellknown URL with trailing slash is normalized", async () => {
|
||||
}
|
||||
})
|
||||
|
||||
describe("getPluginName", () => {
|
||||
test("extracts name from file:// URL", () => {
|
||||
expect(Config.getPluginName("file:///path/to/plugin/foo.js")).toBe("foo")
|
||||
expect(Config.getPluginName("file:///path/to/plugin/bar.ts")).toBe("bar")
|
||||
expect(Config.getPluginName("file:///some/path/my-plugin.js")).toBe("my-plugin")
|
||||
describe("resolvePluginSpec", () => {
|
||||
test("keeps package specs unchanged", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const file = path.join(tmp.path, "opencode.json")
|
||||
expect(await Config.resolvePluginSpec("oh-my-opencode@2.4.3", file)).toBe("oh-my-opencode@2.4.3")
|
||||
expect(await Config.resolvePluginSpec("@scope/pkg", file)).toBe("@scope/pkg")
|
||||
})
|
||||
|
||||
test("extracts name from npm package with version", () => {
|
||||
expect(Config.getPluginName("oh-my-opencode@2.4.3")).toBe("oh-my-opencode")
|
||||
expect(Config.getPluginName("some-plugin@1.0.0")).toBe("some-plugin")
|
||||
expect(Config.getPluginName("plugin@latest")).toBe("plugin")
|
||||
test("resolves relative file plugin paths to file urls", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await Filesystem.write(path.join(dir, "plugin.ts"), "export default {}")
|
||||
},
|
||||
})
|
||||
|
||||
const file = path.join(tmp.path, "opencode.json")
|
||||
const hit = await Config.resolvePluginSpec("./plugin.ts", file)
|
||||
expect(Config.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin.ts")).href)
|
||||
})
|
||||
|
||||
test("extracts name from scoped npm package", () => {
|
||||
expect(Config.getPluginName("@scope/pkg@1.0.0")).toBe("@scope/pkg")
|
||||
expect(Config.getPluginName("@opencode/plugin@2.0.0")).toBe("@opencode/plugin")
|
||||
})
|
||||
test("resolves plugin directory paths to package main files", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const plugin = path.join(dir, "plugin")
|
||||
await fs.mkdir(plugin, { recursive: true })
|
||||
await Filesystem.writeJson(path.join(plugin, "package.json"), {
|
||||
name: "demo-plugin",
|
||||
type: "module",
|
||||
main: "./index.ts",
|
||||
})
|
||||
await Filesystem.write(path.join(plugin, "index.ts"), "export default {}")
|
||||
},
|
||||
})
|
||||
|
||||
test("returns full string for package without version", () => {
|
||||
expect(Config.getPluginName("some-plugin")).toBe("some-plugin")
|
||||
expect(Config.getPluginName("@scope/pkg")).toBe("@scope/pkg")
|
||||
const file = path.join(tmp.path, "opencode.json")
|
||||
const hit = await Config.resolvePluginSpec("./plugin", file)
|
||||
expect(Config.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin", "index.ts")).href)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1747,13 +1858,20 @@ describe("deduplicatePlugins", () => {
|
||||
expect(result.length).toBe(3)
|
||||
})
|
||||
|
||||
test("prefers local file over npm package with same name", () => {
|
||||
test("keeps path plugins separate from package plugins", () => {
|
||||
const plugins = ["oh-my-opencode@2.4.3", "file:///project/.opencode/plugin/oh-my-opencode.js"]
|
||||
|
||||
const result = Config.deduplicatePlugins(plugins)
|
||||
|
||||
expect(result.length).toBe(1)
|
||||
expect(result[0]).toBe("file:///project/.opencode/plugin/oh-my-opencode.js")
|
||||
expect(result).toEqual(plugins)
|
||||
})
|
||||
|
||||
test("deduplicates direct path plugins by exact spec", () => {
|
||||
const plugins = ["file:///project/.opencode/plugin/demo.ts", "file:///project/.opencode/plugin/demo.ts"]
|
||||
|
||||
const result = Config.deduplicatePlugins(plugins)
|
||||
|
||||
expect(result).toEqual(["file:///project/.opencode/plugin/demo.ts"])
|
||||
})
|
||||
|
||||
test("preserves order of remaining plugins", () => {
|
||||
@@ -1764,7 +1882,7 @@ describe("deduplicatePlugins", () => {
|
||||
expect(result).toEqual(["a-plugin@1.0.0", "b-plugin@1.0.0", "c-plugin@1.0.0"])
|
||||
})
|
||||
|
||||
test("local plugin directory overrides global opencode.json plugin", async () => {
|
||||
test("loads auto-discovered local plugins as file urls", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const projectDir = path.join(dir, "project")
|
||||
@@ -1790,9 +1908,8 @@ describe("deduplicatePlugins", () => {
|
||||
const config = await Config.get()
|
||||
const plugins = config.plugin ?? []
|
||||
|
||||
const myPlugins = plugins.filter((p) => Config.getPluginName(p) === "my-plugin")
|
||||
expect(myPlugins.length).toBe(1)
|
||||
expect(myPlugins[0].startsWith("file://")).toBe(true)
|
||||
expect(plugins.some((p) => Config.pluginSpecifier(p) === "my-plugin@1.0.0")).toBe(true)
|
||||
expect(plugins.some((p) => Config.pluginSpecifier(p).startsWith("file://"))).toBe(true)
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
@@ -458,9 +458,15 @@ test("applies file substitutions when first identical token is in a commented li
|
||||
test("loads managed tui config and gives it highest precedence", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await Bun.write(path.join(dir, "tui.json"), JSON.stringify({ theme: "project-theme" }, null, 2))
|
||||
await Bun.write(
|
||||
path.join(dir, "tui.json"),
|
||||
JSON.stringify({ theme: "project-theme", plugin: ["shared-plugin@1.0.0"] }, null, 2),
|
||||
)
|
||||
await fs.mkdir(managedConfigDir, { recursive: true })
|
||||
await Bun.write(path.join(managedConfigDir, "tui.json"), JSON.stringify({ theme: "managed-theme" }, null, 2))
|
||||
await Bun.write(
|
||||
path.join(managedConfigDir, "tui.json"),
|
||||
JSON.stringify({ theme: "managed-theme", plugin: ["shared-plugin@2.0.0"] }, null, 2),
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -469,6 +475,13 @@ test("loads managed tui config and gives it highest precedence", async () => {
|
||||
fn: async () => {
|
||||
const config = await TuiConfig.get()
|
||||
expect(config.theme).toBe("managed-theme")
|
||||
expect(config.plugin).toEqual(["shared-plugin@2.0.0"])
|
||||
expect(config.plugin_meta).toEqual({
|
||||
"shared-plugin@2.0.0": {
|
||||
scope: "global",
|
||||
source: path.join(managedConfigDir, "tui.json"),
|
||||
},
|
||||
})
|
||||
},
|
||||
})
|
||||
})
|
||||
@@ -508,3 +521,147 @@ test("gracefully falls back when tui.json has invalid JSON", async () => {
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
test("supports tuple plugin specs with options in tui.json", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await Bun.write(
|
||||
path.join(dir, "tui.json"),
|
||||
JSON.stringify({
|
||||
plugin: [["acme-plugin@1.2.3", { enabled: true, label: "demo" }]],
|
||||
}),
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
await Instance.provide({
|
||||
directory: tmp.path,
|
||||
fn: async () => {
|
||||
const config = await TuiConfig.get()
|
||||
expect(config.plugin).toEqual([["acme-plugin@1.2.3", { enabled: true, label: "demo" }]])
|
||||
expect(config.plugin_meta).toEqual({
|
||||
"acme-plugin@1.2.3": {
|
||||
scope: "local",
|
||||
source: path.join(tmp.path, "tui.json"),
|
||||
},
|
||||
})
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
test("deduplicates tuple plugin specs by name with higher precedence winning", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await Bun.write(
|
||||
path.join(Global.Path.config, "tui.json"),
|
||||
JSON.stringify({
|
||||
plugin: [["acme-plugin@1.0.0", { source: "global" }]],
|
||||
}),
|
||||
)
|
||||
await Bun.write(
|
||||
path.join(dir, "tui.json"),
|
||||
JSON.stringify({
|
||||
plugin: [
|
||||
["acme-plugin@2.0.0", { source: "project" }],
|
||||
["second-plugin@3.0.0", { source: "project" }],
|
||||
],
|
||||
}),
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
await Instance.provide({
|
||||
directory: tmp.path,
|
||||
fn: async () => {
|
||||
const config = await TuiConfig.get()
|
||||
expect(config.plugin).toEqual([
|
||||
["acme-plugin@2.0.0", { source: "project" }],
|
||||
["second-plugin@3.0.0", { source: "project" }],
|
||||
])
|
||||
expect(config.plugin_meta).toEqual({
|
||||
"acme-plugin@2.0.0": {
|
||||
scope: "local",
|
||||
source: path.join(tmp.path, "tui.json"),
|
||||
},
|
||||
"second-plugin@3.0.0": {
|
||||
scope: "local",
|
||||
source: path.join(tmp.path, "tui.json"),
|
||||
},
|
||||
})
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
test("tracks global and local plugin metadata in merged tui config", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await Bun.write(
|
||||
path.join(Global.Path.config, "tui.json"),
|
||||
JSON.stringify({
|
||||
plugin: ["global-plugin@1.0.0"],
|
||||
}),
|
||||
)
|
||||
await Bun.write(
|
||||
path.join(dir, "tui.json"),
|
||||
JSON.stringify({
|
||||
plugin: ["local-plugin@2.0.0"],
|
||||
}),
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
await Instance.provide({
|
||||
directory: tmp.path,
|
||||
fn: async () => {
|
||||
const config = await TuiConfig.get()
|
||||
expect(config.plugin).toEqual(["global-plugin@1.0.0", "local-plugin@2.0.0"])
|
||||
expect(config.plugin_meta).toEqual({
|
||||
"global-plugin@1.0.0": {
|
||||
scope: "global",
|
||||
source: path.join(Global.Path.config, "tui.json"),
|
||||
},
|
||||
"local-plugin@2.0.0": {
|
||||
scope: "local",
|
||||
source: path.join(tmp.path, "tui.json"),
|
||||
},
|
||||
})
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
test("merges plugin_enabled flags across config layers", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await Bun.write(
|
||||
path.join(Global.Path.config, "tui.json"),
|
||||
JSON.stringify({
|
||||
plugin_enabled: {
|
||||
"internal:sidebar-context": false,
|
||||
"demo.plugin": true,
|
||||
},
|
||||
}),
|
||||
)
|
||||
await Bun.write(
|
||||
path.join(dir, "tui.json"),
|
||||
JSON.stringify({
|
||||
plugin_enabled: {
|
||||
"demo.plugin": false,
|
||||
"local.plugin": true,
|
||||
},
|
||||
}),
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
await Instance.provide({
|
||||
directory: tmp.path,
|
||||
fn: async () => {
|
||||
const config = await TuiConfig.get()
|
||||
expect(config.plugin_enabled).toEqual({
|
||||
"internal:sidebar-context": false,
|
||||
"demo.plugin": false,
|
||||
"local.plugin": true,
|
||||
})
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
72
packages/opencode/test/fixture/flock-worker.ts
Normal file
72
packages/opencode/test/fixture/flock-worker.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import fs from "fs/promises"
|
||||
import { Flock } from "../../src/util/flock"
|
||||
|
||||
type Msg = {
|
||||
key: string
|
||||
dir: string
|
||||
staleMs?: number
|
||||
timeoutMs?: number
|
||||
baseDelayMs?: number
|
||||
maxDelayMs?: number
|
||||
holdMs?: number
|
||||
ready?: string
|
||||
active?: string
|
||||
done?: string
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
|
||||
function input() {
|
||||
const raw = process.argv[2]
|
||||
if (!raw) {
|
||||
throw new Error("Missing flock worker input")
|
||||
}
|
||||
|
||||
return JSON.parse(raw) as Msg
|
||||
}
|
||||
|
||||
async function job(input: Msg) {
|
||||
if (input.ready) {
|
||||
await fs.writeFile(input.ready, String(process.pid))
|
||||
}
|
||||
|
||||
if (input.active) {
|
||||
await fs.writeFile(input.active, String(process.pid), { flag: "wx" })
|
||||
}
|
||||
|
||||
try {
|
||||
if (input.holdMs && input.holdMs > 0) {
|
||||
await sleep(input.holdMs)
|
||||
}
|
||||
|
||||
if (input.done) {
|
||||
await fs.appendFile(input.done, "1\n")
|
||||
}
|
||||
} finally {
|
||||
if (input.active) {
|
||||
await fs.rm(input.active, { force: true })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const msg = input()
|
||||
|
||||
await Flock.withLock(msg.key, () => job(msg), {
|
||||
dir: msg.dir,
|
||||
staleMs: msg.staleMs,
|
||||
timeoutMs: msg.timeoutMs,
|
||||
baseDelayMs: msg.baseDelayMs,
|
||||
maxDelayMs: msg.maxDelayMs,
|
||||
})
|
||||
}
|
||||
|
||||
await main().catch((err) => {
|
||||
const text = err instanceof Error ? (err.stack ?? err.message) : String(err)
|
||||
process.stderr.write(text)
|
||||
process.exit(1)
|
||||
})
|
||||
93
packages/opencode/test/fixture/plug-worker.ts
Normal file
93
packages/opencode/test/fixture/plug-worker.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import path from "path"
|
||||
|
||||
import { createPlugTask, type PlugCtx, type PlugDeps } from "../../src/cli/cmd/plug"
|
||||
import { Filesystem } from "../../src/util/filesystem"
|
||||
|
||||
type Msg = {
|
||||
dir: string
|
||||
target: string
|
||||
mod: string
|
||||
global?: boolean
|
||||
force?: boolean
|
||||
globalDir?: string
|
||||
vcs?: string
|
||||
worktree?: string
|
||||
directory?: string
|
||||
holdMs?: number
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
|
||||
function input() {
|
||||
const raw = process.argv[2]
|
||||
if (!raw) {
|
||||
throw new Error("Missing plug worker input")
|
||||
}
|
||||
|
||||
const msg = JSON.parse(raw) as Partial<Msg>
|
||||
if (!msg.dir || !msg.target || !msg.mod) {
|
||||
throw new Error("Invalid plug worker input")
|
||||
}
|
||||
|
||||
return msg as Msg
|
||||
}
|
||||
|
||||
function deps(msg: Msg): PlugDeps {
|
||||
return {
|
||||
spinner: () => ({
|
||||
start() {},
|
||||
stop() {},
|
||||
}),
|
||||
log: {
|
||||
error() {},
|
||||
info() {},
|
||||
success() {},
|
||||
},
|
||||
resolve: async () => msg.target,
|
||||
readText: (file) => Filesystem.readText(file),
|
||||
write: async (file, text) => {
|
||||
if (msg.holdMs && msg.holdMs > 0) {
|
||||
await sleep(msg.holdMs)
|
||||
}
|
||||
await Filesystem.write(file, text)
|
||||
},
|
||||
exists: (file) => Filesystem.exists(file),
|
||||
files: (dir, name) => [path.join(dir, `${name}.jsonc`), path.join(dir, `${name}.json`)],
|
||||
global: msg.globalDir ?? path.join(msg.dir, ".global"),
|
||||
}
|
||||
}
|
||||
|
||||
function ctx(msg: Msg): PlugCtx {
|
||||
return {
|
||||
vcs: msg.vcs ?? "git",
|
||||
worktree: msg.worktree ?? msg.dir,
|
||||
directory: msg.directory ?? msg.dir,
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const msg = input()
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: msg.mod,
|
||||
global: msg.global,
|
||||
force: msg.force,
|
||||
},
|
||||
deps(msg),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(msg))
|
||||
if (!ok) {
|
||||
throw new Error("Plug task failed")
|
||||
}
|
||||
}
|
||||
|
||||
await main().catch((err) => {
|
||||
const text = err instanceof Error ? (err.stack ?? err.message) : String(err)
|
||||
process.stderr.write(text)
|
||||
process.exit(1)
|
||||
})
|
||||
26
packages/opencode/test/fixture/plugin-meta-worker.ts
Normal file
26
packages/opencode/test/fixture/plugin-meta-worker.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
type Msg = {
|
||||
file: string
|
||||
spec: string
|
||||
target: string
|
||||
id: string
|
||||
}
|
||||
|
||||
const raw = process.argv[2]
|
||||
if (!raw) throw new Error("Missing worker payload")
|
||||
|
||||
const value = JSON.parse(raw)
|
||||
if (!value || typeof value !== "object") {
|
||||
throw new Error("Invalid worker payload")
|
||||
}
|
||||
|
||||
const msg = Object.fromEntries(Object.entries(value))
|
||||
if (typeof msg.file !== "string" || typeof msg.spec !== "string" || typeof msg.target !== "string") {
|
||||
throw new Error("Invalid worker payload")
|
||||
}
|
||||
if (typeof msg.id !== "string") throw new Error("Invalid worker payload")
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = msg.file
|
||||
|
||||
const { PluginMeta } = await import("../../src/plugin/meta")
|
||||
|
||||
await PluginMeta.touch(msg.spec, msg.target, msg.id)
|
||||
334
packages/opencode/test/fixture/tui-plugin.ts
Normal file
334
packages/opencode/test/fixture/tui-plugin.ts
Normal file
@@ -0,0 +1,334 @@
|
||||
import { createOpencodeClient } from "@opencode-ai/sdk/v2"
|
||||
import { RGBA, type CliRenderer } from "@opentui/core"
|
||||
import { createPluginKeybind } from "../../src/cli/cmd/tui/context/plugin-keybinds"
|
||||
import type { HostPluginApi } from "../../src/cli/cmd/tui/plugin/slots"
|
||||
|
||||
type Count = {
|
||||
event_add: number
|
||||
event_drop: number
|
||||
route_add: number
|
||||
route_drop: number
|
||||
command_add: number
|
||||
command_drop: number
|
||||
}
|
||||
|
||||
function themeCurrent(): HostPluginApi["theme"]["current"] {
|
||||
const a = RGBA.fromInts(0, 120, 240)
|
||||
const b = RGBA.fromInts(120, 120, 120)
|
||||
const c = RGBA.fromInts(230, 230, 230)
|
||||
const d = RGBA.fromInts(120, 30, 30)
|
||||
const e = RGBA.fromInts(140, 100, 40)
|
||||
const f = RGBA.fromInts(20, 140, 80)
|
||||
const g = RGBA.fromInts(20, 80, 160)
|
||||
const h = RGBA.fromInts(40, 40, 40)
|
||||
const i = RGBA.fromInts(60, 60, 60)
|
||||
const j = RGBA.fromInts(80, 80, 80)
|
||||
return {
|
||||
primary: a,
|
||||
secondary: b,
|
||||
accent: a,
|
||||
error: d,
|
||||
warning: e,
|
||||
success: f,
|
||||
info: g,
|
||||
text: c,
|
||||
textMuted: b,
|
||||
selectedListItemText: h,
|
||||
background: h,
|
||||
backgroundPanel: h,
|
||||
backgroundElement: i,
|
||||
backgroundMenu: i,
|
||||
border: j,
|
||||
borderActive: c,
|
||||
borderSubtle: i,
|
||||
diffAdded: f,
|
||||
diffRemoved: d,
|
||||
diffContext: b,
|
||||
diffHunkHeader: b,
|
||||
diffHighlightAdded: f,
|
||||
diffHighlightRemoved: d,
|
||||
diffAddedBg: h,
|
||||
diffRemovedBg: h,
|
||||
diffContextBg: h,
|
||||
diffLineNumber: b,
|
||||
diffAddedLineNumberBg: h,
|
||||
diffRemovedLineNumberBg: h,
|
||||
markdownText: c,
|
||||
markdownHeading: c,
|
||||
markdownLink: a,
|
||||
markdownLinkText: g,
|
||||
markdownCode: f,
|
||||
markdownBlockQuote: e,
|
||||
markdownEmph: e,
|
||||
markdownStrong: c,
|
||||
markdownHorizontalRule: b,
|
||||
markdownListItem: a,
|
||||
markdownListEnumeration: g,
|
||||
markdownImage: a,
|
||||
markdownImageText: g,
|
||||
markdownCodeBlock: c,
|
||||
syntaxComment: b,
|
||||
syntaxKeyword: a,
|
||||
syntaxFunction: g,
|
||||
syntaxVariable: c,
|
||||
syntaxString: f,
|
||||
syntaxNumber: e,
|
||||
syntaxType: a,
|
||||
syntaxOperator: a,
|
||||
syntaxPunctuation: c,
|
||||
thinkingOpacity: 0.6,
|
||||
}
|
||||
}
|
||||
|
||||
type Opts = {
|
||||
client?: HostPluginApi["client"] | (() => HostPluginApi["client"])
|
||||
scopedClient?: HostPluginApi["scopedClient"]
|
||||
workspace?: Partial<HostPluginApi["workspace"]>
|
||||
renderer?: HostPluginApi["renderer"]
|
||||
count?: Count
|
||||
keybind?: Partial<HostPluginApi["keybind"]>
|
||||
tuiConfig?: HostPluginApi["tuiConfig"]
|
||||
app?: Partial<HostPluginApi["app"]>
|
||||
state?: {
|
||||
ready?: HostPluginApi["state"]["ready"]
|
||||
config?: HostPluginApi["state"]["config"]
|
||||
provider?: HostPluginApi["state"]["provider"]
|
||||
path?: HostPluginApi["state"]["path"]
|
||||
vcs?: HostPluginApi["state"]["vcs"]
|
||||
workspace?: Partial<HostPluginApi["state"]["workspace"]>
|
||||
session?: Partial<HostPluginApi["state"]["session"]>
|
||||
part?: HostPluginApi["state"]["part"]
|
||||
lsp?: HostPluginApi["state"]["lsp"]
|
||||
mcp?: HostPluginApi["state"]["mcp"]
|
||||
}
|
||||
theme?: {
|
||||
selected?: string
|
||||
has?: HostPluginApi["theme"]["has"]
|
||||
set?: HostPluginApi["theme"]["set"]
|
||||
install?: HostPluginApi["theme"]["install"]
|
||||
mode?: HostPluginApi["theme"]["mode"]
|
||||
ready?: boolean
|
||||
current?: HostPluginApi["theme"]["current"]
|
||||
}
|
||||
}
|
||||
|
||||
export function createTuiPluginApi(opts: Opts = {}): HostPluginApi {
|
||||
const kv: Record<string, unknown> = {}
|
||||
const count = opts.count
|
||||
const ctrl = new AbortController()
|
||||
const own = createOpencodeClient({
|
||||
baseUrl: "http://localhost:4096",
|
||||
})
|
||||
const fallback = () => own
|
||||
const read =
|
||||
typeof opts.client === "function"
|
||||
? opts.client
|
||||
: opts.client
|
||||
? () => opts.client as HostPluginApi["client"]
|
||||
: fallback
|
||||
const client = () => read()
|
||||
const scopedClient = opts.scopedClient ?? ((_workspaceID?: string) => client())
|
||||
const workspace: HostPluginApi["workspace"] = {
|
||||
current: opts.workspace?.current ?? (() => undefined),
|
||||
set: opts.workspace?.set ?? (() => {}),
|
||||
}
|
||||
let depth = 0
|
||||
let size: "medium" | "large" | "xlarge" = "medium"
|
||||
const has = opts.theme?.has ?? (() => false)
|
||||
let selected = opts.theme?.selected ?? "opencode"
|
||||
const key = {
|
||||
match: opts.keybind?.match ?? (() => false),
|
||||
print: opts.keybind?.print ?? ((name: string) => name),
|
||||
}
|
||||
const set =
|
||||
opts.theme?.set ??
|
||||
((name: string) => {
|
||||
if (!has(name)) return false
|
||||
selected = name
|
||||
return true
|
||||
})
|
||||
const renderer: CliRenderer = opts.renderer ?? {
|
||||
...Object.create(null),
|
||||
once(this: CliRenderer) {
|
||||
return this
|
||||
},
|
||||
}
|
||||
|
||||
function kvGet(name: string): unknown
|
||||
function kvGet<Value>(name: string, fallback: Value): Value
|
||||
function kvGet(name: string, fallback?: unknown) {
|
||||
const value = kv[name]
|
||||
if (value === undefined) return fallback
|
||||
return value
|
||||
}
|
||||
|
||||
return {
|
||||
app: {
|
||||
get version() {
|
||||
return opts.app?.version ?? "0.0.0-test"
|
||||
},
|
||||
},
|
||||
get client() {
|
||||
return client()
|
||||
},
|
||||
scopedClient,
|
||||
workspace,
|
||||
event: {
|
||||
on: () => {
|
||||
if (count) count.event_add += 1
|
||||
return () => {
|
||||
if (!count) return
|
||||
count.event_drop += 1
|
||||
}
|
||||
},
|
||||
},
|
||||
renderer,
|
||||
slots: {
|
||||
register: () => "fixture-slot",
|
||||
},
|
||||
plugins: {
|
||||
list: () => [],
|
||||
activate: async () => false,
|
||||
deactivate: async () => false,
|
||||
add: async () => false,
|
||||
install: async () => ({
|
||||
ok: false,
|
||||
message: "not implemented in fixture",
|
||||
}),
|
||||
},
|
||||
lifecycle: {
|
||||
signal: ctrl.signal,
|
||||
onDispose() {
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
command: {
|
||||
register: () => {
|
||||
if (count) count.command_add += 1
|
||||
return () => {
|
||||
if (!count) return
|
||||
count.command_drop += 1
|
||||
}
|
||||
},
|
||||
trigger: () => {},
|
||||
},
|
||||
route: {
|
||||
register: () => {
|
||||
if (count) count.route_add += 1
|
||||
return () => {
|
||||
if (!count) return
|
||||
count.route_drop += 1
|
||||
}
|
||||
},
|
||||
navigate: () => {},
|
||||
get current() {
|
||||
return { name: "home" }
|
||||
},
|
||||
},
|
||||
ui: {
|
||||
Dialog: () => null,
|
||||
DialogAlert: () => null,
|
||||
DialogConfirm: () => null,
|
||||
DialogPrompt: () => null,
|
||||
DialogSelect: () => null,
|
||||
toast: () => {},
|
||||
dialog: {
|
||||
replace: () => {
|
||||
depth = 1
|
||||
},
|
||||
clear: () => {
|
||||
depth = 0
|
||||
size = "medium"
|
||||
},
|
||||
setSize: (next) => {
|
||||
size = next
|
||||
},
|
||||
get size() {
|
||||
return size
|
||||
},
|
||||
get depth() {
|
||||
return depth
|
||||
},
|
||||
get open() {
|
||||
return depth > 0
|
||||
},
|
||||
},
|
||||
},
|
||||
keybind: {
|
||||
...key,
|
||||
create:
|
||||
opts.keybind?.create ??
|
||||
((defaults, over) => {
|
||||
return createPluginKeybind(key, defaults, over)
|
||||
}),
|
||||
},
|
||||
tuiConfig: opts.tuiConfig ?? {},
|
||||
kv: {
|
||||
get: kvGet,
|
||||
set(name, value) {
|
||||
kv[name] = value
|
||||
},
|
||||
get ready() {
|
||||
return true
|
||||
},
|
||||
},
|
||||
state: {
|
||||
get ready() {
|
||||
return opts.state?.ready ?? true
|
||||
},
|
||||
get config() {
|
||||
return opts.state?.config ?? {}
|
||||
},
|
||||
get provider() {
|
||||
return opts.state?.provider ?? []
|
||||
},
|
||||
get path() {
|
||||
return opts.state?.path ?? { state: "", config: "", worktree: "", directory: "" }
|
||||
},
|
||||
get vcs() {
|
||||
return opts.state?.vcs
|
||||
},
|
||||
workspace: {
|
||||
list: opts.state?.workspace?.list ?? (() => []),
|
||||
get: opts.state?.workspace?.get ?? (() => undefined),
|
||||
},
|
||||
session: {
|
||||
count: opts.state?.session?.count ?? (() => 0),
|
||||
diff: opts.state?.session?.diff ?? (() => []),
|
||||
todo: opts.state?.session?.todo ?? (() => []),
|
||||
messages: opts.state?.session?.messages ?? (() => []),
|
||||
status: opts.state?.session?.status ?? (() => undefined),
|
||||
permission: opts.state?.session?.permission ?? (() => []),
|
||||
question: opts.state?.session?.question ?? (() => []),
|
||||
},
|
||||
part: opts.state?.part ?? (() => []),
|
||||
lsp: opts.state?.lsp ?? (() => []),
|
||||
mcp: opts.state?.mcp ?? (() => []),
|
||||
},
|
||||
theme: {
|
||||
get current() {
|
||||
return opts.theme?.current ?? themeCurrent()
|
||||
},
|
||||
get selected() {
|
||||
return selected
|
||||
},
|
||||
has(name) {
|
||||
return has(name)
|
||||
},
|
||||
set(name) {
|
||||
return set(name)
|
||||
},
|
||||
async install(file) {
|
||||
if (opts.theme?.install) return opts.theme.install(file)
|
||||
throw new Error("base theme.install should not run")
|
||||
},
|
||||
mode() {
|
||||
if (opts.theme?.mode) return opts.theme.mode()
|
||||
return "dark"
|
||||
},
|
||||
get ready() {
|
||||
return opts.theme?.ready ?? true
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
34
packages/opencode/test/fixture/tui-runtime.ts
Normal file
34
packages/opencode/test/fixture/tui-runtime.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { spyOn } from "bun:test"
|
||||
import path from "path"
|
||||
import { TuiConfig } from "../../src/config/tui"
|
||||
|
||||
type PluginSpec = string | [string, Record<string, unknown>]
|
||||
|
||||
export function mockTuiRuntime(dir: string, plugin: PluginSpec[]) {
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(dir, "plugin-meta.json")
|
||||
const meta = Object.fromEntries(
|
||||
plugin.map((item) => {
|
||||
const spec = Array.isArray(item) ? item[0] : item
|
||||
return [
|
||||
spec,
|
||||
{
|
||||
scope: "local" as const,
|
||||
source: path.join(dir, "tui.json"),
|
||||
},
|
||||
]
|
||||
}),
|
||||
)
|
||||
const get = spyOn(TuiConfig, "get").mockResolvedValue({
|
||||
plugin,
|
||||
plugin_meta: meta,
|
||||
})
|
||||
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
|
||||
const cwd = spyOn(process, "cwd").mockImplementation(() => dir)
|
||||
|
||||
return () => {
|
||||
cwd.mockRestore()
|
||||
get.mockRestore()
|
||||
wait.mockRestore()
|
||||
delete process.env.OPENCODE_PLUGIN_META_FILE
|
||||
}
|
||||
}
|
||||
@@ -16,15 +16,18 @@ describe("plugin.auth-override", () => {
|
||||
await Bun.write(
|
||||
path.join(pluginDir, "custom-copilot-auth.ts"),
|
||||
[
|
||||
"export default async () => ({",
|
||||
" auth: {",
|
||||
' provider: "github-copilot",',
|
||||
" methods: [",
|
||||
' { type: "api", label: "Test Override Auth" },',
|
||||
" ],",
|
||||
" loader: async () => ({ access: 'test-token' }),",
|
||||
" },",
|
||||
"})",
|
||||
"export default {",
|
||||
' id: "demo.custom-copilot-auth",',
|
||||
" server: async () => ({",
|
||||
" auth: {",
|
||||
' provider: "github-copilot",',
|
||||
" methods: [",
|
||||
' { type: "api", label: "Test Override Auth" },',
|
||||
" ],",
|
||||
" loader: async () => ({ access: 'test-token' }),",
|
||||
" },",
|
||||
" }),",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
|
||||
134
packages/opencode/test/plugin/install-concurrency.test.ts
Normal file
134
packages/opencode/test/plugin/install-concurrency.test.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
|
||||
import { Process } from "../../src/util/process"
|
||||
import { Filesystem } from "../../src/util/filesystem"
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
|
||||
const root = path.join(import.meta.dir, "../..")
|
||||
const worker = path.join(import.meta.dir, "../fixture/plug-worker.ts")
|
||||
|
||||
type Msg = {
|
||||
dir: string
|
||||
target: string
|
||||
mod: string
|
||||
holdMs?: number
|
||||
}
|
||||
|
||||
function run(msg: Msg) {
|
||||
return Process.run([process.execPath, worker, JSON.stringify(msg)], {
|
||||
cwd: root,
|
||||
nothrow: true,
|
||||
})
|
||||
}
|
||||
|
||||
async function plugin(dir: string, kinds: Array<"server" | "tui">) {
|
||||
const p = path.join(dir, "plugin")
|
||||
await fs.mkdir(p, { recursive: true })
|
||||
await Bun.write(
|
||||
path.join(p, "package.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: "acme",
|
||||
version: "1.0.0",
|
||||
"oc-plugin": kinds,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
return p
|
||||
}
|
||||
|
||||
async function read(file: string) {
|
||||
return Filesystem.readJson<{ plugin?: unknown[] }>(file)
|
||||
}
|
||||
|
||||
function mods(prefix: string, n: number) {
|
||||
return Array.from({ length: n }, (_, i) => `${prefix}-${i}@1.0.0`)
|
||||
}
|
||||
|
||||
function expectPlugins(list: unknown[] | undefined, expectMods: string[]) {
|
||||
expect(Array.isArray(list)).toBe(true)
|
||||
const hit = (list ?? []).filter((item): item is string => typeof item === "string")
|
||||
expect(hit.length).toBe(expectMods.length)
|
||||
expect(new Set(hit)).toEqual(new Set(expectMods))
|
||||
}
|
||||
|
||||
describe("plugin.install.concurrent", () => {
|
||||
test("serializes concurrent server config updates across processes", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const all = mods("mod-server", 12)
|
||||
|
||||
const out = await Promise.all(
|
||||
all.map((mod) =>
|
||||
run({
|
||||
dir: tmp.path,
|
||||
target,
|
||||
mod,
|
||||
holdMs: 30,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
expect(out.map((x) => x.code)).toEqual(Array.from({ length: all.length }, () => 0))
|
||||
expect(out.map((x) => x.stderr.toString()).filter(Boolean)).toEqual([])
|
||||
|
||||
const cfg = await read(path.join(tmp.path, ".opencode", "opencode.jsonc"))
|
||||
expectPlugins(cfg.plugin, all)
|
||||
}, 25_000)
|
||||
|
||||
test("serializes concurrent server+tui config updates across processes", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server", "tui"])
|
||||
const all = mods("mod-both", 10)
|
||||
|
||||
const out = await Promise.all(
|
||||
all.map((mod) =>
|
||||
run({
|
||||
dir: tmp.path,
|
||||
target,
|
||||
mod,
|
||||
holdMs: 30,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
expect(out.map((x) => x.code)).toEqual(Array.from({ length: all.length }, () => 0))
|
||||
expect(out.map((x) => x.stderr.toString()).filter(Boolean)).toEqual([])
|
||||
|
||||
const server = await read(path.join(tmp.path, ".opencode", "opencode.jsonc"))
|
||||
const tui = await read(path.join(tmp.path, ".opencode", "tui.jsonc"))
|
||||
expectPlugins(server.plugin, all)
|
||||
expectPlugins(tui.plugin, all)
|
||||
}, 25_000)
|
||||
|
||||
test("preserves updates when existing config uses .json", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
await Bun.write(cfg, JSON.stringify({ plugin: ["seed@1.0.0"] }, null, 2))
|
||||
|
||||
const next = mods("mod-json", 8)
|
||||
const out = await Promise.all(
|
||||
next.map((mod) =>
|
||||
run({
|
||||
dir: tmp.path,
|
||||
target,
|
||||
mod,
|
||||
holdMs: 30,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
expect(out.map((x) => x.code)).toEqual(Array.from({ length: next.length }, () => 0))
|
||||
expect(out.map((x) => x.stderr.toString()).filter(Boolean)).toEqual([])
|
||||
|
||||
const json = await read(cfg)
|
||||
expectPlugins(json.plugin, ["seed@1.0.0", ...next])
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
}, 25_000)
|
||||
})
|
||||
410
packages/opencode/test/plugin/install.test.ts
Normal file
410
packages/opencode/test/plugin/install.test.ts
Normal file
@@ -0,0 +1,410 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { Filesystem } from "../../src/util/filesystem"
|
||||
import { createPlugTask, type PlugCtx, type PlugDeps } from "../../src/cli/cmd/plug"
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
|
||||
function deps(global: string, target: string | Error): PlugDeps {
|
||||
return {
|
||||
spinner: () => ({
|
||||
start() {},
|
||||
stop() {},
|
||||
}),
|
||||
log: {
|
||||
error() {},
|
||||
info() {},
|
||||
success() {},
|
||||
},
|
||||
resolve: async () => {
|
||||
if (target instanceof Error) throw target
|
||||
return target
|
||||
},
|
||||
readText: (file) => Filesystem.readText(file),
|
||||
write: async (file, text) => {
|
||||
await Filesystem.write(file, text)
|
||||
},
|
||||
exists: (file) => Filesystem.exists(file),
|
||||
files: (dir, name) => [path.join(dir, `${name}.jsonc`), path.join(dir, `${name}.json`)],
|
||||
global,
|
||||
}
|
||||
}
|
||||
|
||||
function ctx(dir: string): PlugCtx {
|
||||
return {
|
||||
vcs: "git",
|
||||
worktree: dir,
|
||||
directory: dir,
|
||||
}
|
||||
}
|
||||
|
||||
function ctxDir(dir: string, worktree: string): PlugCtx {
|
||||
return {
|
||||
vcs: "none",
|
||||
worktree,
|
||||
directory: dir,
|
||||
}
|
||||
}
|
||||
|
||||
function ctxRoot(dir: string): PlugCtx {
|
||||
return {
|
||||
vcs: "git",
|
||||
worktree: "/",
|
||||
directory: dir,
|
||||
}
|
||||
}
|
||||
|
||||
async function plugin(dir: string, kinds?: unknown) {
|
||||
const p = path.join(dir, "plugin")
|
||||
await fs.mkdir(p, { recursive: true })
|
||||
await Bun.write(
|
||||
path.join(p, "package.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: "acme",
|
||||
version: "1.0.0",
|
||||
...(kinds === undefined ? {} : { "oc-plugin": kinds }),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
return p
|
||||
}
|
||||
|
||||
async function read(file: string) {
|
||||
return Filesystem.readJson<{
|
||||
plugin?: unknown[]
|
||||
}>(file)
|
||||
}
|
||||
|
||||
describe("plugin.install.task", () => {
|
||||
test("writes both server and tui config entries", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server", "tui"])
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
|
||||
const server = await read(path.join(tmp.path, ".opencode", "opencode.jsonc"))
|
||||
const tui = await read(path.join(tmp.path, ".opencode", "tui.jsonc"))
|
||||
expect(server.plugin).toEqual(["acme@1.2.3"])
|
||||
expect(tui.plugin).toEqual(["acme@1.2.3"])
|
||||
})
|
||||
|
||||
test("writes default options from tuple manifest targets", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, [
|
||||
["server", { custom: true, other: false }],
|
||||
["tui", { compact: true }],
|
||||
])
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
|
||||
const server = await read(path.join(tmp.path, ".opencode", "opencode.jsonc"))
|
||||
const tui = await read(path.join(tmp.path, ".opencode", "tui.jsonc"))
|
||||
expect(server.plugin).toEqual([["acme@1.2.3", { custom: true, other: false }]])
|
||||
expect(tui.plugin).toEqual([["acme@1.2.3", { compact: true }]])
|
||||
})
|
||||
|
||||
test("supports resolver target pointing to a file", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const file = path.join(target, "index.js")
|
||||
await Bun.write(file, "export {}")
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), file),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const server = await read(path.join(tmp.path, ".opencode", "opencode.jsonc"))
|
||||
expect(server.plugin).toEqual(["acme@1.2.3"])
|
||||
})
|
||||
|
||||
test("does not change configured package version without force", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
await Bun.write(cfg, JSON.stringify({ plugin: ["acme@1.0.0"] }, null, 2))
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@2.0.0",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const json = await read(cfg)
|
||||
expect(json.plugin).toEqual(["acme@1.0.0"])
|
||||
})
|
||||
|
||||
test("does not change scoped package version without force", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
await Bun.write(cfg, JSON.stringify({ plugin: ["@scope/acme@1.0.0"] }, null, 2))
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "@scope/acme@2.0.0",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const json = await read(cfg)
|
||||
expect(json.plugin).toEqual(["@scope/acme@1.0.0"])
|
||||
})
|
||||
|
||||
test("keeps file plugin entries and still adds npm plugin", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
await Bun.write(cfg, JSON.stringify({ plugin: ["file:///tmp/acme.ts"] }, null, 2))
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const json = await read(cfg)
|
||||
expect(json.plugin).toEqual(["file:///tmp/acme.ts", "acme@1.2.3"])
|
||||
})
|
||||
|
||||
test("force replaces configured package version and keeps tuple options", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
await Bun.write(
|
||||
cfg,
|
||||
JSON.stringify(
|
||||
{
|
||||
plugin: [["acme@1.0.0", { mode: "safe" }], "acme@1.1.0", "other@1.0.0"],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@2.0.0",
|
||||
force: true,
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const json = await read(cfg)
|
||||
expect(json.plugin).toEqual([["acme@2.0.0", { mode: "safe" }], "other@1.0.0"])
|
||||
})
|
||||
|
||||
test("writes to global scope when global flag is set", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const global = path.join(tmp.path, "global")
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
global: true,
|
||||
},
|
||||
deps(global, target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
|
||||
expect(await Filesystem.exists(path.join(global, "opencode.jsonc"))).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
})
|
||||
|
||||
test("writes local scope under directory when vcs is not git", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const directory = path.join(tmp.path, "dir")
|
||||
const worktree = path.join(tmp.path, "worktree")
|
||||
await fs.mkdir(directory, { recursive: true })
|
||||
await fs.mkdir(worktree, { recursive: true })
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctxDir(directory, worktree))
|
||||
expect(ok).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(directory, ".opencode", "opencode.jsonc"))).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(worktree, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
})
|
||||
|
||||
test("writes local scope under directory when worktree is root slash", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const directory = path.join(tmp.path, "dir")
|
||||
await fs.mkdir(directory, { recursive: true })
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctxRoot(directory))
|
||||
expect(ok).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(directory, ".opencode", "opencode.jsonc"))).toBe(true)
|
||||
})
|
||||
|
||||
test("writes tui local scope under directory when worktree is root slash", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["tui"])
|
||||
const directory = path.join(tmp.path, "dir")
|
||||
await fs.mkdir(directory, { recursive: true })
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctxRoot(directory))
|
||||
expect(ok).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(directory, ".opencode", "tui.jsonc"))).toBe(true)
|
||||
})
|
||||
|
||||
test("writes only tui config for tui-only plugins", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["tui"])
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "tui.jsonc"))).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
})
|
||||
|
||||
test("force replaces version in both server and tui configs", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server", "tui"])
|
||||
const server = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
const tui = path.join(tmp.path, ".opencode", "tui.json")
|
||||
await fs.mkdir(path.dirname(server), { recursive: true })
|
||||
await Bun.write(server, JSON.stringify({ plugin: ["acme@1.0.0", "other@1.0.0"] }, null, 2))
|
||||
await Bun.write(tui, JSON.stringify({ plugin: [["acme@1.0.0", { mode: "safe" }], "other@1.0.0"] }, null, 2))
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@2.0.0",
|
||||
force: true,
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const serverJson = await read(server)
|
||||
const tuiJson = await read(tui)
|
||||
expect(serverJson.plugin).toEqual(["acme@2.0.0", "other@1.0.0"])
|
||||
expect(tuiJson.plugin).toEqual([["acme@2.0.0", { mode: "safe" }], "other@1.0.0"])
|
||||
})
|
||||
|
||||
test("returns false and keeps config unchanged for invalid JSONC", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.jsonc")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
const bad = '{"plugin": ["acme@1.0.0",}'
|
||||
await Bun.write(cfg, bad)
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@2.0.0",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(false)
|
||||
expect(await fs.readFile(cfg, "utf8")).toBe(bad)
|
||||
})
|
||||
|
||||
test("returns false when manifest declares no supported targets", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path)
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(false)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "tui.jsonc"))).toBe(false)
|
||||
})
|
||||
|
||||
test("returns false when manifest cannot be read", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = path.join(tmp.path, "plugin")
|
||||
await fs.mkdir(target, { recursive: true })
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(false)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
})
|
||||
|
||||
test("returns false when install fails", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@9.9.9",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), new Error("boom")),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(false)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
})
|
||||
})
|
||||
548
packages/opencode/test/plugin/loader-shared.test.ts
Normal file
548
packages/opencode/test/plugin/loader-shared.test.ts
Normal file
@@ -0,0 +1,548 @@
|
||||
import { afterAll, afterEach, describe, expect, spyOn, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
import { Filesystem } from "../../src/util/filesystem"
|
||||
|
||||
const disableDefault = process.env.OPENCODE_DISABLE_DEFAULT_PLUGINS
|
||||
process.env.OPENCODE_DISABLE_DEFAULT_PLUGINS = "1"
|
||||
|
||||
const { Plugin } = await import("../../src/plugin/index")
|
||||
const { Instance } = await import("../../src/project/instance")
|
||||
const { BunProc } = await import("../../src/bun")
|
||||
const { Bus } = await import("../../src/bus")
|
||||
const { Session } = await import("../../src/session")
|
||||
|
||||
afterAll(() => {
|
||||
if (disableDefault === undefined) {
|
||||
delete process.env.OPENCODE_DISABLE_DEFAULT_PLUGINS
|
||||
return
|
||||
}
|
||||
process.env.OPENCODE_DISABLE_DEFAULT_PLUGINS = disableDefault
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await Instance.disposeAll()
|
||||
})
|
||||
|
||||
async function load(dir: string) {
|
||||
return Instance.provide({
|
||||
directory: dir,
|
||||
fn: async () => {
|
||||
await Plugin.list()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async function errs(dir: string) {
|
||||
return Instance.provide({
|
||||
directory: dir,
|
||||
fn: async () => {
|
||||
const errors: string[] = []
|
||||
const off = Bus.subscribe(Session.Event.Error, (evt) => {
|
||||
const error = evt.properties.error
|
||||
if (!error || typeof error !== "object") return
|
||||
if (!("data" in error)) return
|
||||
if (!error.data || typeof error.data !== "object") return
|
||||
if (!("message" in error.data)) return
|
||||
if (typeof error.data.message !== "string") return
|
||||
errors.push(error.data.message)
|
||||
})
|
||||
await Plugin.list()
|
||||
off()
|
||||
return errors
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe("plugin.loader.shared", () => {
|
||||
test("loads a file:// plugin function export", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "plugin.ts")
|
||||
const mark = path.join(dir, "called.txt")
|
||||
await Bun.write(
|
||||
file,
|
||||
[
|
||||
"export default async () => {",
|
||||
` await Bun.write(${JSON.stringify(mark)}, \"called\")`,
|
||||
" return {}",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
path.join(dir, "opencode.json"),
|
||||
JSON.stringify({ plugin: [pathToFileURL(file).href] }, null, 2),
|
||||
)
|
||||
|
||||
return { mark }
|
||||
},
|
||||
})
|
||||
|
||||
await load(tmp.path)
|
||||
expect(await fs.readFile(tmp.extra.mark, "utf8")).toBe("called")
|
||||
})
|
||||
|
||||
test("deduplicates same function exported as default and named", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "plugin.ts")
|
||||
const mark = path.join(dir, "count.txt")
|
||||
await Bun.write(mark, "")
|
||||
await Bun.write(
|
||||
file,
|
||||
[
|
||||
"const run = async () => {",
|
||||
` const text = await Bun.file(${JSON.stringify(mark)}).text().catch(() => \"\")`,
|
||||
` await Bun.write(${JSON.stringify(mark)}, text + \"1\")`,
|
||||
" return {}",
|
||||
"}",
|
||||
"export default run",
|
||||
"export const named = run",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
path.join(dir, "opencode.json"),
|
||||
JSON.stringify({ plugin: [pathToFileURL(file).href] }, null, 2),
|
||||
)
|
||||
|
||||
return { mark }
|
||||
},
|
||||
})
|
||||
|
||||
await load(tmp.path)
|
||||
expect(await fs.readFile(tmp.extra.mark, "utf8")).toBe("1")
|
||||
})
|
||||
|
||||
test("uses only default v1 server plugin when present", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "plugin.ts")
|
||||
const mark = path.join(dir, "count.txt")
|
||||
await Bun.write(
|
||||
file,
|
||||
[
|
||||
"export default {",
|
||||
" server: async () => {",
|
||||
` await Bun.write(${JSON.stringify(mark)}, "default")`,
|
||||
" return {}",
|
||||
" },",
|
||||
"}",
|
||||
"export const named = async () => {",
|
||||
` await Bun.write(${JSON.stringify(mark)}, "named")`,
|
||||
" return {}",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
path.join(dir, "opencode.json"),
|
||||
JSON.stringify({ plugin: [pathToFileURL(file).href] }, null, 2),
|
||||
)
|
||||
|
||||
return { mark }
|
||||
},
|
||||
})
|
||||
|
||||
await load(tmp.path)
|
||||
expect(await Bun.file(tmp.extra.mark).text()).toBe("default")
|
||||
})
|
||||
|
||||
test("resolves npm plugin specs with explicit and default versions", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const acme = path.join(dir, "node_modules", "acme-plugin")
|
||||
const scope = path.join(dir, "node_modules", "scope-plugin")
|
||||
await fs.mkdir(acme, { recursive: true })
|
||||
await fs.mkdir(scope, { recursive: true })
|
||||
await Bun.write(
|
||||
path.join(acme, "package.json"),
|
||||
JSON.stringify({ name: "acme-plugin", type: "module", main: "./index.js" }, null, 2),
|
||||
)
|
||||
await Bun.write(path.join(acme, "index.js"), "export default { server: async () => ({}) }\n")
|
||||
await Bun.write(
|
||||
path.join(scope, "package.json"),
|
||||
JSON.stringify({ name: "scope-plugin", type: "module", main: "./index.js" }, null, 2),
|
||||
)
|
||||
await Bun.write(path.join(scope, "index.js"), "export default { server: async () => ({}) }\n")
|
||||
|
||||
await Bun.write(
|
||||
path.join(dir, "opencode.json"),
|
||||
JSON.stringify({ plugin: ["acme-plugin", "scope-plugin@2.3.4"] }, null, 2),
|
||||
)
|
||||
|
||||
return { acme, scope }
|
||||
},
|
||||
})
|
||||
|
||||
const install = spyOn(BunProc, "install").mockImplementation(async (pkg) => {
|
||||
if (pkg === "acme-plugin") return tmp.extra.acme
|
||||
return tmp.extra.scope
|
||||
})
|
||||
|
||||
try {
|
||||
await load(tmp.path)
|
||||
|
||||
expect(install.mock.calls).toContainEqual(["acme-plugin", "latest"])
|
||||
expect(install.mock.calls).toContainEqual(["scope-plugin", "2.3.4"])
|
||||
} finally {
|
||||
install.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
test("loads npm server plugin from package ./server export", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const mod = path.join(dir, "mods", "acme-plugin")
|
||||
const mark = path.join(dir, "server-called.txt")
|
||||
await fs.mkdir(mod, { recursive: true })
|
||||
|
||||
await Bun.write(
|
||||
path.join(mod, "package.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: "acme-plugin",
|
||||
type: "module",
|
||||
exports: {
|
||||
".": "./index.js",
|
||||
"./server": "./server.js",
|
||||
"./tui": "./tui.js",
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
await Bun.write(path.join(mod, "index.js"), 'import "./main-throws.js"\nexport default {}\n')
|
||||
await Bun.write(path.join(mod, "main-throws.js"), 'throw new Error("main loaded")\n')
|
||||
await Bun.write(
|
||||
path.join(mod, "server.js"),
|
||||
[
|
||||
"export default {",
|
||||
" server: async () => {",
|
||||
` await Bun.write(${JSON.stringify(mark)}, "called")`,
|
||||
" return {}",
|
||||
" },",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
await Bun.write(path.join(mod, "tui.js"), "export default {}\n")
|
||||
|
||||
await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ plugin: ["acme-plugin@1.0.0"] }, null, 2))
|
||||
|
||||
return {
|
||||
mod,
|
||||
mark,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const install = spyOn(BunProc, "install").mockResolvedValue(tmp.extra.mod)
|
||||
|
||||
try {
|
||||
await load(tmp.path)
|
||||
expect(await Bun.file(tmp.extra.mark).text()).toBe("called")
|
||||
} finally {
|
||||
install.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
test("rejects npm server export that resolves outside plugin directory", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const mod = path.join(dir, "mods", "acme-plugin")
|
||||
const outside = path.join(dir, "outside")
|
||||
const mark = path.join(dir, "outside-server.txt")
|
||||
await fs.mkdir(mod, { recursive: true })
|
||||
await fs.mkdir(outside, { recursive: true })
|
||||
|
||||
await Bun.write(
|
||||
path.join(mod, "package.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: "acme-plugin",
|
||||
type: "module",
|
||||
exports: {
|
||||
".": "./index.js",
|
||||
"./server": "./escape/server.js",
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
await Bun.write(path.join(mod, "index.js"), "export default {}\n")
|
||||
await Bun.write(
|
||||
path.join(outside, "server.js"),
|
||||
[
|
||||
"export default {",
|
||||
" server: async () => {",
|
||||
` await Bun.write(${JSON.stringify(mark)}, "outside")`,
|
||||
" return {}",
|
||||
" },",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
await fs.symlink(outside, path.join(mod, "escape"), process.platform === "win32" ? "junction" : "dir")
|
||||
|
||||
await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ plugin: ["acme-plugin"] }, null, 2))
|
||||
|
||||
return {
|
||||
mod,
|
||||
mark,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const install = spyOn(BunProc, "install").mockResolvedValue(tmp.extra.mod)
|
||||
|
||||
try {
|
||||
const errors = await errs(tmp.path)
|
||||
const called = await Bun.file(tmp.extra.mark)
|
||||
.text()
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
expect(called).toBe(false)
|
||||
expect(errors.some((x) => x.includes("outside plugin directory"))).toBe(true)
|
||||
} finally {
|
||||
install.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
test("skips legacy codex and copilot auth plugin specs", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await Bun.write(
|
||||
path.join(dir, "opencode.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
plugin: ["opencode-openai-codex-auth@1.0.0", "opencode-copilot-auth@1.0.0", "regular-plugin@1.0.0"],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
const install = spyOn(BunProc, "install").mockResolvedValue("")
|
||||
|
||||
try {
|
||||
await load(tmp.path)
|
||||
|
||||
const pkgs = install.mock.calls.map((call) => call[0])
|
||||
expect(pkgs).toContain("regular-plugin")
|
||||
expect(pkgs).not.toContain("opencode-openai-codex-auth")
|
||||
expect(pkgs).not.toContain("opencode-copilot-auth")
|
||||
} finally {
|
||||
install.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
test("publishes session.error when install fails", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ plugin: ["broken-plugin@9.9.9"] }, null, 2))
|
||||
},
|
||||
})
|
||||
|
||||
const install = spyOn(BunProc, "install").mockRejectedValue(new Error("boom"))
|
||||
|
||||
try {
|
||||
const errors = await errs(tmp.path)
|
||||
|
||||
expect(errors.some((x) => x.includes("Failed to install plugin broken-plugin@9.9.9") && x.includes("boom"))).toBe(
|
||||
true,
|
||||
)
|
||||
} finally {
|
||||
install.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
test("publishes session.error when plugin init throws", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = pathToFileURL(path.join(dir, "throws.ts")).href
|
||||
await Bun.write(
|
||||
path.join(dir, "throws.ts"),
|
||||
[
|
||||
"export default {",
|
||||
' id: "demo.throws",',
|
||||
" server: async () => {",
|
||||
' throw new Error("explode")',
|
||||
" },",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
|
||||
await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ plugin: [file] }, null, 2))
|
||||
|
||||
return { file }
|
||||
},
|
||||
})
|
||||
|
||||
const errors = await errs(tmp.path)
|
||||
|
||||
expect(errors.some((x) => x.includes(`Failed to load plugin ${tmp.extra.file}: explode`))).toBe(true)
|
||||
})
|
||||
|
||||
test("publishes session.error when plugin module has invalid export", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = pathToFileURL(path.join(dir, "invalid.ts")).href
|
||||
await Bun.write(
|
||||
path.join(dir, "invalid.ts"),
|
||||
["export default {", ' id: "demo.invalid",', " nope: true,", "}", ""].join("\n"),
|
||||
)
|
||||
|
||||
await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ plugin: [file] }, null, 2))
|
||||
|
||||
return { file }
|
||||
},
|
||||
})
|
||||
|
||||
const errors = await errs(tmp.path)
|
||||
|
||||
expect(errors.some((x) => x.includes(`Failed to load plugin ${tmp.extra.file}`))).toBe(true)
|
||||
})
|
||||
|
||||
test("publishes session.error when plugin import fails", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const missing = pathToFileURL(path.join(dir, "missing-plugin.ts")).href
|
||||
await Bun.write(path.join(dir, "opencode.json"), JSON.stringify({ plugin: [missing] }, null, 2))
|
||||
|
||||
return { missing }
|
||||
},
|
||||
})
|
||||
|
||||
const errors = await errs(tmp.path)
|
||||
|
||||
expect(errors.some((x) => x.includes(`Failed to load plugin ${tmp.extra.missing}`))).toBe(true)
|
||||
})
|
||||
|
||||
test("loads object plugin via plugin.server", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "object-plugin.ts")
|
||||
const mark = path.join(dir, "object-called.txt")
|
||||
await Bun.write(
|
||||
file,
|
||||
[
|
||||
"const plugin = {",
|
||||
' id: "demo.object",',
|
||||
" server: async () => {",
|
||||
` await Bun.write(${JSON.stringify(mark)}, \"called\")`,
|
||||
" return {}",
|
||||
" },",
|
||||
"}",
|
||||
"export default plugin",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
path.join(dir, "opencode.json"),
|
||||
JSON.stringify({ plugin: [pathToFileURL(file).href] }, null, 2),
|
||||
)
|
||||
|
||||
return { mark }
|
||||
},
|
||||
})
|
||||
|
||||
await load(tmp.path)
|
||||
expect(await fs.readFile(tmp.extra.mark, "utf8")).toBe("called")
|
||||
})
|
||||
|
||||
test("passes tuple plugin options into server plugin", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "options-plugin.ts")
|
||||
const mark = path.join(dir, "options.json")
|
||||
await Bun.write(
|
||||
file,
|
||||
[
|
||||
"const plugin = {",
|
||||
' id: "demo.options",',
|
||||
" server: async (_input, options) => {",
|
||||
` await Bun.write(${JSON.stringify(mark)}, JSON.stringify(options ?? null))`,
|
||||
" return {}",
|
||||
" },",
|
||||
"}",
|
||||
"export default plugin",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
path.join(dir, "opencode.json"),
|
||||
JSON.stringify({ plugin: [[pathToFileURL(file).href, { source: "tuple", enabled: true }]] }, null, 2),
|
||||
)
|
||||
|
||||
return { mark }
|
||||
},
|
||||
})
|
||||
|
||||
await load(tmp.path)
|
||||
expect(await Filesystem.readJson<{ source: string; enabled: boolean }>(tmp.extra.mark)).toEqual({
|
||||
source: "tuple",
|
||||
enabled: true,
|
||||
})
|
||||
})
|
||||
|
||||
test("skips external plugins in pure mode", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "plugin.ts")
|
||||
const mark = path.join(dir, "called.txt")
|
||||
await Bun.write(
|
||||
file,
|
||||
[
|
||||
"export default {",
|
||||
' id: "demo.pure",',
|
||||
" server: async () => {",
|
||||
` await Bun.write(${JSON.stringify(mark)}, \"called\")`,
|
||||
" return {}",
|
||||
" },",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
|
||||
await Bun.write(
|
||||
path.join(dir, "opencode.json"),
|
||||
JSON.stringify({ plugin: [pathToFileURL(file).href] }, null, 2),
|
||||
)
|
||||
|
||||
return { mark }
|
||||
},
|
||||
})
|
||||
|
||||
const pure = process.env.OPENCODE_PURE
|
||||
process.env.OPENCODE_PURE = "1"
|
||||
|
||||
try {
|
||||
await load(tmp.path)
|
||||
const called = await fs
|
||||
.readFile(tmp.extra.mark, "utf8")
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
expect(called).toBe(false)
|
||||
} finally {
|
||||
if (pure === undefined) {
|
||||
delete process.env.OPENCODE_PURE
|
||||
} else {
|
||||
process.env.OPENCODE_PURE = pure
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
137
packages/opencode/test/plugin/meta.test.ts
Normal file
137
packages/opencode/test/plugin/meta.test.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
import { Process } from "../../src/util/process"
|
||||
import { Filesystem } from "../../src/util/filesystem"
|
||||
|
||||
const { PluginMeta } = await import("../../src/plugin/meta")
|
||||
const root = path.join(import.meta.dir, "../..")
|
||||
const worker = path.join(import.meta.dir, "../fixture/plugin-meta-worker.ts")
|
||||
|
||||
function run(input: { file: string; spec: string; target: string; id: string }) {
|
||||
return Process.run([process.execPath, worker, JSON.stringify(input)], {
|
||||
cwd: root,
|
||||
nothrow: true,
|
||||
})
|
||||
}
|
||||
|
||||
async function map<Value>(file: string): Promise<Record<string, Value>> {
|
||||
return Filesystem.readJson<Record<string, Value>>(file)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.OPENCODE_PLUGIN_META_FILE
|
||||
})
|
||||
|
||||
describe("plugin.meta", () => {
|
||||
test("tracks file plugin loads and changes", async () => {
|
||||
await using tmp = await tmpdir<{ file: string }>({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "plugin.ts")
|
||||
await Bun.write(file, "export default async () => ({})\n")
|
||||
return { file }
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "state", "plugin-meta.json")
|
||||
const file = process.env.OPENCODE_PLUGIN_META_FILE!
|
||||
const spec = pathToFileURL(tmp.extra.file).href
|
||||
|
||||
const one = await PluginMeta.touch(spec, spec, "demo.file")
|
||||
expect(one.state).toBe("first")
|
||||
expect(one.entry.source).toBe("file")
|
||||
expect(one.entry.id).toBe("demo.file")
|
||||
expect(one.entry.modified).toBeDefined()
|
||||
|
||||
const two = await PluginMeta.touch(spec, spec, "demo.file")
|
||||
expect(two.state).toBe("same")
|
||||
expect(two.entry.load_count).toBe(2)
|
||||
|
||||
await Bun.write(tmp.extra.file, "export default async () => ({ ok: true })\n")
|
||||
const stamp = new Date(Date.now() + 10_000)
|
||||
await fs.utimes(tmp.extra.file, stamp, stamp)
|
||||
|
||||
const three = await PluginMeta.touch(spec, spec, "demo.file")
|
||||
expect(three.state).toBe("updated")
|
||||
expect(three.entry.load_count).toBe(3)
|
||||
expect((three.entry.modified ?? 0) > (one.entry.modified ?? 0)).toBe(true)
|
||||
|
||||
const all = await PluginMeta.list()
|
||||
expect(Object.values(all).some((item) => item.spec === spec && item.source === "file")).toBe(true)
|
||||
const saved = await map<{ spec: string; load_count: number }>(file)
|
||||
expect(saved["demo.file"]?.spec).toBe(spec)
|
||||
expect(saved["demo.file"]?.load_count).toBe(3)
|
||||
})
|
||||
|
||||
test("tracks npm plugin versions", async () => {
|
||||
await using tmp = await tmpdir<{ mod: string; pkg: string }>({
|
||||
init: async (dir) => {
|
||||
const mod = path.join(dir, "node_modules", "acme-plugin")
|
||||
const pkg = path.join(mod, "package.json")
|
||||
await fs.mkdir(mod, { recursive: true })
|
||||
await Bun.write(pkg, JSON.stringify({ name: "acme-plugin", version: "1.0.0" }, null, 2))
|
||||
return { mod, pkg }
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "state", "plugin-meta.json")
|
||||
const file = process.env.OPENCODE_PLUGIN_META_FILE!
|
||||
|
||||
const one = await PluginMeta.touch("acme-plugin@latest", tmp.extra.mod, "acme-plugin")
|
||||
expect(one.state).toBe("first")
|
||||
expect(one.entry.source).toBe("npm")
|
||||
expect(one.entry.requested).toBe("latest")
|
||||
expect(one.entry.version).toBe("1.0.0")
|
||||
|
||||
await Bun.write(tmp.extra.pkg, JSON.stringify({ name: "acme-plugin", version: "1.1.0" }, null, 2))
|
||||
|
||||
const two = await PluginMeta.touch("acme-plugin@latest", tmp.extra.mod, "acme-plugin")
|
||||
expect(two.state).toBe("updated")
|
||||
expect(two.entry.version).toBe("1.1.0")
|
||||
expect(two.entry.load_count).toBe(2)
|
||||
|
||||
const all = await PluginMeta.list()
|
||||
expect(Object.values(all).some((item) => item.id === "acme-plugin" && item.version === "1.1.0")).toBe(true)
|
||||
const saved = await map<{ id: string; version?: string }>(file)
|
||||
expect(Object.values(saved).some((item) => item.id === "acme-plugin" && item.version === "1.1.0")).toBe(true)
|
||||
})
|
||||
|
||||
test("serializes concurrent metadata updates across processes", async () => {
|
||||
await using tmp = await tmpdir<{ file: string }>({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "plugin.ts")
|
||||
await Bun.write(file, "export default async () => ({})\n")
|
||||
return { file }
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "state", "plugin-meta.json")
|
||||
const file = process.env.OPENCODE_PLUGIN_META_FILE!
|
||||
const spec = pathToFileURL(tmp.extra.file).href
|
||||
const n = 12
|
||||
|
||||
const out = await Promise.all(
|
||||
Array.from({ length: n }, () =>
|
||||
run({
|
||||
file,
|
||||
spec,
|
||||
target: spec,
|
||||
id: "demo.file",
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
expect(out.map((item) => item.code)).toEqual(Array.from({ length: n }, () => 0))
|
||||
expect(out.map((item) => item.stderr.toString()).filter(Boolean)).toEqual([])
|
||||
|
||||
const all = await PluginMeta.list()
|
||||
const hit = Object.values(all).find((item) => item.spec === spec)
|
||||
expect(hit?.load_count).toBe(n)
|
||||
|
||||
const saved = await map<{ spec: string; load_count: number }>(file)
|
||||
expect(Object.values(saved).find((item) => item.spec === spec)?.load_count).toBe(n)
|
||||
}, 20_000)
|
||||
})
|
||||
38
packages/opencode/test/util/error.test.ts
Normal file
38
packages/opencode/test/util/error.test.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { errorData, errorFormat, errorMessage } from "../../src/util/error"
|
||||
|
||||
describe("util.error", () => {
|
||||
test("formats native Error instances", () => {
|
||||
const err = new Error("boom")
|
||||
expect(errorMessage(err)).toBe("boom")
|
||||
expect(errorFormat(err)).toContain("boom")
|
||||
|
||||
const data = errorData(err)
|
||||
expect(data.type).toBe("Error")
|
||||
expect(data.message).toBe("boom")
|
||||
expect(String(data.formatted)).toContain("boom")
|
||||
})
|
||||
|
||||
test("extracts message from record-like values", () => {
|
||||
const err = { message: "bad input", code: "E_BAD" }
|
||||
expect(errorMessage(err)).toBe("bad input")
|
||||
|
||||
const data = errorData(err)
|
||||
expect(data.message).toBe("bad input")
|
||||
expect(data.code).toBe("E_BAD")
|
||||
})
|
||||
|
||||
test("handles opaque throwables with custom toString", () => {
|
||||
const err = {
|
||||
toString() {
|
||||
return "ResolveMessage: Cannot resolve module"
|
||||
},
|
||||
}
|
||||
|
||||
expect(errorMessage(err)).toBe("ResolveMessage: Cannot resolve module")
|
||||
|
||||
const data = errorData(err)
|
||||
expect(data.message).toBe("ResolveMessage: Cannot resolve module")
|
||||
expect(String(data.formatted)).toContain("ResolveMessage")
|
||||
})
|
||||
})
|
||||
383
packages/opencode/test/util/flock.test.ts
Normal file
383
packages/opencode/test/util/flock.test.ts
Normal file
@@ -0,0 +1,383 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { Flock } from "../../src/util/flock"
|
||||
import { Hash } from "../../src/util/hash"
|
||||
import { Process } from "../../src/util/process"
|
||||
import { Filesystem } from "../../src/util/filesystem"
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
|
||||
const root = path.join(import.meta.dir, "../..")
|
||||
const worker = path.join(import.meta.dir, "../fixture/flock-worker.ts")
|
||||
|
||||
type Msg = {
|
||||
key: string
|
||||
dir: string
|
||||
staleMs?: number
|
||||
timeoutMs?: number
|
||||
baseDelayMs?: number
|
||||
maxDelayMs?: number
|
||||
holdMs?: number
|
||||
ready?: string
|
||||
active?: string
|
||||
done?: string
|
||||
}
|
||||
|
||||
function lock(dir: string, key: string) {
|
||||
return path.join(dir, Hash.fast(key) + ".lock")
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
|
||||
async function exists(file: string) {
|
||||
return fs
|
||||
.stat(file)
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
}
|
||||
|
||||
async function wait(file: string, timeout = 3_000) {
|
||||
const stop = Date.now() + timeout
|
||||
while (Date.now() < stop) {
|
||||
if (await exists(file)) return
|
||||
await sleep(20)
|
||||
}
|
||||
|
||||
throw new Error(`Timed out waiting for file: ${file}`)
|
||||
}
|
||||
|
||||
function run(msg: Msg) {
|
||||
return Process.run([process.execPath, worker, JSON.stringify(msg)], {
|
||||
cwd: root,
|
||||
nothrow: true,
|
||||
})
|
||||
}
|
||||
|
||||
function spawn(msg: Msg) {
|
||||
return Process.spawn([process.execPath, worker, JSON.stringify(msg)], {
|
||||
cwd: root,
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
})
|
||||
}
|
||||
|
||||
describe("util.flock", () => {
|
||||
test("enforces mutual exclusion under process contention", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const dir = path.join(tmp.path, "locks")
|
||||
const done = path.join(tmp.path, "done.log")
|
||||
const active = path.join(tmp.path, "active")
|
||||
const key = "flock:stress"
|
||||
const n = 16
|
||||
|
||||
const out = await Promise.all(
|
||||
Array.from({ length: n }, () =>
|
||||
run({
|
||||
key,
|
||||
dir,
|
||||
done,
|
||||
active,
|
||||
holdMs: 30,
|
||||
staleMs: 1_000,
|
||||
timeoutMs: 15_000,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
expect(out.map((x) => x.code)).toEqual(Array.from({ length: n }, () => 0))
|
||||
expect(out.map((x) => x.stderr.toString()).filter(Boolean)).toEqual([])
|
||||
|
||||
const lines = (await fs.readFile(done, "utf8"))
|
||||
.split("\n")
|
||||
.map((x) => x.trim())
|
||||
.filter(Boolean)
|
||||
expect(lines.length).toBe(n)
|
||||
}, 20_000)
|
||||
|
||||
test("times out while waiting when lock is still healthy", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const dir = path.join(tmp.path, "locks")
|
||||
const key = "flock:timeout"
|
||||
const ready = path.join(tmp.path, "ready")
|
||||
const proc = spawn({
|
||||
key,
|
||||
dir,
|
||||
ready,
|
||||
holdMs: 20_000,
|
||||
staleMs: 10_000,
|
||||
timeoutMs: 30_000,
|
||||
})
|
||||
|
||||
try {
|
||||
await wait(ready, 5_000)
|
||||
const seen: string[] = []
|
||||
const err = await Flock.withLock(key, async () => {}, {
|
||||
dir,
|
||||
staleMs: 10_000,
|
||||
timeoutMs: 1_000,
|
||||
onWait: (tick) => {
|
||||
seen.push(tick.key)
|
||||
},
|
||||
}).catch((err) => err)
|
||||
|
||||
expect(err).toBeInstanceOf(Error)
|
||||
if (!(err instanceof Error)) throw err
|
||||
expect(err.message).toContain("Timed out waiting for lock")
|
||||
expect(seen.length).toBeGreaterThan(0)
|
||||
expect(seen.every((x) => x === key)).toBe(true)
|
||||
} finally {
|
||||
await Process.stop(proc).catch(() => undefined)
|
||||
await proc.exited.catch(() => undefined)
|
||||
}
|
||||
}, 15_000)
|
||||
|
||||
test("recovers after a crashed lock owner", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const dir = path.join(tmp.path, "locks")
|
||||
const key = "flock:crash"
|
||||
const ready = path.join(tmp.path, "ready")
|
||||
const proc = spawn({
|
||||
key,
|
||||
dir,
|
||||
ready,
|
||||
holdMs: 20_000,
|
||||
staleMs: 500,
|
||||
timeoutMs: 30_000,
|
||||
})
|
||||
|
||||
await wait(ready, 5_000)
|
||||
await Process.stop(proc)
|
||||
await proc.exited.catch(() => undefined)
|
||||
|
||||
let hit = false
|
||||
await Flock.withLock(
|
||||
key,
|
||||
async () => {
|
||||
hit = true
|
||||
},
|
||||
{
|
||||
dir,
|
||||
staleMs: 500,
|
||||
timeoutMs: 8_000,
|
||||
},
|
||||
)
|
||||
|
||||
expect(hit).toBe(true)
|
||||
}, 20_000)
|
||||
|
||||
test("breaks stale lock dirs when heartbeat is missing", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const dir = path.join(tmp.path, "locks")
|
||||
const key = "flock:missing-heartbeat"
|
||||
const lockDir = lock(dir, key)
|
||||
|
||||
await fs.mkdir(lockDir, { recursive: true })
|
||||
const old = new Date(Date.now() - 2_000)
|
||||
await fs.utimes(lockDir, old, old)
|
||||
|
||||
let hit = false
|
||||
await Flock.withLock(
|
||||
key,
|
||||
async () => {
|
||||
hit = true
|
||||
},
|
||||
{
|
||||
dir,
|
||||
staleMs: 200,
|
||||
timeoutMs: 3_000,
|
||||
},
|
||||
)
|
||||
|
||||
expect(hit).toBe(true)
|
||||
})
|
||||
|
||||
test("recovers when a stale breaker claim was left behind", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const dir = path.join(tmp.path, "locks")
|
||||
const key = "flock:stale-breaker"
|
||||
const lockDir = lock(dir, key)
|
||||
const breaker = lockDir + ".breaker"
|
||||
|
||||
await fs.mkdir(lockDir, { recursive: true })
|
||||
await fs.mkdir(breaker)
|
||||
|
||||
const old = new Date(Date.now() - 2_000)
|
||||
await fs.utimes(lockDir, old, old)
|
||||
await fs.utimes(breaker, old, old)
|
||||
|
||||
let hit = false
|
||||
await Flock.withLock(
|
||||
key,
|
||||
async () => {
|
||||
hit = true
|
||||
},
|
||||
{
|
||||
dir,
|
||||
staleMs: 200,
|
||||
timeoutMs: 3_000,
|
||||
},
|
||||
)
|
||||
|
||||
expect(hit).toBe(true)
|
||||
expect(await exists(breaker)).toBe(false)
|
||||
})
|
||||
|
||||
test("fails clearly if lock dir is removed while held", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const dir = path.join(tmp.path, "locks")
|
||||
const key = "flock:compromised"
|
||||
const lockDir = lock(dir, key)
|
||||
|
||||
const err = await Flock.withLock(
|
||||
key,
|
||||
async () => {
|
||||
await fs.rm(lockDir, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
})
|
||||
},
|
||||
{
|
||||
dir,
|
||||
staleMs: 1_000,
|
||||
timeoutMs: 3_000,
|
||||
},
|
||||
).catch((err) => err)
|
||||
|
||||
expect(err).toBeInstanceOf(Error)
|
||||
if (!(err instanceof Error)) throw err
|
||||
expect(err.message).toContain("compromised")
|
||||
|
||||
let hit = false
|
||||
await Flock.withLock(
|
||||
key,
|
||||
async () => {
|
||||
hit = true
|
||||
},
|
||||
{
|
||||
dir,
|
||||
staleMs: 200,
|
||||
timeoutMs: 3_000,
|
||||
},
|
||||
)
|
||||
expect(hit).toBe(true)
|
||||
})
|
||||
|
||||
test("writes owner metadata while lock is held", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const dir = path.join(tmp.path, "locks")
|
||||
const key = "flock:meta"
|
||||
const file = path.join(lock(dir, key), "meta.json")
|
||||
|
||||
await Flock.withLock(
|
||||
key,
|
||||
async () => {
|
||||
const json = await Filesystem.readJson<{
|
||||
token?: unknown
|
||||
pid?: unknown
|
||||
hostname?: unknown
|
||||
createdAt?: unknown
|
||||
}>(file)
|
||||
|
||||
expect(typeof json.token).toBe("string")
|
||||
expect(typeof json.pid).toBe("number")
|
||||
expect(typeof json.hostname).toBe("string")
|
||||
expect(typeof json.createdAt).toBe("string")
|
||||
},
|
||||
{
|
||||
dir,
|
||||
staleMs: 1_000,
|
||||
timeoutMs: 3_000,
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test("supports acquire with await using", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const dir = path.join(tmp.path, "locks")
|
||||
const key = "flock:acquire"
|
||||
const lockDir = lock(dir, key)
|
||||
|
||||
{
|
||||
await using _ = await Flock.acquire(key, {
|
||||
dir,
|
||||
staleMs: 1_000,
|
||||
timeoutMs: 3_000,
|
||||
})
|
||||
expect(await exists(lockDir)).toBe(true)
|
||||
}
|
||||
|
||||
expect(await exists(lockDir)).toBe(false)
|
||||
})
|
||||
|
||||
test("refuses token mismatch release and recovers from stale", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const dir = path.join(tmp.path, "locks")
|
||||
const key = "flock:token"
|
||||
const lockDir = lock(dir, key)
|
||||
const meta = path.join(lockDir, "meta.json")
|
||||
|
||||
const err = await Flock.withLock(
|
||||
key,
|
||||
async () => {
|
||||
const json = await Filesystem.readJson<{ token?: string }>(meta)
|
||||
json.token = "tampered"
|
||||
await fs.writeFile(meta, JSON.stringify(json, null, 2))
|
||||
},
|
||||
{
|
||||
dir,
|
||||
staleMs: 500,
|
||||
timeoutMs: 3_000,
|
||||
},
|
||||
).catch((err) => err)
|
||||
|
||||
expect(err).toBeInstanceOf(Error)
|
||||
if (!(err instanceof Error)) throw err
|
||||
expect(err.message).toContain("token mismatch")
|
||||
expect(await exists(lockDir)).toBe(true)
|
||||
|
||||
let hit = false
|
||||
await Flock.withLock(
|
||||
key,
|
||||
async () => {
|
||||
hit = true
|
||||
},
|
||||
{
|
||||
dir,
|
||||
staleMs: 500,
|
||||
timeoutMs: 6_000,
|
||||
},
|
||||
)
|
||||
expect(hit).toBe(true)
|
||||
})
|
||||
|
||||
test("fails clearly on unwritable lock roots", async () => {
|
||||
if (process.platform === "win32") return
|
||||
|
||||
await using tmp = await tmpdir()
|
||||
const dir = path.join(tmp.path, "locks")
|
||||
const key = "flock:perm"
|
||||
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
await fs.chmod(dir, 0o500)
|
||||
|
||||
try {
|
||||
const err = await Flock.withLock(key, async () => {}, {
|
||||
dir,
|
||||
staleMs: 100,
|
||||
timeoutMs: 500,
|
||||
}).catch((err) => err)
|
||||
|
||||
expect(err).toBeInstanceOf(Error)
|
||||
if (!(err instanceof Error)) throw err
|
||||
const text = err.message
|
||||
expect(text.includes("EACCES") || text.includes("EPERM")).toBe(true)
|
||||
} finally {
|
||||
await fs.chmod(dir, 0o700)
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user