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

OpenCode2OrchestratorV2.live.test.ts

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