The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | // @effect-diagnostics nodeBuiltinImport:off |
| 2 | import * as NodeFS from "node:fs"; |
| 3 | import * as NodeOS from "node:os"; |
| 4 | import * as NodePath from "node:path"; |
| 5 | |
| 6 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 7 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 8 | import { assert, it } from "@effect/vitest"; |
| 9 | import { |
| 10 | DEFAULT_SERVER_SETTINGS, |
| 11 | ProviderInstanceId, |
| 12 | ProviderSessionId, |
| 13 | ThreadId, |
| 14 | } from "@t3tools/contracts"; |
| 15 | import type { OpenCodeSettings } from "../settings.ts"; |
| 16 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 17 | import * as Deferred from "effect/Deferred"; |
| 18 | import * as Effect from "effect/Effect"; |
| 19 | import * as Duration from "effect/Duration"; |
| 20 | import * as Fiber from "effect/Fiber"; |
| 21 | import * as FileSystem from "effect/FileSystem"; |
| 22 | import * as Layer from "effect/Layer"; |
| 23 | import * as Logger from "effect/Logger"; |
| 24 | import * as Option from "effect/Option"; |
| 25 | import * as References from "effect/References"; |
| 26 | import * as Stream from "effect/Stream"; |
| 27 | import * as TestClock from "effect/testing/TestClock"; |
| 28 | import * as HttpClient from "effect/http/HttpClient"; |
| 29 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 30 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 31 | import * as UrlParams from "effect/http/UrlParams"; |
| 32 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 33 | |
| 34 | import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; |
| 35 | import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 36 | import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; |
| 37 | import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; |
| 38 | import * as ProviderMaintenance from "@t3tools/provider-core/server/maintenanceResolver"; |
| 39 | import * as OpenCodeRuntime from "./OpenCodeRuntime.ts"; |
| 40 | import { OpenCodeDriver, isLocalOpenCodeServerUrl, openCodeUpdateFor } from "./driver.ts"; |
| 41 | import * as OpenCodeServerLedger from "./OpenCodeServerLedger.ts"; |
| 42 | import { |
| 43 | OPENCODE_2_RESPONSES, |
| 44 | OPENCODE_2_WORKSPACE_RESPONSES, |
| 45 | replayOpenCodeServer, |
| 46 | } from "./probeResponses.fixture.ts"; |
| 47 | import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; |
| 48 | |
| 49 | it("only probes a locally configured OpenCode server's installed CLI", () => { |
| 50 | assert.isTrue(isLocalOpenCodeServerUrl("http://127.0.0.1:35768")); |
| 51 | assert.isTrue(isLocalOpenCodeServerUrl("http://127.255.255.254:4096")); |
| 52 | assert.isFalse(isLocalOpenCodeServerUrl("http://127.example.com:4096")); |
| 53 | assert.isFalse(isLocalOpenCodeServerUrl("http://128.0.0.1:4096")); |
| 54 | assert.isTrue(isLocalOpenCodeServerUrl("http://localhost:4096")); |
| 55 | assert.isTrue(isLocalOpenCodeServerUrl("http://[::1]:4096")); |
| 56 | assert.isFalse(isLocalOpenCodeServerUrl("https://remote.example.com:4096")); |
| 57 | assert.isFalse(isLocalOpenCodeServerUrl("")); |
| 58 | assert.isFalse(isLocalOpenCodeServerUrl("file:///tmp/opencode")); |
| 59 | }); |
| 60 | |
| 61 | const serverStarts: Array<string> = []; |
| 62 | const reachedServer = (operation: string) => |
| 63 | Effect.sync(() => serverStarts.push(operation)).pipe( |
| 64 | Effect.andThen( |
| 65 | Effect.fail( |
| 66 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 67 | operation, |
| 68 | detail: "reached a 1.x server path", |
| 69 | }), |
| 70 | ), |
| 71 | ), |
| 72 | ); |
| 73 | const openCode2Runtime = { |
| 74 | runOpenCodeCommand: () => Effect.succeed({ stdout: "opencode v2.0.18\n", stderr: "", code: 0 }), |
| 75 | startOpenCodeServerProcess: () => reachedServer("start"), |
| 76 | connectToOpenCodeServer: () => reachedServer("connect"), |
| 77 | } as unknown as OpenCodeRuntime.OpenCodeRuntime["Service"]; |
| 78 | |
| 79 | const layer = Layer.mergeAll( |
| 80 | IdAllocator.layer, |
| 81 | McpProviderSessions.layer, |
| 82 | ProviderLatestVersions.layer, |
| 83 | TestProviderHost.layer(), |
| 84 | Layer.succeed( |
| 85 | ProviderEventLoggers.ProviderEventLoggers, |
| 86 | ProviderEventLoggers.NoOpProviderEventLoggers, |
| 87 | ), |
| 88 | Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, openCode2Runtime), |
| 89 | ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); |
| 90 | |
| 91 | const create = (config: Partial<OpenCodeSettings>, http: HttpClient.HttpClient, enabled = true) => |
| 92 | OpenCodeDriver.create({ |
| 93 | instanceId: ProviderInstanceId.make("opencode-test"), |
| 94 | displayName: undefined, |
| 95 | environment: [], |
| 96 | enabled, |
| 97 | config: { ...OpenCodeDriver.defaultConfig(), ...config }, |
| 98 | }).pipe(Effect.provideService(HttpClient.HttpClient, http)); |
| 99 | |
| 100 | const noHttp = HttpClient.make(() => Effect.die("A local binary must not be probed over HTTP")); |
| 101 | |
| 102 | const openCode2Project = "/work/project-with-config"; |
| 103 | const openCode2Model = (providerID: string, id: string, name: string) => ({ |
| 104 | id, |
| 105 | modelID: id, |
| 106 | providerID, |
| 107 | name, |
| 108 | package: "@opencode/ai/providers/openai-compatible", |
| 109 | settings: {}, |
| 110 | compatibility: {}, |
| 111 | capabilities: { tools: true, input: ["text"], output: ["text"] }, |
| 112 | variants: [], |
| 113 | time: { released: 1789516800000 }, |
| 114 | cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }], |
| 115 | status: "active", |
| 116 | enabled: true, |
| 117 | limit: { context: 1000000, output: 65536 }, |
| 118 | }); |
| 119 | // Serves one machine catalog everywhere plus extra models for the project directory. |
| 120 | const makeOpenCode2ProjectInstance = ( |
| 121 | projectCatalog: "listed" | "models-unavailable" | "providers-unavailable", |
| 122 | ) => |
| 123 | Effect.gen(function* () { |
| 124 | const machineModels = [openCode2Model("opencode", "big-pickle", "Big Pickle")]; |
| 125 | const projectModels = [ |
| 126 | ...machineModels, |
| 127 | openCode2Model("uni", "medium-gpt", "Medium GPT"), |
| 128 | openCode2Model("uni", "large-gpt", "Large GPT"), |
| 129 | ]; |
| 130 | const replay = replayOpenCodeServer( |
| 131 | { ...OPENCODE_2_RESPONSES, ...OPENCODE_2_WORKSPACE_RESPONSES }, |
| 132 | "secret", |
| 133 | ); |
| 134 | const server = HttpClient.make((request) => { |
| 135 | const pathname = new URL(request.url).pathname; |
| 136 | if (pathname !== "/api/model" && pathname !== "/api/provider") { |
| 137 | return replay.execute(request); |
| 138 | } |
| 139 | const directory = Option.getOrUndefined( |
| 140 | UrlParams.getFirst(request.urlParams, "location[directory]"), |
| 141 | ); |
| 142 | const isProject = directory === openCode2Project; |
| 143 | const data = pathname === "/api/provider" ? [] : isProject ? projectModels : machineModels; |
| 144 | const unavailable = |
| 145 | isProject && |
| 146 | ((pathname === "/api/model" && projectCatalog === "models-unavailable") || |
| 147 | (pathname === "/api/provider" && projectCatalog === "providers-unavailable")); |
| 148 | return Effect.succeed( |
| 149 | HttpClientResponse.fromWeb( |
| 150 | request, |
| 151 | // An external server without a requested location answers for its own default. |
| 152 | new Response( |
| 153 | JSON.stringify({ location: { directory: directory ?? "/srv/remote" }, data }), |
| 154 | { |
| 155 | status: unavailable ? 503 : 200, |
| 156 | headers: { "content-type": "application/json" }, |
| 157 | }, |
| 158 | ), |
| 159 | ), |
| 160 | ); |
| 161 | }); |
| 162 | const instance = yield* create( |
| 163 | { serverUrl: "http://127.0.0.1:4096", serverPassword: "secret" }, |
| 164 | server, |
| 165 | ); |
| 166 | const ready = yield* instance.snapshot.streamChanges.pipe( |
| 167 | Stream.filter((snapshot) => snapshot.status === "ready"), |
| 168 | Stream.take(1), |
| 169 | Stream.runCollect, |
| 170 | Effect.forkChild, |
| 171 | ); |
| 172 | yield* TestClock.adjust("5 seconds"); |
| 173 | yield* Fiber.join(ready); |
| 174 | // Catalog reads repeat until two agree, so let them settle on the test clock. |
| 175 | return (cwd: string) => |
| 176 | Effect.gen(function* () { |
| 177 | const read = yield* Effect.forkChild(instance.snapshotForCwd!(cwd)); |
| 178 | yield* TestClock.adjust("5 seconds"); |
| 179 | return yield* Fiber.join(read); |
| 180 | }); |
| 181 | }); |
| 182 | |
| 183 | it.live("discovers models through a home-relative OpenCode wrapper", () => |
| 184 | Effect.gen(function* () { |
| 185 | const fs = yield* FileSystem.FileSystem; |
| 186 | const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-home with spaces-" }); |
| 187 | const binaryPath = NodePath.join(home, "opencode"); |
| 188 | const scriptPath = NodePath.join(home, "opencode.cjs"); |
| 189 | yield* fs.writeFileString( |
| 190 | scriptPath, |
| 191 | `if (process.argv.includes('--version')) { |
| 192 | console.log('1.18.32'); |
| 193 | } else { |
| 194 | const server = require('node:http').createServer((req, res) => { |
| 195 | const route = new URL(req.url, 'http://localhost').pathname; |
| 196 | res.setHeader('content-type', 'application/json'); |
| 197 | res.end(JSON.stringify(route === '/global/health' |
| 198 | ? { healthy: true, version: '1.18.32' } |
| 199 | : route === '/provider' |
| 200 | ? { connected: ['opencode'], default: {}, all: [{ |
| 201 | id: 'opencode', name: 'OpenCode', models: { |
| 202 | 'big-pickle': { id: 'big-pickle', name: 'Big Pickle' } |
| 203 | } |
| 204 | }] } |
| 205 | : [])); |
| 206 | }); |
| 207 | server.listen(0, '127.0.0.1', () => { |
| 208 | console.log('opencode server listening on http://127.0.0.1:' + server.address().port); |
| 209 | }); |
| 210 | }`, |
| 211 | ); |
| 212 | const windows = (yield* HostProcess.Platform) === "win32"; |
| 213 | const wrapperPath = windows ? `${binaryPath}.cmd` : binaryPath; |
| 214 | const node = yield* HostProcess.ExecutablePath; |
| 215 | yield* fs.writeFileString( |
| 216 | wrapperPath, |
| 217 | windows |
| 218 | ? `@echo off\r\n"${node}" "${scriptPath}" %*\r\n` |
| 219 | : `#!/bin/sh\nexec "${node}" "${scriptPath}" "$@"\n`, |
| 220 | ); |
| 221 | if (!windows) yield* fs.chmod(wrapperPath, 0o755); |
| 222 | |
| 223 | const instance = yield* OpenCodeDriver.create({ |
| 224 | instanceId: ProviderInstanceId.make("opencode-home"), |
| 225 | displayName: undefined, |
| 226 | environment: [], |
| 227 | enabled: true, |
| 228 | config: { |
| 229 | ...OpenCodeDriver.defaultConfig(), |
| 230 | binaryPath: windows ? "~/opencode.cmd" : "~/opencode", |
| 231 | }, |
| 232 | }).pipe(Effect.provideService(HostProcess.HomeDirectory, home)); |
| 233 | const snapshot = yield* instance.snapshot.refresh; |
| 234 | assert.strictEqual(snapshot.status, "ready"); |
| 235 | assert.strictEqual(snapshot.version, "1.18.32"); |
| 236 | assert.isTrue(snapshot.models.some((model) => model.slug === "opencode/big-pickle")); |
| 237 | }).pipe( |
| 238 | Effect.scoped, |
| 239 | Effect.provide( |
| 240 | Layer.mergeAll( |
| 241 | IdAllocator.layer, |
| 242 | McpProviderSessions.layer, |
| 243 | ProviderLatestVersions.layer, |
| 244 | TestProviderHost.layer({ runBackgroundWork: false }), |
| 245 | Layer.succeed( |
| 246 | ProviderEventLoggers.ProviderEventLoggers, |
| 247 | ProviderEventLoggers.NoOpProviderEventLoggers, |
| 248 | ), |
| 249 | OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)), |
| 250 | ).pipe( |
| 251 | Layer.provideMerge( |
| 252 | Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, FetchHttpClient.layer), |
| 253 | ), |
| 254 | ), |
| 255 | ), |
| 256 | ), |
| 257 | ); |
| 258 | |
| 259 | // Under MISE_OFFLINE the shim cannot install OpenCode; a normal run installs 2.x first. |
| 260 | const lazyMiseShim = { |
| 261 | ...openCode2Runtime, |
| 262 | runOpenCodeCommand: ({ environment }: { readonly environment?: NodeJS.ProcessEnv }) => |
| 263 | environment?.MISE_OFFLINE === "1" |
| 264 | ? Effect.fail( |
| 265 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 266 | operation: "runOpenCodeCommand", |
| 267 | detail: "mise ERROR Failed to install opencode@latest", |
| 268 | }), |
| 269 | ) |
| 270 | : Effect.succeed({ stdout: "opencode v2.0.18\n", stderr: "", code: 0 }), |
| 271 | } as unknown as OpenCodeRuntime.OpenCodeRuntime["Service"]; |
| 272 | |
| 273 | it.layer(layer)("OpenCodeDriver runtime selection", (it) => { |
| 274 | it.effect("never starts a 1.x server for an OpenCode 2 instance", () => |
| 275 | Effect.gen(function* () { |
| 276 | serverStarts.length = 0; |
| 277 | const instance = yield* create({}, noHttp); |
| 278 | yield* Effect.flip( |
| 279 | instance.textGeneration.generateThreadTitle({ |
| 280 | cwd: process.cwd(), |
| 281 | message: "hello", |
| 282 | modelSelection: { instanceId: instance.instanceId, model: "opencode/big-pickle" }, |
| 283 | }), |
| 284 | ); |
| 285 | assert.deepStrictEqual(serverStarts, ["start"]); |
| 286 | }), |
| 287 | ); |
| 288 | |
| 289 | it.effect.each(["2.1.2", null])( |
| 290 | "reports the installed CLI version independently of the loopback server (%s)", |
| 291 | (installedVersion) => |
| 292 | Effect.gen(function* () { |
| 293 | const probeOffline: Array<string | undefined> = []; |
| 294 | const runtime = { |
| 295 | ...openCode2Runtime, |
| 296 | runOpenCodeCommand: (input) => |
| 297 | Effect.sync(() => { |
| 298 | probeOffline.push(input.environment?.MISE_OFFLINE); |
| 299 | return { |
| 300 | stdout: |
| 301 | installedVersion === null ? "unrecognized" : `opencode v${installedVersion}\n`, |
| 302 | stderr: "", |
| 303 | code: 0, |
| 304 | }; |
| 305 | }), |
| 306 | } as OpenCodeRuntime.OpenCodeRuntime["Service"]; |
| 307 | const instance = yield* create( |
| 308 | { serverUrl: "http://127.0.0.1:4096" }, |
| 309 | replayOpenCodeServer(OPENCODE_2_RESPONSES, ""), |
| 310 | ).pipe(Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, runtime)); |
| 311 | |
| 312 | const snapshot = yield* instance.snapshot.refresh; |
| 313 | assert.strictEqual(snapshot.version, "2.0.18"); |
| 314 | assert.strictEqual(snapshot.installedVersion, installedVersion ?? undefined); |
| 315 | const maintenance = yield* instance.snapshot.resolveMaintenance({ fresh: true }); |
| 316 | assert.strictEqual(maintenance.packageName, "@opencode/cli"); |
| 317 | assert.isNotEmpty(probeOffline); |
| 318 | assert.isTrue(probeOffline.every((offline) => offline === "1")); |
| 319 | }), |
| 320 | ); |
| 321 | |
| 322 | it.effect("skips the installed CLI probe when a localhost provider is disabled", () => |
| 323 | Effect.gen(function* () { |
| 324 | const probed: string[] = []; |
| 325 | const runtime = { |
| 326 | ...openCode2Runtime, |
| 327 | runOpenCodeCommand: () => |
| 328 | Effect.sync(() => { |
| 329 | probed.push("--version"); |
| 330 | return { stdout: "opencode v2.1.2\n", stderr: "", code: 0 }; |
| 331 | }), |
| 332 | } as OpenCodeRuntime.OpenCodeRuntime["Service"]; |
| 333 | const instance = yield* create({ serverUrl: "http://127.0.0.1:4096" }, noHttp, false).pipe( |
| 334 | Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, runtime), |
| 335 | ); |
| 336 | |
| 337 | const snapshot = yield* instance.snapshot.refresh; |
| 338 | assert.isFalse(snapshot.enabled); |
| 339 | assert.deepStrictEqual(probed, []); |
| 340 | }), |
| 341 | ); |
| 342 | |
| 343 | it.effect("opens a session through OpenCode 2 that a lazy mise shim installs on first use", () => |
| 344 | Effect.gen(function* () { |
| 345 | serverStarts.length = 0; |
| 346 | const instance = yield* create({}, noHttp).pipe( |
| 347 | Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, lazyMiseShim), |
| 348 | // The background status check probes offline, which this shim always fails. |
| 349 | Effect.provide(TestProviderHost.layer({ runBackgroundWork: false })), |
| 350 | ); |
| 351 | |
| 352 | yield* instance.orchestrationAdapter |
| 353 | .openSession({ |
| 354 | threadId: ThreadId.make("thread-lazy-mise"), |
| 355 | providerSessionId: ProviderSessionId.make("session-lazy-mise"), |
| 356 | modelSelection: { instanceId: instance.instanceId, model: "opencode/big-pickle" }, |
| 357 | runtimePolicy: { runtimeMode: "full-access", interactionMode: "default", cwd: null }, |
| 358 | }) |
| 359 | .pipe(Effect.scoped, Effect.flip); |
| 360 | assert.deepStrictEqual(serverStarts, ["start"], "the OpenCode 2 adapter starts its server"); |
| 361 | const capabilities = yield* instance.orchestrationAdapter.getCapabilities(); |
| 362 | assert.isTrue(capabilities.sessions.supportsRuntimeModeSwitchInSession); |
| 363 | }), |
| 364 | ); |
| 365 | |
| 366 | it.effect("does not scan a workspace through a 1.x server it could not probe offline", () => |
| 367 | Effect.gen(function* () { |
| 368 | serverStarts.length = 0; |
| 369 | const instance = yield* create({}, noHttp).pipe( |
| 370 | Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, lazyMiseShim), |
| 371 | ); |
| 372 | |
| 373 | yield* Effect.flip(instance.snapshotForCwd!(process.cwd())); |
| 374 | assert.deepStrictEqual(serverStarts, []); |
| 375 | }), |
| 376 | ); |
| 377 | |
| 378 | it.effect.each([ |
| 379 | "1.18.32", |
| 380 | "opencode v2.0.18", |
| 381 | "opencode v2.2.4", |
| 382 | "opencode v2.2.5", |
| 383 | "opencode v2.2.6", |
| 384 | ])("advertises native goal support only for supported OpenCode versions: %s", (version) => |
| 385 | Effect.gen(function* () { |
| 386 | const fs = yield* FileSystem.FileSystem; |
| 387 | const root = yield* fs.makeTempDirectoryScoped({ prefix: "opencode-goal-capability-" }); |
| 388 | const binaryPath = NodePath.join( |
| 389 | root, |
| 390 | "lib", |
| 391 | "node_modules", |
| 392 | "@opencode", |
| 393 | "cli", |
| 394 | "bin", |
| 395 | "opencode", |
| 396 | ); |
| 397 | yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true }); |
| 398 | yield* fs.writeFileString(binaryPath, ""); |
| 399 | const instance = yield* create({ binaryPath }, noHttp).pipe( |
| 400 | Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, { |
| 401 | ...openCode2Runtime, |
| 402 | runOpenCodeCommand: () => Effect.succeed({ stdout: version, stderr: "", code: 0 }), |
| 403 | }), |
| 404 | ); |
| 405 | yield* instance.snapshot.resolveMaintenance({ fresh: true }); |
| 406 | const capabilities = yield* instance.orchestrationAdapter.getCapabilities(); |
| 407 | assert.equal( |
| 408 | capabilities.turns.supportsNativeGoals === true, |
| 409 | version.endsWith("2.2.5") || version.endsWith("2.2.6"), |
| 410 | ); |
| 411 | }), |
| 412 | ); |
| 413 | |
| 414 | it.effect("uses the connected OpenCode version for goal support after an upgrade", () => |
| 415 | Effect.gen(function* () { |
| 416 | const fs = yield* FileSystem.FileSystem; |
| 417 | const root = yield* fs.makeTempDirectoryScoped({ prefix: "opencode-upgraded-goals-" }); |
| 418 | const binaryPath = NodePath.join( |
| 419 | root, |
| 420 | "lib", |
| 421 | "node_modules", |
| 422 | "@opencode", |
| 423 | "cli", |
| 424 | "bin", |
| 425 | "opencode", |
| 426 | ); |
| 427 | yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true }); |
| 428 | yield* fs.writeFileString(binaryPath, ""); |
| 429 | const http = HttpClient.make((request) => { |
| 430 | const path = new URL(request.url).pathname; |
| 431 | if (path === "/api/info") |
| 432 | return Effect.succeed( |
| 433 | HttpClientResponse.fromWeb( |
| 434 | request, |
| 435 | Response.json({ |
| 436 | ...JSON.parse(OPENCODE_2_RESPONSES["/api/info"].body), |
| 437 | version: "2.2.5", |
| 438 | }), |
| 439 | ), |
| 440 | ); |
| 441 | if (path === "/api/model") |
| 442 | return Effect.succeed( |
| 443 | HttpClientResponse.fromWeb( |
| 444 | request, |
| 445 | Response.json({ location: { directory: "/work" }, data: [] }), |
| 446 | ), |
| 447 | ); |
| 448 | if (path === "/api/event") |
| 449 | return Effect.succeed( |
| 450 | HttpClientResponse.fromWeb( |
| 451 | request, |
| 452 | new Response(new ReadableStream(), { |
| 453 | headers: { "content-type": "text/event-stream" }, |
| 454 | }), |
| 455 | ), |
| 456 | ); |
| 457 | return Effect.die(`Unexpected request: ${path}`); |
| 458 | }); |
| 459 | const instance = yield* create({ binaryPath }, http).pipe( |
| 460 | Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, { |
| 461 | ...openCode2Runtime, |
| 462 | runOpenCodeCommand: () => |
| 463 | Effect.succeed({ stdout: "opencode v2.2.4", stderr: "", code: 0 }), |
| 464 | startOpenCodeServerProcess: ({ verify }) => |
| 465 | Effect.gen(function* () { |
| 466 | const url = "http://127.0.0.1:4096"; |
| 467 | const version = verify ? yield* verify(url) : "2.2.5"; |
| 468 | return { url, version, isRunning: Effect.succeed(true), exitCode: Effect.never }; |
| 469 | }), |
| 470 | }), |
| 471 | ); |
| 472 | yield* instance.snapshot.resolveMaintenance({ fresh: true }); |
| 473 | assert.isFalse( |
| 474 | (yield* instance.orchestrationAdapter.getCapabilities()).turns.supportsNativeGoals, |
| 475 | ); |
| 476 | const session = yield* instance.orchestrationAdapter.openSession({ |
| 477 | threadId: ThreadId.make("upgraded-goal"), |
| 478 | providerSessionId: ProviderSessionId.make("upgraded-goal"), |
| 479 | modelSelection: { instanceId: instance.instanceId, model: "opencode/big-pickle" }, |
| 480 | runtimePolicy: { runtimeMode: "full-access", interactionMode: "default", cwd: null }, |
| 481 | }); |
| 482 | assert.isTrue(session.providerSession.capabilities.turns.supportsNativeGoals); |
| 483 | assert.isTrue( |
| 484 | (yield* instance.orchestrationAdapter.getCapabilities()).turns.supportsNativeGoals, |
| 485 | ); |
| 486 | }), |
| 487 | ); |
| 488 | |
| 489 | it.effect("answers capability reads without waiting on an unreachable server", () => |
| 490 | Effect.gen(function* () { |
| 491 | const hang = HttpClient.make(() => Effect.never); |
| 492 | const instance = yield* create({ serverUrl: "http://127.0.0.1:9" }, hang); |
| 493 | |
| 494 | const capabilities = yield* instance.orchestrationAdapter |
| 495 | .getCapabilities() |
| 496 | .pipe(Effect.forkChild); |
| 497 | yield* Effect.yieldNow; |
| 498 | assert.isDefined(capabilities.pollUnsafe()); |
| 499 | yield* Fiber.join(capabilities); |
| 500 | }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), |
| 501 | ); |
| 502 | |
| 503 | it.effect.each(["/api/debug/location", "/api/event"])( |
| 504 | "lists workspace skills from an external OpenCode 2 server whose %s never answers", |
| 505 | (stalled) => |
| 506 | Effect.gen(function* () { |
| 507 | const answers: Record<string, string> = { |
| 508 | "/api/info": OPENCODE_2_RESPONSES["/api/info"].body, |
| 509 | "/api/debug/location": "[]", |
| 510 | "/api/model": '{"location":{"directory":"/work"},"data":[]}', |
| 511 | "/api/provider": '{"location":{"directory":"/work"},"data":[]}', |
| 512 | "/api/command": OPENCODE_2_WORKSPACE_RESPONSES["/api/command"].body, |
| 513 | "/api/skill": OPENCODE_2_WORKSPACE_RESPONSES["/api/skill"].body, |
| 514 | }; |
| 515 | const http = HttpClient.make((request) => { |
| 516 | const path = new URL(request.url).pathname; |
| 517 | if (path === stalled) return Effect.never; |
| 518 | if (path === "/api/event") |
| 519 | return Effect.succeed( |
| 520 | HttpClientResponse.fromWeb( |
| 521 | request, |
| 522 | new Response(new ReadableStream(), { |
| 523 | headers: { "content-type": "text/event-stream" }, |
| 524 | }), |
| 525 | ), |
| 526 | ); |
| 527 | const body = answers[path]; |
| 528 | return body === undefined |
| 529 | ? Effect.die(`Unexpected request: ${path}`) |
| 530 | : Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(JSON.parse(body)))); |
| 531 | }); |
| 532 | const instance = yield* create({ serverUrl: "http://127.0.0.1:4096" }, http); |
| 533 | |
| 534 | const snapshot = yield* instance.snapshotForCwd!("/work").pipe(Effect.forkChild); |
| 535 | yield* TestClock.adjust("30 seconds"); |
| 536 | const { skills } = yield* Fiber.join(snapshot); |
| 537 | assert.include( |
| 538 | skills.map((skill) => skill.name), |
| 539 | "plum", |
| 540 | ); |
| 541 | }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), |
| 542 | ); |
| 543 | |
| 544 | it.effect("caches a cold OpenCode 2 directory's skills only after its scan ends", () => |
| 545 | Effect.gen(function* () { |
| 546 | // OpenCode 2.2.7: touching a location lists it as loaded with built-in commands and skills |
| 547 | // at once, while provider.list waits for the scan that adds the project's skills. |
| 548 | const scanEnded = yield* Deferred.make<void>(); |
| 549 | const builtinSkills = JSON.stringify({ |
| 550 | location: { directory: "/work" }, |
| 551 | data: ( |
| 552 | JSON.parse(OPENCODE_2_WORKSPACE_RESPONSES["/api/skill"].body).data as Array<{ |
| 553 | id: string; |
| 554 | }> |
| 555 | ).filter((skill) => skill.id !== "plum"), |
| 556 | }); |
| 557 | const http = HttpClient.make((request) => { |
| 558 | const path = new URL(request.url).pathname; |
| 559 | const json = (body: string) => |
| 560 | Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(JSON.parse(body)))); |
| 561 | const afterScan = (body: string) => |
| 562 | Deferred.await(scanEnded).pipe(Effect.andThen(json(body))); |
| 563 | switch (path) { |
| 564 | case "/api/info": |
| 565 | return json( |
| 566 | JSON.stringify({ |
| 567 | ...JSON.parse(OPENCODE_2_RESPONSES["/api/info"].body), |
| 568 | version: "2.2.7", |
| 569 | }), |
| 570 | ); |
| 571 | case "/api/event": |
| 572 | return Effect.succeed( |
| 573 | HttpClientResponse.fromWeb( |
| 574 | request, |
| 575 | new Response(new ReadableStream(), { |
| 576 | headers: { "content-type": "text/event-stream" }, |
| 577 | }), |
| 578 | ), |
| 579 | ); |
| 580 | case "/api/debug/location": |
| 581 | return json('[{"directory":"/work"}]'); |
| 582 | case "/api/provider": |
| 583 | case "/api/model": |
| 584 | return afterScan('{"location":{"directory":"/work"},"data":[]}'); |
| 585 | case "/api/command": |
| 586 | return json(OPENCODE_2_WORKSPACE_RESPONSES["/api/command"].body); |
| 587 | case "/api/skill": |
| 588 | return Deferred.isDone(scanEnded).pipe( |
| 589 | Effect.flatMap((done) => |
| 590 | json(done ? OPENCODE_2_WORKSPACE_RESPONSES["/api/skill"].body : builtinSkills), |
| 591 | ), |
| 592 | ); |
| 593 | default: |
| 594 | return Effect.die(`Unexpected request: ${path}`); |
| 595 | } |
| 596 | }); |
| 597 | const instance = yield* create({ serverUrl: "http://127.0.0.1:4096" }, http); |
| 598 | |
| 599 | const snapshot = yield* instance.snapshotForCwd!("/work").pipe(Effect.forkChild); |
| 600 | yield* TestClock.adjust("1 second"); |
| 601 | yield* Deferred.succeed(scanEnded, undefined); |
| 602 | yield* TestClock.adjust("30 seconds"); |
| 603 | const { skills } = yield* Fiber.join(snapshot); |
| 604 | assert.include( |
| 605 | skills.map((skill) => skill.name), |
| 606 | "plum", |
| 607 | ); |
| 608 | }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), |
| 609 | ); |
| 610 | |
| 611 | it.effect.each(["probe", "error", "empty"] as const)( |
| 612 | "recovers discovery without a manual refresh after %s", |
| 613 | (initialCatalog) => |
| 614 | Effect.gen(function* () { |
| 615 | const releaseCatalog = yield* Deferred.make<void>(); |
| 616 | const discoveryLogs: Array<Record<string, unknown>> = []; |
| 617 | const logger = Logger.make(({ message, fiber }) => { |
| 618 | if (Array.isArray(message) && message.includes("OpenCode discovery failed")) { |
| 619 | discoveryLogs.push({ ...fiber.getRef(References.CurrentLogAnnotations) }); |
| 620 | } |
| 621 | }); |
| 622 | let catalogAvailable = false; |
| 623 | let modelReads = 0; |
| 624 | const replies = { |
| 625 | ...OPENCODE_2_RESPONSES, |
| 626 | "/api/provider": { |
| 627 | status: 200, |
| 628 | contentType: "application/json", |
| 629 | body: '{"location":{"directory":"/work"},"data":[]}', |
| 630 | }, |
| 631 | "/api/model": { |
| 632 | status: 200, |
| 633 | contentType: "application/json", |
| 634 | body: JSON.stringify({ |
| 635 | location: { directory: "/work" }, |
| 636 | data: [ |
| 637 | { |
| 638 | id: "big-pickle", |
| 639 | modelID: "big-pickle", |
| 640 | providerID: "opencode", |
| 641 | name: "Big Pickle", |
| 642 | package: "@opencode/ai/providers/openai-compatible", |
| 643 | settings: {}, |
| 644 | compatibility: {}, |
| 645 | capabilities: { tools: true, input: ["text"], output: ["text"] }, |
| 646 | variants: [], |
| 647 | time: { released: 1789516800000 }, |
| 648 | cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }], |
| 649 | status: "active", |
| 650 | enabled: true, |
| 651 | limit: { context: 1000000, output: 65536 }, |
| 652 | }, |
| 653 | ], |
| 654 | }), |
| 655 | }, |
| 656 | }; |
| 657 | const replay = replayOpenCodeServer(replies, "secret"); |
| 658 | const server = HttpClient.make((request) => |
| 659 | Effect.gen(function* () { |
| 660 | if (initialCatalog === "probe" && !catalogAvailable) { |
| 661 | yield* Deferred.await(releaseCatalog); |
| 662 | return HttpClientResponse.fromWeb( |
| 663 | request, |
| 664 | new Response('{"_tag":"InternalServerError","message":"server starting"}', { |
| 665 | status: 503, |
| 666 | headers: { "content-type": "application/json" }, |
| 667 | }), |
| 668 | ); |
| 669 | } |
| 670 | if (new URL(request.url).pathname === "/api/model") { |
| 671 | modelReads += 1; |
| 672 | yield* Deferred.await(releaseCatalog); |
| 673 | if (!catalogAvailable) { |
| 674 | return HttpClientResponse.fromWeb( |
| 675 | request, |
| 676 | new Response( |
| 677 | initialCatalog === "error" |
| 678 | ? '{"_tag":"InternalServerError","message":"catalog unavailable"}' |
| 679 | : '{"location":{"directory":"/work"},"data":[]}', |
| 680 | { |
| 681 | status: initialCatalog === "error" ? 500 : 200, |
| 682 | headers: { "content-type": "application/json" }, |
| 683 | }, |
| 684 | ), |
| 685 | ); |
| 686 | } |
| 687 | } |
| 688 | return yield* replay.execute(request); |
| 689 | }), |
| 690 | ); |
| 691 | const instance = yield* create( |
| 692 | { serverUrl: "http://127.0.0.1:4096", serverPassword: "secret" }, |
| 693 | server, |
| 694 | ).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))); |
| 695 | const initial = yield* instance.snapshot.streamChanges.pipe( |
| 696 | Stream.filter( |
| 697 | (snapshot) => |
| 698 | snapshot.installed && |
| 699 | snapshot.status === (initialCatalog === "empty" ? "warning" : "error"), |
| 700 | ), |
| 701 | Stream.take(1), |
| 702 | Stream.runCollect, |
| 703 | Effect.forkChild, |
| 704 | ); |
| 705 | yield* Effect.yieldNow; |
| 706 | yield* Deferred.succeed(releaseCatalog, undefined); |
| 707 | yield* TestClock.adjust("5 seconds"); |
| 708 | const [failed] = Array.from(yield* Fiber.join(initial)); |
| 709 | assert.strictEqual(failed?.auth.status, "unknown"); |
| 710 | assert.deepStrictEqual(failed?.models, []); |
| 711 | if (initialCatalog === "probe") assert.strictEqual(failed?.version, null); |
| 712 | assert.strictEqual(discoveryLogs.length, 1); |
| 713 | assert.strictEqual(discoveryLogs[0]?.providerInstanceId, "opencode-test"); |
| 714 | assert.strictEqual(discoveryLogs[0]?.serverMode, "external"); |
| 715 | assert.strictEqual( |
| 716 | discoveryLogs[0]?.phase, |
| 717 | initialCatalog === "probe" ? "version" : "models", |
| 718 | ); |
| 719 | |
| 720 | catalogAvailable = true; |
| 721 | const recovered = yield* instance.snapshot.streamChanges.pipe( |
| 722 | Stream.filter((snapshot) => snapshot.status === "ready"), |
| 723 | Stream.take(1), |
| 724 | Stream.runCollect, |
| 725 | Effect.forkChild, |
| 726 | ); |
| 727 | yield* TestClock.adjust("5 minutes"); |
| 728 | assert.strictEqual((yield* instance.snapshot.getSnapshot).status, "ready"); |
| 729 | const [ready] = Array.from(yield* Fiber.join(recovered)); |
| 730 | assert.strictEqual(ready?.auth.status, "authenticated"); |
| 731 | assert.deepStrictEqual( |
| 732 | ready?.models.map((model) => model.slug), |
| 733 | ["opencode/big-pickle"], |
| 734 | ); |
| 735 | |
| 736 | const readsAfterRecovery = modelReads; |
| 737 | yield* TestClock.adjust("15 minutes"); |
| 738 | assert.strictEqual(modelReads, readsAfterRecovery); |
| 739 | assert.strictEqual(discoveryLogs.length, 1); |
| 740 | }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), |
| 741 | ); |
| 742 | |
| 743 | it.effect("lists models from an external server that lacks the host's directory", () => |
| 744 | Effect.gen(function* () { |
| 745 | const replay = replayOpenCodeServer(OPENCODE_2_RESPONSES, "secret"); |
| 746 | const catalog = (directory: string | undefined) => ({ |
| 747 | location: { directory: directory ?? "/srv/remote" }, |
| 748 | data: [ |
| 749 | { |
| 750 | id: "big-pickle", |
| 751 | modelID: "big-pickle", |
| 752 | providerID: "opencode", |
| 753 | name: "Big Pickle", |
| 754 | package: "@opencode/ai/providers/openai-compatible", |
| 755 | settings: {}, |
| 756 | compatibility: {}, |
| 757 | capabilities: { tools: true, input: ["text"], output: ["text"] }, |
| 758 | variants: [], |
| 759 | time: { released: 1789516800000 }, |
| 760 | cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }], |
| 761 | status: "active", |
| 762 | enabled: true, |
| 763 | limit: { context: 1000000, output: 65536 }, |
| 764 | }, |
| 765 | ], |
| 766 | }); |
| 767 | // Like a real remote OpenCode 2 server: a directory it does not have is a 404. |
| 768 | const server = HttpClient.make((request) => { |
| 769 | const url = new URL(request.url); |
| 770 | if (url.pathname !== "/api/model" && url.pathname !== "/api/provider") { |
| 771 | return replay.execute(request); |
| 772 | } |
| 773 | const directory = Option.getOrUndefined( |
| 774 | UrlParams.getFirst(request.urlParams, "location[directory]"), |
| 775 | ); |
| 776 | const known = directory === undefined || directory === "/srv/remote"; |
| 777 | const body = known |
| 778 | ? url.pathname === "/api/model" |
| 779 | ? catalog(directory) |
| 780 | : { |
| 781 | location: { directory: directory ?? "/srv/remote" }, |
| 782 | data: [ |
| 783 | { |
| 784 | id: "opencode", |
| 785 | integrationID: "opencode", |
| 786 | name: "OpenCode Zen", |
| 787 | activation: "enabled", |
| 788 | package: "@opencode/ai/providers/openai-compatible", |
| 789 | settings: {}, |
| 790 | }, |
| 791 | ], |
| 792 | } |
| 793 | : { |
| 794 | _tag: "LocationNotFoundError", |
| 795 | message: `Location not found: ${directory}`, |
| 796 | }; |
| 797 | return Effect.succeed( |
| 798 | HttpClientResponse.fromWeb( |
| 799 | request, |
| 800 | new Response(JSON.stringify(body), { |
| 801 | status: known ? 200 : 404, |
| 802 | headers: { "content-type": "application/json" }, |
| 803 | }), |
| 804 | ), |
| 805 | ); |
| 806 | }); |
| 807 | const instance = yield* create( |
| 808 | { serverUrl: "http://127.0.0.1:4096", serverPassword: "secret" }, |
| 809 | server, |
| 810 | ); |
| 811 | const settled = yield* instance.snapshot.streamChanges.pipe( |
| 812 | Stream.filter( |
| 813 | (snapshot) => |
| 814 | snapshot.installed && (snapshot.status === "ready" || snapshot.status === "error"), |
| 815 | ), |
| 816 | Stream.take(1), |
| 817 | Stream.runCollect, |
| 818 | Effect.forkChild, |
| 819 | ); |
| 820 | yield* Effect.yieldNow; |
| 821 | yield* TestClock.adjust("5 seconds"); |
| 822 | const [snapshot] = Array.from(yield* Fiber.join(settled)); |
| 823 | assert.deepStrictEqual( |
| 824 | { status: snapshot?.status, message: snapshot?.message }, |
| 825 | { status: "ready", message: "OpenCode 2.0.18 lists 1 model." }, |
| 826 | ); |
| 827 | assert.deepStrictEqual( |
| 828 | snapshot?.models.map((model) => [model.slug, model.subProvider]), |
| 829 | [["opencode/big-pickle", "OpenCode Zen"]], |
| 830 | ); |
| 831 | }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), |
| 832 | ); |
| 833 | |
| 834 | it.effect("lists a project's own opencode.jsonc models in that project's snapshot", () => |
| 835 | Effect.gen(function* () { |
| 836 | const snapshotFor = yield* makeOpenCode2ProjectInstance("listed"); |
| 837 | |
| 838 | const projectSnapshot = yield* snapshotFor(openCode2Project); |
| 839 | assert.deepStrictEqual(projectSnapshot.models.map((entry) => entry.slug).toSorted(), [ |
| 840 | "opencode/big-pickle", |
| 841 | "uni/large-gpt", |
| 842 | "uni/medium-gpt", |
| 843 | ]); |
| 844 | const otherSnapshot = yield* snapshotFor("/work/other-project"); |
| 845 | assert.deepStrictEqual( |
| 846 | otherSnapshot.models.map((entry) => entry.slug), |
| 847 | ["opencode/big-pickle"], |
| 848 | ); |
| 849 | assert.strictEqual(otherSnapshot.workspaceModels, undefined); |
| 850 | assert.strictEqual(otherSnapshot.workspaceModelsPending, undefined); |
| 851 | }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), |
| 852 | ); |
| 853 | |
| 854 | it.effect.each(["models-unavailable", "providers-unavailable"] as const)( |
| 855 | "reports a project's catalog unknown when its read fails (%s)", |
| 856 | (projectCatalog) => |
| 857 | Effect.gen(function* () { |
| 858 | const snapshotFor = yield* makeOpenCode2ProjectInstance(projectCatalog); |
| 859 | |
| 860 | const projectSnapshot = yield* snapshotFor(openCode2Project); |
| 861 | assert.deepStrictEqual( |
| 862 | projectSnapshot.models.map((entry) => entry.slug), |
| 863 | ["opencode/big-pickle"], |
| 864 | ); |
| 865 | assert.strictEqual(projectSnapshot.workspaceModels, undefined); |
| 866 | assert.strictEqual(projectSnapshot.workspaceModelsPending, true); |
| 867 | }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), |
| 868 | ); |
| 869 | |
| 870 | it.effect("does not retry a rejected server password in the background", () => |
| 871 | Effect.gen(function* () { |
| 872 | const releaseResponse = yield* Deferred.make<void>(); |
| 873 | const requested: Array<string> = []; |
| 874 | const server = replayOpenCodeServer(OPENCODE_2_RESPONSES, "secret", requested); |
| 875 | const instance = yield* create( |
| 876 | { serverUrl: "http://127.0.0.1:4096", serverPassword: "wrong" }, |
| 877 | HttpClient.make((request) => |
| 878 | Deferred.await(releaseResponse).pipe(Effect.andThen(server.execute(request))), |
| 879 | ), |
| 880 | ); |
| 881 | // Wait for startup and its maintenance enrichment, both of which probe. |
| 882 | const rejected = yield* instance.snapshot.streamChanges.pipe( |
| 883 | Stream.filter( |
| 884 | (snapshot) => snapshot.status === "error" && snapshot.versionAdvisory !== undefined, |
| 885 | ), |
| 886 | Stream.take(1), |
| 887 | Stream.runCollect, |
| 888 | Effect.forkChild, |
| 889 | ); |
| 890 | yield* Effect.yieldNow; |
| 891 | yield* Deferred.succeed(releaseResponse, undefined); |
| 892 | const [snapshot] = Array.from(yield* Fiber.join(rejected)); |
| 893 | assert.strictEqual(snapshot?.version, null); |
| 894 | assert.strictEqual(snapshot?.auth.status, "unauthenticated"); |
| 895 | const readsAfterRejection = requested.length; |
| 896 | |
| 897 | yield* TestClock.adjust("15 minutes"); |
| 898 | assert.strictEqual(requested.length, readsAfterRejection); |
| 899 | }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), |
| 900 | ); |
| 901 | |
| 902 | it.effect.each([ |
| 903 | { status: 200, data: null, reason: "unsupported" }, |
| 904 | { status: 404, data: null, reason: "unsupported" }, |
| 905 | { status: 503, data: null, reason: "probeFailed" }, |
| 906 | { |
| 907 | status: 200, |
| 908 | data: { |
| 909 | workspace: { |
| 910 | id: "remote-workspace", |
| 911 | name: "Remote workspace", |
| 912 | usageURL: "https://opencode.ai/console/remote-workspace", |
| 913 | }, |
| 914 | budgets: [ |
| 915 | { |
| 916 | id: "all", |
| 917 | limit: 20, |
| 918 | spent: 15, |
| 919 | scope: "combined", |
| 920 | per: "set", |
| 921 | coverage: "all", |
| 922 | models: [], |
| 923 | shared: true, |
| 924 | resetsAt: 1793491200000, |
| 925 | }, |
| 926 | ], |
| 927 | }, |
| 928 | reason: undefined, |
| 929 | }, |
| 930 | ])( |
| 931 | "reads external workspace usage without local credentials, HTTP $status, $reason", |
| 932 | (scenario) => |
| 933 | Effect.gen(function* () { |
| 934 | const requested: string[] = []; |
| 935 | const replay = replayOpenCodeServer(OPENCODE_2_RESPONSES, "secret", requested); |
| 936 | const server = HttpClient.make((request) => { |
| 937 | assert.notInclude(request.url, "opencode.ai/zen"); |
| 938 | if (request.url.endsWith("/api/experimental/usage/limits")) { |
| 939 | assert.strictEqual(request.headers.authorization, "Basic b3BlbmNvZGU6c2VjcmV0"); |
| 940 | return Effect.succeed( |
| 941 | HttpClientResponse.fromWeb( |
| 942 | request, |
| 943 | Response.json( |
| 944 | { |
| 945 | location: { directory: "/work" }, |
| 946 | data: scenario.data, |
| 947 | }, |
| 948 | { status: scenario.status }, |
| 949 | ), |
| 950 | ), |
| 951 | ); |
| 952 | } |
| 953 | return replay.execute(request); |
| 954 | }); |
| 955 | const instance = yield* create( |
| 956 | { serverUrl: "https://remote.example", serverPassword: "secret" }, |
| 957 | server, |
| 958 | ); |
| 959 | const [snapshot] = Array.from( |
| 960 | yield* instance.snapshot.streamChanges.pipe( |
| 961 | Stream.filter((snapshot) => snapshot.usageLimits !== undefined), |
| 962 | Stream.take(1), |
| 963 | Stream.runCollect, |
| 964 | ), |
| 965 | ); |
| 966 | assert.strictEqual(snapshot?.usageLimits?.unavailable?.reason, scenario.reason); |
| 967 | if (scenario.reason === undefined) { |
| 968 | assert.strictEqual(snapshot?.usageLimits?.windows[0]?.usedPercent, 75); |
| 969 | assert.strictEqual(snapshot?.usageLimits?.externalUsage?.label, "Remote workspace"); |
| 970 | assert.deepStrictEqual(snapshot?.usageLimits?.windows[0]?.providerIds, []); |
| 971 | } else { |
| 972 | assert.deepStrictEqual(snapshot?.usageLimits?.windows, []); |
| 973 | } |
| 974 | }), |
| 975 | ); |
| 976 | |
| 977 | it.effect.each( |
| 978 | [ |
| 979 | { name: "recovers" }, |
| 980 | { name: "skips without demand", demand: false }, |
| 981 | { name: "respects a disabled interval", intervalOff: true }, |
| 982 | { name: "skips disabled instances", enabled: false }, |
| 983 | { name: "skips unsupported usage", unsupported: true }, |
| 984 | ].map((scenario) => ({ |
| 985 | enabled: true, |
| 986 | demand: true, |
| 987 | intervalOff: false, |
| 988 | unsupported: false, |
| 989 | ...scenario, |
| 990 | })), |
| 991 | )("Go usage recovery $name without restarting a ready catalog", (scenario) => |
| 992 | Effect.gen(function* () { |
| 993 | const usageStarted = yield* Deferred.make<void>(); |
| 994 | let usageReads = 0; |
| 995 | let serverStarts = 0; |
| 996 | let modelReads = 0; |
| 997 | const server = HttpClient.make((request) => { |
| 998 | if (request.url === "https://opencode.ai/zen/go/v1/usage") { |
| 999 | usageReads += 1; |
| 1000 | assert.strictEqual(request.headers.authorization, "Bearer test-go-key"); |
| 1001 | if (scenario.unsupported) |
| 1002 | return Effect.succeed( |
| 1003 | HttpClientResponse.fromWeb(request, new Response(null, { status: 403 })), |
| 1004 | ); |
| 1005 | if (usageReads === 1) |
| 1006 | return Deferred.succeed(usageStarted, undefined).pipe(Effect.andThen(Effect.never)); |
| 1007 | const window = { percent: 10, resetsAt: "2026-11-01T00:00:00.000Z" }; |
| 1008 | return Effect.succeed( |
| 1009 | HttpClientResponse.fromWeb( |
| 1010 | request, |
| 1011 | Response.json({ usage: { rolling: window, weekly: window, monthly: window } }), |
| 1012 | ), |
| 1013 | ); |
| 1014 | } |
| 1015 | const path = new URL(request.url).pathname; |
| 1016 | if (path === "/api/experimental/usage/limits") |
| 1017 | return Effect.succeed( |
| 1018 | HttpClientResponse.fromWeb(request, new Response(null, { status: 404 })), |
| 1019 | ); |
| 1020 | if (path === "/api/model") modelReads += 1; |
| 1021 | const body = |
| 1022 | path === "/api/info" |
| 1023 | ? JSON.parse(OPENCODE_2_RESPONSES["/api/info"].body) |
| 1024 | : { |
| 1025 | location: { directory: "/work" }, |
| 1026 | data: |
| 1027 | path === "/api/model" |
| 1028 | ? [ |
| 1029 | { |
| 1030 | id: "big-pickle", |
| 1031 | modelID: "big-pickle", |
| 1032 | providerID: "opencode", |
| 1033 | name: "Big Pickle", |
| 1034 | package: "@opencode/ai/providers/openai-compatible", |
| 1035 | settings: {}, |
| 1036 | compatibility: {}, |
| 1037 | capabilities: { tools: true, input: ["text"], output: ["text"] }, |
| 1038 | variants: [], |
| 1039 | time: { released: 1789516800000 }, |
| 1040 | cost: [], |
| 1041 | status: "active", |
| 1042 | enabled: true, |
| 1043 | limit: { context: 1000000, output: 65536 }, |
| 1044 | }, |
| 1045 | ] |
| 1046 | : [], |
| 1047 | }; |
| 1048 | return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(body))); |
| 1049 | }); |
| 1050 | const runtime = { |
| 1051 | ...openCode2Runtime, |
| 1052 | startOpenCodeServerProcess: ({ |
| 1053 | verify, |
| 1054 | }: Parameters< |
| 1055 | OpenCodeRuntime.OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] |
| 1056 | >[0]) => |
| 1057 | Effect.gen(function* () { |
| 1058 | serverStarts += 1; |
| 1059 | const url = "http://127.0.0.1:4096"; |
| 1060 | const version = verify ? yield* verify(url) : "2.0.18"; |
| 1061 | return { url, version, isRunning: Effect.succeed(true), exitCode: Effect.never }; |
| 1062 | }), |
| 1063 | }; |
| 1064 | const instance = yield* OpenCodeDriver.create({ |
| 1065 | instanceId: ProviderInstanceId.make("opencode-usage-recovery"), |
| 1066 | displayName: undefined, |
| 1067 | environment: [ |
| 1068 | { |
| 1069 | name: "OPENCODE_AUTH_CONTENT", |
| 1070 | sensitive: true, |
| 1071 | value: JSON.stringify({ |
| 1072 | "opencode-go": { type: "api", key: "test-go-key" }, |
| 1073 | }), |
| 1074 | }, |
| 1075 | ], |
| 1076 | enabled: scenario.enabled, |
| 1077 | config: OpenCodeDriver.defaultConfig(), |
| 1078 | }).pipe( |
| 1079 | Effect.provide( |
| 1080 | TestProviderHost.layer({ |
| 1081 | runBackgroundWork: scenario.demand, |
| 1082 | settings: scenario.intervalOff |
| 1083 | ? { |
| 1084 | ...DEFAULT_SERVER_SETTINGS, |
| 1085 | backgroundActivity: { |
| 1086 | ...DEFAULT_SERVER_SETTINGS.backgroundActivity, |
| 1087 | profile: "custom", |
| 1088 | overrides: { providerHealthRefreshInterval: Duration.zero }, |
| 1089 | }, |
| 1090 | } |
| 1091 | : DEFAULT_SERVER_SETTINGS, |
| 1092 | }), |
| 1093 | ), |
| 1094 | Effect.provideService(HttpClient.HttpClient, server), |
| 1095 | Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, runtime), |
| 1096 | ); |
| 1097 | const initial = scenario.enabled |
| 1098 | ? yield* instance.snapshot.streamChanges.pipe( |
| 1099 | Stream.filter((snapshot) => snapshot.usageLimits !== undefined), |
| 1100 | Stream.take(1), |
| 1101 | Stream.runCollect, |
| 1102 | Effect.forkChild, |
| 1103 | ) |
| 1104 | : undefined; |
| 1105 | if (scenario.enabled && !scenario.unsupported) yield* Deferred.await(usageStarted); |
| 1106 | yield* TestClock.adjust("5 seconds"); |
| 1107 | const failed = initial |
| 1108 | ? Array.from(yield* Fiber.join(initial))[0] |
| 1109 | : yield* instance.snapshot.getSnapshot; |
| 1110 | if (scenario.enabled) { |
| 1111 | assert.strictEqual(failed?.status, "ready"); |
| 1112 | assert.strictEqual(failed?.auth.status, "authenticated"); |
| 1113 | } |
| 1114 | const initialReason = |
| 1115 | scenario.enabled && !scenario.unsupported ? "probeFailed" : "unsupported"; |
| 1116 | assert.strictEqual(failed?.usageLimits?.unavailable?.reason, initialReason); |
| 1117 | const catalogReads = modelReads; |
| 1118 | const starts = serverStarts; |
| 1119 | |
| 1120 | const shouldRecover = |
| 1121 | scenario.enabled && scenario.demand && !scenario.intervalOff && !scenario.unsupported; |
| 1122 | const recovery = shouldRecover |
| 1123 | ? yield* instance.snapshot.streamChanges.pipe( |
| 1124 | Stream.filter((snapshot) => snapshot.usageLimits?.windows.length === 3), |
| 1125 | Stream.take(1), |
| 1126 | Stream.runCollect, |
| 1127 | Effect.forkChild, |
| 1128 | ) |
| 1129 | : undefined; |
| 1130 | yield* TestClock.adjust("5 minutes"); |
| 1131 | const recovered = yield* instance.snapshot.getSnapshot; |
| 1132 | const expectedReads = !scenario.enabled ? 0 : shouldRecover ? 2 : 1; |
| 1133 | assert.strictEqual(usageReads, expectedReads); |
| 1134 | if (recovery) assert.deepStrictEqual(Array.from(yield* Fiber.join(recovery)), [recovered]); |
| 1135 | assert.strictEqual( |
| 1136 | recovered.usageLimits?.unavailable?.reason, |
| 1137 | shouldRecover ? undefined : initialReason, |
| 1138 | ); |
| 1139 | assert.deepStrictEqual( |
| 1140 | recovered.usageLimits?.windows.map((window) => window.kind), |
| 1141 | shouldRecover ? ["session", "weekly", "monthly"] : [], |
| 1142 | ); |
| 1143 | assert.strictEqual(modelReads, catalogReads); |
| 1144 | assert.strictEqual(serverStarts, starts); |
| 1145 | yield* TestClock.adjust("15 minutes"); |
| 1146 | assert.strictEqual(usageReads, expectedReads); |
| 1147 | assert.strictEqual(modelReads, catalogReads); |
| 1148 | assert.strictEqual(serverStarts, starts); |
| 1149 | }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), |
| 1150 | ); |
| 1151 | |
| 1152 | it.effect("reads Go usage from a stored key when the local server has no Console workspace", () => |
| 1153 | Effect.gen(function* () { |
| 1154 | let goUsageReads = 0; |
| 1155 | const usageStarted = yield* Deferred.make<void>(); |
| 1156 | const server = HttpClient.make((request) => { |
| 1157 | if (request.url === "https://opencode.ai/zen/go/v1/usage") { |
| 1158 | goUsageReads += 1; |
| 1159 | assert.strictEqual(request.headers.authorization, "Bearer test-go-key"); |
| 1160 | const window = { percent: 10, resetsAt: "2026-11-01T00:00:00.000Z" }; |
| 1161 | return Effect.succeed( |
| 1162 | HttpClientResponse.fromWeb( |
| 1163 | request, |
| 1164 | Response.json({ usage: { rolling: window, weekly: window, monthly: window } }), |
| 1165 | ), |
| 1166 | ); |
| 1167 | } |
| 1168 | const path = new URL(request.url).pathname; |
| 1169 | if (path === "/api/experimental/usage/limits") { |
| 1170 | const response = HttpClientResponse.fromWeb( |
| 1171 | request, |
| 1172 | Response.json({ location: { directory: "/work" }, data: null }), |
| 1173 | ); |
| 1174 | return Deferred.succeed(usageStarted, undefined).pipe(Effect.as(response)); |
| 1175 | } |
| 1176 | const body = |
| 1177 | path === "/api/info" |
| 1178 | ? JSON.parse(OPENCODE_2_RESPONSES["/api/info"].body) |
| 1179 | : { location: { directory: "/work" }, data: [] }; |
| 1180 | return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(body))); |
| 1181 | }); |
| 1182 | const runtime = { |
| 1183 | ...openCode2Runtime, |
| 1184 | startOpenCodeServerProcess: ({ |
| 1185 | verify, |
| 1186 | }: Parameters< |
| 1187 | OpenCodeRuntime.OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] |
| 1188 | >[0]) => |
| 1189 | Effect.gen(function* () { |
| 1190 | const url = "http://127.0.0.1:4096"; |
| 1191 | const version = verify ? yield* verify(url) : "2.0.18"; |
| 1192 | return { url, version, isRunning: Effect.succeed(true), exitCode: Effect.never }; |
| 1193 | }), |
| 1194 | }; |
| 1195 | const instance = yield* OpenCodeDriver.create({ |
| 1196 | instanceId: ProviderInstanceId.make("opencode-go-key-only"), |
| 1197 | displayName: undefined, |
| 1198 | environment: [ |
| 1199 | { |
| 1200 | name: "OPENCODE_AUTH_CONTENT", |
| 1201 | sensitive: true, |
| 1202 | value: JSON.stringify({ "opencode-go": { type: "api", key: "test-go-key" } }), |
| 1203 | }, |
| 1204 | { name: "OPENCODE_API_KEY", sensitive: true, value: "" }, |
| 1205 | ], |
| 1206 | enabled: true, |
| 1207 | config: OpenCodeDriver.defaultConfig(), |
| 1208 | }).pipe( |
| 1209 | Effect.provide(TestProviderHost.layer()), |
| 1210 | Effect.provideService(HttpClient.HttpClient, server), |
| 1211 | Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, runtime), |
| 1212 | ); |
| 1213 | const initial = yield* instance.snapshot.streamChanges.pipe( |
| 1214 | Stream.filter((entry) => entry.usageLimits !== undefined), |
| 1215 | Stream.take(1), |
| 1216 | Stream.runCollect, |
| 1217 | Effect.forkChild, |
| 1218 | ); |
| 1219 | yield* Deferred.await(usageStarted); |
| 1220 | yield* TestClock.adjust("5 seconds"); |
| 1221 | const [snapshot] = Array.from(yield* Fiber.join(initial)); |
| 1222 | assert.strictEqual(snapshot?.usageLimits?.unavailable, undefined); |
| 1223 | assert.deepStrictEqual( |
| 1224 | snapshot?.usageLimits?.windows.map((window) => window.kind), |
| 1225 | ["session", "weekly", "monthly"], |
| 1226 | ); |
| 1227 | assert.strictEqual(goUsageReads, 1); |
| 1228 | }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), |
| 1229 | ); |
| 1230 | }); |
| 1231 | |
| 1232 | // npm links into opencode-ai for 1.x and @opencode/cli for 2.x. |
| 1233 | const npmGlobalInstall = (prefix: string, packagePath: ReadonlyArray<string>, bin: string) => { |
| 1234 | const target = NodePath.join(prefix, "lib", "node_modules", ...packagePath, "bin", bin); |
| 1235 | NodeFS.mkdirSync(NodePath.dirname(target), { recursive: true }); |
| 1236 | NodeFS.writeFileSync(target, "#!/bin/sh\n"); |
| 1237 | NodeFS.chmodSync(target, 0o755); |
| 1238 | const link = NodePath.join(prefix, "bin", "opencode"); |
| 1239 | NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true }); |
| 1240 | NodeFS.symlinkSync(target, link); |
| 1241 | return link; |
| 1242 | }; |
| 1243 | const resolveUpdate = (generation: "v1" | "v2", binaryPath: string) => |
| 1244 | ProviderMaintenance.resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation), { |
| 1245 | binaryPath, |
| 1246 | env: { PATH: "" }, |
| 1247 | }).pipe( |
| 1248 | Effect.provideService( |
| 1249 | ChildProcessSpawner.ChildProcessSpawner, |
| 1250 | ChildProcessSpawner.make(() => Effect.die("resolving an update must not spawn")), |
| 1251 | ), |
| 1252 | Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1253 | ); |
| 1254 | |
| 1255 | it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 1256 | "updates npm-global OpenCode by generation and runs upgrade only for its own installer's path", |
| 1257 | () => |
| 1258 | Effect.gen(function* () { |
| 1259 | const root = NodeFS.realpathSync( |
| 1260 | NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-opencode-update-")), |
| 1261 | ); |
| 1262 | const v2Prefix = NodePath.join(root, "v2"); |
| 1263 | const v1Prefix = NodePath.join(root, "v1"); |
| 1264 | const v2 = yield* resolveUpdate( |
| 1265 | "v2", |
| 1266 | npmGlobalInstall(v2Prefix, ["@opencode", "cli"], "opencode.exe"), |
| 1267 | ); |
| 1268 | assert.deepStrictEqual(v2.update?.args, [ |
| 1269 | "install", |
| 1270 | "-g", |
| 1271 | "--prefix", |
| 1272 | v2Prefix, |
| 1273 | "--allow-scripts=@opencode/cli", |
| 1274 | "@opencode/cli@latest", |
| 1275 | ]); |
| 1276 | const v1 = yield* resolveUpdate( |
| 1277 | "v1", |
| 1278 | npmGlobalInstall(v1Prefix, ["opencode-ai"], "opencode"), |
| 1279 | ); |
| 1280 | assert.strictEqual(v1.update?.args.at(-1), "opencode-ai@latest"); |
| 1281 | assert.isNull( |
| 1282 | (yield* resolveUpdate("v2", NodePath.join(v1Prefix, "bin", "opencode"))).update, |
| 1283 | ); |
| 1284 | assert.isNull( |
| 1285 | (yield* resolveUpdate("v1", NodePath.join(v2Prefix, "bin", "opencode"))).update, |
| 1286 | ); |
| 1287 | const executable = (...segments: ReadonlyArray<string>) => { |
| 1288 | const path = NodePath.join(root, ...segments); |
| 1289 | NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true }); |
| 1290 | NodeFS.writeFileSync(path, "#!/bin/sh\n"); |
| 1291 | NodeFS.chmodSync(path, 0o755); |
| 1292 | return path; |
| 1293 | }; |
| 1294 | const launcher = executable("launcher", "opencode"); |
| 1295 | const native = executable(".opencode", "bin", "opencode"); |
| 1296 | for (const generation of ["v1", "v2"] as const) { |
| 1297 | assert.isNull((yield* resolveUpdate(generation, launcher)).update); |
| 1298 | const update = (yield* resolveUpdate(generation, native)).update; |
| 1299 | assert.deepStrictEqual(update?.args, ["upgrade", "--method", "curl"]); |
| 1300 | assert.strictEqual(update?.env?.HOME, root); |
| 1301 | } |
| 1302 | }), |
| 1303 | ); |
| 1304 | |
| 1305 | const versionOutput: { current: string | undefined } = { current: undefined }; |
| 1306 | const versionProbes: Array<string> = []; |
| 1307 | const changingRuntime = { |
| 1308 | runOpenCodeCommand: ({ binaryPath }: { readonly binaryPath: string }) => |
| 1309 | Effect.sync(() => versionProbes.push(binaryPath)).pipe( |
| 1310 | Effect.andThen( |
| 1311 | versionOutput.current === undefined |
| 1312 | ? Effect.fail( |
| 1313 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 1314 | operation: "version", |
| 1315 | detail: "no version", |
| 1316 | }), |
| 1317 | ) |
| 1318 | : Effect.succeed({ stdout: versionOutput.current, stderr: "", code: 0 }), |
| 1319 | ), |
| 1320 | ), |
| 1321 | startOpenCodeServerProcess: () => reachedServer("start"), |
| 1322 | connectToOpenCodeServer: () => reachedServer("connect"), |
| 1323 | } as unknown as OpenCodeRuntime.OpenCodeRuntime["Service"]; |
| 1324 | const layerUpdate = Layer.mergeAll( |
| 1325 | IdAllocator.layer, |
| 1326 | McpProviderSessions.layer, |
| 1327 | ProviderLatestVersions.layer, |
| 1328 | TestProviderHost.layer(), |
| 1329 | Layer.succeed( |
| 1330 | ProviderEventLoggers.ProviderEventLoggers, |
| 1331 | ProviderEventLoggers.NoOpProviderEventLoggers, |
| 1332 | ), |
| 1333 | Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, changingRuntime), |
| 1334 | ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); |
| 1335 | |
| 1336 | const openCode1Provider = (id: string, models: ReadonlyArray<string>) => ({ |
| 1337 | id, |
| 1338 | name: id, |
| 1339 | models: Object.fromEntries( |
| 1340 | models.map((model) => [model, { id: model, name: model, release_date: "2026-01-01" }]), |
| 1341 | ), |
| 1342 | }); |
| 1343 | const openCode1Project = "/work/project-with-config"; |
| 1344 | const openCode1UnreadableProject = "/work/unreadable-project"; |
| 1345 | const openCode1Providers = (directory: string) => { |
| 1346 | const all = [ |
| 1347 | openCode1Provider("opencode", ["big-pickle"]), |
| 1348 | ...(directory === openCode1Project ? [openCode1Provider("uni", ["medium-gpt"])] : []), |
| 1349 | ]; |
| 1350 | return { all, connected: all.map((provider) => provider.id), default: {} }; |
| 1351 | }; |
| 1352 | const openCode1Runtime = { |
| 1353 | runOpenCodeCommand: () => Effect.succeed({ stdout: "1.18.18\n", stderr: "", code: 0 }), |
| 1354 | startOpenCodeServerProcess: () => |
| 1355 | Effect.succeed({ |
| 1356 | url: "http://127.0.0.1:4096", |
| 1357 | version: "1.18.18", |
| 1358 | isRunning: Effect.succeed(true), |
| 1359 | exitCode: Effect.never, |
| 1360 | }), |
| 1361 | createOpenCodeSdkClient: ({ directory }: { readonly directory: string }) => ({ |
| 1362 | provider: { |
| 1363 | list: () => |
| 1364 | directory === openCode1UnreadableProject |
| 1365 | ? Promise.reject(new Error("provider list failed")) |
| 1366 | : Promise.resolve({ data: openCode1Providers(directory) }), |
| 1367 | }, |
| 1368 | app: { agents: () => Promise.resolve({ data: [] }) }, |
| 1369 | command: { list: () => Promise.resolve({ data: [] }) }, |
| 1370 | }), |
| 1371 | loadOpenCodeInventory: () => |
| 1372 | Effect.succeed({ providerList: openCode1Providers("/machine"), agents: [], skills: [] }), |
| 1373 | loadOpenCodeSkills: () => Effect.succeed([]), |
| 1374 | } as unknown as OpenCodeRuntime.OpenCodeRuntime["Service"]; |
| 1375 | |
| 1376 | it.layer(Layer.mergeAll(layer, Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, openCode1Runtime)))( |
| 1377 | "OpenCodeDriver on OpenCode 1", |
| 1378 | (it) => { |
| 1379 | it.effect("lists a project's own opencode.jsonc models in that project's snapshot", () => |
| 1380 | Effect.gen(function* () { |
| 1381 | const instance = yield* create({}, noHttp); |
| 1382 | const ready = yield* instance.snapshot.streamChanges.pipe( |
| 1383 | Stream.filter((snapshot) => snapshot.status === "ready"), |
| 1384 | Stream.take(1), |
| 1385 | Stream.runCollect, |
| 1386 | Effect.forkChild, |
| 1387 | ); |
| 1388 | yield* Fiber.join(ready); |
| 1389 | const slugsOf = (snapshot: { readonly models: ReadonlyArray<{ readonly slug: string }> }) => |
| 1390 | snapshot.models.map((model) => model.slug).toSorted(); |
| 1391 | |
| 1392 | assert.deepStrictEqual(slugsOf(yield* instance.snapshotForCwd!(openCode1Project)), [ |
| 1393 | "opencode/big-pickle", |
| 1394 | "uni/medium-gpt", |
| 1395 | ]); |
| 1396 | const otherSnapshot = yield* instance.snapshotForCwd!("/work/other-project"); |
| 1397 | assert.deepStrictEqual(slugsOf(otherSnapshot), ["opencode/big-pickle"]); |
| 1398 | assert.strictEqual(otherSnapshot.workspaceModels, undefined); |
| 1399 | assert.strictEqual(otherSnapshot.workspaceModelsPending, undefined); |
| 1400 | const unreadable = yield* instance.snapshotForCwd!(openCode1UnreadableProject); |
| 1401 | assert.deepStrictEqual(slugsOf(unreadable), ["opencode/big-pickle"]); |
| 1402 | assert.strictEqual(unreadable.workspaceModels, undefined); |
| 1403 | assert.strictEqual(unreadable.workspaceModelsPending, true); |
| 1404 | }), |
| 1405 | ); |
| 1406 | }, |
| 1407 | ); |
| 1408 | |
| 1409 | it.layer(layerUpdate)("OpenCodeDriver updates", (it) => { |
| 1410 | it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 1411 | "offers no package update for an unknown version and follows a changed one on a fresh read", |
| 1412 | () => |
| 1413 | Effect.gen(function* () { |
| 1414 | const root = NodeFS.realpathSync( |
| 1415 | NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-opencode-driver-update-")), |
| 1416 | ); |
| 1417 | const binaryPath = npmGlobalInstall(NodePath.join(root, "v1"), ["opencode-ai"], "opencode"); |
| 1418 | const instance = yield* OpenCodeDriver.create({ |
| 1419 | instanceId: ProviderInstanceId.make("opencode-update"), |
| 1420 | displayName: undefined, |
| 1421 | environment: [], |
| 1422 | enabled: true, |
| 1423 | config: { ...OpenCodeDriver.defaultConfig(), binaryPath }, |
| 1424 | }).pipe(Effect.provideService(HttpClient.HttpClient, noHttp)); |
| 1425 | |
| 1426 | versionOutput.current = undefined; |
| 1427 | const unknown = yield* instance.snapshot.resolveMaintenance({ fresh: true }); |
| 1428 | assert.isNull(unknown.update); |
| 1429 | assert.isNull(unknown.packageName); |
| 1430 | |
| 1431 | versionOutput.current = "1.18.32\n"; |
| 1432 | const v1 = yield* instance.snapshot.resolveMaintenance({ fresh: true }); |
| 1433 | assert.strictEqual(v1.packageName, "opencode-ai"); |
| 1434 | |
| 1435 | versionOutput.current = "opencode v2.0.18\n"; |
| 1436 | const v2 = yield* instance.snapshot.resolveMaintenance({ fresh: true }); |
| 1437 | assert.strictEqual(v2.packageName, "@opencode/cli"); |
| 1438 | assert.isNull(v2.update); |
| 1439 | }), |
| 1440 | ); |
| 1441 | |
| 1442 | it.effect( |
| 1443 | "opens sessions through OpenCode 2 after the binary is upgraded in place from 1.x", |
| 1444 | () => |
| 1445 | Effect.gen(function* () { |
| 1446 | versionOutput.current = "1.18.18\n"; |
| 1447 | const instance = yield* create({}, noHttp); |
| 1448 | // Let the startup status check claim the refresh permit, then wait behind it so it |
| 1449 | // cannot probe after the upgrade below. |
| 1450 | yield* Effect.yieldNow; |
| 1451 | yield* instance.snapshot.refresh; |
| 1452 | serverStarts.length = 0; |
| 1453 | const openSession = instance.orchestrationAdapter |
| 1454 | .openSession({ |
| 1455 | threadId: ThreadId.make("thread-upgraded"), |
| 1456 | providerSessionId: ProviderSessionId.make("session-upgraded"), |
| 1457 | modelSelection: { instanceId: instance.instanceId, model: "opencode/big-pickle" }, |
| 1458 | runtimePolicy: { runtimeMode: "full-access", interactionMode: "default", cwd: null }, |
| 1459 | }) |
| 1460 | .pipe(Effect.scoped, Effect.flip); |
| 1461 | |
| 1462 | yield* openSession; |
| 1463 | assert.deepStrictEqual(serverStarts, ["connect"], "1.x opens through the 1.x adapter"); |
| 1464 | |
| 1465 | versionOutput.current = "opencode v2.2.4\n"; |
| 1466 | serverStarts.length = 0; |
| 1467 | yield* openSession; |
| 1468 | assert.notInclude( |
| 1469 | serverStarts, |
| 1470 | "connect", |
| 1471 | "after upgrading to 2.x, the next session must not open through the 1.x adapter", |
| 1472 | ); |
| 1473 | assert.include(serverStarts, "start", "the OpenCode 2 adapter starts its server"); |
| 1474 | }), |
| 1475 | ); |
| 1476 | }); |