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

OpenCodeRuntime.environment.test.ts

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