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

OpenCode2OrchestratorV2.live.test.ts

1,116 lines47.0 KB

1import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
2import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as NodeSqlite from "node:sqlite";
5import { assert, it } from "@effect/vitest";
6import {
7 CommandId,
8 EnvironmentId,
9 MessageId,
10 type ModelSelection,
11 type OrchestrationV2Command,
12 type OrchestrationV2ThreadProjection,
13 ProjectId,
14 ProviderDriverKind,
15 ProviderInstanceId,
16 ThreadId,
17} from "@t3tools/contracts";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Path from "effect/Path";
22import * as Schema from "effect/Schema";
23import { FetchHttpClient, HttpClient } from "effect/http";
24import { ChildProcess, ChildProcessSpawner } from "effect/process";
25import { describe } from "vite-plus/test";
26​
27import * as ResetCreditCoordinator from "../provider/resetCreditCoordinator.ts";
28import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
29import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
30import * as HostPowerMonitor from "../background/HostPowerMonitor.ts";
31import * as ServerConfig from "../config.ts";
32import * as SqlitePersistence from "../persistence/Sqlite.ts";
33import * as AntigravityInstallation from "../provider/AntigravityInstallation.ts";
34import * as CodexInstallation from "../provider/CodexInstallation.ts";
35import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
36import * as ModelManifest from "../provider/ModelManifest.ts";
37import * as ProviderInstanceRegistryHydration from "../provider/ProviderInstanceRegistryHydration.ts";
38import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
39import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
40import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
41import * as OpenCode2Client from "@t3tools/provider-opencode/server/v2/OpenCode2Client";
42import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime";
43import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger";
44import * as ServerSettings from "../serverSettings.ts";
45import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
46import * as VcsProcess from "../vcs/VcsProcess.ts";
47import * as EffectWorker from "./EffectWorker.ts";
48import * as Orchestrator from "./Orchestrator.ts";
49import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
50import * as ProviderTurnStartServiceTestkit from "./ProviderTurnStartService.testkit.ts";
51import * as RuntimeLayer from "./runtimeLayer.ts";
52import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
53import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
54import * as ProviderContinuationService from "./ProviderContinuationService.ts";
55import * as ThreadManagementService from "./ThreadManagementService.ts";
56import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
57​
58const binaryPath = process.env.OPENCODE2_BIN;
59const ROOT = process.env.OPENCODE2_LIVE_ROOT ?? "";
60const INSTANCE = ProviderInstanceId.make("opencode");
61const MODEL: ModelSelection = {
62 instanceId: INSTANCE,
63 model: process.env.OPENCODE2_MODEL ?? "opencode/big-pickle",
64};
65const SWITCHED_MODEL = "opencode/mimo-v2.6-flash-free";
66​
67const spawnedPids: Array<number> = [];
68const layerSpawnedServers = Layer.succeed(
69 OpenCodeServerLedger.OpenCodeServerLedger,
70 OpenCodeServerLedger.OpenCodeServerLedger.of({
71 track: ({ pid }) =>
72 Effect.sync(() => {
73 spawnedPids.push(pid);
74 return Effect.void;
75 }),
76 }),
77);
78​
79const MCP_URL = process.env.OPENCODE2_MCP_URL ?? "http://127.0.0.1/mcp";
80const layerMcpRegistry = Layer.succeed(
81 McpSessionRegistry.McpSessionRegistry,
82 McpSessionRegistry.McpSessionRegistry.of({
83 issue: ({ threadId, providerInstanceId }) =>
84 Effect.succeed({
85 config: {
86 environmentId: EnvironmentId.make("environment:opencode2-live"),
87 threadId,
88 providerSessionId: `mcp-live:${threadId}`,
89 providerInstanceId,
90 endpoint: MCP_URL,
91 authorizationHeader: `Bearer mcp-live:${threadId}`,
92 browserToolsAvailable: false,
93 },
94 }),
95 resolve: () => Effect.succeed(undefined),
96 touch: () => Effect.void,
97 revokeProviderSession: () => Effect.void,
98 revokeThread: () => Effect.void,
99 revokeAll: Effect.void,
100 }),
101);
102​
103const layerPlatformTest = Layer.merge(
104 NodeServices.layer,
105 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
106 resolveLink: () => Effect.die("unused title link"),
107 }),
108);
109const layerServerConfig = ServerConfig.layerTest(`${ROOT}/work`, { prefix: "t3-opencode2-live-" });
110const layerVcsDriverRegistry = VcsDriverRegistry.layer.pipe(
111 Layer.provide(VcsProcess.layer),
112 Layer.provide(layerServerConfig),
113 Layer.provide(layerPlatformTest),
114);
115const layerServerSettings = ServerSettings.layerTest({
116 providerInstances: {
117 [INSTANCE]: {
118 driver: ProviderDriverKind.make("opencode"),
119 enabled: true,
120 environment: [
121 { name: "HOME", value: ROOT },
122 { name: "XDG_CONFIG_HOME", value: `${ROOT}/config` },
123 { name: "XDG_DATA_HOME", value: `${ROOT}/data` },
124 { name: "XDG_STATE_HOME", value: `${ROOT}/state` },
125 { name: "XDG_CACHE_HOME", value: `${ROOT}/cache` },
126 ],
127 config: {
128 enabled: true,
129 binaryPath,
130 ...(process.env.OPENCODE2_SERVER_URL === undefined
131 ? {}
132 : {
133 serverUrl: process.env.OPENCODE2_SERVER_URL,
134 serverPassword: process.env.OPENCODE2_SERVER_PASSWORD ?? "",
135 }),
136 },
137 },
138 },
139});
140const layerBackgroundPolicy = BackgroundPolicy.layer.pipe(
141 Layer.provide(Layer.effect(HostPowerMonitor.HostPowerMonitor, HostPowerMonitor.make())),
142 Layer.provide(layerServerSettings),
143);
144const layerProviderInstanceRegistry = ProviderInstanceRegistryHydration.layer.pipe(
145 Layer.provide(
146 Layer.mergeAll(
147 layerServerConfig.pipe(Layer.provide(layerPlatformTest)),
148 layerServerSettings,
149 ServerSecretStore.layer.pipe(
150 Layer.provide(layerServerConfig),
151 Layer.provide(layerPlatformTest),
152 ),
153 NodeServices.layer,
154 FetchHttpClient.layer,
155 OpenCodeRuntime.layer.pipe(
156 Layer.provide(layerSpawnedServers),
157 Layer.provide(layerPlatformTest),
158 ),
159 Layer.succeed(
160 ProviderEventLoggers.ProviderEventLoggers,
161 ProviderEventLoggers.NoOpProviderEventLoggers,
162 ),
163 ProviderLatestVersions.layer,
164 ModelManifest.layerTest,
165 AntigravityInstallation.AntigravityInstallation.layer.pipe(
166 Layer.provide(layerServerConfig.pipe(Layer.provide(layerPlatformTest))),
167 Layer.provide(FetchHttpClient.layer),
168 Layer.provide(layerPlatformTest),
169 ),
170 Layer.mock(CodexInstallation.CodexInstallation)({
171 managedDirectory: "unused-managed-installation",
172 }),
173 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
174 getEnvironmentId: Effect.succeed(
175 EnvironmentId.make("00000000-0000-4000-8000-000000000001"),
176 ),
177 }),
178 ),
179 ),
180);
181const layerOrchestration = RuntimeLayer.layer.pipe(
182 Layer.provide(ProviderTurnStartServiceTestkit.layer),
183 Layer.provide(layerMcpRegistry),
184 Layer.provide(SqlitePersistence.layerMemory),
185 Layer.provide(CheckpointStore.layer.pipe(Layer.provide(layerVcsDriverRegistry))),
186 Layer.provide(layerServerConfig),
187 Layer.provide(layerServerSettings),
188 Layer.provideMerge(layerProviderInstanceRegistry),
189 Layer.provide(ResetCreditCoordinator.layer),
190 Layer.provide(layerBackgroundPolicy),
191 Layer.provide(layerPlatformTest),
192 Layer.provide(McpProviderSessions.layer),
193);
194​
195const layerContinuationWorker = ProviderContinuationService.layer.pipe(
196 Layer.provide(
197 Layer.unwrap(
198 Effect.gen(function* () {
199 const orchestrator = yield* Orchestrator.OrchestratorV2;
200 return Layer.mock(ThreadManagementService.ThreadManagementService)({
201 dispatch: orchestrator.dispatch,
202 getThreadRecords: orchestrator.getThreadRecords,
203 getThreadProjection: orchestrator.getThreadProjection,
204 });
205 }),
206 ),
207 ),
208 Layer.provide(IdAllocator.layer),
209 Layer.provide(ProviderContinuationRequests.layer),
210);
211const layerLive = layerContinuationWorker.pipe(Layer.provideMerge(layerOrchestration));
212​
213const STEP_WAIT_SECONDS = Number(process.env.OPENCODE2_STEP_WAIT ?? "120");
214​
215const settled = (projection: OrchestrationV2ThreadProjection) =>
216 projection.runs.length > 0 &&
217 projection.runs.every(
218 (run) => !["queued", "starting", "running", "waiting"].includes(run.status),
219 );
220​
221const waitFor = Effect.fn("OpenCode2Live.waitFor")(function* (
222 threadId: ThreadId,
223 done: (projection: OrchestrationV2ThreadProjection) => boolean,
224) {
225 const orchestrator = yield* Orchestrator.OrchestratorV2;
226 for (let attempt = 0; attempt < STEP_WAIT_SECONDS * 2; attempt += 1) {
227 const projection = yield* orchestrator.getThreadProjection(threadId);
228 if (done(projection)) return projection;
229 yield* Effect.sleep("500 millis");
230 }
231 const last = yield* orchestrator.getThreadProjection(threadId);
232 const items = last.turnItems.map((item) =>
233 item.type === "error" ? `error:${item.failure.message}` : `${item.type}:${item.status}`,
234 );
235 return yield* Effect.die(
236 new Error(
237 `Timed out waiting on OpenCode 2 thread ${threadId}: runs ${last.runs.map((run) => run.status).join(",")}; items ${items.join(",")}`,
238 ),
239 );
240});
241​
242const send = Effect.fn("OpenCode2Live.send")(function* (
243 threadId: ThreadId,
244 key: string,
245 text: string,
246 modelSelection: ModelSelection = MODEL,
247) {
248 const orchestrator = yield* Orchestrator.OrchestratorV2;
249 yield* orchestrator.dispatch({
250 type: "message.dispatch",
251 createdBy: "user",
252 creationSource: "web",
253 commandId: CommandId.make(`command:opencode2-live:${key}`),
254 threadId,
255 messageId: MessageId.make(`message:opencode2-live:${key}`),
256 text,
257 attachments: [],
258 modelSelection,
259 dispatchMode: { type: "start_immediately" },
260 });
261});
262​
263const AssistantModel = Schema.fromJsonString(
264 Schema.Struct({
265 model: Schema.Struct({ providerID: Schema.String, id: Schema.String }),
266 agent: Schema.optional(Schema.String),
267 }),
268);
269const decodeAssistantModel = Schema.decodeUnknownSync(AssistantModel);
270​
271const assistantModels = (nativeSessionId: string) =>
272 Effect.sync(() => {
273 const db = new NodeSqlite.DatabaseSync(`${ROOT}/data/opencode/opencode.db`, { readOnly: true });
274 try {
275 return db
276 .prepare(
277 "SELECT data FROM session_message WHERE session_id = ? AND type = 'assistant' ORDER BY seq",
278 )
279 .all(nativeSessionId)
280 .map((row) => decodeAssistantModel(row.data).model)
281 .map((model) => `${model.providerID}/${model.id}`);
282 } finally {
283 db.close();
284 }
285 });
286​
287const assistantAgents = (nativeSessionId: string) =>
288 Effect.sync(() => {
289 const db = new NodeSqlite.DatabaseSync(`${ROOT}/data/opencode/opencode.db`, { readOnly: true });
290 try {
291 return db
292 .prepare(
293 "SELECT data FROM session_message WHERE session_id = ? AND type = 'assistant' ORDER BY seq",
294 )
295 .all(nativeSessionId)
296 .map((row) => decodeAssistantModel(row.data).agent);
297 } finally {
298 db.close();
299 }
300 });
301​
302describe.runIf(binaryPath !== undefined && ROOT !== "")("OpenCode 2 live orchestrator", () => {
303 it.live(
304 "runs a tool turn and stops a running shell command through the real driver",
305 () =>
306 Effect.gen(function* () {
307 const fs = yield* FileSystem.FileSystem;
308 const path = yield* Path.Path;
309 yield* fs.writeFileString(path.join(ROOT, "work", "hello.txt"), "hello from t3 live\n");
310 yield* EffectWorker.runDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
311​
312 // A status check starts a fresh server, which lists no models for its
313 // first few hundred milliseconds; the picker must still get them.
314 const instance =
315 yield* (yield* ProviderInstanceRegistry.ProviderInstanceRegistry).getInstance(INSTANCE);
316 assert.isDefined(instance);
317 const status = yield* instance!.snapshot.refresh;
318 assert.equal(status.status, "ready");
319 assert.include(
320 status.models.map((model) => model.slug),
321 "opencode/big-pickle",
322 );
323 const orchestrator = yield* Orchestrator.OrchestratorV2;
324 const threadId = ThreadId.make("thread:opencode2-live");
325 yield* orchestrator.dispatch({
326 type: "thread.create",
327 createdBy: "user",
328 creationSource: "web",
329 commandId: CommandId.make("command:opencode2-live:create"),
330 threadId,
331 projectId: ProjectId.make("project:opencode2-live"),
332 title: "OpenCode 2 live",
333 modelSelection: MODEL,
334 runtimeMode: "full-access",
335 interactionMode: "default",
336 branch: null,
337 worktreePath: `${ROOT}/work`,
338 });
339​
340 yield* send(
341 threadId,
342 "tools",
343 // The shell call outlasts the spawned server's 30 second idle timeout.
344 "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.",
345 );
346 const first = yield* waitFor(threadId, settled);
347 assert.deepEqual(
348 first.runs.map((run) => run.status),
349 ["completed"],
350 );
351 const shell = first.turnItems.find((item) => item.type === "command_execution");
352 assert.deepInclude(shell, { status: "completed", exitCode: 0 });
353 assert.include(shell?.type === "command_execution" ? shell.output : "", "TOOL_OK");
354 assert.isDefined(
355 first.turnItems.find((item) => item.type === "dynamic_tool" && item.toolName === "read"),
356 );
357 assert.isAbove(first.providerTurns[0]?.tokenUsage?.maxTokens ?? 0, 0);
358​
359 yield* send(
360 threadId,
361 "stop",
362 "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.",
363 );
364 const running = yield* waitFor(threadId, (projection) =>
365 projection.turnItems.some(
366 (item) =>
367 item.type === "command_execution" &&
368 item.status === "running" &&
369 item.input.includes("sleep 60"),
370 ),
371 );
372 const secondRun = running.runs.at(-1)!;
373 yield* orchestrator.dispatch({
374 type: "run.interrupt",
375 commandId: CommandId.make("command:opencode2-live:interrupt"),
376 threadId,
377 runId: secondRun.id,
378 });
379 const stopped = yield* waitFor(threadId, settled);
380 assert.deepEqual(
381 stopped.runs.map((run) => run.status),
382 ["completed", "interrupted"],
383 );
384 const sleep = stopped.turnItems.find(
385 (item) => item.type === "command_execution" && item.input.includes("sleep 60"),
386 );
387 assert.equal(sleep?.status, "interrupted");
388​
389 const switched: ModelSelection = { instanceId: INSTANCE, model: SWITCHED_MODEL };
390 yield* send(threadId, "switch", "Reply with exactly: SWITCHED", switched);
391 const third = yield* waitFor(
392 threadId,
393 (projection) => projection.runs.length === 3 && settled(projection),
394 );
395 assert.equal(third.runs.at(-1)?.status, "completed");
396 const sessionId = third.providerThreads[0]?.nativeThreadRef?.nativeId;
397 assert.isDefined(sessionId);
398 const models = yield* assistantModels(sessionId!);
399 assert.equal(models.at(-1), SWITCHED_MODEL);
400 assert.notEqual(models[0], SWITCHED_MODEL);
401 }).pipe(Effect.provide(Layer.merge(layerLive, NodeServices.layer)), Effect.scoped),
402 360_000,
403 );
404​
405 it.live(
406 "asks before each shell command in Supervised, runs the approved one, skips the declined one, and answers a question",
407 () =>
408 Effect.gen(function* () {
409 const fs = yield* FileSystem.FileSystem;
410 const path = yield* Path.Path;
411 yield* EffectWorker.runDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
412 const orchestrator = yield* Orchestrator.OrchestratorV2;
413 const threadId = ThreadId.make("thread:opencode2-live-supervised");
414 yield* orchestrator.dispatch({
415 type: "thread.create",
416 createdBy: "user",
417 creationSource: "web",
418 commandId: CommandId.make("command:opencode2-live:supervised-create"),
419 threadId,
420 projectId: ProjectId.make("project:opencode2-live"),
421 title: "OpenCode 2 live supervised",
422 modelSelection: MODEL,
423 runtimeMode: "approval-required",
424 interactionMode: "default",
425 branch: null,
426 worktreePath: `${ROOT}/work`,
427 });
428 const pendingAsk = (projection: OrchestrationV2ThreadProjection) =>
429 projection.runtimeRequests.find((request) => request.status === "pending");
430 const answer = (
431 key: string,
432 request: OrchestrationV2ThreadProjection["runtimeRequests"][number],
433 response: { decision: "accept" | "decline" } | { answers: Record<string, string> },
434 ) =>
435 orchestrator.dispatch({
436 type: "runtime-request.respond",
437 commandId: CommandId.make(`command:opencode2-live:${key}`),
438 threadId,
439 requestId: request.id,
440 ...response,
441 });
442​
443 yield* send(
444 threadId,
445 "approve",
446 "Run the shell command `touch approved.txt` with the shell tool, then reply DONE.",
447 );
448 const asked = yield* waitFor(
449 threadId,
450 (projection) => pendingAsk(projection) !== undefined,
451 );
452 assert.equal(pendingAsk(asked)?.kind, "command");
453 yield* answer("approve-answer", pendingAsk(asked)!, { decision: "accept" });
454 const approved = yield* waitFor(threadId, settled);
455 assert.equal(approved.runs.at(-1)?.status, "completed");
456 assert.isTrue(yield* fs.exists(path.join(ROOT, "work", "approved.txt")));
457​
458 yield* send(
459 threadId,
460 "decline",
461 "Run the shell command `touch declined.txt` with the shell tool, then reply DONE.",
462 );
463 const second = yield* waitFor(
464 threadId,
465 (projection) => projection.runs.length === 2 && pendingAsk(projection) !== undefined,
466 );
467 yield* answer("decline-answer", pendingAsk(second)!, { decision: "decline" });
468 let declined = yield* waitFor(
469 threadId,
470 (projection) =>
471 (projection.runs.length === 2 && settled(projection)) ||
472 pendingAsk(projection) !== undefined,
473 );
474 for (let retry = 0; pendingAsk(declined) !== undefined && retry < 3; retry += 1) {
475 yield* answer(`decline-retry-${retry}`, pendingAsk(declined)!, { decision: "decline" });
476 declined = yield* waitFor(
477 threadId,
478 (projection) =>
479 (projection.runs.length === 2 && settled(projection)) ||
480 pendingAsk(projection) !== undefined,
481 );
482 }
483 assert.equal(declined.runs.at(-1)?.status, "completed");
484 assert.isFalse(yield* fs.exists(path.join(ROOT, "work", "declined.txt")));
485​
486 yield* send(
487 threadId,
488 "question",
489 "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.",
490 );
491 const questioned = yield* waitFor(
492 threadId,
493 (projection) => projection.runs.length === 3 && pendingAsk(projection) !== undefined,
494 );
495 const question = pendingAsk(questioned)!;
496 assert.equal(question.kind, "user_input");
497 const form = questioned.turnItems.find(
498 (item) => item.type === "user_input_request" && item.requestId === question.id,
499 );
500 const firstQuestion = form?.type === "user_input_request" ? form.questions[0] : undefined;
501 assert.isDefined(firstQuestion);
502 yield* answer("question-answer", question, { answers: { [firstQuestion!.id]: "Blue" } });
503 const answered = yield* waitFor(
504 threadId,
505 (projection) => projection.runs.length === 3 && settled(projection),
506 );
507 assert.equal(answered.runs.at(-1)?.status, "completed");
508 const reply = answered.messages.findLast((message) => message.role === "assistant");
509 assert.match(reply?.text ?? "", /blue/i);
510 }).pipe(Effect.provide(Layer.merge(layerLive, NodeServices.layer)), Effect.scoped),
511 600_000,
512 );
513​
514 it.live(
515 "lets plan mode write only the plan agent's plan directory under Full access",
516 () =>
517 Effect.gen(function* () {
518 const fs = yield* FileSystem.FileSystem;
519 const path = yield* Path.Path;
520 yield* EffectWorker.runDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
521 const orchestrator = yield* Orchestrator.OrchestratorV2;
522 const threadId = ThreadId.make("thread:opencode2-live-plan");
523 yield* orchestrator.dispatch({
524 type: "thread.create",
525 createdBy: "user",
526 creationSource: "web",
527 commandId: CommandId.make("command:opencode2-live:plan-create"),
528 threadId,
529 projectId: ProjectId.make("project:opencode2-live"),
530 title: "OpenCode 2 live plan",
531 modelSelection: MODEL,
532 runtimeMode: "full-access",
533 interactionMode: "plan",
534 branch: null,
535 worktreePath: `${ROOT}/work`,
536 });
537 const planDir = path.join(ROOT, ".opencode", "plan");
538 yield* send(
539 threadId,
540 "plan",
541 `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.`,
542 );
543 const planned = yield* waitFor(threadId, settled);
544 assert.equal(planned.runs.at(-1)?.status, "completed");
545 assert.isFalse(yield* fs.exists(path.join(ROOT, "work", "plan_write_probe.txt")));
546 assert.isTrue(yield* fs.exists(path.join(planDir, "probe-plan.md")));
547 }).pipe(Effect.provide(Layer.merge(layerLive, NodeServices.layer)), Effect.scoped),
548 360_000,
549 );
550​
551 it.live(
552 "runs subagents, wakes the thread for a background one, and stops one still running",
553 () =>
554 Effect.gen(function* () {
555 yield* EffectWorker.runDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
556 const orchestrator = yield* Orchestrator.OrchestratorV2;
557 // One thread per case: a model that just answered one prompt may repeat it.
558 const thread = Effect.fn("OpenCode2Live.subagentThread")(function* (key: string) {
559 const threadId = ThreadId.make(`thread:opencode2-live-subagents-${key}`);
560 yield* orchestrator.dispatch({
561 type: "thread.create",
562 createdBy: "user",
563 creationSource: "web",
564 commandId: CommandId.make(`command:opencode2-live:subagents-${key}-create`),
565 threadId,
566 projectId: ProjectId.make("project:opencode2-live"),
567 title: `OpenCode 2 live subagents ${key}`,
568 modelSelection: MODEL,
569 runtimeMode: "full-access",
570 interactionMode: "default",
571 branch: null,
572 worktreePath: `${ROOT}/work`,
573 });
574 return threadId;
575 });
576 const childOf = (projection: OrchestrationV2ThreadProjection) =>
577 Effect.gen(function* () {
578 const childThreadId = projection.subagents[0]?.childThreadId;
579 assert.isDefined(childThreadId ?? undefined);
580 return yield* orchestrator.getThreadProjection(childThreadId!);
581 });
582​
583 const fgThread = yield* thread("fg");
584 yield* send(
585 fgThread,
586 "subagents-fg",
587 "Use the subagent tool (foreground, not background) to delegate to the general subagent with the prompt: 'Reply exactly FG_CHILD_OK.' Wait for it, then reply exactly FG_PARENT_OK.",
588 );
589 const foreground = yield* waitFor(fgThread, settled);
590 assert.deepEqual(
591 foreground.runs.map((run) => run.status),
592 ["completed"],
593 );
594 assert.equal(foreground.subagents[0]?.status, "completed");
595 const fgChild = yield* childOf(foreground);
596 assert.isTrue(
597 fgChild.turnItems.some(
598 (item) => item.type === "assistant_message" && item.text.includes("FG_CHILD_OK"),
599 ),
600 );
601​
602 const bgThread = yield* thread("bg");
603 yield* send(
604 bgThread,
605 "subagents-bg",
606 "Use the subagent tool with background set to true to delegate to the general subagent with the prompt: 'Run the shell command `sleep 8` with the shell tool, then reply exactly BG_CHILD_OK.' As soon as it is launched, reply exactly BG_LAUNCHED and end your turn without waiting.",
607 );
608 const woke = yield* waitFor(
609 bgThread,
610 (projection) =>
611 settled(projection) &&
612 projection.subagents[0]?.status === "completed" &&
613 !projection.turnItems.some(
614 (item) => item.status === "running" || item.status === "waiting",
615 ),
616 );
617 assert.isTrue(woke.runs.every((run) => run.status === "completed"));
618 const answeredIn = woke.runs.at(-1)!;
619 if (woke.runs.length === 2) {
620 const wakeMessage = woke.messages.find(
621 (message) => message.id === answeredIn.userMessageId,
622 );
623 assert.equal(
624 `${wakeMessage?.createdBy}:${wakeMessage?.creationSource}`,
625 "agent:provider",
626 );
627 } else {
628 assert.lengthOf(woke.runs, 1);
629 }
630 assert.isTrue(
631 woke.turnItems.some(
632 (item) => item.runId === answeredIn.id && item.type === "assistant_message",
633 ),
634 "the parent's answer to the report lands in the run that took it",
635 );
636​
637 const stopThread = yield* thread("stop");
638 yield* send(
639 stopThread,
640 "subagents-stop",
641 "Use the subagent tool with background set to true to delegate to the general subagent with the prompt: 'Run the shell command `sleep 60` with the shell tool, then reply exactly LATE.' As soon as it is launched, reply exactly STOP_LAUNCHED and end your turn without waiting.",
642 );
643 const launched = yield* waitFor(
644 stopThread,
645 (projection) =>
646 projection.runs[0]?.status !== "running" &&
647 projection.subagents[0]?.status === "running",
648 );
649 yield* orchestrator.dispatch({
650 type: "run.interrupt",
651 commandId: CommandId.make("command:opencode2-live:subagents-stop-interrupt"),
652 threadId: stopThread,
653 runId: launched.runs[0]!.id,
654 });
655 yield* waitFor(
656 stopThread,
657 (projection) =>
658 settled(projection) &&
659 projection.subagents[0] !== undefined &&
660 projection.subagents[0].status !== "running",
661 );
662 yield* Effect.sleep("5 seconds");
663 const final = yield* orchestrator.getThreadProjection(stopThread);
664 assert.lengthOf(final.runs, 1);
665 assert.equal(final.subagents[0]?.status, "interrupted");
666 assert.isFalse(
667 final.turnItems.some((item) => item.status === "running" || item.status === "waiting"),
668 );
669 const stoppedChild = yield* childOf(final);
670 assert.isFalse(
671 stoppedChild.turnItems.some((item) => item.status === "running"),
672 "the stopped child shows nothing running",
673 );
674 }).pipe(Effect.provide(Layer.merge(layerLive, NodeServices.layer)), Effect.scoped),
675 480_000,
676 );
677​
678 it.live(
679 "steers a running turn, queues two messages, forks an earlier turn and rolls back a write",
680 () =>
681 Effect.gen(function* () {
682 const fs = yield* FileSystem.FileSystem;
683 const path = yield* Path.Path;
684 yield* EffectWorker.runDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
685 const orchestrator = yield* Orchestrator.OrchestratorV2;
686 const work = path.join(ROOT, "inbox-work");
687 yield* fs.makeDirectory(work, { recursive: true });
688 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
689 const git = (...args: ReadonlyArray<string>) =>
690 spawner.exitCode(ChildProcess.make("git", ["-C", work, ...args]));
691 yield* git("init", "-q");
692 yield* git(
693 "-c",
694 "user.name=t3",
695 "-c",
696 "user.email=t3@example.com",
697 "commit",
698 "-q",
699 "--allow-empty",
700 "-m",
701 "init",
702 );
703 const threadId = ThreadId.make("thread:opencode2-live-inbox");
704 yield* orchestrator.dispatch({
705 type: "thread.create",
706 createdBy: "user",
707 creationSource: "web",
708 commandId: CommandId.make("command:opencode2-live-inbox:create"),
709 threadId,
710 projectId: ProjectId.make("project:opencode2-live-inbox"),
711 title: "OpenCode 2 live inbox",
712 modelSelection: MODEL,
713 runtimeMode: "full-access",
714 interactionMode: "default",
715 branch: null,
716 worktreePath: work,
717 });
718 const dispatch = (
719 key: string,
720 text: string,
721 dispatchMode: Extract<
722 OrchestrationV2Command,
723 { type: "message.dispatch" }
724 >["dispatchMode"],
725 ) =>
726 orchestrator.dispatch({
727 type: "message.dispatch",
728 createdBy: "user",
729 creationSource: "web",
730 commandId: CommandId.make(`command:opencode2-live-inbox:${key}`),
731 threadId,
732 messageId: MessageId.make(`message:opencode2-live-inbox:${key}`),
733 text,
734 attachments: [],
735 modelSelection: MODEL,
736 dispatchMode,
737 });
738 const assistantText = (projection: OrchestrationV2ThreadProjection, runId: string) =>
739 projection.turnItems
740 .flatMap((item) =>
741 item.type === "assistant_message" && item.runId === runId ? [item.text] : [],
742 )
743 .join("\n");
744​
745 yield* dispatch(
746 "alpha",
747 "Use the write tool to create reverted.txt containing exactly ALPHA, then reply DONE.",
748 { type: "start_immediately" },
749 );
750 const first = yield* waitFor(threadId, settled);
751 assert.equal(first.runs[0]?.status, "completed");
752 assert.equal((yield* fs.readFileString(path.join(work, "reverted.txt"))).trim(), "ALPHA");
753​
754 yield* dispatch(
755 "shell",
756 "Run the shell command `sleep 15 && echo A` with the shell tool in the foreground (not in the background) and wait for it, then use the write tool to overwrite reverted.txt with exactly BETA, then reply DONE_A.",
757 { type: "start_immediately" },
758 );
759 const running = yield* waitFor(threadId, (projection) =>
760 projection.turnItems.some(
761 (item) => item.type === "command_execution" && item.status === "running",
762 ),
763 );
764 const shellRun = running.runs.at(-1)!;
765 yield* dispatch("steer", "Also include the word STEERED in your final reply.", {
766 type: "steer_active",
767 targetRunId: shellRun.id,
768 });
769 yield* dispatch("queued-b", "Reply with exactly QUEUED_B.", { type: "queue_after_active" });
770 yield* dispatch("queued-c", "Reply with exactly QUEUED_C.", { type: "queue_after_active" });
771 const drained = yield* waitFor(
772 threadId,
773 (projection) => projection.runs.length === 4 && settled(projection),
774 );
775 const [, shell, queuedB, queuedC] = drained.runs;
776 assert.deepEqual(
777 drained.runs.map((run) => run.status),
778 ["completed", "completed", "completed", "completed"],
779 );
780 assert.include(assistantText(drained, shell!.id), "STEERED");
781 assert.include(assistantText(drained, queuedB!.id), "QUEUED_B");
782 assert.include(assistantText(drained, queuedC!.id), "QUEUED_C");
783 assert.lengthOf(drained.providerTurns, 4);
784 assert.deepEqual(
785 drained.turnItems.flatMap((item) =>
786 item.type === "user_message" && item.runId === shell!.id ? [item.inputIntent] : [],
787 ),
788 ["turn_start", "steer"],
789 );
790 assert.lengthOf(
791 drained.attempts.filter((attempt) => attempt.runId === shell!.id),
792 1,
793 );
794 assert.equal((yield* fs.readFileString(path.join(work, "reverted.txt"))).trim(), "BETA");
795​
796 const forkId = ThreadId.make("thread:opencode2-live-inbox-fork");
797 yield* orchestrator.dispatch({
798 type: "thread.fork",
799 createdBy: "user",
800 creationSource: "web",
801 commandId: CommandId.make("command:opencode2-live-inbox:fork"),
802 sourceThreadId: threadId,
803 targetThreadId: forkId,
804 sourcePoint: { type: "run", runId: first.runs[0]!.id },
805 });
806 const forkWork = path.join(ROOT, "inbox-fork-work");
807 yield* fs.makeDirectory(forkWork, { recursive: true });
808 yield* orchestrator.dispatch({
809 type: "thread.metadata.update",
810 commandId: CommandId.make("command:opencode2-live-inbox:fork-worktree"),
811 threadId: forkId,
812 worktreePath: forkWork,
813 });
814 yield* orchestrator.dispatch({
815 type: "message.dispatch",
816 createdBy: "user",
817 creationSource: "web",
818 commandId: CommandId.make("command:opencode2-live-inbox:fork-ask"),
819 threadId: forkId,
820 messageId: MessageId.make("message:opencode2-live-inbox:fork-ask"),
821 text: "Did I ask you to reply with QUEUED_B in this conversation? Answer only YES or NO.",
822 attachments: [],
823 modelSelection: MODEL,
824 dispatchMode: { type: "start_immediately" },
825 });
826 const forked = yield* waitFor(forkId, settled);
827 assert.equal(forked.contextTransfers[0]?.resolution?.strategy, "native_fork");
828 assert.equal(forked.runs[0]?.status, "completed");
829 assert.include(assistantText(forked, forked.runs[0]!.id).toUpperCase(), "NO");
830​
831 const checkpoint = drained.checkpoints.find(
832 (candidate) => candidate.appRunOrdinal === 1 && candidate.status === "ready",
833 );
834 assert.isDefined(checkpoint);
835 yield* orchestrator.dispatch({
836 type: "checkpoint.rollback",
837 commandId: CommandId.make("command:opencode2-live-inbox:rollback"),
838 threadId,
839 scopeId: checkpoint!.scopeId,
840 checkpointId: checkpoint!.id,
841 });
842 const rolledBack = yield* waitFor(threadId, (projection) =>
843 projection.runs.slice(1).every((run) => run.status === "rolled_back"),
844 );
845 assert.deepEqual(
846 rolledBack.runs.map((run) => run.status),
847 ["completed", "rolled_back", "rolled_back", "rolled_back"],
848 );
849 assert.equal((yield* fs.readFileString(path.join(work, "reverted.txt"))).trim(), "ALPHA");
850 yield* dispatch(
851 "after",
852 "Did I ask you to reply with QUEUED_B in this conversation? Answer only YES or NO.",
853 { type: "start_immediately" },
854 );
855 const after = yield* waitFor(
856 threadId,
857 (projection) => projection.runs.length === 5 && settled(projection),
858 );
859 assert.include(assistantText(after, after.runs[4]!.id).toUpperCase(), "NO");
860 const sessionId = after.providerThreads[0]?.nativeThreadRef?.nativeId;
861 const db = new NodeSqlite.DatabaseSync(`${ROOT}/data/opencode/opencode.db`, {
862 readOnly: true,
863 });
864 const userMessages = db
865 .prepare(
866 "SELECT id FROM session_message WHERE session_id = ? AND type = 'user' ORDER BY seq",
867 )
868 .all(sessionId!)
869 .map((row) => String(row.id));
870 db.close();
871 assert.lengthOf(userMessages, 2);
872 }).pipe(Effect.provide(Layer.merge(layerLive, NodeServices.layer)), Effect.scoped),
873 600_000,
874 );
875​
876 it.live(
877 "runs plan mode, a workspace command and skill, and /compact through the real driver",
878 () =>
879 Effect.gen(function* () {
880 const fs = yield* FileSystem.FileSystem;
881 const path = yield* Path.Path;
882 const work = path.join(ROOT, "work");
883 yield* fs.makeDirectory(path.join(work, ".opencode", "command"), { recursive: true });
884 yield* fs.makeDirectory(path.join(work, ".opencode", "skills", "greet"), {
885 recursive: true,
886 });
887 yield* fs.writeFileString(
888 path.join(work, ".opencode", "command", "hello.md"),
889 "---\ndescription: Say hello to the workspace\n---\nReply with exactly: HELLO $ARGUMENTS\n",
890 );
891 yield* fs.writeFileString(
892 path.join(work, ".opencode", "skills", "greet", "SKILL.md"),
893 "---\nname: greet\ndescription: Greets the user with the secret word MANGO.\n---\nWhen this skill is active, begin your reply with the exact word MANGO.\n",
894 );
895 yield* EffectWorker.runDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
896​
897 const instance =
898 yield* (yield* ProviderInstanceRegistry.ProviderInstanceRegistry).getInstance(INSTANCE);
899 assert.isDefined(instance);
900 const workspace = yield* instance!.snapshotForCwd!(work);
901 assert.include(
902 workspace.skills.map((skill) => skill.name),
903 "greet",
904 );
905 assert.includeMembers(
906 workspace.slashCommands.map((command) => command.name),
907 ["compact", "hello"],
908 );
909​
910 const orchestrator = yield* Orchestrator.OrchestratorV2;
911 const threadId = ThreadId.make("thread:opencode2-live-modes");
912 yield* orchestrator.dispatch({
913 type: "thread.create",
914 createdBy: "user",
915 creationSource: "web",
916 commandId: CommandId.make("command:opencode2-live-modes:create"),
917 threadId,
918 projectId: ProjectId.make("project:opencode2-live-modes"),
919 title: "OpenCode 2 live modes",
920 modelSelection: MODEL,
921 runtimeMode: "full-access",
922 interactionMode: "plan",
923 branch: null,
924 worktreePath: work,
925 });
926 const runs = (count: number) => (projection: OrchestrationV2ThreadProjection) =>
927 projection.runs.length === count && settled(projection);
928 const lastReply = (projection: OrchestrationV2ThreadProjection) =>
929 projection.turnItems.findLast((item) => item.type === "assistant_message");
930​
931 yield* send(
932 threadId,
933 "modes-plan",
934 "Plan how to add a --verbose flag to a script named cli.js; the file may not exist yet, so plan it from scratch. Do not ask me anything. Present a short plan; do not implement it.",
935 );
936 const planned = yield* waitFor(threadId, runs(1));
937 assert.equal(planned.runs[0]?.status, "completed");
938 const sessionId = planned.providerThreads[0]?.nativeThreadRef?.nativeId;
939 assert.isDefined(sessionId);
940 const planSteps = yield* assistantAgents(sessionId!);
941 assert.isAbove(planSteps.length, 0);
942 assert.isTrue(planSteps.every((agent) => agent === "plan"));
943​
944 yield* orchestrator.dispatch({
945 type: "thread.interaction-mode.set",
946 commandId: CommandId.make("command:opencode2-live-modes:default"),
947 threadId,
948 interactionMode: "default",
949 });
950 yield* send(threadId, "modes-command", "/hello WORLD");
951 const commanded = yield* waitFor(threadId, runs(2));
952 assert.equal(commanded.runs[1]?.status, "completed");
953 assert.include(lastReply(commanded)?.text ?? "", "HELLO WORLD");
954 assert.equal((yield* assistantAgents(sessionId!)).at(-1), "build");
955​
956 yield* send(threadId, "modes-skill", "Use $greet to say hi in three words.");
957 const skilled = yield* waitFor(threadId, runs(3));
958 assert.equal(skilled.runs[2]?.status, "completed");
959 assert.include(lastReply(skilled)?.text ?? "", "MANGO");
960​
961 yield* send(threadId, "modes-compact", "/compact");
962 const compacted = yield* waitFor(threadId, runs(4));
963 assert.equal(compacted.runs[3]?.status, "completed");
964 const compaction = compacted.turnItems.find((item) => item.type === "compaction");
965 assert.equal(compaction?.status, "completed");
966 assert.equal(compaction?.runId, compacted.runs[3]?.id);
967 assert.isAbove(
968 compaction?.type === "compaction" ? (compaction.summary ?? "").length : 0,
969 0,
970 );
971 }).pipe(Effect.provide(Layer.merge(layerLive, NodeServices.layer)), Effect.scoped),
972 360_000,
973 );
974​
975 it.live(
976 "generates a title, calls T3's MCP server, and reconciles a turn cut off by a killed server",
977 () =>
978 Effect.gen(function* () {
979 const work = `${ROOT}/work`;
980 yield* EffectWorker.runDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
981 const orchestrator = yield* Orchestrator.OrchestratorV2;
982 const instance =
983 yield* (yield* ProviderInstanceRegistry.ProviderInstanceRegistry).getInstance(INSTANCE);
984 assert.isDefined(instance);
985 yield* instance!.snapshot.refresh;
986​
987 const title = yield* instance!.textGeneration.generateThreadTitle({
988 cwd: work,
989 message: "fix the login redirect loop after oauth",
990 modelSelection: MODEL,
991 });
992 assert.isAbove(title.title.length, 0);
993​
994 const threadId = ThreadId.make("thread:opencode2-live-restart");
995 yield* orchestrator.dispatch({
996 type: "thread.create",
997 createdBy: "user",
998 creationSource: "web",
999 commandId: CommandId.make("command:opencode2-live-restart:create"),
1000 threadId,
1001 projectId: ProjectId.make("project:opencode2-live-restart"),
1002 title: "OpenCode 2 live restart",
1003 modelSelection: MODEL,
1004 runtimeMode: "full-access",
1005 interactionMode: "default",
1006 branch: null,
1007 worktreePath: work,
1008 });
1009 const runs = (count: number) => (projection: OrchestrationV2ThreadProjection) =>
1010 projection.runs.length === count && settled(projection);
1011​
1012 if (process.env.OPENCODE2_MCP_URL !== undefined) {
1013 yield* send(
1014 threadId,
1015 "restart-mcp",
1016 "Call the echo_marker tool from the T3 Code MCP server with word 'kiwi', then reply with its exact output and nothing else.",
1017 );
1018 const called = yield* waitFor(threadId, runs(1));
1019 assert.equal(called.runs[0]?.status, "completed");
1020 const reply = called.turnItems.findLast((item) => item.type === "assistant_message");
1021 assert.include(reply?.type === "assistant_message" ? reply.text : "", "MARKER-KIWI-7Q9");
1023 const before = (yield* orchestrator.getThreadProjection(threadId)).runs.length;
1024​
1025 yield* send(
1026 threadId,
1027 "restart-killed",
1028 "Run the shell command `sleep 60 && echo LATE` with the shell tool in the foreground and wait for it, then reply DONE.",
1029 );
1030 yield* waitFor(threadId, (projection) =>
1031 projection.turnItems.some(
1032 (item) =>
1033 item.type === "command_execution" &&
1034 item.status === "running" &&
1035 item.input.includes("sleep 60"),
1036 ),
1037 );
1038 const pid = spawnedPids.at(-1);
1039 assert.isDefined(pid);
1040 process.kill(pid!, "SIGKILL");
1041 const reconciled = yield* waitFor(threadId, runs(before + 1));
1042 assert.equal(reconciled.runs.at(-1)?.status, "interrupted");
1043​
1044 yield* send(
1045 threadId,
1046 "restart-next",
1047 "What did I last ask you to run? Answer in one short sentence.",
1048 );
1049 const next = yield* waitFor(threadId, runs(before + 2));
1050 assert.equal(next.runs.at(-1)?.status, "completed");
1051 const answer = next.turnItems.findLast((item) => item.type === "assistant_message");
1052 assert.include(answer?.type === "assistant_message" ? answer.text : "", "sleep 60");
1053 assert.lengthOf(next.providerThreads, 1);
1054 }).pipe(Effect.provide(Layer.merge(layerLive, NodeServices.layer)), Effect.scoped),
1055 360_000,
1056 );
1057​
1058 // Needs an external server behind a proxy that cuts its event streams on
1059 // `GET <proxy>/__drop`, so only the stream drops while the server stays up.
1060 it.live.runIf(process.env.OPENCODE2_DROP_URL !== undefined)(
1061 "picks a turn back up after an external server's event stream drops mid-turn",
1062 () =>
1063 Effect.gen(function* () {
1064 const work = `${ROOT}/work`;
1065 yield* EffectWorker.runDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped);
1066 const orchestrator = yield* Orchestrator.OrchestratorV2;
1067 const threadId = ThreadId.make("thread:opencode2-live-drop");
1068 yield* orchestrator.dispatch({
1069 type: "thread.create",
1070 createdBy: "user",
1071 creationSource: "web",
1072 commandId: CommandId.make("command:opencode2-live-drop:create"),
1073 threadId,
1074 projectId: ProjectId.make("project:opencode2-live-drop"),
1075 title: "OpenCode 2 live drop",
1076 modelSelection: MODEL,
1077 runtimeMode: "full-access",
1078 interactionMode: "default",
1079 branch: null,
1080 worktreePath: work,
1081 });
1082 yield* send(
1083 threadId,
1084 "drop-running",
1085 "Run the shell command `sleep 8 && echo AFTER_DROP` with the shell tool in the foreground and wait for it, then reply with its exact output.",
1086 );
1087 yield* waitFor(threadId, (projection) =>
1088 projection.turnItems.some(
1089 (item) => item.type === "command_execution" && item.status === "running",
1090 ),
1091 );
1092 yield* HttpClient.get(process.env.OPENCODE2_DROP_URL!).pipe(
1093 Effect.provide(FetchHttpClient.layer),
1094 Effect.orDie,
1095 );
1096 const done = yield* waitFor(threadId, settled);
1097 assert.equal(done.runs[0]?.status, "completed");
1098 const shell = done.turnItems.find((item) => item.type === "command_execution");
1099 assert.equal(shell?.status, "completed");
1100 const reply = done.turnItems.findLast((item) => item.type === "assistant_message");
1101 assert.include(reply?.type === "assistant_message" ? reply.text : "", "AFTER_DROP");
1102 const opencode = yield* OpenCode2Client.make.pipe(Effect.provide(FetchHttpClient.layer));
1103 const api = yield* opencode.connect({
1104 baseUrl: process.env.OPENCODE2_SERVER_URL!,
1105 password: process.env.OPENCODE2_SERVER_PASSWORD ?? "",
1106 });
1107 const servers = yield* api.client.mcp.list({ location: { directory: work } });
1108 assert.deepEqual(
1109 servers.data.map((server) => server.name),
1110 [],
1111 "an external server gets no T3 MCP server, as with 1.x",
1112 );
1113 }).pipe(Effect.provide(Layer.merge(layerLive, NodeServices.layer)), Effect.scoped),
1114 360_000,
1115 );
1116});