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

OpenCode2Server.live.test.ts

238 lines9.4 KB

1/**
2 * Live check of the OpenCode 2 server lifecycle against a real binary:
3 *
4 * OPENCODE2_BIN=/path/to/opencode vp test run src/provider/opencode2/OpenCode2Server.live.test.ts
5 *
6 * No model is called. The server runs with isolated HOME and XDG directories.
7 */
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { AbsolutePath, Location } from "@opencode/client/effect";
10import { assert, it } from "@effect/vitest";
11import * as Context from "effect/Context";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as FileSystem from "effect/FileSystem";
15import * as Filter from "effect/Filter";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19import * as Redacted from "effect/Redacted";
20import * as Scope from "effect/Scope";
21import * as Stream from "effect/Stream";
22import { FetchHttpClient } from "effect/unstable/http";
23import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
24import { describe } from "vite-plus/test";
25​
26import * as OpenCodeRuntime from "../opencodeRuntime.ts";
27import * as OpenCodeServerLedger from "../OpenCodeServerLedger.ts";
28import * as OpenCode2Client from "./OpenCode2Client.ts";
29import * as OpenCode2Server from "./OpenCode2Server.ts";
30​
31const binaryPath = process.env.OPENCODE2_BIN;
32​
33// A negative pid probes the whole process group, which T3 stops as one unit.
34const isAlive = (pid: number) => {
35 try {
36 process.kill(pid, 0);
37 return true;
38 } catch {
39 return false;
40 }
41};
42​
43/**
44 * Stops a server the test spawned itself: SIGTERM, then SIGKILL if it is still
45 * alive after five seconds. Keyed on the PID captured at spawn, never on a
46 * pattern. Servers T3 spawns are stopped by T3, through the instance scope.
47 */
48const stopByPid = (pid: number) =>
49 Effect.gen(function* () {
50 const signal = (name: NodeJS.Signals) => {
51 try {
52 process.kill(pid, name);
53 } catch {
54 // Already exited.
55 }
56 };
57 signal("SIGTERM");
58 for (let attempt = 0; attempt < 50 && isAlive(pid); attempt++) {
59 yield* Effect.sleep("100 millis");
60 }
61 if (isAlive(pid)) signal("SIGKILL");
62 });
63​
64/**
65 * Starts `opencode serve` the way a user would run it themselves. It is stopped
66 * by its PID when the calling scope closes, whether or not the test passed.
67 */
68const startExternalServer = Effect.fn("OpenCode2ServerLive.startExternalServer")(function* (input: {
69 readonly environment: NodeJS.ProcessEnv;
70 readonly directory: string;
71}) {
72 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
73 const child = yield* spawner.spawn(
74 ChildProcess.make(binaryPath!, ["serve", "--hostname=127.0.0.1", "--port=0"], {
75 cwd: input.directory,
76 env: input.environment,
77 }),
78 );
79 const pid = Number(child.pid);
80 yield* Effect.addFinalizer(() => stopByPid(pid));
81 const url = yield* child.stdout.pipe(
82 Stream.decodeText(),
83 Stream.splitLines,
84 Stream.filterMap(
85 Filter.fromPredicateOption((line: string) =>
86 Option.fromUndefinedOr(/server listening on\s+(https?:\/\/\S+)/i.exec(line)?.[1]),
87 ),
88 ),
89 Stream.runHead,
90 Effect.flatMap(Effect.fromOption),
91 Effect.timeout("30 seconds"),
92 );
93 return { url, pid };
94});
95​
96describe.runIf(binaryPath !== undefined)("OpenCode2Server live", () => {
97 it.live(
98 "spawns one authenticated server per instance and stops it by PID",
99 () =>
100 Effect.gen(function* () {
101 const fs = yield* FileSystem.FileSystem;
102 const path = yield* Path.Path;
103 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode2-server-live-" });
104 const first = path.join(root, "first");
105 const second = path.join(root, "second");
106 yield* fs.makeDirectory(first);
107 yield* fs.makeDirectory(second);
108 const environment = {
109 PATH: process.env.PATH,
110 HOME: root,
111 XDG_CONFIG_HOME: path.join(root, "config"),
112 XDG_DATA_HOME: path.join(root, "data"),
113 XDG_STATE_HOME: path.join(root, "state"),
114 XDG_CACHE_HOME: path.join(root, "cache"),
115 // Ignored: the T3 password is the only one the server sees.
116 OPENCODE_SERVER_PASSWORD: "ambient-password",
117 };
118​
119 // The instance owns its server: building the layer spawns nothing, and
120 // closing its scope stops whatever it spawned. The scope is released
121 // even when an assertion below fails; it is closed early on purpose.
122 const instanceScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
123 Scope.close(scope, Exit.void),
124 );
125 const server = Context.get(
126 yield* Layer.buildWithScope(
127 OpenCode2Server.layer({
128 binaryPath: binaryPath!,
129 serverUrl: "",
130 serverPassword: "",
131 directory: first,
132 environment,
133 }),
134 instanceScope,
135 ),
136 OpenCode2Server.OpenCode2Server,
137 );
138​
139 const spawned = yield* server.withConnection((connection) =>
140 Effect.gen(function* () {
141 const info = yield* connection.client.server.info();
142 const session = yield* connection.client.session.create({
143 title: "first location",
144 location: Location.PublicRef.make({ directory: AbsolutePath.make(first) }),
145 });
146 return { ...connection, pid: info.pid, session };
147 }),
148 );
149 assert.strictEqual(spawned.version, "2.0.18");
150 assert.isFalse(spawned.external);
151 assert.isTrue(isAlive(spawned.pid));
152​
153 // A second location is served by the same process.
154 const secondLocation = yield* server.withConnection((connection) =>
155 Effect.gen(function* () {
156 const info = yield* connection.client.server.info();
157 const session = yield* connection.client.session.create({
158 title: "second location",
159 location: Location.PublicRef.make({ directory: AbsolutePath.make(second) }),
160 });
161 return { url: connection.url, pid: info.pid, session };
162 }),
163 );
164 assert.strictEqual(secondLocation.url, spawned.url);
165 assert.strictEqual(secondLocation.pid, spawned.pid);
166 assert.strictEqual(secondLocation.session.location.directory, second);
167 assert.strictEqual(spawned.session.location.directory, first);
168​
169 // External URL: the configured password works, a wrong one is a 401.
170 const external = yield* OpenCode2Server.make({
171 binaryPath: binaryPath!,
172 serverUrl: spawned.url,
173 serverPassword: "wrong-password",
174 directory: first,
175 environment,
176 });
177 const rejected = yield* external.withConnection(() => Effect.void).pipe(Effect.flip);
178 assert.include(rejected.detail, "rejected the server password");
179 const ambient = yield* OpenCode2Server.make({
180 binaryPath: binaryPath!,
181 serverUrl: spawned.url,
182 serverPassword: environment.OPENCODE_SERVER_PASSWORD,
183 directory: first,
184 environment,
185 });
186 const ambientRejected = yield* ambient.withConnection(() => Effect.void).pipe(Effect.flip);
187 assert.include(ambientRejected.detail, "rejected the server password");
188​
189 // An external server whose password is not ASCII: OpenCode decodes Basic
190 // credentials as UTF-8, so the configured password must be sent that way.
191 const utf8Password = "pässwörd€";
192 const externalServer = yield* startExternalServer({
193 environment: OpenCode2Server.serverEnvironment(environment, Redacted.make(utf8Password)),
194 directory: second,
195 });
196 const utf8 = yield* OpenCode2Server.make({
197 binaryPath: binaryPath!,
198 serverUrl: externalServer.url,
199 serverPassword: utf8Password,
200 directory: second,
201 environment,
202 });
203 const utf8Connection = yield* utf8.withConnection((connection) =>
204 Effect.succeed(connection),
205 );
206 assert.strictEqual(utf8Connection.version, "2.0.18");
207 assert.isTrue(utf8Connection.external);
208 const asciiOnly = yield* OpenCode2Server.make({
209 binaryPath: binaryPath!,
210 serverUrl: externalServer.url,
211 serverPassword: "passwrd",
212 directory: second,
213 environment,
214 });
215 const asciiRejected = yield* asciiOnly.withConnection(() => Effect.void).pipe(Effect.flip);
216 assert.include(asciiRejected.detail, "rejected the server password");
217​
218 // Closing the instance stops the server it spawned.
219 yield* Scope.close(instanceScope, Exit.void);
220 for (let attempt = 0; attempt < 50 && isAlive(-spawned.pid); attempt++) {
221 yield* Effect.sleep("100 millis");
222 }
223 assert.isFalse(isAlive(spawned.pid), `opencode serve ${spawned.pid} outlived its instance`);
224 assert.isFalse(isAlive(-spawned.pid), `a process in group ${spawned.pid} outlived it`);
225 const unreachable = yield* external.withConnection(() => Effect.void).pipe(Effect.flip);
226 assert.include(unreachable.detail, "Could not reach the OpenCode server");
227 }).pipe(
228 Effect.scoped,
229 Effect.provide(
230 Layer.mergeAll(
231 OpenCode2Client.layer,
232 OpenCodeRuntime.OpenCodeRuntimeLive.pipe(Layer.provide(OpenCodeServerLedger.layerTest)),
233 ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer))),
234 ),
235 ),
236 60_000,
237 );
238});