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

OpenCode2OrchestratorV2.live.test.ts

1,185 lines51.7 KB

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