Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

opencodeRuntime.environment.test.ts

239 lines8.2 KB

1import type { OpencodeClient } from "@opencode-ai/sdk/v2";
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 an empty config", () => {
38 expect(
39 resolveOpenCodeConfigContent(undefined, {
40 OPENCODE_CONFIG_CONTENT: '{"source":"process"}',
41 }),
42 ).toBe('{"source":"process"}');
43 expect(resolveOpenCodeConfigContent(undefined, {})).toBe("{}");
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("uses the settings password for a local server", () => {
58 expect(
59 resolveOpenCodeServerPassword({ external: false, serverPassword: " settings password " }, {}),
60 ).toBe(" settings password ");
61 });
62​
63 it("uses the settings password when local settings and environment differ", () => {
64 expect(
65 resolveOpenCodeServerPassword(
66 {
67 external: false,
68 serverPassword: "settings-password",
69 environment: { OPENCODE_SERVER_PASSWORD: "environment-password" },
70 },
71 {},
72 ),
73 ).toBe("settings-password");
74 });
75​
76 it("does not send an inherited local password to an external server", () => {
77 expect(
78 resolveOpenCodeServerPassword(
79 { external: true, environment: { OPENCODE_SERVER_PASSWORD: "local-secret" } },
80 { OPENCODE_SERVER_PASSWORD: "inherited-secret" },
81 ),
82 ).toBeUndefined();
83 });
84});
85​
86function makeHealthClient(
87 result: (options?: { readonly signal?: AbortSignal }) => Promise<unknown>,
88): OpencodeClient {
89 return {
90 global: {
91 health: result,
92 },
93 } as unknown as OpencodeClient;
95​
96describe("verifyOpenCodeServerVersion", () => {
97 effectIt.effect("accepts a supported server version", () =>
98 Effect.gen(function* () {
99 const version = yield* verifyOpenCodeServerVersion(
100 makeHealthClient(() => Promise.resolve({ data: { healthy: true, version: "1.14.19" } })),
101 );
102 expect(version).toBe("1.14.19");
103 }),
104 );
105​
106 effectIt.effect("rejects a server below the supported version", () =>
107 Effect.gen(function* () {
108 const error = yield* verifyOpenCodeServerVersion(
109 makeHealthClient(() => Promise.resolve({ data: { healthy: true, version: "1.14.18" } })),
110 ).pipe(Effect.flip);
111 expect(error).toBeInstanceOf(OpenCodeRuntimeError);
112 expect(error.detail).toContain("v1.14.18 is too old");
113 }),
114 );
115​
116 for (const data of [
117 { healthy: true },
118 { healthy: true, version: "not-a-version" },
119 { healthy: false, version: "1.14.19" },
120 ]) {
121 effectIt.effect(`rejects an invalid health response: ${JSON.stringify(data)}`, () =>
122 Effect.gen(function* () {
123 const error = yield* verifyOpenCodeServerVersion(
124 makeHealthClient(() => Promise.resolve({ data })),
125 ).pipe(Effect.flip);
126 expect(error).toBeInstanceOf(OpenCodeRuntimeError);
127 expect(error.detail).toContain("requires OpenCode v1.14.19 or newer");
128 }),
129 );
130 }
131​
132 effectIt.effect("preserves an unauthorized health error", () =>
133 Effect.gen(function* () {
134 const error = yield* verifyOpenCodeServerVersion(
135 makeHealthClient(() =>
136 Promise.reject({ response: { status: 401 }, error: { message: "Unauthorized" } }),
137 ),
138 ).pipe(Effect.flip);
139 expect(error).toBeInstanceOf(OpenCodeRuntimeError);
140 expect(error.detail).toContain("status=401");
141 expect(error.detail).toContain("Unauthorized");
142 }),
143 );
144​
145 effectIt.effect("aborts a health request when the version check times out", () =>
146 Effect.gen(function* () {
147 let requestSignal: AbortSignal | undefined;
148 const checkFiber = yield* verifyOpenCodeServerVersion(
149 makeHealthClient((options) => {
150 requestSignal = options?.signal;
151 return new Promise(() => undefined);
152 }),
153 ).pipe(Effect.flip, Effect.forkChild);
154​
155 yield* Effect.yieldNow;
156 expect(requestSignal).toBeDefined();
157 yield* TestClock.adjust("6 seconds");
158​
159 const error = yield* Fiber.join(checkFiber);
160 expect(error.detail).toBe("Timed out while checking the OpenCode server version.");
161 expect(requestSignal?.aborted).toBe(true);
162 }).pipe(Effect.provide(TestClock.layer())),
163 );
164});
165​
166describe("OpenCode server output", () => {
167 effectIt.live(
168 "drains stdout and stderr after startup so server requests can finish",
169 () =>
170 Effect.gen(function* () {
171 const fs = yield* FileSystem.FileSystem;
172 const path = yield* Path.Path;
173 const environment = yield* HostProcessEnvironment;
174 const executablePath = yield* HostProcessExecutablePath;
175 const platform = yield* HostProcessPlatform;
176 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-output-" });
177 const isWindows = platform === "win32";
178 const binaryPath = path.join(tempDir, isWindows ? "opencode.cmd" : "opencode");
179 const scriptPath = path.join(tempDir, "opencode.mjs");
180​
181 yield* fs.writeFileString(
182 scriptPath,
183 `import { createServer } from "node:http";
184const writeOutput = (stream) => new Promise((resolve, reject) => {
185 stream.write("x".repeat(2 * 1024 * 1024), (error) => error ? reject(error) : resolve());
186});
187const server = createServer(async (request, response) => {
188 if (request.url.startsWith("/global/health")) {
189 response.setHeader("Content-Type", "application/json");
190 response.end(JSON.stringify({ healthy: true, version: "1.14.19" }));
191 return;
192 }
193 await Promise.all([writeOutput(process.stdout), writeOutput(process.stderr)]);
194 response.end("drained");
195});
196server.listen(0, "127.0.0.1", () => {
197 process.stdout.write("opencode server listening on http://127.0.0.1:" + server.address().port + "\\n");
198});
199`,
200 );
201 yield* fs.writeFileString(
202 binaryPath,
203 [
204 ...(isWindows ? ["@echo off"] : ["#!/bin/sh"]),
205 isWindows
206 ? '"%T3_TEST_NODE_BINARY%" "%T3_TEST_OPENCODE_SCRIPT%" %*'
207 : 'exec "$T3_TEST_NODE_BINARY" "$T3_TEST_OPENCODE_SCRIPT" "$@"',
208 "",
209 ].join("\n"),
210 );
211 if (!isWindows) {
212 yield* fs.chmod(binaryPath, 0o755);
213 }
214​
215 const runtime = yield* OpenCodeRuntime;
216 const server = yield* runtime.startOpenCodeServerProcess({
217 binaryPath,
218 directory: tempDir,
219 port: 0,
220 environment: {
221 ...environment,
222 T3_TEST_NODE_BINARY: executablePath,
223 T3_TEST_OPENCODE_SCRIPT: scriptPath,
224 },
225 });
226 const response = yield* HttpClient.get(`${server.url}/output`);
227​
228 expect(yield* response.text).toBe("drained");
229 expect(yield* server.isRunning).toBe(true);
230 }).pipe(
231 Effect.scoped,
232 Effect.provide([
233 OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer)),
234 FetchHttpClient.layer,
235 ]),
236 ),
237 10_000,
238 );
239});