Open History to see the last commit
1import * as NodeAssert from "node:assert/strict";
2
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { it } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import { beforeEach } from "vite-plus/test";
11
12import { OpenCodeSettings } from "@t3tools/contracts";
13import { ServerConfig } from "../../config.ts";
14import {
15 OpenCodeRuntime,
16 OpenCodeRuntimeError,
17 type OpenCodeRuntimeShape,
18} from "../opencodeRuntime.ts";
19import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts";
20import type { OpenCodeInventory } from "../opencodeRuntime.ts";
21const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
22
23const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n";
24
25/**
26 * The legacy `OpenCodeProviderLive` Layer + `OpenCodeProvider` service tag
27 * are deleted. The snapshot-producing logic they wrapped now lives in the
28 * standalone `checkOpenCodeProviderStatus(settings, cwd)` Effect, which
29 * drivers call directly when building their per-instance snapshot
30 * `ServerProviderShape`. Tests mirror that shape: build a settings payload,
31 * invoke the check, assert on the returned snapshot.
32 */
33
34const runtimeMock = {
35 state: {
36 runVersionError: null as Error | null,
37 versionStdout: DEFAULT_VERSION_STDOUT,
38 inventoryError: null as Error | null,
39 inventoryCwd: null as string | null,
40 closeCalls: 0,
41 inventory: {
42 providerList: { connected: [] as string[], all: [] as unknown[], default: {} },
43 agents: [] as unknown[],
44 skills: [] as unknown[],
45 } as unknown,
46 },
47 reset() {
48 this.state.runVersionError = null;
49 this.state.versionStdout = DEFAULT_VERSION_STDOUT;
50 this.state.inventoryError = null;
51 this.state.inventoryCwd = null;
52 this.state.closeCalls = 0;
53 this.state.inventory = {
54 providerList: { connected: [], all: [] as unknown[], default: {} },
55 agents: [] as unknown[],
56 skills: [] as unknown[],
57 };
58 },
59};
60
61const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
62 startOpenCodeServerProcess: () =>
63 Effect.succeed({
64 url: "http://127.0.0.1:4301",
65 exitCode: Effect.never,
66 }),
67 connectToOpenCodeServer: ({ serverUrl }) =>
68 Effect.gen(function* () {
69 if (!serverUrl) {
70 yield* Effect.addFinalizer(() =>
71 Effect.sync(() => {
72 runtimeMock.state.closeCalls += 1;
73 }),
74 );
75 }
76 return {
77 url: serverUrl ?? "http://127.0.0.1:4301",
78 exitCode: null,
79 external: Boolean(serverUrl),
80 };
81 }),
82 runOpenCodeCommand: () =>
83 runtimeMock.state.runVersionError
84 ? Effect.fail(
85 new OpenCodeRuntimeError({
86 operation: "runOpenCodeCommand",
87 detail: runtimeMock.state.runVersionError.message,
88 cause: runtimeMock.state.runVersionError,
89 }),
90 )
91 : Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
92 createOpenCodeSdkClient: () =>
93 ({}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
94 loadOpenCodeInventory: () =>
95 runtimeMock.state.inventoryError
96 ? Effect.fail(
97 new OpenCodeRuntimeError({
98 operation: "loadOpenCodeInventory",
99 detail: runtimeMock.state.inventoryError.message,
100 cause: runtimeMock.state.inventoryError,
101 }),
102 )
103 : Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
104 loadInventoryFromCli: ({ cwd }) => {
105 runtimeMock.state.inventoryCwd = cwd;
106 return runtimeMock.state.inventoryError
107 ? Effect.fail(
108 new OpenCodeRuntimeError({
109 operation: "loadInventoryFromCli",
110 detail: runtimeMock.state.inventoryError.message,
111 cause: runtimeMock.state.inventoryError,
112 }),
113 )
114 : Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory);
115 },
116};
117
118beforeEach(() => {
119 runtimeMock.reset();
120});
121
122const testLayer = Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(
123 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
124 Layer.provideMerge(NodeServices.layer),
125);
126
127const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSettings =>
128 decodeOpenCodeSettings({
129 enabled: true,
130 binaryPath: "opencode",
131 serverUrl: "",
132 serverPassword: "",
133 customModels: [],
134 ...overrides,
135 });
136
137it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
138 it.effect("shows a codex-style missing binary message", () =>
139 Effect.gen(function* () {
140 runtimeMock.state.runVersionError = new Error("spawn opencode ENOENT");
141 const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
142
143 NodeAssert.equal(snapshot.status, "error");
144 NodeAssert.equal(snapshot.installed, false);
145 NodeAssert.equal(
146 snapshot.message,
147 "OpenCode CLI (`opencode`) is not installed or not on PATH.",
148 );
149 }),
150 );
151
152 it.effect("hides generic Effect.tryPromise text for local CLI probe failures", () =>
153 Effect.gen(function* () {
154 runtimeMock.state.runVersionError = new Error("An error occurred in Effect.tryPromise");
155 const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
156
157 NodeAssert.equal(snapshot.status, "error");
158 NodeAssert.equal(snapshot.installed, true);
159 NodeAssert.equal(snapshot.message, "Failed to execute OpenCode CLI health check.");
160 }),
161 );
162
163 it.effect("emits OpenCode variant defaults so trait picker can resolve a visible selection", () =>
164 Effect.gen(function* () {
165 runtimeMock.state.inventory = {
166 providerList: {
167 connected: ["openai"],
168 all: [
169 {
170 id: "openai",
171 name: "OpenAI",
172 models: {
173 "gpt-5.4": {
174 id: "gpt-5.4",
175 name: "GPT-5.4",
176 variants: {
177 none: {},
178 low: {},
179 medium: {},
180 high: {},
181 xhigh: {},
182 },
183 },
184 },
185 },
186 ],
187 default: {},
188 },
189 agents: [
190 { name: "build", hidden: false, mode: "primary" },
191 { name: "plan", hidden: false, mode: "primary" },
192 ],
193 };
194
195 const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
196 const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4");
197
198 NodeAssert.ok(model);
199 const variantDescriptor = model.capabilities?.optionDescriptors?.find(
200 (descriptor) => descriptor.id === "variant" && descriptor.type === "select",
201 );
202 NodeAssert.ok(variantDescriptor && variantDescriptor.type === "select");
203 NodeAssert.equal(
204 variantDescriptor.options.find((option) => option.isDefault === true)?.id,
205 "medium",
206 );
207 const agentDescriptor = model.capabilities?.optionDescriptors?.find(
208 (descriptor) => descriptor.id === "agent" && descriptor.type === "select",
209 );
210 NodeAssert.ok(agentDescriptor && agentDescriptor.type === "select");
211 NodeAssert.equal(
212 agentDescriptor.options.find((option) => option.isDefault === true)?.id,
213 "build",
214 );
215 }),
216 );
217
218 it.effect("includes OpenCode skills in the provider snapshot", () =>
219 Effect.gen(function* () {
220 runtimeMock.state.inventory = {
221 providerList: {
222 connected: ["openai"],
223 all: [
224 {
225 id: "openai",
226 name: "OpenAI",
227 models: {
228 "gpt-5.4": {
229 id: "gpt-5.4",
230 name: "GPT-5.4",
231 variants: {},
232 },
233 },
234 },
235 ],
236 default: {},
237 },
238 agents: [],
239 skills: [
240 {
241 name: "openclaw-review",
242 description: "Review OpenClaw workflow changes.",
243 location: "/Users/test/.agents/skills/openclaw-review/SKILL.md",
244 content: "---\nname: openclaw-review\n---\n",
245 },
246 {
247 name: "openclaw-triage",
248 description: "Triage OpenClaw routing issues.",
249 location: "/Users/test/.agents/skills/openclaw-triage/SKILL.md",
250 content: "---\nname: openclaw-triage\n---\n",
251 },
252 {
253 name: "missing-location",
254 description: "This incomplete SDK row should be skipped.",
255 location: "",
256 content: "---\nname: missing-location\n---\n",
257 },
258 ],
259 };
260
261 const fs = yield* FileSystem.FileSystem;
262 const path = yield* Path.Path;
263 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-inventory-test-" });
264
265 const snapshot = yield* checkOpenCodeProviderStatus(
266 makeOpenCodeSettings(),
267 path.join(tempDir, "workspace"),
268 {
269 HOME: path.join(tempDir, "empty-home"),
270 OPENCODE_CONFIG_DIR: path.join(tempDir, "empty-config"),
271 },
272 );
273
274 NodeAssert.deepEqual(
275 snapshot.skills.map((skill) => ({
276 name: skill.name,
277 path: skill.path,
278 enabled: skill.enabled,
279 shortDescription: skill.shortDescription,
280 })),
281 [
282 {
283 name: "openclaw-review",
284 path: "/Users/test/.agents/skills/openclaw-review/SKILL.md",
285 enabled: true,
286 shortDescription: "Review OpenClaw workflow changes.",
287 },
288 {
289 name: "openclaw-triage",
290 path: "/Users/test/.agents/skills/openclaw-triage/SKILL.md",
291 enabled: true,
292 shortDescription: "Triage OpenClaw routing issues.",
293 },
294 ],
295 );
296 }),
297 );
298
299 it.effect("does not spawn a local server for health check (uses CLI instead)", () =>
300 Effect.gen(function* () {
301 yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
302
303 NodeAssert.equal(runtimeMock.state.closeCalls, 0);
304 NodeAssert.equal(runtimeMock.state.inventoryCwd, process.cwd());
305 }),
306 );
307
308 it.effect("reports local model inventory failures without treating them as empty", () =>
309 Effect.gen(function* () {
310 runtimeMock.state.inventoryError = new Error("opencode models failed");
311 const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
312
313 NodeAssert.equal(snapshot.status, "error");
314 NodeAssert.equal(snapshot.installed, true);
315 NodeAssert.equal(snapshot.models.length, 0);
316 NodeAssert.equal(
317 snapshot.message,
318 "Failed to execute OpenCode CLI health check: opencode models failed",
319 );
320 }),
321 );
322
323 it.effect("includes discovered skills from workspace in provider snapshot", () =>
324 Effect.gen(function* () {
325 const fs = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
327 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-provider-test-" });
328 const workspace = path.join(tempDir, "workspace");
329 const skillDir = path.join(workspace, ".opencode", "skills", "test-skill");
330
331 yield* fs.makeDirectory(skillDir, { recursive: true });
332 yield* fs.writeFileString(
333 path.join(skillDir, "SKILL.md"),
334 ["---", "name: test-skill", "description: Test skill description.", "---"].join("\n"),
335 );
336
337 const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), workspace, {
338 HOME: path.join(tempDir, "empty-home"),
339 OPENCODE_CONFIG_DIR: path.join(tempDir, "empty-config"),
340 });
341
342 NodeAssert.equal(snapshot.skills.length, 1);
343 NodeAssert.equal(snapshot.skills[0]?.name, "test-skill");
344 NodeAssert.equal(snapshot.skills[0]?.description, "Test skill description.");
345 NodeAssert.equal(snapshot.skills[0]?.scope, "project");
346 }),
347 );
348});
349
350it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (it) => {
351 it.effect("surfaces a friendly auth error for configured servers", () =>
352 Effect.gen(function* () {
353 runtimeMock.state.inventoryError = new Error("401 Unauthorized");
354 const snapshot = yield* checkOpenCodeProviderStatus(
355 makeOpenCodeSettings({
356 serverUrl: "http://127.0.0.1:9999",
357 serverPassword: "secret-password",
358 }),
359 process.cwd(),
360 );
361
362 NodeAssert.equal(snapshot.status, "error");
363 NodeAssert.equal(snapshot.installed, true);
364 NodeAssert.equal(
365 snapshot.message,
366 "OpenCode server rejected authentication. Check the server URL and password.",
367 );
368 }),
369 );
370
371 it.effect("surfaces a friendly connection error for configured servers", () =>
372 Effect.gen(function* () {
373 runtimeMock.state.inventoryError = new Error(
374 "fetch failed: connect ECONNREFUSED 127.0.0.1:9999",
375 );
376 const snapshot = yield* checkOpenCodeProviderStatus(
377 makeOpenCodeSettings({
378 serverUrl: "http://127.0.0.1:9999",
379 serverPassword: "secret-password",
380 }),
381 process.cwd(),
382 );
383
384 NodeAssert.equal(snapshot.status, "error");
385 NodeAssert.equal(snapshot.installed, true);
386 NodeAssert.equal(
387 snapshot.message,
388 "Couldn't reach the configured OpenCode server at http://127.0.0.1:9999. Check that the server is running and the URL is correct.",
389 );
390 }),
391 );
392
393 it.effect("does not publish locally discovered skills for configured servers", () =>
394 Effect.gen(function* () {
395 const fs = yield* FileSystem.FileSystem;
396 const path = yield* Path.Path;
397 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-provider-test-" });
398 const workspace = path.join(tempDir, "workspace");
399 const skillDir = path.join(workspace, ".opencode", "skills", "local-only-skill");
400
401 yield* fs.makeDirectory(skillDir, { recursive: true });
402 yield* fs.writeFileString(
403 path.join(skillDir, "SKILL.md"),
404 ["---", "name: local-only-skill", "---"].join("\n"),
405 );
406 runtimeMock.state.inventory = {
407 providerList: { connected: ["openai"], all: [], default: {} },
408 agents: [],
409 skills: [],
410 };
411
412 const snapshot = yield* checkOpenCodeProviderStatus(
413 makeOpenCodeSettings({ serverUrl: "http://127.0.0.1:9999" }),
414 workspace,
415 );
416
417 NodeAssert.deepEqual(snapshot.skills, []);
418 }),
419 );
420});