Open History to see the last commit
1import type { OpenCodeClient } from "@opencode/client";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { it as effectIt } from "@effect/vitest";
4import {
5 HostProcessEnvironment,
6 HostProcessExecutablePath,
7 HostProcessPlatform,
8} from "@t3tools/shared/hostProcess";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as TestClock from "effect/testing/TestClock";
15import { FetchHttpClient, HttpClient } from "effect/unstable/http";
16import { describe, expect, it } from "vite-plus/test";
17
18import {
19 OpenCodeRuntime,
20 OpenCodeRuntimeError,
21 OpenCodeRuntimeLive,
22 resolveOpenCodeConfigContent,
23 resolveOpenCodeServerPassword,
24 verifyOpenCodeServerVersion,
25} from "./opencodeRuntime.ts";
26
27describe("resolveOpenCodeConfigContent", () => {
28 it("prefers the caller environment over the inherited environment", () => {
29 expect(
30 resolveOpenCodeConfigContent(
31 { OPENCODE_CONFIG_CONTENT: '{"source":"caller"}' },
32 { OPENCODE_CONFIG_CONTENT: '{"source":"process"}' },
33 ),
34 ).toBe('{"source":"caller"}');
35 });
36
37 it("falls back to the inherited environment and then undefined", () => {
38 expect(
39 resolveOpenCodeConfigContent(undefined, {
40 OPENCODE_CONFIG_CONTENT: '{"source":"process"}',
41 }),
42 ).toBe('{"source":"process"}');
43 expect(resolveOpenCodeConfigContent(undefined, {})).toBeUndefined();
44 });
45});
46
47describe("resolveOpenCodeServerPassword", () => {
48 it("uses the local environment password when settings do not provide one", () => {
49 expect(
50 resolveOpenCodeServerPassword(
51 { external: false, environment: { OPENCODE_SERVER_PASSWORD: " env password " } },
52 {},
53 ),
54 ).toBe(" env password ");
55 });
56
57 it("prefers the v2 password environment variable", () => {
58 expect(
59 resolveOpenCodeServerPassword(
60 {
61 external: false,
62 environment: {
63 OPENCODE_PASSWORD: "v2-password",
64 OPENCODE_SERVER_PASSWORD: "legacy-password",
65 },
66 },
67 {},
68 ),
69 ).toBe("v2-password");
70 });
71
72 it("uses the settings password for a local server", () => {
73 expect(
74 resolveOpenCodeServerPassword({ external: false, serverPassword: " settings password " }, {}),
75 ).toBe(" settings password ");
76 });
77
78 it("uses the settings password when local settings and environment differ", () => {
79 expect(
80 resolveOpenCodeServerPassword(
81 {
82 external: false,
83 serverPassword: "settings-password",
84 environment: { OPENCODE_SERVER_PASSWORD: "environment-password" },
85 },
86 {},
87 ),
88 ).toBe("settings-password");
89 });
90
91 it("does not send an inherited local password to an external server", () => {
92 expect(
93 resolveOpenCodeServerPassword(
94 { external: true, environment: { OPENCODE_SERVER_PASSWORD: "local-secret" } },
95 { OPENCODE_SERVER_PASSWORD: "inherited-secret" },
96 ),
97 ).toBeUndefined();
98 });
99});
100
101function makeHealthClient(
102 result: (options?: { readonly signal?: AbortSignal }) => Promise<unknown>,
103): OpenCodeClient {
104 return {
105 server: {
106 info: result,
107 },
108 } as unknown as OpenCodeClient;
109}
110
111describe("verifyOpenCodeServerVersion", () => {
112 effectIt.effect("accepts a supported server version", () =>
113 Effect.gen(function* () {
114 const version = yield* verifyOpenCodeServerVersion(
115 makeHealthClient(() => Promise.resolve({ version: "2.0.12" })),
116 );
117 expect(version).toBe("2.0.12");
118 }),
119 );
120
121 effectIt.effect("rejects a server below the supported version", () =>
122 Effect.gen(function* () {
123 const error = yield* verifyOpenCodeServerVersion(
124 makeHealthClient(() => Promise.resolve({ version: "1.14.18" })),
125 ).pipe(Effect.flip);
126 expect(error).toBeInstanceOf(OpenCodeRuntimeError);
127 expect(error.detail).toContain("v1.14.18 is too old");
128 }),
129 );
130
131 for (const data of [{ healthy: true }, { healthy: true, version: "not-a-version" }]) {
132 effectIt.effect(`rejects an invalid health response: ${JSON.stringify(data)}`, () =>
133 Effect.gen(function* () {
134 const error = yield* verifyOpenCodeServerVersion(
135 makeHealthClient(() => Promise.resolve(data)),
136 ).pipe(Effect.flip);
137 expect(error).toBeInstanceOf(OpenCodeRuntimeError);
138 expect(error.detail).toContain("requires OpenCode v2.0.12 or newer");
139 }),
140 );
141 }
142
143 effectIt.effect("preserves an unauthorized health error", () =>
144 Effect.gen(function* () {
145 const error = yield* verifyOpenCodeServerVersion(
146 makeHealthClient(() =>
147 Promise.reject({ response: { status: 401 }, error: { message: "Unauthorized" } }),
148 ),
149 ).pipe(Effect.flip);
150 expect(error).toBeInstanceOf(OpenCodeRuntimeError);
151 expect(error.detail).toContain("status=401");
152 expect(error.detail).toContain("Unauthorized");
153 }),
154 );
155
156 effectIt.effect("aborts a health request when the version check times out", () =>
157 Effect.gen(function* () {
158 let requestSignal: AbortSignal | undefined;
159 const checkFiber = yield* verifyOpenCodeServerVersion(
160 makeHealthClient((options) => {
161 requestSignal = options?.signal;
162 return new Promise(() => undefined);
163 }),
164 ).pipe(Effect.flip, Effect.forkChild);
165
166 yield* Effect.yieldNow;
167 expect(requestSignal).toBeDefined();
168 yield* TestClock.adjust("6 seconds");
169
170 const error = yield* Fiber.join(checkFiber);
171 expect(error.detail).toBe("Timed out while checking the OpenCode server version.");
172 expect(requestSignal?.aborted).toBe(true);
173 }).pipe(Effect.provide(TestClock.layer())),
174 );
175});
176
177describe("OpenCode server output", () => {
178 effectIt.live(
179 "drains stdout and stderr after startup so server requests can finish",
180 () =>
181 Effect.gen(function* () {
182 const fs = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 const environment = yield* HostProcessEnvironment;
185 const executablePath = yield* HostProcessExecutablePath;
186 const platform = yield* HostProcessPlatform;
187 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-output-" });
188 const isWindows = platform === "win32";
189 const binaryPath = path.join(tempDir, isWindows ? "opencode.cmd" : "opencode");
190 const scriptPath = path.join(tempDir, "opencode.mjs");
191
192 yield* fs.writeFileString(
193 scriptPath,
194 `import { createServer } from "node:http";
195const writeOutput = (stream) => new Promise((resolve, reject) => {
196 stream.write("x".repeat(2 * 1024 * 1024), (error) => error ? reject(error) : resolve());
197});
198const server = createServer(async (request, response) => {
199 if (request.url.startsWith("/api/info")) {
200 response.setHeader("Content-Type", "application/json");
201 response.end(JSON.stringify({ version: "2.0.12", pid: 1, urls: [], paths: { tmp: "/tmp" } }));
202 return;
203 }
204 await Promise.all([writeOutput(process.stdout), writeOutput(process.stderr)]);
205 response.end("drained");
206});
207server.listen(0, "127.0.0.1", () => {
208 process.stdout.write("server listening on http://127.0.0.1:" + server.address().port + "\\n");
209});
210`,
211 );
212 yield* fs.writeFileString(
213 binaryPath,
214 [
215 ...(isWindows ? ["@echo off"] : ["#!/bin/sh"]),
216 isWindows
217 ? '"%T3_TEST_NODE_BINARY%" "%T3_TEST_OPENCODE_SCRIPT%" %*'
218 : 'exec "$T3_TEST_NODE_BINARY" "$T3_TEST_OPENCODE_SCRIPT" "$@"',
219 "",
220 ].join("\n"),
221 );
222 if (!isWindows) {
223 yield* fs.chmod(binaryPath, 0o755);
224 }
225
226 const runtime = yield* OpenCodeRuntime;
227 const server = yield* runtime.startOpenCodeServerProcess({
228 binaryPath,
229 directory: tempDir,
230 port: 0,
231 environment: {
232 ...environment,
233 T3_TEST_NODE_BINARY: executablePath,
234 T3_TEST_OPENCODE_SCRIPT: scriptPath,
235 },
236 });
237 const response = yield* HttpClient.get(`${server.url}/output`);
238
239 expect(yield* response.text).toBe("drained");
240 expect(yield* server.isRunning).toBe(true);
241 }).pipe(
242 Effect.scoped,
243 Effect.provide([
244 OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer)),
245 FetchHttpClient.layer,
246 ]),
247 ),
248 10_000,
249 );
250});