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

opencodeRuntime.environment.test.ts

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