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

OpenCode2Client.live.test.ts

151 lines5.8 KB

1/**
2 * Live contract check for `@opencode/client` against a real OpenCode 2 server.
3 * It re-proves that OpenCode's schemas decode under the workspace Effect
4 * version, which the pnpm overrides force. Run it after bumping either side:
5 *
6 * OPENCODE2_BIN=/path/to/opencode vp test run src/provider/opencode2/OpenCode2Client.live.test.ts
7 *
8 * The turn uses the free `opencode/big-pickle` model.
9 */
10import * as NodeServices from "@effect/platform-node/NodeServices";
11import { AbsolutePath, Location, Model, Provider } from "@opencode/client/effect";
12import { assert, it } from "@effect/vitest";
13import * as Crypto from "effect/Crypto";
14import * as Effect from "effect/Effect";
15import * as Base64Url from "effect/encoding/Base64Url";
16import * as Fiber from "effect/Fiber";
17import * as FileSystem from "effect/FileSystem";
18import * as Filter from "effect/Filter";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Path from "effect/Path";
22import * as Stream from "effect/Stream";
23import { FetchHttpClient } from "effect/http";
24import { ChildProcess, ChildProcessSpawner } from "effect/process";
25import { describe } from "vite-plus/test";
26​
27import * as OpenCode2Client from "./OpenCode2Client.ts";
28​
29const binaryPath = process.env.OPENCODE2_BIN;
30​
31const startServer = Effect.fn("OpenCode2ClientLive.startServer")(function* (binary: string) {
32 const fs = yield* FileSystem.FileSystem;
33 const path = yield* Path.Path;
34 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
35 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode2-live-" });
36 const directory = path.join(root, "work");
37 yield* fs.makeDirectory(directory);
38 // Non-ASCII on purpose: OpenCode decodes Basic credentials as UTF-8.
39 const crypto = yield* Crypto.Crypto;
40 const password = `${Base64Url.encode(yield* crypto.randomBytes(32))}-pässwörd€`;
41 const child = yield* spawner.spawn(
42 ChildProcess.make(binary, ["serve", "--hostname=127.0.0.1", "--port=0"], {
43 cwd: directory,
44 env: {
45 PATH: process.env.PATH,
46 HOME: root,
47 XDG_CONFIG_HOME: path.join(root, "config"),
48 XDG_DATA_HOME: path.join(root, "data"),
49 XDG_STATE_HOME: path.join(root, "state"),
50 XDG_CACHE_HOME: path.join(root, "cache"),
51 OPENCODE_PASSWORD: password,
52 },
53 }),
54 );
55 // Stop by the PID captured at spawn, before the temp directory is removed.
56 yield* Effect.addFinalizer(() =>
57 Effect.sync(() => {
58 try {
59 process.kill(Number(child.pid), "SIGTERM");
60 } catch {
61 // Already exited.
62 }
63 }).pipe(Effect.andThen(child.exitCode), Effect.timeout("10 seconds"), Effect.ignore),
64 );
65 const baseUrl = yield* child.stdout.pipe(
66 Stream.decodeText(),
67 Stream.splitLines,
68 Stream.filterMap(
69 Filter.fromPredicateOption((line: string) =>
70 Option.fromUndefinedOr(/server listening on\s+(https?:\/\/\S+)/i.exec(line)?.[1]),
71 ),
72 ),
73 Stream.runHead,
74 Effect.flatMap(Effect.fromOption),
75 Effect.timeout("30 seconds"),
76 );
77 return { baseUrl, password, directory, pid: Number(child.pid) };
78});
79​
80describe.runIf(binaryPath !== undefined)("OpenCode2Client live", () => {
81 it.live(
82 "reads server info, runs one turn, and pages the history",
83 () =>
84 Effect.gen(function* () {
85 const server = yield* startServer(binaryPath!);
86 const opencode = yield* OpenCode2Client.OpenCode2Client;
87 const { client, events } = yield* opencode.connect({
88 baseUrl: server.baseUrl,
89 password: server.password,
90 });
91​
92 const info = yield* client.server.info();
93 assert.strictEqual(info.version, "2.0.23");
94 assert.strictEqual(info.pid, server.pid);
95​
96 const session = yield* client.session.create({
97 title: "t3 client live check",
98 location: Location.PublicRef.make({ directory: AbsolutePath.make(server.directory) }),
99 model: Model.Ref.make({
100 providerID: Provider.ID.make("opencode"),
101 id: Model.ID.make("big-pickle"),
102 }),
103 });
104 const finished = yield* (yield* events).pipe(
105 Stream.filter(
106 (event) =>
107 event.type !== "unreadable.execution.ended" &&
108 event.type !== "unreadable.execution.started" &&
109 (event.data as { readonly sessionID?: string }).sessionID === session.id &&
110 event.type.startsWith("session.execution.") &&
111 event.type !== "session.execution.started",
112 ),
113 Stream.runHead,
114 Effect.forkChild,
115 );
116 yield* client.session.prompt({
117 sessionID: session.id,
118 text: "Reply with exactly: OPENCODE2_CLIENT_OK",
119 });
120 const terminal = yield* Fiber.join(finished).pipe(
121 Effect.flatMap(Effect.fromOption),
122 Effect.timeout("120 seconds"),
123 );
124 assert.strictEqual(terminal.type, "session.execution.succeeded");
125​
126 // One message per page makes every request after the first send only a cursor.
127 const history = yield* OpenCode2Client.paginate(
128 { sessionID: session.id, order: "asc", limit: 1 },
129 client.message.list,
130 ).pipe(Stream.runCollect);
131 assert.deepStrictEqual(
132 history.map((message) => message.type),
133 ["user", "assistant", "idle"],
134 );
135 const assistant = history[1];
136 assert(assistant?.type === "assistant");
137 const reply = assistant.content.flatMap((part) =>
138 part.type === "text" ? [part.text] : [],
139 );
140 assert.include(reply.join(""), "OPENCODE2_CLIENT_OK");
141 }).pipe(
142 Effect.scoped,
143 Effect.provide(
144 OpenCode2Client.layer.pipe(
145 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer)),
146 ),
147 ),
148 ),
149 180_000,
150 );
151});