Open History to see the last commit
1/**
2 * Runs OpenCode 2 through the whole orchestrator with the real driver: the
3 * driver probes the binary, spawns `opencode serve`, and routes to the 2.x
4 * adapter. One thread reads a file, runs a shell command, and stops another;
5 * a Supervised thread approves one command, declines another, and answers a
6 * question; a plan-mode thread may write only its plan.
7 *
8 * OPENCODE2_BIN=/path/to/opencode OPENCODE2_LIVE_ROOT=/scratch/dir \
9 * vp test run src/orchestration-v2/OpenCode2OrchestratorV2.live.test.ts
10 *
11 * The server runs with isolated HOME and XDG directories on the free
12 * `opencode/big-pickle` model; `OPENCODE2_MODEL` picks another (its provider's
13 * key comes from the test's environment, which the spawned server inherits).
14 */
15import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
16import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
17import * as NodeServices from "@effect/platform-node/NodeServices";
18import * as NodeSqlite from "node:sqlite";
19import { assert, it } from "@effect/vitest";
20import {
21 CommandId,
22 EnvironmentId,
23 MessageId,
24 type ModelSelection,
25 type OrchestrationV2ThreadProjection,
26 ProjectId,
27 ProviderDriverKind,
28 ProviderInstanceId,
29 ThreadId,
30} from "@t3tools/contracts";
31import * as Effect from "effect/Effect";
32import * as FileSystem from "effect/FileSystem";
33import * as Layer from "effect/Layer";
34import * as Path from "effect/Path";
35import * as Schema from "effect/Schema";
36import { FetchHttpClient } from "effect/unstable/http";
37import { describe } from "vite-plus/test";
38
39import * as ResetCreditCoordinator from "../provider/Layers/resetCreditCoordinator.ts";
40import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
41import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
42import * as HostPowerMonitor from "../background/HostPowerMonitor.ts";
43import * as ServerConfig from "../config.ts";
44import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
45import * as AntigravityInstallation from "../provider/AntigravityInstallation.ts";
46import * as CodexInstallation from "../provider/CodexInstallation.ts";
47import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
48import * as ModelManifest from "../provider/ModelManifest.ts";
49import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts";
50import * as ProviderEventLoggers from "../provider/Layers/ProviderEventLoggers.ts";
51import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
52import * as OpenCodeServerLedger from "../provider/OpenCodeServerLedger.ts";
53import * as ServerSettings from "../serverSettings.ts";
54import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
55import * as VcsProcess from "../vcs/VcsProcess.ts";
56import * as EffectWorker from "./EffectWorker.ts";
57import * as Orchestrator from "./Orchestrator.ts";
58import * as ProviderInstanceRegistry from "../provider/Services/ProviderInstanceRegistry.ts";
59import { worktreeRepairDependenciesTestLayer } from "./ProviderTurnStartService.testkit.ts";
60import { OrchestrationV2LayerLive } from "./runtimeLayer.ts";
61import * as McpSessionRegistryTestkit from "../mcp/McpSessionRegistry.testkit.ts";
62
63const binaryPath = process.env.OPENCODE2_BIN;
64const ROOT = process.env.OPENCODE2_LIVE_ROOT ?? "";
65const INSTANCE = ProviderInstanceId.make("opencode");
66const MODEL: ModelSelection = {
67 instanceId: INSTANCE,
68 model: process.env.OPENCODE2_MODEL ?? "opencode/big-pickle",
69};
70// The free model the thread switches to mid-conversation.
71const SWITCHED_MODEL = "opencode/mimo-v2.6-flash-free";
72
73const PlatformTestLayer = Layer.merge(
74 NodeServices.layer,
75 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
76 resolveLink: () => Effect.die("unused title link"),
77 }),
78);
79const serverConfigLayer = ServerConfig.layerTest(`${ROOT}/work`, { prefix: "t3-opencode2-live-" });
80const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe(
81 Layer.provide(VcsProcess.layer),
82 Layer.provide(serverConfigLayer),
83 Layer.provide(PlatformTestLayer),
84);
85// Isolated OpenCode state: the server never touches the developer's own data.
86const serverSettingsLayer = ServerSettings.layerTest({
87 providerInstances: {
88 [INSTANCE]: {
89 driver: ProviderDriverKind.make("opencode"),
90 enabled: true,
91 environment: [
92 { name: "HOME", value: ROOT },
93 { name: "XDG_CONFIG_HOME", value: `${ROOT}/config` },
94 { name: "XDG_DATA_HOME", value: `${ROOT}/data` },
95 { name: "XDG_STATE_HOME", value: `${ROOT}/state` },
96 { name: "XDG_CACHE_HOME", value: `${ROOT}/cache` },
97 ],
98 config: { enabled: true, binaryPath },
99 },
100 },
101});
102const backgroundPolicyLayer = BackgroundPolicy.layer.pipe(
103 Layer.provide(Layer.effect(HostPowerMonitor.HostPowerMonitor, HostPowerMonitor.make())),
104 Layer.provide(serverSettingsLayer),
105);
106const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe(
107 Layer.provide(
108 Layer.mergeAll(
109 serverConfigLayer.pipe(Layer.provide(PlatformTestLayer)),
110 serverSettingsLayer,
111 ServerSecretStore.layer.pipe(
112 Layer.provide(serverConfigLayer),
113 Layer.provide(PlatformTestLayer),
114 ),
115 NodeServices.layer,
116 FetchHttpClient.layer,
117 OpenCodeRuntime.OpenCodeRuntimeLive.pipe(
118 Layer.provide(OpenCodeServerLedger.layerTest),
119 Layer.provide(PlatformTestLayer),
120 ),
121 Layer.succeed(
122 ProviderEventLoggers.ProviderEventLoggers,
123 ProviderEventLoggers.NoOpProviderEventLoggers,
124 ),
125 ModelManifest.layerTest,
126 AntigravityInstallation.AntigravityInstallation.layer.pipe(
127 Layer.provide(serverConfigLayer.pipe(Layer.provide(PlatformTestLayer))),
128 Layer.provide(FetchHttpClient.layer),
129 Layer.provide(PlatformTestLayer),
130 ),
131 // The Codex driver now resolves managed ChatGPT installs; these runs never launch Codex.
132 Layer.mock(CodexInstallation.CodexInstallation)({
133 managedDirectory: "unused-managed-installation",
134 }),
135 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
136 getEnvironmentId: Effect.succeed(
137 EnvironmentId.make("00000000-0000-4000-8000-000000000001"),
138 ),
139 }),
140 ),
141 ),
142);
143const liveLayer = OrchestrationV2LayerLive.pipe(
144 Layer.provide(worktreeRepairDependenciesTestLayer),
145 Layer.provide(McpSessionRegistryTestkit.layer),
146 Layer.provide(SqlitePersistenceMemory),
147 Layer.provide(CheckpointStore.layer.pipe(Layer.provide(vcsDriverRegistryLayer))),
148 Layer.provide(serverConfigLayer),
149 Layer.provide(serverSettingsLayer),
150 // Merged, not only provided: the test reads the same instance the orchestrator uses.
151 Layer.provideMerge(providerInstanceRegistryLayer),
152 Layer.provide(ResetCreditCoordinator.layer),
153 Layer.provide(backgroundPolicyLayer),
154 Layer.provide(PlatformTestLayer),
155);
156
157const settled = (projection: OrchestrationV2ThreadProjection) =>
158 projection.runs.length > 0 &&
159 projection.runs.every(
160 (run) => !["queued", "starting", "running", "waiting"].includes(run.status),
161 );
162
163const waitFor = Effect.fn("OpenCode2Live.waitFor")(function* (
164 threadId: ThreadId,
165 done: (projection: OrchestrationV2ThreadProjection) => boolean,
166) {
167 const orchestrator = yield* Orchestrator.OrchestratorV2;
168 for (let attempt = 0; attempt < 240; attempt += 1) {
169 const projection = yield* orchestrator.getThreadProjection(threadId);
170 if (done(projection)) return projection;
171 yield* Effect.sleep("500 millis");
172 }
173 const last = yield* orchestrator.getThreadProjection(threadId);
174 const items = last.turnItems.map((item) =>
175 item.type === "error" ? `error:${item.failure.message}` : `${item.type}:${item.status}`,
176 );
177 return yield* Effect.die(
178 new Error(
179 `Timed out waiting on OpenCode 2 thread ${threadId}: runs ${last.runs.map((run) => run.status).join(",")}; items ${items.join(",")}`,
180 ),
181 );
182});
183
184const send = Effect.fn("OpenCode2Live.send")(function* (
185 threadId: ThreadId,
186 key: string,
187 text: string,
188 modelSelection: ModelSelection = MODEL,
189) {
190 const orchestrator = yield* Orchestrator.OrchestratorV2;
191 yield* orchestrator.dispatch({
192 type: "message.dispatch",
193 createdBy: "user",
194 creationSource: "web",
195 commandId: CommandId.make(`command:opencode2-live:${key}`),
196 threadId,
197 messageId: MessageId.make(`message:opencode2-live:${key}`),
198 text,
199 attachments: [],
200 modelSelection,
201 dispatchMode: { type: "start_immediately" },
202 });
203});
204
205const AssistantModel = Schema.fromJsonString(
206 Schema.Struct({ model: Schema.Struct({ providerID: Schema.String, id: Schema.String }) }),
207);
208const decodeAssistantModel = Schema.decodeUnknownSync(AssistantModel);
209
210/**
211 * The `provider/model` of each assistant message in a native session, oldest
212 * first, from the spawned server's own database under the isolated XDG root.
213 */
214const assistantModels = (nativeSessionId: string) =>
215 Effect.sync(() => {
216 const db = new NodeSqlite.DatabaseSync(`${ROOT}/data/opencode/opencode.db`, { readOnly: true });
217 try {
218 return db
219 .prepare(
220 "SELECT data FROM session_message WHERE session_id = ? AND type = 'assistant' ORDER BY seq",
221 )
222 .all(nativeSessionId)
223 .map((row) => decodeAssistantModel(row.data).model)
224 .map((model) => `${model.providerID}/${model.id}`);
225 } finally {
226 db.close();
227 }
228 });
229
230describe.runIf(binaryPath !== undefined && ROOT !== "")("OpenCode 2 live orchestrator", () => {
231 it.live(
232 "runs a tool turn and stops a running shell command through the real driver",
233 () =>
234 Effect.gen(function* () {
235 const fs = yield* FileSystem.FileSystem;
236 const path = yield* Path.Path;
237 yield* fs.writeFileString(path.join(ROOT, "work", "hello.txt"), "hello from t3 live\n");
238 yield* EffectWorker.runDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
239
240 // A status check starts a fresh server, which lists no models for its
241 // first few hundred milliseconds; the picker must still get them.
242 const instance =
243 yield* (yield* ProviderInstanceRegistry.ProviderInstanceRegistry).getInstance(INSTANCE);
244 assert.isDefined(instance);
245 const status = yield* instance!.snapshot.refresh;
246 assert.equal(status.status, "ready");
247 assert.include(
248 status.models.map((model) => model.slug),
249 "opencode/big-pickle",
250 );
251 const orchestrator = yield* Orchestrator.OrchestratorV2;
252 const threadId = ThreadId.make("thread:opencode2-live");
253 yield* orchestrator.dispatch({
254 type: "thread.create",
255 createdBy: "user",
256 creationSource: "web",
257 commandId: CommandId.make("command:opencode2-live:create"),
258 threadId,
259 projectId: ProjectId.make("project:opencode2-live"),
260 title: "OpenCode 2 live",
261 modelSelection: MODEL,
262 runtimeMode: "full-access",
263 interactionMode: "default",
264 branch: null,
265 worktreePath: `${ROOT}/work`,
266 });
267
268 yield* send(
269 threadId,
270 "tools",
271 // The shell call outlasts the spawned server's 30 second idle timeout.
272 "Use the read tool to read hello.txt, then run the shell command `sleep 35 && echo TOOL_OK` with the shell tool in the foreground (not in the background) and wait for it to finish, then reply DONE.",
273 );
274 const first = yield* waitFor(threadId, settled);
275 assert.deepEqual(
276 first.runs.map((run) => run.status),
277 ["completed"],
278 );
279 const shell = first.turnItems.find((item) => item.type === "command_execution");
280 assert.deepInclude(shell, { status: "completed", exitCode: 0 });
281 assert.include(shell?.type === "command_execution" ? shell.output : "", "TOOL_OK");
282 assert.isDefined(
283 first.turnItems.find((item) => item.type === "dynamic_tool" && item.toolName === "read"),
284 );
285 assert.isAbove(first.providerTurns[0]?.tokenUsage?.maxTokens ?? 0, 0);
286
287 yield* send(
288 threadId,
289 "stop",
290 "Run the shell command `sleep 60 && echo LATE` with the shell tool in the foreground (not in the background) and wait for it to finish, then reply DONE.",
291 );
292 const running = yield* waitFor(threadId, (projection) =>
293 projection.turnItems.some(
294 (item) =>
295 item.type === "command_execution" &&
296 item.status === "running" &&
297 item.input.includes("sleep 60"),
298 ),
299 );
300 const secondRun = running.runs.at(-1)!;
301 yield* orchestrator.dispatch({
302 type: "run.interrupt",
303 commandId: CommandId.make("command:opencode2-live:interrupt"),
304 threadId,
305 runId: secondRun.id,
306 });
307 const stopped = yield* waitFor(threadId, settled);
308 assert.deepEqual(
309 stopped.runs.map((run) => run.status),
310 ["completed", "interrupted"],
311 );
312 const sleep = stopped.turnItems.find(
313 (item) => item.type === "command_execution" && item.input.includes("sleep 60"),
314 );
315 assert.equal(sleep?.status, "interrupted");
316
317 // A model change applies to the same native session on the next turn.
318 const switched: ModelSelection = { instanceId: INSTANCE, model: SWITCHED_MODEL };
319 yield* send(threadId, "switch", "Reply with exactly: SWITCHED", switched);
320 const third = yield* waitFor(
321 threadId,
322 (projection) => projection.runs.length === 3 && settled(projection),
323 );
324 assert.equal(third.runs.at(-1)?.status, "completed");
325 const sessionId = third.providerThreads[0]?.nativeThreadRef?.nativeId;
326 assert.isDefined(sessionId);
327 const models = yield* assistantModels(sessionId!);
328 assert.equal(models.at(-1), SWITCHED_MODEL);
329 assert.notEqual(models[0], SWITCHED_MODEL);
330 }).pipe(Effect.provide(Layer.merge(liveLayer, NodeServices.layer)), Effect.scoped),
331 360_000,
332 );
333
334 it.live(
335 "asks before each shell command in Supervised, runs the approved one, skips the declined one, and answers a question",
336 () =>
337 Effect.gen(function* () {
338 const fs = yield* FileSystem.FileSystem;
339 const path = yield* Path.Path;
340 yield* EffectWorker.runDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
341 const orchestrator = yield* Orchestrator.OrchestratorV2;
342 const threadId = ThreadId.make("thread:opencode2-live-supervised");
343 yield* orchestrator.dispatch({
344 type: "thread.create",
345 createdBy: "user",
346 creationSource: "web",
347 commandId: CommandId.make("command:opencode2-live:supervised-create"),
348 threadId,
349 projectId: ProjectId.make("project:opencode2-live"),
350 title: "OpenCode 2 live supervised",
351 modelSelection: MODEL,
352 runtimeMode: "approval-required",
353 interactionMode: "default",
354 branch: null,
355 worktreePath: `${ROOT}/work`,
356 });
357 const pendingAsk = (projection: OrchestrationV2ThreadProjection) =>
358 projection.runtimeRequests.find((request) => request.status === "pending");
359 const answer = (
360 key: string,
361 request: OrchestrationV2ThreadProjection["runtimeRequests"][number],
362 response: { decision: "accept" | "decline" } | { answers: Record<string, string> },
363 ) =>
364 orchestrator.dispatch({
365 type: "runtime-request.respond",
366 commandId: CommandId.make(`command:opencode2-live:${key}`),
367 threadId,
368 requestId: request.id,
369 ...response,
370 });
371
372 yield* send(
373 threadId,
374 "approve",
375 "Run the shell command `touch approved.txt` with the shell tool, then reply DONE.",
376 );
377 const asked = yield* waitFor(
378 threadId,
379 (projection) => pendingAsk(projection) !== undefined,
380 );
381 assert.equal(pendingAsk(asked)?.kind, "command");
382 yield* answer("approve-answer", pendingAsk(asked)!, { decision: "accept" });
383 const approved = yield* waitFor(threadId, settled);
384 assert.equal(approved.runs.at(-1)?.status, "completed");
385 assert.isTrue(yield* fs.exists(path.join(ROOT, "work", "approved.txt")));
386
387 yield* send(
388 threadId,
389 "decline",
390 "Run the shell command `touch declined.txt` with the shell tool, then reply DONE.",
391 );
392 const second = yield* waitFor(
393 threadId,
394 (projection) => projection.runs.length === 2 && pendingAsk(projection) !== undefined,
395 );
396 yield* answer("decline-answer", pendingAsk(second)!, { decision: "decline" });
397 // The model may try again; every retry is declined too.
398 let declined = yield* waitFor(
399 threadId,
400 (projection) =>
401 (projection.runs.length === 2 && settled(projection)) ||
402 pendingAsk(projection) !== undefined,
403 );
404 for (let retry = 0; pendingAsk(declined) !== undefined && retry < 3; retry += 1) {
405 yield* answer(`decline-retry-${retry}`, pendingAsk(declined)!, { decision: "decline" });
406 declined = yield* waitFor(
407 threadId,
408 (projection) =>
409 (projection.runs.length === 2 && settled(projection)) ||
410 pendingAsk(projection) !== undefined,
411 );
412 }
413 assert.equal(declined.runs.at(-1)?.status, "completed");
414 assert.isFalse(yield* fs.exists(path.join(ROOT, "work", "declined.txt")));
415
416 yield* send(
417 threadId,
418 "question",
419 "Before doing anything, use the question tool to ask me which color I prefer, offering the options red and blue. After I answer, reply with only the chosen color.",
420 );
421 const questioned = yield* waitFor(
422 threadId,
423 (projection) => projection.runs.length === 3 && pendingAsk(projection) !== undefined,
424 );
425 const question = pendingAsk(questioned)!;
426 assert.equal(question.kind, "user_input");
427 const form = questioned.turnItems.find(
428 (item) => item.type === "user_input_request" && item.requestId === question.id,
429 );
430 const firstQuestion = form?.type === "user_input_request" ? form.questions[0] : undefined;
431 assert.isDefined(firstQuestion);
432 yield* answer("question-answer", question, { answers: { [firstQuestion!.id]: "Blue" } });
433 const answered = yield* waitFor(
434 threadId,
435 (projection) => projection.runs.length === 3 && settled(projection),
436 );
437 assert.equal(answered.runs.at(-1)?.status, "completed");
438 const reply = answered.messages.findLast((message) => message.role === "assistant");
439 assert.match(reply?.text ?? "", /blue/i);
440 }).pipe(Effect.provide(Layer.merge(liveLayer, NodeServices.layer)), Effect.scoped),
441 600_000,
442 );
443
444 it.live(
445 "lets plan mode write only the plan agent's plan directory under Full access",
446 () =>
447 Effect.gen(function* () {
448 const fs = yield* FileSystem.FileSystem;
449 const path = yield* Path.Path;
450 yield* EffectWorker.runDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
451 const orchestrator = yield* Orchestrator.OrchestratorV2;
452 const threadId = ThreadId.make("thread:opencode2-live-plan");
453 yield* orchestrator.dispatch({
454 type: "thread.create",
455 createdBy: "user",
456 creationSource: "web",
457 commandId: CommandId.make("command:opencode2-live:plan-create"),
458 threadId,
459 projectId: ProjectId.make("project:opencode2-live"),
460 title: "OpenCode 2 live plan",
461 modelSelection: MODEL,
462 runtimeMode: "full-access",
463 interactionMode: "plan",
464 branch: null,
465 worktreePath: `${ROOT}/work`,
466 });
467 // The plan agent's directory: `$HOME/.opencode/plan` under the isolated HOME.
468 const planDir = path.join(ROOT, ".opencode", "plan");
469 // No agent switch yet (a later layer adds it), so the build agent runs
470 // under the session's plan rules: the edit deny holds on its own.
471 yield* send(
472 threadId,
473 "plan",
474 `This is a permission test. Do exactly these two tool calls and nothing else: 1) use the write tool to create ${planDir}/probe-plan.md containing PLAN_OK; 2) use the write tool to create plan_write_probe.txt in the current directory containing NO. Then reply with which calls succeeded.`,
475 );
476 const planned = yield* waitFor(threadId, settled);
477 assert.equal(planned.runs.at(-1)?.status, "completed");
478 assert.isFalse(yield* fs.exists(path.join(ROOT, "work", "plan_write_probe.txt")));
479 assert.isTrue(yield* fs.exists(path.join(planDir, "probe-plan.md")));
480 }).pipe(Effect.provide(Layer.merge(liveLayer, NodeServices.layer)), Effect.scoped),
481 360_000,
482 );
483});