Open History to see the last commit
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 Effect from "effect/Effect";
14import * as Base64Url from "effect/encoding/Base64Url";
15import * as Fiber from "effect/Fiber";
16import * as FileSystem from "effect/FileSystem";
17import * as Filter from "effect/Filter";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Path from "effect/Path";
21import * as Stream from "effect/Stream";
22import { FetchHttpClient } from "effect/http";
23import { ChildProcess, ChildProcessSpawner } from "effect/process";
24import * as NodeCrypto from "node:crypto";
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 password = `${Base64Url.encode(NodeCrypto.randomBytes(32))}-pässwörd€`;
40 const child = yield* spawner.spawn(
41 ChildProcess.make(binary, ["serve", "--hostname=127.0.0.1", "--port=0"], {
42 cwd: directory,
43 env: {
44 PATH: process.env.PATH,
45 HOME: root,
46 XDG_CONFIG_HOME: path.join(root, "config"),
47 XDG_DATA_HOME: path.join(root, "data"),
48 XDG_STATE_HOME: path.join(root, "state"),
49 XDG_CACHE_HOME: path.join(root, "cache"),
50 OPENCODE_PASSWORD: password,
51 },
52 }),
53 );
54 // Stop by the PID captured at spawn, before the temp directory is removed.
55 yield* Effect.addFinalizer(() =>
56 Effect.sync(() => {
57 try {
58 process.kill(Number(child.pid), "SIGTERM");
59 } catch {
60 // Already exited.
61 }
62 }).pipe(Effect.andThen(child.exitCode), Effect.timeout("10 seconds"), Effect.ignore),
63 );
64 const baseUrl = yield* child.stdout.pipe(
65 Stream.decodeText(),
66 Stream.splitLines,
67 Stream.filterMap(
68 Filter.fromPredicateOption((line: string) =>
69 Option.fromUndefinedOr(/server listening on\s+(https?:\/\/\S+)/i.exec(line)?.[1]),
70 ),
71 ),
72 Stream.runHead,
73 Effect.flatMap(Effect.fromOption),
74 Effect.timeout("30 seconds"),
75 );
76 return { baseUrl, password, directory, pid: Number(child.pid) };
77});
78
79describe.runIf(binaryPath !== undefined)("OpenCode2Client live", () => {
80 it.live(
81 "reads server info, runs one turn, and pages the history",
82 () =>
83 Effect.gen(function* () {
84 const server = yield* startServer(binaryPath!);
85 const opencode = yield* OpenCode2Client.OpenCode2Client;
86 const { client, events } = yield* opencode.connect({
87 baseUrl: server.baseUrl,
88 password: server.password,
89 });
90
91 const info = yield* client.server.info();
92 assert.strictEqual(info.version, "2.0.23");
93 assert.strictEqual(info.pid, server.pid);
94
95 const session = yield* client.session.create({
96 title: "t3 client live check",
97 location: Location.PublicRef.make({ directory: AbsolutePath.make(server.directory) }),
98 model: Model.Ref.make({
99 providerID: Provider.ID.make("opencode"),
100 id: Model.ID.make("big-pickle"),
101 }),
102 });
103 const finished = yield* (yield* events).pipe(
104 Stream.filter(
105 (event) =>
106 event.type !== "unreadable.execution.ended" &&
107 event.type !== "unreadable.execution.started" &&
108 (event.data as { readonly sessionID?: string }).sessionID === session.id &&
109 event.type.startsWith("session.execution.") &&
110 event.type !== "session.execution.started",
111 ),
112 Stream.runHead,
113 Effect.forkChild,
114 );
115 yield* client.session.prompt({
116 sessionID: session.id,
117 text: "Reply with exactly: OPENCODE2_CLIENT_OK",
118 });
119 const terminal = yield* Fiber.join(finished).pipe(
120 Effect.flatMap(Effect.fromOption),
121 Effect.timeout("120 seconds"),
122 );
123 assert.strictEqual(terminal.type, "session.execution.succeeded");
124
125 // One message per page makes every request after the first send only a cursor.
126 const history = yield* OpenCode2Client.paginate(
127 { sessionID: session.id, order: "asc", limit: 1 },
128 client.message.list,
129 ).pipe(Stream.runCollect);
130 assert.deepStrictEqual(
131 history.map((message) => message.type),
132 ["user", "assistant", "idle"],
133 );
134 const assistant = history[1];
135 assert(assistant?.type === "assistant");
136 const reply = assistant.content.flatMap((part) =>
137 part.type === "text" ? [part.text] : [],
138 );
139 assert.include(reply.join(""), "OPENCODE2_CLIENT_OK");
140 }).pipe(
141 Effect.scoped,
142 Effect.provide(
143 OpenCode2Client.layer.pipe(
144 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer)),
145 ),
146 ),
147 ),
148 180_000,
149 );
150});