Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { assert, it } from "@effect/vitest";
8import { ProviderInstanceId, type OpenCodeSettings } from "@t3tools/contracts";
9import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as Layer from "effect/Layer";
13import * as TestClock from "effect/testing/TestClock";
14import { HttpClient } from "effect/unstable/http";
15import { ChildProcessSpawner } from "effect/unstable/process";
16
17import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
18import * as ServerConfig from "../../config.ts";
19import * as IdAllocator from "../../orchestration-v2/IdAllocator.ts";
20import * as ServerSettings from "../../serverSettings.ts";
21import * as ProviderEventLoggers from "../Layers/ProviderEventLoggers.ts";
22import * as ProviderMaintenance from "../providerMaintenance.ts";
23import * as OpenCodeRuntime from "../opencodeRuntime.ts";
24import {
25 OPENCODE_2_RESPONSES,
26 OPENCODE_2_WORKSPACE_RESPONSES,
27 replayOpenCodeServer,
28} from "../testFixtures/opencodeProbeResponses.ts";
29import { OpenCodeDriver, openCodeUpdateFor } from "./OpenCodeDriver.ts";
30
31const serverStarts: Array<string> = [];
32const reachedServer = (operation: string) =>
33 Effect.sync(() => serverStarts.push(operation)).pipe(
34 Effect.andThen(
35 Effect.fail(
36 new OpenCodeRuntime.OpenCodeRuntimeError({
37 operation,
38 detail: "reached a 1.x server path",
39 }),
40 ),
41 ),
42 );
43// Reports OpenCode 2 from `--version`; any attempt to reach a server is recorded and refused.
44const openCode2Runtime = {
45 runOpenCodeCommand: () => Effect.succeed({ stdout: "opencode v2.0.18\n", stderr: "", code: 0 }),
46 startOpenCodeServerProcess: () => reachedServer("start"),
47 connectToOpenCodeServer: () => reachedServer("connect"),
48} as unknown as OpenCodeRuntime.OpenCodeRuntimeShape;
49
50const layer = Layer.mergeAll(
51 ServerConfig.layerTest(process.cwd(), { prefix: "t3-opencode-driver-" }),
52 IdAllocator.layer,
53 ServerSettings.layerTest(),
54 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
55 Layer.succeed(
56 ProviderEventLoggers.ProviderEventLoggers,
57 ProviderEventLoggers.NoOpProviderEventLoggers,
58 ),
59 Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, openCode2Runtime),
60).pipe(Layer.provideMerge(NodeServices.layer));
61
62const create = (config: Partial<OpenCodeSettings>, http: HttpClient.HttpClient) =>
63 OpenCodeDriver.create({
64 instanceId: ProviderInstanceId.make("opencode-test"),
65 displayName: undefined,
66 environment: [],
67 enabled: true,
68 config: { ...OpenCodeDriver.defaultConfig(), ...config },
69 }).pipe(Effect.provideService(HttpClient.HttpClient, http));
70
71const noHttp = HttpClient.make(() => Effect.die("A local binary must not be probed over HTTP"));
72
73it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
74 it.effect("never starts a 1.x server for an OpenCode 2 instance", () =>
75 Effect.gen(function* () {
76 serverStarts.length = 0;
77 const instance = yield* create({}, noHttp);
78 // Text generation goes to the instance's 2.x server, which this test refuses to start.
79 yield* Effect.flip(
80 instance.textGeneration.generateThreadTitle({
81 cwd: process.cwd(),
82 message: "hello",
83 modelSelection: { instanceId: instance.instanceId, model: "opencode/big-pickle" },
84 }),
85 );
86 assert.deepStrictEqual(serverStarts, ["start"]);
87 }).pipe(Effect.scoped),
88 );
89
90 it.effect("lists an OpenCode 2 workspace's own skills and commands from its server", () =>
91 Effect.gen(function* () {
92 serverStarts.length = 0;
93 const requested: Array<string> = [];
94 const server = replayOpenCodeServer(
95 { ...OPENCODE_2_RESPONSES, ...OPENCODE_2_WORKSPACE_RESPONSES },
96 "secret",
97 requested,
98 );
99 const instance = yield* create(
100 { serverUrl: "http://127.0.0.1:4096", serverPassword: "secret" },
101 server,
102 );
103
104 const workspace = yield* instance.snapshotForCwd!("/work");
105 assert.includeMembers(
106 workspace.skills.map((skill) => skill.name),
107 ["plum", "opencode"],
108 );
109 assert.deepStrictEqual(
110 workspace.slashCommands.map((command) => command.name),
111 ["compact", "init", "review", "bee"],
112 );
113 assert.include(requested, "/api/skill");
114 assert.deepStrictEqual(serverStarts, []);
115 }).pipe(Effect.scoped),
116 );
117
118 it.effect("answers capability reads without waiting on an unreachable server", () =>
119 Effect.gen(function* () {
120 const hang = HttpClient.make(() => Effect.never);
121 const instance = yield* create({ serverUrl: "http://127.0.0.1:9" }, hang);
122
123 // No probe has succeeded yet, and the server never answers: the 1.x default applies.
124 const capabilities = yield* instance.orchestrationAdapter
125 .getCapabilities()
126 .pipe(Effect.forkChild);
127 yield* Effect.yieldNow;
128 assert.isDefined(capabilities.pollUnsafe());
129 yield* Fiber.join(capabilities);
130 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
131 );
132});
133
134// npm links `<prefix>/bin/opencode` into the package that installed it:
135// `opencode-ai` for 1.x and `@opencode/cli` (whose bin is `bin/opencode.exe`) for 2.x.
136const npmGlobalInstall = (prefix: string, packagePath: ReadonlyArray<string>, bin: string) => {
137 const target = NodePath.join(prefix, "lib", "node_modules", ...packagePath, "bin", bin);
138 NodeFS.mkdirSync(NodePath.dirname(target), { recursive: true });
139 NodeFS.writeFileSync(target, "#!/bin/sh\n");
140 NodeFS.chmodSync(target, 0o755);
141 const link = NodePath.join(prefix, "bin", "opencode");
142 NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });
143 NodeFS.symlinkSync(target, link);
144 return link;
145};
146const resolveUpdate = (generation: "v1" | "v2", binaryPath: string) =>
147 ProviderMaintenance.resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation), {
148 binaryPath,
149 env: { PATH: "" },
150 }).pipe(
151 Effect.provideService(
152 ChildProcessSpawner.ChildProcessSpawner,
153 ChildProcessSpawner.make(() => Effect.die("resolving an update must not spawn")),
154 ),
155 Effect.provide(NodeServices.layer),
156 );
157
158it.effect.skipIf(HostProcessPlatform.defaultValue() === "win32")(
159 "updates an npm-global OpenCode 2 install as @opencode/cli and a 1.x one as opencode-ai",
160 () =>
161 Effect.gen(function* () {
162 const root = NodeFS.realpathSync(
163 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-opencode-update-")),
164 );
165 const v2Prefix = NodePath.join(root, "v2");
166 const v1Prefix = NodePath.join(root, "v1");
167 const v2 = yield* resolveUpdate(
168 "v2",
169 npmGlobalInstall(v2Prefix, ["@opencode", "cli"], "opencode.exe"),
170 );
171 assert.deepStrictEqual(v2.update?.args, [
172 "install",
173 "-g",
174 "--prefix",
175 v2Prefix,
176 "--allow-scripts=@opencode/cli",
177 "@opencode/cli@latest",
178 ]);
179 const v1 = yield* resolveUpdate(
180 "v1",
181 npmGlobalInstall(v1Prefix, ["opencode-ai"], "opencode"),
182 );
183 assert.strictEqual(v1.update?.args.at(-1), "opencode-ai@latest");
184 // A 1.x install is never offered 2.x's package, or the reverse.
185 assert.isNull(
186 (yield* resolveUpdate("v2", NodePath.join(v1Prefix, "bin", "opencode"))).update,
187 );
188 assert.isNull(
189 (yield* resolveUpdate("v1", NodePath.join(v2Prefix, "bin", "opencode"))).update,
190 );
191 }),
192);
193
194// The update the driver offers follows the version the binary reports now.
195const versionOutput: { current: string | undefined } = { current: undefined };
196const versionProbes: Array<string> = [];
197const changingRuntime = {
198 runOpenCodeCommand: ({ binaryPath }: { readonly binaryPath: string }) =>
199 Effect.sync(() => versionProbes.push(binaryPath)).pipe(
200 Effect.andThen(
201 versionOutput.current === undefined
202 ? Effect.fail(
203 new OpenCodeRuntime.OpenCodeRuntimeError({
204 operation: "version",
205 detail: "no version",
206 }),
207 )
208 : Effect.succeed({ stdout: versionOutput.current, stderr: "", code: 0 }),
209 ),
210 ),
211 startOpenCodeServerProcess: () => reachedServer("start"),
212 connectToOpenCodeServer: () => reachedServer("connect"),
213} as unknown as OpenCodeRuntime.OpenCodeRuntimeShape;
214const updateLayer = Layer.mergeAll(
215 ServerConfig.layerTest(process.cwd(), { prefix: "t3-opencode-driver-update-" }),
216 IdAllocator.layer,
217 ServerSettings.layerTest(),
218 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
219 Layer.succeed(
220 ProviderEventLoggers.ProviderEventLoggers,
221 ProviderEventLoggers.NoOpProviderEventLoggers,
222 ),
223 Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, changingRuntime),
224).pipe(Layer.provideMerge(NodeServices.layer));
225
226it.layer(updateLayer)("OpenCodeDriver updates", (it) => {
227 it.effect("never runs the binary for a disabled instance's update check", () =>
228 Effect.gen(function* () {
229 versionProbes.length = 0;
230 versionOutput.current = "opencode v2.0.18\n";
231 const instance = yield* OpenCodeDriver.create({
232 instanceId: ProviderInstanceId.make("opencode-disabled"),
233 displayName: undefined,
234 environment: [],
235 enabled: false,
236 config: { ...OpenCodeDriver.defaultConfig(), binaryPath: "opencode" },
237 }).pipe(Effect.provideService(HttpClient.HttpClient, noHttp));
238 const maintenance = yield* instance.snapshot.resolveMaintenance();
239 yield* instance.snapshot.resolveMaintenance({ fresh: true });
240 assert.isNull(maintenance.update);
241 assert.deepStrictEqual(versionProbes, []);
242 }).pipe(Effect.scoped),
243 );
244
245 it.effect.skipIf(HostProcessPlatform.defaultValue() === "win32")(
246 "offers no package update for an unknown version and follows a changed one on a fresh read",
247 () =>
248 Effect.gen(function* () {
249 const root = NodeFS.realpathSync(
250 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-opencode-driver-update-")),
251 );
252 const binaryPath = npmGlobalInstall(NodePath.join(root, "v1"), ["opencode-ai"], "opencode");
253 const instance = yield* OpenCodeDriver.create({
254 instanceId: ProviderInstanceId.make("opencode-update"),
255 displayName: undefined,
256 environment: [],
257 enabled: true,
258 config: { ...OpenCodeDriver.defaultConfig(), binaryPath },
259 }).pipe(Effect.provideService(HttpClient.HttpClient, noHttp));
260
261 // The version could not be read: which package owns the binary is unknown.
262 versionOutput.current = undefined;
263 const unknown = yield* instance.snapshot.resolveMaintenance({ fresh: true });
264 assert.isNull(unknown.update);
265 assert.isNull(unknown.packageName);
266
267 versionOutput.current = "1.18.32\n";
268 const v1 = yield* instance.snapshot.resolveMaintenance({ fresh: true });
269 assert.strictEqual(v1.packageName, "opencode-ai");
270
271 // The same path now reports 2.x (reinstalled in place): a fresh read re-probes
272 // and never offers 1.x's package for it.
273 versionOutput.current = "opencode v2.0.18\n";
274 const v2 = yield* instance.snapshot.resolveMaintenance({ fresh: true });
275 assert.strictEqual(v2.packageName, "@opencode/cli");
276 assert.isNull(v2.update);
277 }).pipe(Effect.scoped),
278 );
279});