merge dev

This commit is contained in:
Shoubhit Dash 2026-04-16 17:30:14 +05:30
commit 2e18a603f0
137 changed files with 59696 additions and 106347 deletions

View file

@ -79,3 +79,55 @@ await using tmp = await tmpdir({
- Directories are created in the system temp folder with prefix `opencode-test-`
- Use `await using` for automatic cleanup when the variable goes out of scope
- Paths are sanitized to strip null bytes (defensive fix for CI environments)
## Testing With Effects
Use `testEffect(...)` from `test/lib/effect.ts` for tests that exercise Effect services or Effect-based workflows.
### Core Pattern
```typescript
import { describe, expect } from "bun:test"
import { Effect, Layer } from "effect"
import { provideTmpdirInstance } from "../fixture/fixture"
import { testEffect } from "../lib/effect"
const it = testEffect(Layer.mergeAll(MyService.defaultLayer))
describe("my service", () => {
it.live("does the thing", () =>
provideTmpdirInstance(() =>
Effect.gen(function* () {
const svc = yield* MyService.Service
const out = yield* svc.run()
expect(out).toEqual("ok")
}),
),
)
})
```
### `it.effect` vs `it.live`
- Use `it.effect(...)` when the test should run with `TestClock` and `TestConsole`.
- Use `it.live(...)` when the test depends on real time, filesystem mtimes, child processes, git, locks, or other live OS behavior.
- Most integration-style tests in this package use `it.live(...)`.
### Effect Fixtures
Prefer the Effect-aware helpers from `fixture/fixture.ts` instead of building a manual runtime in each test.
- `tmpdirScoped(options?)` creates a scoped temp directory and cleans it up when the Effect scope closes.
- `provideInstance(dir)(effect)` is the low-level helper. It does not create a directory; it just runs an Effect with `Instance.current` bound to `dir`.
- `provideTmpdirInstance((dir) => effect, options?)` is the convenience helper. It creates a temp directory, binds it as the active instance, and disposes the instance on cleanup.
- `provideTmpdirServer((input) => effect, options?)` does the same, but also provides the test LLM server.
Use `provideTmpdirInstance(...)` by default when a test only needs one temp instance. Use `tmpdirScoped()` plus `provideInstance(...)` when a test needs multiple directories, custom setup before binding, or needs to switch instance context within one test.
### Style
- Define `const it = testEffect(...)` near the top of the file.
- Keep the test body inside `Effect.gen(function* () { ... })`.
- Yield services directly with `yield* MyService.Service` or `yield* MyTool`.
- Avoid custom `ManagedRuntime`, `attach(...)`, or ad hoc `run(...)` wrappers when `testEffect(...)` already provides the runtime.
- When a test needs instance-local state, prefer `provideTmpdirInstance(...)` or `provideInstance(...)` over manual `Instance.provide(...)` inside Promise-style tests.

View file

@ -3,7 +3,7 @@ import { Effect, Layer, Option } from "effect"
import { AccountRepo } from "../../src/account/repo"
import { AccessToken, AccountID, OrgID, RefreshToken } from "../../src/account/schema"
import { Database } from "../../src/storage/db"
import { Database } from "../../src/storage"
import { testEffect } from "../lib/effect"
const truncate = Layer.effectDiscard(

View file

@ -15,7 +15,7 @@ import {
RefreshToken,
UserCode,
} from "../../src/account/schema"
import { Database } from "../../src/storage/db"
import { Database } from "../../src/storage"
import { testEffect } from "../lib/effect"
const truncate = Layer.effectDiscard(

View file

@ -295,6 +295,46 @@ describe("acp.agent event subscription", () => {
})
})
test("does not emit user_message_chunk for live prompt parts", async () => {
await using tmp = await tmpdir()
await Instance.provide({
directory: tmp.path,
fn: async () => {
const { agent, controller, sessionUpdates, stop } = createFakeAgent()
const cwd = "/tmp/opencode-acp-test"
const sessionId = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId)
controller.push({
directory: cwd,
payload: {
type: "message.part.updated",
properties: {
sessionID: sessionId,
time: Date.now(),
part: {
id: "part_1",
sessionID: sessionId,
messageID: "msg_user",
type: "text",
text: "hello",
},
},
},
} as any)
await new Promise((r) => setTimeout(r, 20))
expect(
sessionUpdates
.filter((u) => u.sessionId === sessionId)
.some((u) => u.update.sessionUpdate === "user_message_chunk"),
).toBe(false)
stop()
},
})
})
test("keeps concurrent sessions isolated when message.part.delta events are interleaved", async () => {
await using tmp = await tmpdir()
await Instance.provide({
@ -423,9 +463,9 @@ describe("acp.agent event subscription", () => {
// Make permission request for session A block until we release it
const originalRequestPermission = connection.requestPermission.bind(connection)
let permissionCalls = 0
let _permissionCalls = 0
connection.requestPermission = async (params: RequestPermissionParams) => {
permissionCalls++
_permissionCalls++
if (params.sessionId.endsWith("1")) {
await permissionABlocking
}

View file

@ -1,6 +1,7 @@
import { afterEach, test, expect } from "bun:test"
import { Effect } from "effect"
import path from "path"
import { tmpdir } from "../fixture/fixture"
import { provideInstance, tmpdir } from "../fixture/fixture"
import { Instance } from "../../src/project/instance"
import { Agent } from "../../src/agent/agent"
import { Permission } from "../../src/permission"
@ -11,6 +12,10 @@ function evalPerm(agent: Agent.Info | undefined, permission: string): Permission
return Permission.evaluate(permission, "*", agent.permission).action
}
function load<A>(dir: string, fn: (svc: Agent.Interface) => Effect.Effect<A>) {
return Effect.runPromise(provideInstance(dir)(Agent.Service.use(fn)).pipe(Effect.provide(Agent.defaultLayer)))
}
afterEach(async () => {
await Instance.disposeAll()
})
@ -20,7 +25,7 @@ test("returns default native agents when no config", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const agents = await Agent.list()
const agents = await load(tmp.path, (svc) => svc.list())
const names = agents.map((a) => a.name)
expect(names).toContain("build")
expect(names).toContain("plan")
@ -38,7 +43,7 @@ test("build agent has correct default properties", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(build).toBeDefined()
expect(build?.mode).toBe("primary")
expect(build?.native).toBe(true)
@ -53,7 +58,7 @@ test("plan agent denies edits except .opencode/plans/*", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const plan = await Agent.get("plan")
const plan = await load(tmp.path, (svc) => svc.get("plan"))
expect(plan).toBeDefined()
// Wildcard is denied
expect(evalPerm(plan, "edit")).toBe("deny")
@ -68,7 +73,7 @@ test("explore agent denies edit and write", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const explore = await Agent.get("explore")
const explore = await load(tmp.path, (svc) => svc.get("explore"))
expect(explore).toBeDefined()
expect(explore?.mode).toBe("subagent")
expect(evalPerm(explore, "edit")).toBe("deny")
@ -79,12 +84,12 @@ test("explore agent denies edit and write", async () => {
})
test("explore agent asks for external directories and allows Truncate.GLOB", async () => {
const { Truncate } = await import("../../src/tool/truncate")
const { Truncate } = await import("../../src/tool")
await using tmp = await tmpdir()
await Instance.provide({
directory: tmp.path,
fn: async () => {
const explore = await Agent.get("explore")
const explore = await load(tmp.path, (svc) => svc.get("explore"))
expect(explore).toBeDefined()
expect(Permission.evaluate("external_directory", "/some/other/path", explore!.permission).action).toBe("ask")
expect(Permission.evaluate("external_directory", Truncate.GLOB, explore!.permission).action).toBe("allow")
@ -97,7 +102,7 @@ test("general agent denies todo tools", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const general = await Agent.get("general")
const general = await load(tmp.path, (svc) => svc.get("general"))
expect(general).toBeDefined()
expect(general?.mode).toBe("subagent")
expect(general?.hidden).toBeUndefined()
@ -111,7 +116,7 @@ test("compaction agent denies all permissions", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const compaction = await Agent.get("compaction")
const compaction = await load(tmp.path, (svc) => svc.get("compaction"))
expect(compaction).toBeDefined()
expect(compaction?.hidden).toBe(true)
expect(evalPerm(compaction, "bash")).toBe("deny")
@ -137,7 +142,7 @@ test("custom agent from config creates new agent", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const custom = await Agent.get("my_custom_agent")
const custom = await load(tmp.path, (svc) => svc.get("my_custom_agent"))
expect(custom).toBeDefined()
expect(String(custom?.model?.providerID)).toBe("openai")
expect(String(custom?.model?.modelID)).toBe("gpt-4")
@ -166,7 +171,7 @@ test("custom agent config overrides native agent properties", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(build).toBeDefined()
expect(String(build?.model?.providerID)).toBe("anthropic")
expect(String(build?.model?.modelID)).toBe("claude-3")
@ -189,9 +194,9 @@ test("agent disable removes agent from list", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const explore = await Agent.get("explore")
const explore = await load(tmp.path, (svc) => svc.get("explore"))
expect(explore).toBeUndefined()
const agents = await Agent.list()
const agents = await load(tmp.path, (svc) => svc.list())
const names = agents.map((a) => a.name)
expect(names).not.toContain("explore")
},
@ -215,7 +220,7 @@ test("agent permission config merges with defaults", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(build).toBeDefined()
// Specific pattern is denied
expect(Permission.evaluate("bash", "rm -rf *", build!.permission).action).toBe("deny")
@ -236,7 +241,7 @@ test("global permission config applies to all agents", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(build).toBeDefined()
expect(evalPerm(build, "bash")).toBe("deny")
},
@ -255,8 +260,8 @@ test("agent steps/maxSteps config sets steps property", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const plan = await Agent.get("plan")
const build = await load(tmp.path, (svc) => svc.get("build"))
const plan = await load(tmp.path, (svc) => svc.get("plan"))
expect(build?.steps).toBe(50)
expect(plan?.steps).toBe(100)
},
@ -274,7 +279,7 @@ test("agent mode can be overridden", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const explore = await Agent.get("explore")
const explore = await load(tmp.path, (svc) => svc.get("explore"))
expect(explore?.mode).toBe("primary")
},
})
@ -291,7 +296,7 @@ test("agent name can be overridden", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(build?.name).toBe("Builder")
},
})
@ -308,7 +313,7 @@ test("agent prompt can be set from config", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(build?.prompt).toBe("Custom system prompt")
},
})
@ -328,7 +333,7 @@ test("unknown agent properties are placed into options", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(build?.options.random_property).toBe("hello")
expect(build?.options.another_random).toBe(123)
},
@ -351,7 +356,7 @@ test("agent options merge correctly", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(build?.options.custom_option).toBe(true)
expect(build?.options.another_option).toBe("value")
},
@ -376,8 +381,8 @@ test("multiple custom agents can be defined", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const agentA = await Agent.get("agent_a")
const agentB = await Agent.get("agent_b")
const agentA = await load(tmp.path, (svc) => svc.get("agent_a"))
const agentB = await load(tmp.path, (svc) => svc.get("agent_b"))
expect(agentA?.description).toBe("Agent A")
expect(agentA?.mode).toBe("subagent")
expect(agentB?.description).toBe("Agent B")
@ -405,7 +410,7 @@ test("Agent.list keeps the default agent first and sorts the rest by name", asyn
await Instance.provide({
directory: tmp.path,
fn: async () => {
const names = (await Agent.list()).map((a) => a.name)
const names = (await load(tmp.path, (svc) => svc.list())).map((a) => a.name)
expect(names[0]).toBe("plan")
expect(names.slice(1)).toEqual(names.slice(1).toSorted((a, b) => a.localeCompare(b)))
},
@ -417,7 +422,7 @@ test("Agent.get returns undefined for non-existent agent", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const nonExistent = await Agent.get("does_not_exist")
const nonExistent = await load(tmp.path, (svc) => svc.get("does_not_exist"))
expect(nonExistent).toBeUndefined()
},
})
@ -428,7 +433,7 @@ test("default permission includes doom_loop and external_directory as ask", asyn
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(evalPerm(build, "doom_loop")).toBe("ask")
expect(evalPerm(build, "external_directory")).toBe("ask")
},
@ -440,7 +445,7 @@ test("webfetch is allowed by default", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(evalPerm(build, "webfetch")).toBe("allow")
},
})
@ -462,7 +467,7 @@ test("legacy tools config converts to permissions", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(evalPerm(build, "bash")).toBe("deny")
expect(evalPerm(build, "read")).toBe("deny")
},
@ -484,14 +489,14 @@ test("legacy tools config maps write/edit/patch/multiedit to edit permission", a
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(evalPerm(build, "edit")).toBe("deny")
},
})
})
test("Truncate.GLOB is allowed even when user denies external_directory globally", async () => {
const { Truncate } = await import("../../src/tool/truncate")
const { Truncate } = await import("../../src/tool")
await using tmp = await tmpdir({
config: {
permission: {
@ -502,7 +507,7 @@ test("Truncate.GLOB is allowed even when user denies external_directory globally
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(Permission.evaluate("external_directory", Truncate.GLOB, build!.permission).action).toBe("allow")
expect(Permission.evaluate("external_directory", Truncate.DIR, build!.permission).action).toBe("deny")
expect(Permission.evaluate("external_directory", "/some/other/path", build!.permission).action).toBe("deny")
@ -511,7 +516,7 @@ test("Truncate.GLOB is allowed even when user denies external_directory globally
})
test("Truncate.GLOB is allowed even when user denies external_directory per-agent", async () => {
const { Truncate } = await import("../../src/tool/truncate")
const { Truncate } = await import("../../src/tool")
await using tmp = await tmpdir({
config: {
agent: {
@ -526,7 +531,7 @@ test("Truncate.GLOB is allowed even when user denies external_directory per-agen
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(Permission.evaluate("external_directory", Truncate.GLOB, build!.permission).action).toBe("allow")
expect(Permission.evaluate("external_directory", Truncate.DIR, build!.permission).action).toBe("deny")
expect(Permission.evaluate("external_directory", "/some/other/path", build!.permission).action).toBe("deny")
@ -535,7 +540,7 @@ test("Truncate.GLOB is allowed even when user denies external_directory per-agen
})
test("explicit Truncate.GLOB deny is respected", async () => {
const { Truncate } = await import("../../src/tool/truncate")
const { Truncate } = await import("../../src/tool")
await using tmp = await tmpdir({
config: {
permission: {
@ -549,7 +554,7 @@ test("explicit Truncate.GLOB deny is respected", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
expect(Permission.evaluate("external_directory", Truncate.GLOB, build!.permission).action).toBe("deny")
expect(Permission.evaluate("external_directory", Truncate.DIR, build!.permission).action).toBe("deny")
},
@ -581,7 +586,7 @@ description: Permission skill.
await Instance.provide({
directory: tmp.path,
fn: async () => {
const build = await Agent.get("build")
const build = await load(tmp.path, (svc) => svc.get("build"))
const skillDir = path.join(tmp.path, ".opencode", "skill", "perm-skill")
const target = path.join(skillDir, "reference", "notes.md")
expect(Permission.evaluate("external_directory", target, build!.permission).action).toBe("allow")
@ -597,7 +602,7 @@ test("defaultAgent returns build when no default_agent config", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const agent = await Agent.defaultAgent()
const agent = await load(tmp.path, (svc) => svc.defaultAgent())
expect(agent).toBe("build")
},
})
@ -612,7 +617,7 @@ test("defaultAgent respects default_agent config set to plan", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const agent = await Agent.defaultAgent()
const agent = await load(tmp.path, (svc) => svc.defaultAgent())
expect(agent).toBe("plan")
},
})
@ -632,7 +637,7 @@ test("defaultAgent respects default_agent config set to custom agent with mode a
await Instance.provide({
directory: tmp.path,
fn: async () => {
const agent = await Agent.defaultAgent()
const agent = await load(tmp.path, (svc) => svc.defaultAgent())
expect(agent).toBe("my_custom")
},
})
@ -647,7 +652,7 @@ test("defaultAgent throws when default_agent points to subagent", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
await expect(Agent.defaultAgent()).rejects.toThrow('default agent "explore" is a subagent')
await expect(load(tmp.path, (svc) => svc.defaultAgent())).rejects.toThrow('default agent "explore" is a subagent')
},
})
})
@ -661,7 +666,7 @@ test("defaultAgent throws when default_agent points to hidden agent", async () =
await Instance.provide({
directory: tmp.path,
fn: async () => {
await expect(Agent.defaultAgent()).rejects.toThrow('default agent "compaction" is hidden')
await expect(load(tmp.path, (svc) => svc.defaultAgent())).rejects.toThrow('default agent "compaction" is hidden')
},
})
})
@ -675,7 +680,9 @@ test("defaultAgent throws when default_agent points to non-existent agent", asyn
await Instance.provide({
directory: tmp.path,
fn: async () => {
await expect(Agent.defaultAgent()).rejects.toThrow('default agent "does_not_exist" not found')
await expect(load(tmp.path, (svc) => svc.defaultAgent())).rejects.toThrow(
'default agent "does_not_exist" not found',
)
},
})
})
@ -691,7 +698,7 @@ test("defaultAgent returns plan when build is disabled and default_agent not set
await Instance.provide({
directory: tmp.path,
fn: async () => {
const agent = await Agent.defaultAgent()
const agent = await load(tmp.path, (svc) => svc.defaultAgent())
// build is disabled, so it should return plan (next primary agent)
expect(agent).toBe("plan")
},
@ -711,7 +718,7 @@ test("defaultAgent throws when all primary agents are disabled", async () => {
directory: tmp.path,
fn: async () => {
// build and plan are disabled, no primary-capable agents remain
await expect(Agent.defaultAgent()).rejects.toThrow("no primary visible agent found")
await expect(load(tmp.path, (svc) => svc.defaultAgent())).rejects.toThrow("no primary visible agent found")
},
})
})

View file

@ -1,58 +1,86 @@
import { test, expect } from "bun:test"
import { describe, expect } from "bun:test"
import { Effect, Layer } from "effect"
import { Auth } from "../../src/auth"
import * as CrossSpawnSpawner from "../../src/effect/cross-spawn-spawner"
import { provideTmpdirInstance } from "../fixture/fixture"
import { testEffect } from "../lib/effect"
test("set normalizes trailing slashes in keys", async () => {
await Auth.set("https://example.com/", {
type: "wellknown",
key: "TOKEN",
token: "abc",
})
const data = await Auth.all()
expect(data["https://example.com"]).toBeDefined()
expect(data["https://example.com/"]).toBeUndefined()
})
const node = CrossSpawnSpawner.defaultLayer
test("set cleans up pre-existing trailing-slash entry", async () => {
// Simulate a pre-fix entry with trailing slash
await Auth.set("https://example.com/", {
type: "wellknown",
key: "TOKEN",
token: "old",
})
// Re-login with normalized key (as the CLI does post-fix)
await Auth.set("https://example.com", {
type: "wellknown",
key: "TOKEN",
token: "new",
})
const data = await Auth.all()
const keys = Object.keys(data).filter((k) => k.includes("example.com"))
expect(keys).toEqual(["https://example.com"])
const entry = data["https://example.com"]!
expect(entry.type).toBe("wellknown")
if (entry.type === "wellknown") expect(entry.token).toBe("new")
})
const it = testEffect(Layer.mergeAll(Auth.defaultLayer, node))
test("remove deletes both trailing-slash and normalized keys", async () => {
await Auth.set("https://example.com", {
type: "wellknown",
key: "TOKEN",
token: "abc",
})
await Auth.remove("https://example.com/")
const data = await Auth.all()
expect(data["https://example.com"]).toBeUndefined()
expect(data["https://example.com/"]).toBeUndefined()
})
describe("Auth", () => {
it.live("set normalizes trailing slashes in keys", () =>
provideTmpdirInstance(() =>
Effect.gen(function* () {
const auth = yield* Auth.Service
yield* auth.set("https://example.com/", {
type: "wellknown",
key: "TOKEN",
token: "abc",
})
const data = yield* auth.all()
expect(data["https://example.com"]).toBeDefined()
expect(data["https://example.com/"]).toBeUndefined()
}),
),
)
test("set and remove are no-ops on keys without trailing slashes", async () => {
await Auth.set("anthropic", {
type: "api",
key: "sk-test",
})
const data = await Auth.all()
expect(data["anthropic"]).toBeDefined()
await Auth.remove("anthropic")
const after = await Auth.all()
expect(after["anthropic"]).toBeUndefined()
it.live("set cleans up pre-existing trailing-slash entry", () =>
provideTmpdirInstance(() =>
Effect.gen(function* () {
const auth = yield* Auth.Service
yield* auth.set("https://example.com/", {
type: "wellknown",
key: "TOKEN",
token: "old",
})
yield* auth.set("https://example.com", {
type: "wellknown",
key: "TOKEN",
token: "new",
})
const data = yield* auth.all()
const keys = Object.keys(data).filter((key) => key.includes("example.com"))
expect(keys).toEqual(["https://example.com"])
const entry = data["https://example.com"]!
expect(entry.type).toBe("wellknown")
if (entry.type === "wellknown") expect(entry.token).toBe("new")
}),
),
)
it.live("remove deletes both trailing-slash and normalized keys", () =>
provideTmpdirInstance(() =>
Effect.gen(function* () {
const auth = yield* Auth.Service
yield* auth.set("https://example.com", {
type: "wellknown",
key: "TOKEN",
token: "abc",
})
yield* auth.remove("https://example.com/")
const data = yield* auth.all()
expect(data["https://example.com"]).toBeUndefined()
expect(data["https://example.com/"]).toBeUndefined()
}),
),
)
it.live("set and remove are no-ops on keys without trailing slashes", () =>
provideTmpdirInstance(() =>
Effect.gen(function* () {
const auth = yield* Auth.Service
yield* auth.set("anthropic", {
type: "api",
key: "sk-test",
})
const data = yield* auth.all()
expect(data["anthropic"]).toBeDefined()
yield* auth.remove("anthropic")
const after = yield* auth.all()
expect(after["anthropic"]).toBeUndefined()
}),
),
)
})

View file

@ -1,10 +1,10 @@
import { NodeChildProcessSpawner, NodeFileSystem, NodePath } from "@effect/platform-node"
import { describe, expect } from "bun:test"
import { Deferred, Effect, Layer, Stream } from "effect"
import z from "zod"
import { Bus } from "../../src/bus"
import { BusEvent } from "../../src/bus/bus-event"
import { Instance } from "../../src/project/instance"
import * as CrossSpawnSpawner from "../../src/effect/cross-spawn-spawner"
import { provideInstance, provideTmpdirInstance, tmpdirScoped } from "../fixture/fixture"
import { testEffect } from "../lib/effect"
@ -13,9 +13,7 @@ const TestEvent = {
Pong: BusEvent.define("test.effect.pong", z.object({ message: z.string() })),
}
const node = NodeChildProcessSpawner.layer.pipe(
Layer.provideMerge(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer)),
)
const node = CrossSpawnSpawner.defaultLayer
const live = Layer.mergeAll(Bus.layer, node)

View file

@ -4,7 +4,7 @@ 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"
import { TuiConfig } from "../../../src/cli/cmd/tui/config/tui"
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
@ -31,15 +31,18 @@ test("adds tui plugin at runtime from spec", async () => {
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [],
plugin_origins: undefined,
})
}
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
try {
await TuiPluginRuntime.init(createTuiPluginApi())
await TuiPluginRuntime.init({
api: createTuiPluginApi(),
config,
})
await expect(TuiPluginRuntime.addPlugin(tmp.extra.spec)).resolves.toBe(true)
await expect(fs.readFile(tmp.extra.marker, "utf8")).resolves.toBe("called")
@ -54,7 +57,6 @@ test("adds tui plugin at runtime from spec", async () => {
} finally {
await TuiPluginRuntime.dispose()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}
@ -72,10 +74,10 @@ test("retries runtime add for file plugins after dependency wait", async () => {
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [],
plugin_origins: undefined,
})
}
const wait = spyOn(TuiConfig, "waitForDependencies").mockImplementation(async () => {
await Bun.write(
path.join(tmp.extra.mod, "index.ts"),
@ -91,7 +93,10 @@ test("retries runtime add for file plugins after dependency wait", async () => {
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
try {
await TuiPluginRuntime.init(createTuiPluginApi())
await TuiPluginRuntime.init({
api: createTuiPluginApi(),
config,
})
await expect(TuiPluginRuntime.addPlugin(tmp.extra.spec)).resolves.toBe(true)
await expect(fs.readFile(tmp.extra.marker, "utf8")).resolves.toBe("called")
@ -100,7 +105,6 @@ test("retries runtime add for file plugins after dependency wait", async () => {
} finally {
await TuiPluginRuntime.dispose()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}

View file

@ -4,7 +4,7 @@ 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"
import { TuiConfig } from "../../../src/cli/cmd/tui/config/tui"
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
@ -50,11 +50,10 @@ test("installs plugin without loading it", async () => {
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const cfg: Awaited<ReturnType<typeof TuiConfig.get>> = {
const config: TuiConfig.Info = {
plugin: [],
plugin_origins: 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({
@ -69,7 +68,7 @@ test("installs plugin without loading it", async () => {
})
try {
await TuiPluginRuntime.init(api)
await TuiPluginRuntime.init({ api, config })
const out = await TuiPluginRuntime.installPlugin(tmp.extra.spec)
expect(out).toMatchObject({
ok: true,
@ -82,7 +81,6 @@ test("installs plugin without loading it", async () => {
} finally {
await TuiPluginRuntime.dispose()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}

View file

@ -5,7 +5,6 @@ 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")
@ -40,10 +39,10 @@ test("runs onDispose callbacks with aborted signal and is idempotent", async ()
},
})
const restore = mockTuiRuntime(tmp.path, [[tmp.extra.spec, { marker: tmp.extra.marker }]])
const { config, restore } = mockTuiRuntime(tmp.path, [[tmp.extra.spec, { marker: tmp.extra.marker }]])
try {
await TuiPluginRuntime.init(createTuiPluginApi())
await TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
await TuiPluginRuntime.dispose()
const marker = await fs.readFile(tmp.extra.marker, "utf8")
@ -100,13 +99,13 @@ test("rolls back failed plugin and continues loading next", async () => {
},
})
const restore = mockTuiRuntime(tmp.path, [
const { config, 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())
await TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
// bad plugin's onDispose ran during rollback
await expect(fs.readFile(tmp.extra.badMarker, "utf8")).resolves.toBe("cleaned")
// good plugin still loaded
@ -156,11 +155,11 @@ export default {
},
})
const restore = mockTuiRuntime(tmp.path, [tmp.extra.spec])
const { config, restore } = mockTuiRuntime(tmp.path, [tmp.extra.spec])
const err = spyOn(console, "error").mockImplementation(() => {})
try {
await TuiPluginRuntime.init(createTuiPluginApi())
await TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
const marker = await fs.readFile(tmp.extra.marker, "utf8")
expect(marker).toContain("one")
@ -203,14 +202,14 @@ test(
},
})
const restore = mockTuiRuntime(tmp.path, [tmp.extra.spec])
const { config, restore } = mockTuiRuntime(tmp.path, [tmp.extra.spec])
try {
await TuiPluginRuntime.init(createTuiPluginApi())
await TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
const done = await new Promise<string>((resolve) => {
const timer = setTimeout(() => resolve("timeout"), 7000)
TuiPluginRuntime.dispose().then(() => {
void TuiPluginRuntime.dispose().then(() => {
clearTimeout(timer)
resolve("done")
})

View file

@ -4,7 +4,7 @@ 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"
import { TuiConfig } from "../../../src/cli/cmd/tui/config/tui"
import { Npm } from "../../../src/npm"
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
@ -44,7 +44,7 @@ test("loads npm tui plugin from package ./tui export", async () => {
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [[tmp.extra.spec, { marker: tmp.extra.marker }]],
plugin_origins: [
{
@ -53,13 +53,13 @@ test("loads npm tui plugin from package ./tui export", async () => {
source: path.join(tmp.path, "tui.json"),
},
],
})
}
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
const install = spyOn(Npm, "add").mockResolvedValue({ directory: tmp.extra.mod, entrypoint: tmp.extra.mod })
try {
await TuiPluginRuntime.init(createTuiPluginApi())
await TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
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)
@ -69,7 +69,6 @@ test("loads npm tui plugin from package ./tui export", async () => {
await TuiPluginRuntime.dispose()
install.mockRestore()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}
@ -106,7 +105,7 @@ test("does not use npm package exports dot for tui entry", async () => {
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [tmp.extra.spec],
plugin_origins: [
{
@ -115,20 +114,19 @@ test("does not use npm package exports dot for tui entry", async () => {
source: path.join(tmp.path, "tui.json"),
},
],
})
}
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
const install = spyOn(Npm, "add").mockResolvedValue({ directory: tmp.extra.mod, entrypoint: tmp.extra.mod })
try {
await TuiPluginRuntime.init(createTuiPluginApi())
await TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
await expect(fs.readFile(tmp.extra.marker, "utf8")).rejects.toThrow()
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
}
@ -169,7 +167,7 @@ test("rejects npm tui export that resolves outside plugin directory", async () =
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [tmp.extra.spec],
plugin_origins: [
{
@ -178,13 +176,13 @@ test("rejects npm tui export that resolves outside plugin directory", async () =
source: path.join(tmp.path, "tui.json"),
},
],
})
}
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
const install = spyOn(Npm, "add").mockResolvedValue({ directory: tmp.extra.mod, entrypoint: tmp.extra.mod })
try {
await TuiPluginRuntime.init(createTuiPluginApi())
await TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
// plugin code never ran
await expect(fs.readFile(tmp.extra.marker, "utf8")).rejects.toThrow()
// plugin not listed
@ -193,7 +191,6 @@ test("rejects npm tui export that resolves outside plugin directory", async () =
await TuiPluginRuntime.dispose()
install.mockRestore()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}
@ -232,7 +229,7 @@ test("rejects npm tui plugin that exports server and tui together", async () =>
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [tmp.extra.spec],
plugin_origins: [
{
@ -241,20 +238,19 @@ test("rejects npm tui plugin that exports server and tui together", async () =>
source: path.join(tmp.path, "tui.json"),
},
],
})
}
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
const install = spyOn(Npm, "add").mockResolvedValue({ directory: tmp.extra.mod, entrypoint: tmp.extra.mod })
try {
await TuiPluginRuntime.init(createTuiPluginApi())
await TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
await expect(fs.readFile(tmp.extra.marker, "utf8")).rejects.toThrow()
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
}
@ -291,7 +287,7 @@ test("does not use npm package main for tui entry", async () => {
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [tmp.extra.spec],
plugin_origins: [
{
@ -300,7 +296,7 @@ test("does not use npm package main for tui entry", async () => {
source: path.join(tmp.path, "tui.json"),
},
],
})
}
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
const install = spyOn(Npm, "add").mockResolvedValue({ directory: tmp.extra.mod, entrypoint: tmp.extra.mod })
@ -308,7 +304,7 @@ test("does not use npm package main for tui entry", async () => {
const error = spyOn(console, "error").mockImplementation(() => {})
try {
await TuiPluginRuntime.init(createTuiPluginApi())
await TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
await expect(fs.readFile(tmp.extra.marker, "utf8")).rejects.toThrow()
expect(TuiPluginRuntime.list().some((item) => item.spec === tmp.extra.spec)).toBe(false)
expect(error).not.toHaveBeenCalled()
@ -317,7 +313,6 @@ test("does not use npm package main for tui entry", async () => {
await TuiPluginRuntime.dispose()
install.mockRestore()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
warn.mockRestore()
error.mockRestore()
@ -357,7 +352,7 @@ test("does not use directory package main for tui entry", async () => {
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [tmp.extra.spec],
plugin_origins: [
{
@ -366,18 +361,17 @@ test("does not use directory package main for tui entry", async () => {
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 TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
await expect(fs.readFile(tmp.extra.marker, "utf8")).rejects.toThrow()
expect(TuiPluginRuntime.list().some((item) => item.spec === tmp.extra.spec)).toBe(false)
} finally {
await TuiPluginRuntime.dispose()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}
@ -405,7 +399,7 @@ test("uses directory index fallback for tui when package.json is missing", async
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [tmp.extra.spec],
plugin_origins: [
{
@ -414,18 +408,17 @@ test("uses directory index fallback for tui when package.json is missing", async
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 TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
await expect(fs.readFile(tmp.extra.marker, "utf8")).resolves.toBe("called")
expect(TuiPluginRuntime.list().find((item) => item.id === "demo.dir.index")?.active).toBe(true)
} finally {
await TuiPluginRuntime.dispose()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}
@ -463,7 +456,7 @@ test("uses npm package name when tui plugin id is omitted", async () => {
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [[tmp.extra.spec, { marker: tmp.extra.marker }]],
plugin_origins: [
{
@ -472,20 +465,19 @@ test("uses npm package name when tui plugin id is omitted", async () => {
source: path.join(tmp.path, "tui.json"),
},
],
})
}
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
const install = spyOn(Npm, "add").mockResolvedValue({ directory: tmp.extra.mod, entrypoint: tmp.extra.mod })
try {
await TuiPluginRuntime.init(createTuiPluginApi())
await TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
await expect(fs.readFile(tmp.extra.marker, "utf8")).resolves.toBe("called")
expect(TuiPluginRuntime.list().find((item) => item.spec === tmp.extra.spec)?.id).toBe("acme-plugin")
} finally {
await TuiPluginRuntime.dispose()
install.mockRestore()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}

View file

@ -4,7 +4,7 @@ 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"
import { TuiConfig } from "../../../src/cli/cmd/tui/config/tui"
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
@ -37,7 +37,7 @@ test("skips external tui plugins in pure mode", async () => {
process.env.OPENCODE_PURE = "1"
process.env.OPENCODE_PLUGIN_META_FILE = tmp.extra.meta
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [[tmp.extra.spec, { marker: tmp.extra.marker }]],
plugin_origins: [
{
@ -46,17 +46,16 @@ test("skips external tui plugins in pure mode", async () => {
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 TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
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

View file

@ -5,9 +5,8 @@ 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"
import { TuiConfig } from "../../../src/cli/cmd/tui/config/tui"
import { Filesystem } from "../../../src/util/"
const { allThemes, addTheme } = await import("../../../src/cli/cmd/tui/context/theme")
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
@ -325,13 +324,59 @@ export default {
})
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({
const localOpts = {
fn_marker: tmp.extra.fnMarker,
marker: tmp.extra.localMarker,
source: tmp.extra.localDest.replace(".opencode/themes/", ""),
dest: tmp.extra.localDest,
theme_path: `./${tmp.extra.localThemeFile}`,
theme_name: tmp.extra.localThemeName,
kv_key: "plugin_state_key",
session_id: "ses_test",
keybinds: { modal: "ctrl+alt+m", close: "q" },
}
const invalidOpts = {
marker: tmp.extra.invalidMarker,
theme_path: `./${tmp.extra.invalidThemeFile}`,
theme_name: tmp.extra.invalidThemeName,
}
const preloadedOpts = {
marker: tmp.extra.preloadedMarker,
dest: tmp.extra.preloadedDest,
theme_path: `./${tmp.extra.preloadedThemeFile}`,
theme_name: tmp.extra.preloadedThemeName,
}
const globalOpts = {
marker: tmp.extra.globalMarker,
theme_path: `./${tmp.extra.globalThemeFile}`,
theme_name: tmp.extra.globalThemeName,
}
const config: TuiConfig.Info = {
plugin: [
[tmp.extra.localSpec, localOpts],
[tmp.extra.invalidSpec, invalidOpts],
[tmp.extra.preloadedSpec, preloadedOpts],
[tmp.extra.globalSpec, globalOpts],
],
plugin_origins: [
{ spec: [tmp.extra.localSpec, localOpts], scope: "local", source: path.join(tmp.path, "tui.json") },
{ spec: [tmp.extra.invalidSpec, invalidOpts], scope: "local", source: path.join(tmp.path, "tui.json") },
{ spec: [tmp.extra.preloadedSpec, preloadedOpts], scope: "local", source: path.join(tmp.path, "tui.json") },
{
spec: [tmp.extra.globalSpec, globalOpts],
scope: "global",
source: path.join(Global.Path.config, "tui.json"),
},
],
}
await TuiPluginRuntime.init({
api: createTuiPluginApi({
tuiConfig: {
theme: "smoke",
diff_style: "stacked",
@ -368,7 +413,8 @@ export default {
},
},
}),
)
config,
})
const local = await row(tmp.extra.localMarker)
const global = await row(tmp.extra.globalMarker)
const invalid = await row(tmp.extra.invalidMarker)
@ -407,7 +453,6 @@ export default {
await TuiPluginRuntime.dispose()
cwd.mockRestore()
wait.mockRestore()
install.mockRestore()
if (backup === undefined) {
await fs.rm(globalConfigPath, { force: true })
} else {
@ -462,7 +507,7 @@ test("continues loading when a plugin is missing config metadata", async () => {
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [
[tmp.extra.badSpec, { marker: path.join(tmp.path, "bad.txt") }],
[tmp.extra.goodSpec, { marker: tmp.extra.goodMarker }],
@ -480,12 +525,12 @@ test("continues loading when a plugin is missing config metadata", async () => {
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 TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
// bad plugin was skipped (no metadata entry)
await expect(fs.readFile(path.join(tmp.path, "bad.txt"), "utf8")).rejects.toThrow()
// good plugin loaded fine
@ -495,7 +540,6 @@ test("continues loading when a plugin is missing config metadata", async () => {
} finally {
await TuiPluginRuntime.dispose()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}
@ -558,7 +602,18 @@ export default {
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
try {
await TuiPluginRuntime.init(createTuiPluginApi())
const a = path.join(tmp.path, "order-a.ts")
const b = path.join(tmp.path, "order-b.ts")
const aSpec = pathToFileURL(a).href
const bSpec = pathToFileURL(b).href
const config: TuiConfig.Info = {
plugin: [aSpec, bSpec],
plugin_origins: [
{ spec: aSpec, scope: "local", source: path.join(tmp.path, "tui.json") },
{ spec: bSpec, scope: "local", source: path.join(tmp.path, "tui.json") },
],
}
await TuiPluginRuntime.init({ api: createTuiPluginApi(), config })
const lines = (await fs.readFile(tmp.extra.marker, "utf8")).trim().split("\n")
expect(lines).toEqual(["a-start", "a-end", "b"])
} finally {
@ -701,9 +756,8 @@ test("updates installed theme when plugin metadata changes", async () => {
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
const install = spyOn(Config, "installDependencies").mockResolvedValue()
const api = () =>
const mkApi = () =>
createTuiPluginApi({
theme: {
has(name) {
@ -712,8 +766,19 @@ test("updates installed theme when plugin metadata changes", async () => {
},
})
const mkConfig = (): TuiConfig.Info => ({
plugin: [[tmp.extra.spec, { theme_path: `./theme-update.json` }]],
plugin_origins: [
{
spec: [tmp.extra.spec, { theme_path: `./theme-update.json` }],
scope: "local",
source: path.join(tmp.path, "tui.json"),
},
],
})
try {
await TuiPluginRuntime.init(api())
await TuiPluginRuntime.init({ api: mkApi(), config: mkConfig() })
await TuiPluginRuntime.dispose()
await expect(fs.readFile(tmp.extra.dest, "utf8")).resolves.toContain("#111111")
@ -734,7 +799,7 @@ test("updates installed theme when plugin metadata changes", async () => {
await fs.utimes(tmp.extra.pluginPath, stamp, stamp)
await fs.utimes(tmp.extra.themePath, stamp, stamp)
await TuiPluginRuntime.init(api())
await TuiPluginRuntime.init({ api: mkApi(), config: mkConfig() })
const text = await fs.readFile(tmp.extra.dest, "utf8")
expect(text).toContain("#222222")
expect(text).not.toContain("#111111")
@ -746,7 +811,6 @@ test("updates installed theme when plugin metadata changes", async () => {
await TuiPluginRuntime.dispose()
cwd.mockRestore()
wait.mockRestore()
install.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}
})

View file

@ -4,7 +4,7 @@ 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"
import { TuiConfig } from "../../../src/cli/cmd/tui/config/tui"
const { TuiPluginRuntime } = await import("../../../src/cli/cmd/tui/plugin/runtime")
@ -39,7 +39,7 @@ test("toggles plugin runtime state by exported id", async () => {
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [[tmp.extra.spec, { marker: tmp.extra.marker }]],
plugin_enabled: {
"demo.toggle": false,
@ -51,13 +51,13 @@ test("toggles plugin runtime state by exported id", async () => {
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 TuiPluginRuntime.init({ api, config })
await expect(fs.readFile(tmp.extra.marker, "utf8")).rejects.toThrow()
expect(TuiPluginRuntime.list().find((item) => item.id === "demo.toggle")).toEqual({
@ -85,7 +85,6 @@ test("toggles plugin runtime state by exported id", async () => {
} finally {
await TuiPluginRuntime.dispose()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}
@ -117,7 +116,7 @@ test("kv plugin_enabled overrides tui config on startup", async () => {
})
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "plugin-meta.json")
const get = spyOn(TuiConfig, "get").mockResolvedValue({
const config: TuiConfig.Info = {
plugin: [[tmp.extra.spec, { marker: tmp.extra.marker }]],
plugin_enabled: {
"demo.startup": false,
@ -129,7 +128,7 @@ test("kv plugin_enabled overrides tui config on startup", async () => {
source: path.join(tmp.path, "tui.json"),
},
],
})
}
const wait = spyOn(TuiConfig, "waitForDependencies").mockResolvedValue()
const cwd = spyOn(process, "cwd").mockImplementation(() => tmp.path)
const api = createTuiPluginApi()
@ -138,7 +137,7 @@ test("kv plugin_enabled overrides tui config on startup", async () => {
})
try {
await TuiPluginRuntime.init(api)
await TuiPluginRuntime.init({ api, config })
await expect(fs.readFile(tmp.extra.marker, "utf8")).resolves.toBe("on")
expect(TuiPluginRuntime.list().find((item) => item.id === "demo.startup")).toEqual({
@ -152,7 +151,6 @@ test("kv plugin_enabled overrides tui config on startup", async () => {
} finally {
await TuiPluginRuntime.dispose()
cwd.mockRestore()
get.mockRestore()
wait.mockRestore()
delete process.env.OPENCODE_PLUGIN_META_FILE
}

View file

@ -0,0 +1,292 @@
/** @jsxImportSource @opentui/solid */
import { afterEach, describe, expect, test } from "bun:test"
import { testRender } from "@opentui/solid"
import { onMount } from "solid-js"
import { ArgsProvider } from "../../../src/cli/cmd/tui/context/args"
import { ExitProvider } from "../../../src/cli/cmd/tui/context/exit"
import { ProjectProvider, useProject } from "../../../src/cli/cmd/tui/context/project"
import { SDKProvider } from "../../../src/cli/cmd/tui/context/sdk"
import { SyncProvider, useSync } from "../../../src/cli/cmd/tui/context/sync"
const sighup = new Set(process.listeners("SIGHUP"))
afterEach(() => {
for (const fn of process.listeners("SIGHUP")) {
if (!sighup.has(fn)) process.off("SIGHUP", fn)
}
})
function json(data: unknown) {
return new Response(JSON.stringify(data), {
headers: {
"content-type": "application/json",
},
})
}
async function wait(fn: () => boolean, timeout = 2000) {
const start = Date.now()
while (!fn()) {
if (Date.now() - start > timeout) throw new Error("timed out waiting for condition")
await Bun.sleep(10)
}
}
function data(workspace?: string | null) {
const tag = workspace ?? "root"
return {
session: {
id: "ses_1",
title: `session-${tag}`,
workspaceID: workspace ?? undefined,
time: {
updated: 1,
},
},
message: {
info: {
id: "msg_1",
sessionID: "ses_1",
role: "assistant",
time: {
created: 1,
completed: 1,
},
},
parts: [
{
id: "part_1",
messageID: "msg_1",
sessionID: "ses_1",
type: "text",
text: `part-${tag}`,
},
],
},
todo: [
{
id: `todo-${tag}`,
content: `todo-${tag}`,
status: "pending",
priority: "medium",
},
],
diff: [
{
file: `${tag}.ts`,
patch: "",
additions: 0,
deletions: 0,
},
],
}
}
type Hit = {
path: string
workspace?: string
}
function createFetch(log: Hit[]) {
return Object.assign(
async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init)
const url = new URL(req.url)
const workspace = url.searchParams.get("workspace") ?? req.headers.get("x-opencode-workspace") ?? undefined
log.push({
path: url.pathname,
workspace,
})
if (url.pathname === "/config/providers") {
return json({ providers: [], default: {} })
}
if (url.pathname === "/provider") {
return json({ all: [], default: {}, connected: [] })
}
if (url.pathname === "/experimental/console") {
return json({})
}
if (url.pathname === "/agent") {
return json([])
}
if (url.pathname === "/config") {
return json({})
}
if (url.pathname === "/project/current") {
return json({ id: `proj-${workspace ?? "root"}` })
}
if (url.pathname === "/path") {
return json({
state: `/tmp/${workspace ?? "root"}/state`,
config: `/tmp/${workspace ?? "root"}/config`,
worktree: "/tmp/worktree",
directory: `/tmp/${workspace ?? "root"}`,
})
}
if (url.pathname === "/session") {
return json([])
}
if (url.pathname === "/command") {
return json([])
}
if (url.pathname === "/lsp") {
return json([])
}
if (url.pathname === "/mcp") {
return json({})
}
if (url.pathname === "/experimental/resource") {
return json({})
}
if (url.pathname === "/formatter") {
return json([])
}
if (url.pathname === "/session/status") {
return json({})
}
if (url.pathname === "/provider/auth") {
return json({})
}
if (url.pathname === "/vcs") {
return json({ branch: "main" })
}
if (url.pathname === "/experimental/workspace") {
return json([{ id: "ws_a" }, { id: "ws_b" }])
}
if (url.pathname === "/session/ses_1") {
return json(data(workspace).session)
}
if (url.pathname === "/session/ses_1/message") {
return json([data(workspace).message])
}
if (url.pathname === "/session/ses_1/todo") {
return json(data(workspace).todo)
}
if (url.pathname === "/session/ses_1/diff") {
return json(data(workspace).diff)
}
throw new Error(`unexpected request: ${req.method} ${url.pathname}`)
},
{ preconnect: fetch.preconnect.bind(fetch) },
) satisfies typeof fetch
}
async function mount(log: Hit[]) {
let project!: ReturnType<typeof useProject>
let sync!: ReturnType<typeof useSync>
let done!: () => void
const ready = new Promise<void>((resolve) => {
done = resolve
})
const app = await testRender(() => (
<SDKProvider
url="http://test"
directory="/tmp/root"
fetch={createFetch(log)}
events={{ subscribe: async () => () => {} }}
>
<ArgsProvider continue={false}>
<ExitProvider>
<ProjectProvider>
<SyncProvider>
<Probe
onReady={(ctx) => {
project = ctx.project
sync = ctx.sync
done()
}}
/>
</SyncProvider>
</ProjectProvider>
</ExitProvider>
</ArgsProvider>
</SDKProvider>
))
await ready
return { app, project, sync }
}
async function waitBoot(log: Hit[], workspace?: string) {
await wait(() => log.some((item) => item.path === "/experimental/workspace"))
if (!workspace) return
await wait(() => log.some((item) => item.path === "/project/current" && item.workspace === workspace))
}
function Probe(props: {
onReady: (ctx: { project: ReturnType<typeof useProject>; sync: ReturnType<typeof useSync> }) => void
}) {
const project = useProject()
const sync = useSync()
onMount(() => {
props.onReady({ project, sync })
})
return <box />
}
describe("SyncProvider", () => {
test("re-runs bootstrap requests when the active workspace changes", async () => {
const log: Hit[] = []
const { app, project } = await mount(log)
try {
await waitBoot(log)
log.length = 0
project.workspace.set("ws_a")
await waitBoot(log, "ws_a")
expect(log.some((item) => item.path === "/path" && item.workspace === "ws_a")).toBe(true)
expect(log.some((item) => item.path === "/config" && item.workspace === "ws_a")).toBe(true)
expect(log.some((item) => item.path === "/command" && item.workspace === "ws_a")).toBe(true)
} finally {
app.renderer.destroy()
}
})
test("clears full-sync cache when the active workspace changes", async () => {
const log: Hit[] = []
const { app, project, sync } = await mount(log)
try {
await waitBoot(log)
log.length = 0
project.workspace.set("ws_a")
await waitBoot(log, "ws_a")
expect(project.workspace.current()).toBe("ws_a")
log.length = 0
await sync.session.sync("ses_1")
expect(log.filter((item) => item.path === "/session/ses_1" && item.workspace === "ws_a")).toHaveLength(1)
expect(sync.data.todo.ses_1[0]?.content).toBe("todo-ws_a")
expect(sync.data.message.ses_1[0]?.id).toBe("msg_1")
expect(sync.data.part.msg_1[0]).toMatchObject({ type: "text", text: "part-ws_a" })
expect(sync.data.session_diff.ses_1[0]?.file).toBe("ws_a.ts")
log.length = 0
project.workspace.set("ws_b")
await waitBoot(log, "ws_b")
expect(project.workspace.current()).toBe("ws_b")
log.length = 0
await sync.session.sync("ses_1")
await wait(() => log.some((item) => item.path === "/session/ses_1" && item.workspace === "ws_b"))
expect(log.filter((item) => item.path === "/session/ses_1" && item.workspace === "ws_b")).toHaveLength(1)
expect(sync.data.todo.ses_1[0]?.content).toBe("todo-ws_b")
expect(sync.data.message.ses_1[0]?.id).toBe("msg_1")
expect(sync.data.part.msg_1[0]).toMatchObject({ type: "text", text: "part-ws_b" })
expect(sync.data.session_diff.ses_1[0]?.file).toBe("ws_b.ts")
} finally {
app.renderer.destroy()
}
})
})

View file

@ -41,7 +41,7 @@ test("hasTheme checks theme presence", () => {
test("resolveTheme rejects circular color refs", () => {
const item = structuredClone(DEFAULT_THEMES.opencode)
item.defs = {
...(item.defs ?? {}),
...item.defs,
one: "two",
two: "one",
}

View file

@ -3,18 +3,16 @@ import fs from "fs/promises"
import path from "path"
import { tmpdir } from "../../fixture/fixture"
import * as App from "../../../src/cli/cmd/tui/app"
import { Rpc } from "../../../src/util/rpc"
import { Rpc } from "../../../src/util"
import { UI } from "../../../src/cli/ui"
import * as Timeout from "../../../src/util/timeout"
import * as Network from "../../../src/cli/network"
import * as Win32 from "../../../src/cli/cmd/tui/win32"
import { TuiConfig } from "../../../src/config/tui"
import { Instance } from "../../../src/project/instance"
import { TuiConfig } from "../../../src/cli/cmd/tui/config/tui"
const stop = new Error("stop")
const seen = {
tui: [] as string[],
inst: [] as string[],
}
function setup() {
@ -42,11 +40,6 @@ function setup() {
})
spyOn(Win32, "win32DisableProcessedInput").mockImplementation(() => {})
spyOn(Win32, "win32InstallCtrlCGuard").mockReturnValue(undefined)
spyOn(TuiConfig, "get").mockResolvedValue({})
spyOn(Instance, "provide").mockImplementation(async (input) => {
seen.inst.push(input.directory)
return input.fn()
})
}
describe("tui thread", () => {
@ -86,7 +79,6 @@ describe("tui thread", () => {
const link = path.join(path.dirname(tmp.path), path.basename(tmp.path) + "-link")
const type = process.platform === "win32" ? "junction" : "dir"
seen.tui.length = 0
seen.inst.length = 0
await fs.symlink(tmp.path, link, type)
Object.defineProperty(process.stdin, "isTTY", {
@ -105,7 +97,6 @@ describe("tui thread", () => {
process.chdir(tmp.path)
process.env.PWD = link
await expect(call(project)).rejects.toBe(stop)
expect(seen.inst[0]).toBe(tmp.path)
expect(seen.tui[0]).toBe(tmp.path)
} finally {
process.chdir(cwd)

View file

@ -0,0 +1,175 @@
/** @jsxImportSource @opentui/solid */
import { describe, expect, test } from "bun:test"
import { testRender } from "@opentui/solid"
import type { Event, GlobalEvent } from "@opencode-ai/sdk/v2"
import { onMount } from "solid-js"
import { ProjectProvider, useProject } from "../../../src/cli/cmd/tui/context/project"
import { SDKProvider } from "../../../src/cli/cmd/tui/context/sdk"
import { useEvent } from "../../../src/cli/cmd/tui/context/event"
async function wait(fn: () => boolean, timeout = 2000) {
const start = Date.now()
while (!fn()) {
if (Date.now() - start > timeout) throw new Error("timed out waiting for condition")
await Bun.sleep(10)
}
}
function event(payload: Event, input: { directory: string; workspace?: string }): GlobalEvent {
return {
directory: input.directory,
workspace: input.workspace,
payload,
}
}
function vcs(branch: string): Event {
return {
type: "vcs.branch.updated",
properties: {
branch,
},
}
}
function update(version: string): Event {
return {
type: "installation.update-available",
properties: {
version,
},
}
}
function createSource() {
let fn: ((event: GlobalEvent) => void) | undefined
return {
source: {
subscribe: async (handler: (event: GlobalEvent) => void) => {
fn = handler
return () => {
if (fn === handler) fn = undefined
}
},
},
emit(evt: GlobalEvent) {
if (!fn) throw new Error("event source not ready")
fn(evt)
},
}
}
async function mount() {
const source = createSource()
const seen: Event[] = []
let project!: ReturnType<typeof useProject>
let done!: () => void
const ready = new Promise<void>((resolve) => {
done = resolve
})
const app = await testRender(() => (
<SDKProvider url="http://test" directory="/tmp/root" events={source.source}>
<ProjectProvider>
<Probe
onReady={(ctx) => {
project = ctx.project
done()
}}
seen={seen}
/>
</ProjectProvider>
</SDKProvider>
))
await ready
return { app, emit: source.emit, project, seen }
}
function Probe(props: { seen: Event[]; onReady: (ctx: { project: ReturnType<typeof useProject> }) => void }) {
const project = useProject()
const event = useEvent()
onMount(() => {
event.subscribe((evt) => {
props.seen.push(evt)
})
props.onReady({ project })
})
return <box />
}
describe("useEvent", () => {
test("delivers matching directory events without an active workspace", async () => {
const { app, emit, seen } = await mount()
try {
emit(event(vcs("main"), { directory: "/tmp/root" }))
await wait(() => seen.length === 1)
expect(seen).toEqual([vcs("main")])
} finally {
app.renderer.destroy()
}
})
test("ignores non-matching directory events without an active workspace", async () => {
const { app, emit, seen } = await mount()
try {
emit(event(vcs("other"), { directory: "/tmp/other" }))
await Bun.sleep(30)
expect(seen).toHaveLength(0)
} finally {
app.renderer.destroy()
}
})
test("delivers matching workspace events when a workspace is active", async () => {
const { app, emit, project, seen } = await mount()
try {
project.workspace.set("ws_a")
emit(event(vcs("ws"), { directory: "/tmp/other", workspace: "ws_a" }))
await wait(() => seen.length === 1)
expect(seen).toEqual([vcs("ws")])
} finally {
app.renderer.destroy()
}
})
test("ignores non-matching workspace events when a workspace is active", async () => {
const { app, emit, project, seen } = await mount()
try {
project.workspace.set("ws_a")
emit(event(vcs("ws"), { directory: "/tmp/root", workspace: "ws_b" }))
await Bun.sleep(30)
expect(seen).toHaveLength(0)
} finally {
app.renderer.destroy()
}
})
test("delivers truly global events even when a workspace is active", async () => {
const { app, emit, project, seen } = await mount()
try {
project.workspace.set("ws_a")
emit(event(update("1.2.3"), { directory: "global" }))
await wait(() => seen.length === 1)
expect(seen).toEqual([update("1.2.3")])
} finally {
app.renderer.destroy()
}
})
})

View file

@ -1,10 +1,16 @@
import { test, expect } from "bun:test"
import { Effect } from "effect"
import path from "path"
import { tmpdir } from "../fixture/fixture"
import { provideInstance, tmpdir } from "../fixture/fixture"
import { Instance } from "../../src/project/instance"
import { Config } from "../../src/config/config"
import { Config } from "../../src/config"
import { Agent as AgentSvc } from "../../src/agent/agent"
import { Color } from "../../src/util/color"
import { Color } from "../../src/util"
import { AppRuntime } from "../../src/effect/app-runtime"
const load = () => AppRuntime.runPromise(Config.Service.use((svc) => svc.get()))
const agent = <A>(dir: string, fn: (svc: AgentSvc.Interface) => Effect.Effect<A>) =>
Effect.runPromise(provideInstance(dir)(AgentSvc.Service.use(fn)).pipe(Effect.provide(AgentSvc.defaultLayer)))
test("agent color parsed from project config", async () => {
await using tmp = await tmpdir({
@ -24,7 +30,7 @@ test("agent color parsed from project config", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const cfg = await Config.get()
const cfg = await load()
expect(cfg.agent?.["build"]?.color).toBe("#FFA500")
expect(cfg.agent?.["plan"]?.color).toBe("primary")
},
@ -49,9 +55,9 @@ test("Agent.get includes color from config", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const plan = await AgentSvc.get("plan")
const plan = await agent(tmp.path, (svc) => svc.get("plan"))
expect(plan?.color).toBe("#A855F7")
const build = await AgentSvc.get("build")
const build = await agent(tmp.path, (svc) => svc.get("build"))
expect(build?.color).toBe("accent")
},
})

View file

@ -1,14 +1,18 @@
import { test, expect, describe, mock, afterEach, beforeEach, spyOn } from "bun:test"
import { Effect, Layer, Option } from "effect"
import { Deferred, Effect, Fiber, Layer, Option } from "effect"
import { NodeFileSystem, NodePath } from "@effect/platform-node"
import { Config } from "../../src/config/config"
import { Config } from "../../src/config"
import { EffectFlock } from "@opencode-ai/shared/util/effect-flock"
import { Instance } from "../../src/project/instance"
import { Auth } from "../../src/auth"
import { AccessToken, Account, AccountID, OrgID } from "../../src/account"
import { AppFileSystem } from "../../src/filesystem"
import { AppFileSystem } from "@opencode-ai/shared/filesystem"
import { Env } from "../../src/env"
import { provideTmpdirInstance } from "../fixture/fixture"
import { tmpdir } from "../fixture/fixture"
import { tmpdir, tmpdirScoped } from "../fixture/fixture"
import * as CrossSpawnSpawner from "../../src/effect/cross-spawn-spawner"
import { testEffect } from "../lib/effect"
/** Infra layer that provides FileSystem, Path, ChildProcessSpawner for test fixtures */
const infra = CrossSpawnSpawner.defaultLayer.pipe(
@ -19,9 +23,10 @@ import fs from "fs/promises"
import { pathToFileURL } from "url"
import { Global } from "../../src/global"
import { ProjectID } from "../../src/project/schema"
import { Filesystem } from "../../src/util/filesystem"
import { Filesystem } from "../../src/util"
import * as Network from "../../src/util/network"
import { Npm } from "../../src/npm"
import { ConfigPlugin } from "@/config/plugin"
import { Npm } from "@opencode-ai/shared/npm"
const emptyAccount = Layer.mock(Account.Service)({
active: () => Effect.succeed(Option.none()),
@ -32,16 +37,40 @@ const emptyAuth = Layer.mock(Auth.Service)({
all: () => Effect.succeed({}),
})
const testFlock = EffectFlock.defaultLayer
const layer = Config.layer.pipe(
Layer.provide(testFlock),
Layer.provide(AppFileSystem.defaultLayer),
Layer.provide(Env.defaultLayer),
Layer.provide(emptyAuth),
Layer.provide(emptyAccount),
Layer.provideMerge(infra),
Layer.provide(Npm.defaultLayer),
)
const it = testEffect(layer)
const load = () => Effect.runPromise(Config.Service.use((svc) => svc.get()).pipe(Effect.scoped, Effect.provide(layer)))
const save = (config: Config.Info) =>
Effect.runPromise(Config.Service.use((svc) => svc.update(config)).pipe(Effect.scoped, Effect.provide(layer)))
const clear = (wait = false) =>
Effect.runPromise(Config.Service.use((svc) => svc.invalidate(wait)).pipe(Effect.scoped, Effect.provide(layer)))
const listDirs = () =>
Effect.runPromise(Config.Service.use((svc) => svc.directories()).pipe(Effect.scoped, Effect.provide(layer)))
const ready = () =>
Effect.runPromise(Config.Service.use((svc) => svc.waitForDependencies()).pipe(Effect.scoped, Effect.provide(layer)))
// Get managed config directory from environment (set in preload.ts)
const managedConfigDir = process.env.OPENCODE_TEST_MANAGED_CONFIG_DIR!
beforeEach(async () => {
await Config.invalidate(true)
await clear(true)
})
afterEach(async () => {
await fs.rm(managedConfigDir, { force: true, recursive: true }).catch(() => {})
await Config.invalidate(true)
await clear(true)
})
async function writeManagedSettings(settings: object, filename = "opencode.json") {
@ -59,7 +88,7 @@ async function check(map: (dir: string) => string) {
await using tmp = await tmpdir({ git: true, config: { snapshot: true } })
const prev = Global.Path.config
;(Global.Path as { config: string }).config = globalTmp.path
await Config.invalidate()
await clear()
try {
await writeConfig(globalTmp.path, {
$schema: "https://opencode.ai/config.json",
@ -68,7 +97,7 @@ async function check(map: (dir: string) => string) {
await Instance.provide({
directory: map(tmp.path),
fn: async () => {
const cfg = await Config.get()
const cfg = await load()
expect(cfg.snapshot).toBe(true)
expect(Instance.directory).toBe(Filesystem.resolve(tmp.path))
expect(Instance.project.id).not.toBe(ProjectID.global)
@ -77,7 +106,7 @@ async function check(map: (dir: string) => string) {
} finally {
await Instance.disposeAll()
;(Global.Path as { config: string }).config = prev
await Config.invalidate()
await clear()
}
}
@ -86,7 +115,7 @@ test("loads config with defaults when no files exist", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.username).toBeDefined()
},
})
@ -105,7 +134,7 @@ test("loads JSON config file", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.model).toBe("test/model")
expect(config.username).toBe("testuser")
},
@ -143,7 +172,7 @@ test("ignores legacy tui keys in opencode config", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.model).toBe("test/model")
expect((config as Record<string, unknown>).theme).toBeUndefined()
expect((config as Record<string, unknown>).tui).toBeUndefined()
@ -168,7 +197,7 @@ test("loads JSONC config file", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.model).toBe("test/model")
expect(config.username).toBe("testuser")
},
@ -196,7 +225,7 @@ test("jsonc overrides json in the same directory", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.model).toBe("base")
expect(config.username).toBe("base")
},
@ -219,7 +248,7 @@ test("handles environment variable substitution", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.username).toBe("test-user")
},
})
@ -251,7 +280,7 @@ test("preserves env variables when adding $schema to config", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.username).toBe("secret_value")
// Read the file to verify the env variable was preserved
@ -308,7 +337,9 @@ test("resolves env templates in account config with account token", async () =>
})
const layer = Config.layer.pipe(
Layer.provide(testFlock),
Layer.provide(AppFileSystem.defaultLayer),
Layer.provide(Env.defaultLayer),
Layer.provide(emptyAuth),
Layer.provide(fakeAccount),
Layer.provideMerge(infra),
@ -322,7 +353,7 @@ test("resolves env templates in account config with account token", async () =>
expect(config.provider?.["opencode"]?.options?.apiKey).toBe("st_test_token")
}),
),
).pipe(Effect.scoped, Effect.provide(layer), Effect.runPromise)
).pipe(Effect.scoped, Effect.provide(layer), Effect.provide(Npm.defaultLayer), Effect.runPromise)
} finally {
if (originalControlToken !== undefined) {
process.env["OPENCODE_CONSOLE_TOKEN"] = originalControlToken
@ -345,7 +376,7 @@ test("handles file inclusion substitution", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.username).toBe("test-user")
},
})
@ -364,7 +395,7 @@ test("handles file inclusion with replacement tokens", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.username).toBe("const out = await Bun.$`echo hi`")
},
})
@ -383,7 +414,7 @@ test("validates config schema and throws on invalid fields", async () => {
directory: tmp.path,
fn: async () => {
// Strict schema should throw an error for invalid fields
await expect(Config.get()).rejects.toThrow()
await expect(load()).rejects.toThrow()
},
})
})
@ -397,7 +428,7 @@ test("throws error for invalid JSON", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
await expect(Config.get()).rejects.toThrow()
await expect(load()).rejects.toThrow()
},
})
})
@ -420,7 +451,7 @@ test("handles agent configuration", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["test_agent"]).toEqual(
expect.objectContaining({
model: "test/model",
@ -451,7 +482,7 @@ test("treats agent variant as model-scoped setting (not provider option)", async
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
const agent = config.agent?.["test_agent"]
expect(agent?.variant).toBe("xhigh")
@ -481,7 +512,7 @@ test("handles command configuration", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.command?.["test_command"]).toEqual({
template: "test template",
description: "test command",
@ -506,7 +537,7 @@ test("migrates autoshare to share field", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.share).toBe("auto")
expect(config.autoshare).toBe(true)
},
@ -533,7 +564,7 @@ test("migrates mode field to agent field", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["test_mode"]).toEqual({
model: "test/model",
temperature: 0.5,
@ -565,7 +596,7 @@ Test agent prompt`,
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["test"]).toEqual(
expect.objectContaining({
name: "test",
@ -609,7 +640,7 @@ Nested agent prompt`,
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["helper"]).toMatchObject({
name: "helper",
@ -658,7 +689,7 @@ Nested command template`,
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.command?.["hello"]).toEqual({
description: "Test command",
@ -703,7 +734,7 @@ Nested command template`,
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.command?.["hello"]).toEqual({
description: "Test command",
@ -724,7 +755,7 @@ test("updates config and writes to file", async () => {
directory: tmp.path,
fn: async () => {
const newConfig = { model: "updated/model" }
await Config.update(newConfig as any)
await save(newConfig as any)
const writtenConfig = await Filesystem.readJson(path.join(tmp.path, "config.json"))
expect(writtenConfig.model).toBe("updated/model")
@ -737,7 +768,7 @@ test("gets config directories", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const dirs = await Config.directories()
const dirs = await listDirs()
expect(dirs.length).toBeGreaterThanOrEqual(1)
},
})
@ -767,7 +798,7 @@ test("does not try to install dependencies in read-only OPENCODE_CONFIG_DIR", as
await Instance.provide({
directory: tmp.path,
fn: async () => {
await Config.get()
await load()
},
})
} finally {
@ -787,158 +818,45 @@ 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 install = spyOn(Npm, "install").mockImplementation(async (dir: string) => {
const mod = path.join(dir, "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" }),
)
const noopNpm = Layer.mock(Npm.Service)({
install: () => Effect.void,
add: () => Effect.die("not implemented"),
outdated: () => Effect.succeed(false),
which: () => Effect.succeed(Option.none()),
})
const testLayer = Config.layer.pipe(
Layer.provide(testFlock),
Layer.provide(AppFileSystem.defaultLayer),
Layer.provide(Env.defaultLayer),
Layer.provide(emptyAuth),
Layer.provide(emptyAccount),
Layer.provideMerge(infra),
Layer.provide(noopNpm),
)
try {
await Instance.provide({
directory: tmp.path,
fn: async () => {
await Config.get()
await Config.waitForDependencies()
await Effect.runPromise(Config.Service.use((svc) => svc.get()).pipe(Effect.scoped, Effect.provide(testLayer)))
await Effect.runPromise(
Config.Service.use((svc) => svc.waitForDependencies()).pipe(Effect.scoped, Effect.provide(testLayer)),
)
},
})
expect(await Filesystem.exists(path.join(tmp.extra, "package.json"))).toBe(true)
expect(await Filesystem.exists(path.join(tmp.extra, ".gitignore"))).toBe(true)
expect(await Filesystem.readText(path.join(tmp.extra, ".gitignore"))).toContain("package-lock.json")
} finally {
online.mockRestore()
install.mockRestore()
if (prev === undefined) delete process.env.OPENCODE_CONFIG_DIR
else process.env.OPENCODE_CONFIG_DIR = prev
}
})
test("dedupes concurrent config dependency installs for the same dir", async () => {
await using tmp = await tmpdir()
const dir = path.join(tmp.path, "a")
await fs.mkdir(dir, { recursive: true })
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 targetDir = dir
const run = spyOn(Npm, "install").mockImplementation(async (d: string) => {
const hit = path.normalize(d) === path.normalize(targetDir)
if (hit) {
calls += 1
start()
await gate
}
const mod = path.join(d, "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" }),
)
if (hit) {
start()
await gate
}
})
try {
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(calls).toBe(2)
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(Npm, "install").mockImplementation(async (dir: string) => {
const cwd = path.normalize(dir)
const hit = cwd === path.normalize(a) || cwd === path.normalize(b)
if (hit) {
calls += 1
open += 1
peak = Math.max(peak, open)
if (calls === 1) {
start()
await gate
}
}
const mod = path.join(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" }),
)
if (hit) {
open -= 1
}
})
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)
})
// Note: deduplication and serialization of npm installs is now handled by the
// shared Npm.Service (via EffectFlock). Those behaviors are tested in the shared
// package's npm tests, not here.
test("resolves scoped npm plugins in config", async () => {
await using tmp = await tmpdir({
@ -977,7 +895,7 @@ test("resolves scoped npm plugins in config", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
const pluginEntries = config.plugin ?? []
expect(pluginEntries).toContain("@scope/plugin")
},
@ -1015,7 +933,7 @@ test("merges plugin arrays from global and local configs", async () => {
await Instance.provide({
directory: path.join(tmp.path, "project"),
fn: async () => {
const config = await Config.get()
const config = await load()
const plugins = config.plugin ?? []
// Should contain both global and local plugins
@ -1051,7 +969,7 @@ Helper subagent prompt`,
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["helper"]).toMatchObject({
name: "helper",
model: "test/model",
@ -1090,7 +1008,7 @@ test("merges instructions arrays from global and local configs", async () => {
await Instance.provide({
directory: path.join(tmp.path, "project"),
fn: async () => {
const config = await Config.get()
const config = await load()
const instructions = config.instructions ?? []
expect(instructions).toContain("global-instructions.md")
@ -1129,7 +1047,7 @@ test("deduplicates duplicate instructions from global and local configs", async
await Instance.provide({
directory: path.join(tmp.path, "project"),
fn: async () => {
const config = await Config.get()
const config = await load()
const instructions = config.instructions ?? []
expect(instructions).toContain("global-only.md")
@ -1174,7 +1092,7 @@ test("deduplicates duplicate plugins from global and local configs", async () =>
await Instance.provide({
directory: path.join(tmp.path, "project"),
fn: async () => {
const config = await Config.get()
const config = await load()
const plugins = config.plugin ?? []
// Should contain all unique plugins
@ -1223,10 +1141,10 @@ test("keeps plugin origins aligned with merged plugin list", async () => {
await Instance.provide({
directory: path.join(tmp.path, "project"),
fn: async () => {
const cfg = await Config.get()
const cfg = await load()
const plugins = cfg.plugin ?? []
const origins = cfg.plugin_origins ?? []
const names = plugins.map((item) => Config.pluginSpecifier(item))
const names = plugins.map((item) => ConfigPlugin.pluginSpecifier(item))
expect(names).toContain("shared-plugin@2.0.0")
expect(names).not.toContain("shared-plugin@1.0.0")
@ -1234,7 +1152,7 @@ test("keeps plugin origins aligned with merged plugin list", async () => {
expect(names).toContain("local-only@1.0.0")
expect(origins.map((item) => item.spec)).toEqual(plugins)
const hit = origins.find((item) => Config.pluginSpecifier(item.spec) === "shared-plugin@2.0.0")
const hit = origins.find((item) => ConfigPlugin.pluginSpecifier(item.spec) === "shared-plugin@2.0.0")
expect(hit?.scope).toBe("local")
},
})
@ -1264,7 +1182,7 @@ test("migrates legacy tools config to permissions - allow", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["test"]?.permission).toEqual({
bash: "allow",
read: "allow",
@ -1295,7 +1213,7 @@ test("migrates legacy tools config to permissions - deny", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["test"]?.permission).toEqual({
bash: "deny",
webfetch: "deny",
@ -1325,7 +1243,7 @@ test("migrates legacy write tool to edit permission", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["test"]?.permission).toEqual({
edit: "allow",
})
@ -1357,7 +1275,7 @@ test("managed settings override user settings", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.model).toBe("managed/model")
expect(config.share).toBe("disabled")
expect(config.username).toBe("testuser")
@ -1385,7 +1303,7 @@ test("managed settings override project settings", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.autoupdate).toBe(false)
expect(config.disabled_providers).toEqual(["openai"])
},
@ -1405,7 +1323,7 @@ test("missing managed settings file is not an error", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.model).toBe("user/model")
},
})
@ -1432,7 +1350,7 @@ test("migrates legacy edit tool to edit permission", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["test"]?.permission).toEqual({
edit: "deny",
})
@ -1461,7 +1379,7 @@ test("migrates legacy patch tool to edit permission", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["test"]?.permission).toEqual({
edit: "allow",
})
@ -1490,7 +1408,7 @@ test("migrates legacy multiedit tool to edit permission", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["test"]?.permission).toEqual({
edit: "deny",
})
@ -1522,7 +1440,7 @@ test("migrates mixed legacy tools config", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["test"]?.permission).toEqual({
bash: "allow",
edit: "allow",
@ -1557,7 +1475,7 @@ test("merges legacy tools with existing permission config", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.agent?.["test"]?.permission).toEqual({
glob: "allow",
bash: "allow",
@ -1592,7 +1510,7 @@ test("permission config preserves key order", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(Object.keys(config.permission!)).toEqual([
"*",
"edit",
@ -1652,7 +1570,7 @@ test("project config can override MCP server enabled status", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
// jira should be enabled (overridden by project config)
expect(config.mcp?.jira).toEqual({
type: "remote",
@ -1708,7 +1626,7 @@ test("MCP config deep merges preserving base config properties", async () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.mcp?.myserver).toEqual({
type: "remote",
url: "https://myserver.example.com/mcp",
@ -1759,7 +1677,7 @@ test("local .opencode config can override MCP from project config", async () =>
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.mcp?.docs?.enabled).toBe(true)
},
})
@ -1769,7 +1687,7 @@ test("project config overrides remote well-known config", async () => {
const originalFetch = globalThis.fetch
let fetchedUrl: string | undefined
globalThis.fetch = mock((url: string | URL | Request) => {
const urlStr = url.toString()
const urlStr = url instanceof Request ? url.url : url instanceof URL ? url.href : url
if (urlStr.includes(".well-known/opencode")) {
fetchedUrl = urlStr
return Promise.resolve(
@ -1794,10 +1712,13 @@ test("project config overrides remote well-known config", async () => {
})
const layer = Config.layer.pipe(
Layer.provide(testFlock),
Layer.provide(AppFileSystem.defaultLayer),
Layer.provide(Env.defaultLayer),
Layer.provide(fakeAuth),
Layer.provide(emptyAccount),
Layer.provideMerge(infra),
Layer.provide(Npm.defaultLayer),
)
try {
@ -1824,7 +1745,7 @@ test("wellknown URL with trailing slash is normalized", async () => {
const originalFetch = globalThis.fetch
let fetchedUrl: string | undefined
globalThis.fetch = mock((url: string | URL | Request) => {
const urlStr = url.toString()
const urlStr = url instanceof Request ? url.url : url instanceof URL ? url.href : url
if (urlStr.includes(".well-known/opencode")) {
fetchedUrl = urlStr
return Promise.resolve(
@ -1849,10 +1770,13 @@ test("wellknown URL with trailing slash is normalized", async () => {
})
const layer = Config.layer.pipe(
Layer.provide(testFlock),
Layer.provide(AppFileSystem.defaultLayer),
Layer.provide(Env.defaultLayer),
Layer.provide(fakeAuth),
Layer.provide(emptyAccount),
Layer.provideMerge(infra),
Layer.provide(Npm.defaultLayer),
)
try {
@ -1875,8 +1799,8 @@ 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")
expect(await ConfigPlugin.resolvePluginSpec("oh-my-opencode@2.4.3", file)).toBe("oh-my-opencode@2.4.3")
expect(await ConfigPlugin.resolvePluginSpec("@scope/pkg", file)).toBe("@scope/pkg")
})
test("resolves windows-style relative plugin directory specs", async () => {
@ -1891,8 +1815,8 @@ describe("resolvePluginSpec", () => {
})
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)
const hit = await ConfigPlugin.resolvePluginSpec(".\\plugin", file)
expect(ConfigPlugin.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin", "index.ts")).href)
})
test("resolves relative file plugin paths to file urls", async () => {
@ -1903,8 +1827,8 @@ describe("resolvePluginSpec", () => {
})
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)
const hit = await ConfigPlugin.resolvePluginSpec("./plugin.ts", file)
expect(ConfigPlugin.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin.ts")).href)
})
test("resolves plugin directory paths to directory urls", async () => {
@ -1922,8 +1846,8 @@ describe("resolvePluginSpec", () => {
})
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")).href)
const hit = await ConfigPlugin.resolvePluginSpec("./plugin", file)
expect(ConfigPlugin.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin")).href)
})
test("resolves plugin directories without package.json to index.ts", async () => {
@ -2010,7 +1934,7 @@ describe("deduplicatePluginOrigins", () => {
await Instance.provide({
directory: path.join(tmp.path, "project"),
fn: async () => {
const config = await Config.get()
const config = await load()
const plugins = config.plugin ?? []
expect(plugins.some((p) => Config.pluginSpecifier(p) === "my-plugin@1.0.0")).toBe(true)
@ -2042,7 +1966,7 @@ describe("OPENCODE_DISABLE_PROJECT_CONFIG", () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
// Project config should NOT be loaded - model should be default, not "project/model"
expect(config.model).not.toBe("project/model")
expect(config.username).not.toBe("project-user")
@ -2073,7 +1997,7 @@ describe("OPENCODE_DISABLE_PROJECT_CONFIG", () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const directories = await Config.directories()
const directories = await listDirs()
// Project .opencode should NOT be in directories list
const hasProjectOpencode = directories.some((d) => d.startsWith(tmp.path))
expect(hasProjectOpencode).toBe(false)
@ -2098,7 +2022,7 @@ describe("OPENCODE_DISABLE_PROJECT_CONFIG", () => {
directory: tmp.path,
fn: async () => {
// Should still get default config (from global or defaults)
const config = await Config.get()
const config = await load()
expect(config).toBeDefined()
expect(config.username).toBeDefined()
},
@ -2141,7 +2065,7 @@ describe("OPENCODE_DISABLE_PROJECT_CONFIG", () => {
fn: async () => {
// The relative instruction should be skipped without error
// We're mainly verifying this doesn't throw and the config loads
const config = await Config.get()
const config = await load()
expect(config).toBeDefined()
// The instruction should have been skipped (warning logged)
// We can't easily test the warning was logged, but we verify
@ -2199,7 +2123,7 @@ describe("OPENCODE_DISABLE_PROJECT_CONFIG", () => {
await Instance.provide({
directory: projectTmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
// Should load from OPENCODE_CONFIG_DIR, not project
expect(config.model).toBe("configdir/model")
},
@ -2234,7 +2158,7 @@ describe("OPENCODE_CONFIG_CONTENT token substitution", () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.username).toBe("test_api_key_12345")
},
})
@ -2268,7 +2192,7 @@ describe("OPENCODE_CONFIG_CONTENT token substitution", () => {
await Instance.provide({
directory: tmp.path,
fn: async () => {
const config = await Config.get()
const config = await load()
expect(config.username).toBe("secret_key_from_file")
},
})

Some files were not shown because too many files have changed in this diff Show more