The best way to control Claude Code, Codex and more from any computer or phone

main
ts 8,734 lines 339 KB
Raw
1 import * as NodeURL from "node:url";
2 import { toolOutputImages } from "@t3tools/shared/toolOutput";
3 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { assert, it } from "@effect/vitest";
6 import {
7 ChatAttachmentId,
8 ChatFileAttachment,
9 ChatImageAttachment,
10 CheckpointId,
11 EnvironmentId,
12 MessageId,
13 NodeId,
14 ProviderInstanceId,
15 ProviderSessionId,
16 ProviderThreadId,
17 ProviderTurnId,
18 RunAttemptId,
19 RunId,
20 type RuntimeRequestId,
21 ThreadId,
22 type ModelSelection,
23 type OrchestrationV2AppThread,
24 type OrchestrationV2ProviderFailure,
25 type OrchestrationV2ProviderThread,
26 type OrchestrationV2ProviderTurn,
27 type ProviderReplayEntry,
28 } from "@t3tools/contracts";
29 import * as Cause from "effect/Cause";
30 import * as DateTime from "effect/DateTime";
31 import * as Deferred from "effect/Deferred";
32 import * as Effect from "effect/Effect";
33 import * as Fiber from "effect/Fiber";
34 import * as FileSystem from "effect/FileSystem";
35 import * as Layer from "effect/Layer";
36 import * as Option from "effect/Option";
37 import * as Queue from "effect/Queue";
38 import * as Scope from "effect/Scope";
39 import * as Stream from "effect/Stream";
40 import * as Exit from "effect/Exit";
41 import { TestClock } from "effect/testing";
42
43 import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
44 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
45 import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
46 import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
47 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
48 import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
49 import {
50 OPENCODE_2_STILL_STOPPING,
51 OPENCODE_PROVIDER,
52 t3McpServerName,
53 } from "@t3tools/provider-opencode/testing";
54 import { resolveAttachmentPath } from "../../attachmentStore.ts";
55 import { openCode2ReplayRuntime } from "./OpenCode2AdapterV2.testkit.ts";
56 import {
57 makeProviderReplayGate,
58 type ProviderReplayGate,
59 } from "@t3tools/provider-testing/replayGate";
60
61 const SESSION = "ses_f148ca2deffeJcwCnRQtb0YFNX";
62 const WORK = "/work/opencode2";
63 const instanceId = ProviderInstanceId.make("opencode");
64 const threadId = ThreadId.make("thread:opencode2-adapter");
65
66 const out = (type: string, input?: unknown): ProviderReplayEntry => ({
67 type: "expect_outbound",
68 frame: input === undefined ? { type } : { type, input },
69 });
70 const reply = (operation: string, data: unknown): ProviderReplayEntry => ({
71 type: "emit_inbound",
72 frame: { type: "sdk.response", operation, data },
73 });
74 const replyData = (operation: string, data: unknown) => reply(operation, { data });
75 const event = (
76 type: string,
77 data: Record<string, unknown>,
78 label?: string,
79 version = 1,
80 ): ProviderReplayEntry => ({
81 type: "emit_inbound",
82 frame: {
83 type: "sdk.event",
84 event: {
85 id: `evt_${type.replaceAll(".", "")}0000`,
86 created: 1,
87 type,
88 ...(type.startsWith("rpc.") ? { location: { directory: WORK } } : {}),
89 data,
90 durable: { ...durable.durable, version },
91 },
92 },
93 ...(label === undefined ? {} : { label }),
94 });
95 const durable = { durable: { aggregateID: SESSION, seq: 1, version: 1 } };
96
97 const mcpRules = [
98 { action: "t3-code-*", resource: "*", effect: "deny" },
99 { action: "t3-code-thread_opencode2-adapter_*", resource: "*", effect: "allow" },
100 ];
101 const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, ...mcpRules];
102 const TITLE = "Prime check";
103 const sessionInfo = (overrides: Record<string, unknown> = {}) => ({
104 id: SESSION,
105 title: TITLE,
106 permissions: t3Rules,
107 projectID: "global",
108 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
109 cost: 0,
110 tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
111 time: { created: 1790656601394, updated: 1790656601394 },
112 location: { directory: WORK },
113 ...overrides,
114 });
115 const modelCatalog = {
116 location: { directory: WORK },
117 data: [
118 {
119 id: "big-pickle",
120 modelID: "big-pickle",
121 providerID: "opencode",
122 family: "big-pickle",
123 name: "Big Pickle",
124 compatibility: { reasoningField: "reasoning_content" },
125 package: "@opencode/ai/providers/openai-compatible",
126 settings: { apiKey: "public", baseURL: "https://opencode.ai/zen/v1", provider: "opencode" },
127 capabilities: { tools: true, input: ["text"], output: ["text"] },
128 variants: [],
129 time: { released: 1760659200000 },
130 cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }],
131 status: "active",
132 enabled: true,
133 limit: { context: 200000, input: 160000, output: 32000 },
134 },
135 ],
136 };
137
138 const PROMPT_ID = "msg_0eb735d41001NJee1EvVePJAK5";
139 const promptAccepted = replyData("session.prompt", {
140 id: PROMPT_ID,
141 sessionID: SESSION,
142 time: { created: 1790656601410 },
143 type: "user",
144 payload: { text: "hi" },
145 delivery: "steer",
146 });
147
148 const emptyShellInventory: ReadonlyArray<ProviderReplayEntry> = [
149 out("shell.list", "<any>"),
150 reply("shell.list", { location: { directory: WORK }, data: [] }),
151 ];
152
153 const noOpenRequests: ReadonlyArray<ProviderReplayEntry> = [
154 out("permission.list", { sessionID: SESSION }),
155 replyData("permission.list", []),
156 out("session.form.list", { sessionID: SESSION }),
157 replyData("session.form.list", []),
158 ];
159
160 const withInstructions = (
161 entries: ReadonlyArray<ProviderReplayEntry>,
162 ): ReadonlyArray<ProviderReplayEntry> => {
163 const first = entries.findIndex(
164 (entry) =>
165 entry.type === "expect_outbound" &&
166 typeof entry.frame === "object" &&
167 entry.frame !== null &&
168 "type" in entry.frame &&
169 [
170 "session.prompt",
171 "session.command",
172 "session.compact",
173 "command.list",
174 "skill.list",
175 "rpc.call",
176 ].includes(String(entry.frame.type)),
177 );
178 const after = entries.findIndex(
179 (entry, index) =>
180 index < first &&
181 entry.type === "emit_inbound" &&
182 typeof entry.frame === "object" &&
183 entry.frame !== null &&
184 "operation" in entry.frame &&
185 entry.frame.operation === "mcp.add",
186 );
187 const at = after < 0 ? first : after + 1;
188 return first < 0
189 ? entries
190 : [
191 ...entries.slice(0, at),
192 out("session.instructions.entry.put", {
193 sessionID: SESSION,
194 key: "t3-code",
195 value: "<any>",
196 }),
197 reply("session.instructions.entry.put", null),
198 ...entries.slice(at),
199 ];
200 };
201
202 const openCode2ReplayRuntimeWithInstructions = (
203 entries: ReadonlyArray<ProviderReplayEntry>,
204 options?: { readonly external?: boolean },
205 ) => openCode2ReplayRuntime(withInstructions(entries), options);
206
207 const opening: ReadonlyArray<ProviderReplayEntry> = [
208 out("event.subscribe"),
209 out("model.list", "<any>"),
210 reply("model.list", modelCatalog),
211 ];
212 const directoryModels = (directory: string): ReadonlyArray<ProviderReplayEntry> => [
213 out("model.list", { "location[directory]": directory }),
214 reply("model.list", { ...modelCatalog, location: { directory } }),
215 ];
216
217 const bigPickle: ModelSelection = { instanceId, model: "opencode/big-pickle" };
218 const policy = (runtimeMode: "full-access" | "approval-required" = "full-access") => ({
219 runtimeMode,
220 interactionMode: "default" as const,
221 cwd: WORK,
222 });
223
224 const providerThread = (now: DateTime.Utc): OrchestrationV2ProviderThread => ({
225 id: ProviderThreadId.make("provider-thread:opencode2-adapter"),
226 driver: OPENCODE_PROVIDER,
227 providerInstanceId: instanceId,
228 providerSessionId: ProviderSessionId.make("provider-session:opencode2-adapter"),
229 appThreadId: threadId,
230 ownerNodeId: null,
231 nativeThreadRef: { driver: OPENCODE_PROVIDER, nativeId: SESSION, strength: "strong" },
232 nativeConversationHeadRef: null,
233 status: "idle",
234 firstRunOrdinal: null,
235 lastRunOrdinal: null,
236 handoffIds: [],
237 forkedFrom: null,
238 createdAt: now,
239 updatedAt: now,
240 });
241
242 const turnInput = (
243 thread: OrchestrationV2ProviderThread,
244 modelSelection: ModelSelection = bigPickle,
245 runtimeMode: "full-access" | "approval-required" = "full-access",
246 ) => ({
247 appThread: { title: TITLE } as OrchestrationV2AppThread,
248 threadId,
249 runId: RunId.make("run:opencode2-adapter"),
250 runOrdinal: 1,
251 providerTurnOrdinal: 1,
252 attemptId: RunAttemptId.make("attempt:opencode2-adapter"),
253 rootNodeId: NodeId.make("node:opencode2-adapter"),
254 providerThread: thread,
255 message: {
256 messageId: MessageId.make("message:opencode2-adapter"),
257 text: "hi",
258 attachments: [],
259 createdBy: "user" as const,
260 creationSource: "web" as const,
261 scheduledTaskId: undefined,
262 senderThreadId: undefined,
263 },
264 modelSelection,
265 runtimePolicy: policy(runtimeMode),
266 });
267
268 const buildPaths = [
269 {
270 action: "external_directory",
271 resource: "/home/.local/share/opencode/tool-output/*",
272 effect: "allow",
273 },
274 ];
275 const agentList = {
276 location: { directory: WORK },
277 data: [
278 {
279 id: "build",
280 name: "Build",
281 request: { settings: {}, headers: {}, body: {} },
282 description: "The default agent.",
283 mode: "primary",
284 hidden: false,
285 permissions: [{ action: "*", resource: "*", effect: "allow" }, ...buildPaths],
286 },
287 ],
288 };
289 const supervisedRules = [
290 { action: "shell", resource: "*", effect: "ask" },
291 { action: "edit", resource: "*", effect: "ask" },
292 { action: "external_directory", resource: "*", effect: "ask" },
293 ...buildPaths,
294 ...mcpRules,
295 ];
296
297 const shellAsk = {
298 data: {
299 id: "per_0eb7c4d7e001Pyt8o50Vi4KrOO",
300 sessionID: SESSION,
301 action: "shell",
302 resources: ["echo FIRST"],
303 save: ["echo *"],
304 source: { type: "tool", messageID: "msg_0eb7c4330001dYFQKuTpfD780v", id: "call_1" },
305 },
306 };
307 const shellAskEvent = event("permission.asked", shellAsk.data);
308 const colorForm = {
309 id: "frm_0eb79ab35001fkvFECSh3wYNVD",
310 sessionID: SESSION,
311 title: "Questions",
312 metadata: { kind: "question" },
313 fields: [
314 {
315 key: "q0",
316 title: "Color preference",
317 description: "Which color do you prefer?",
318 type: "string",
319 options: [{ value: "Red", label: "Red" }],
320 custom: true,
321 },
322 ],
323 };
324
325 const resumed = (
326 entries: ReadonlyArray<ProviderReplayEntry>,
327 options?: {
328 readonly version?: "2.2.1" | "2.2.5" | "2.2.6";
329 readonly shellRecovery?: ReadonlyArray<ProviderReplayEntry>;
330 readonly lastRunOrdinal?: number;
331 readonly pendingBackgroundTasks?: OrchestrationV2ProviderThread["pendingBackgroundTasks"];
332 readonly goal?: OrchestrationV2ProviderThread["goal"];
333 readonly contextUsage?: OrchestrationV2ProviderThread["contextUsage"];
334 readonly external?: boolean;
335 readonly supervised?: boolean;
336 readonly processExit?: Effect.Effect<void>;
337 readonly beforeResponse?: (path: string) => Effect.Effect<void>;
338 readonly borrowers?: { current: number };
339 readonly replayGate?: ProviderReplayGate;
340 readonly attachmentsDir?: string;
341 readonly resolveExtractedTextPath?: (path: string) => Effect.Effect<string | undefined>;
342 readonly fileSystem?: FileSystem.FileSystem;
343 readonly onPrompt?: (input: unknown) => void;
344 },
345 ) =>
346 Effect.gen(function* () {
347 const runtime = yield* openCode2ReplayRuntime(
348 [
349 ...opening,
350 out("session.get", { sessionID: SESSION }),
351 replyData("session.get", sessionInfo()),
352 ...noOpenRequests,
353 ...(options?.version === "2.2.5" || options?.version === "2.2.6"
354 ? [out("rpc.call", "<any>"), reply("rpc.call", { output: null })]
355 : []),
356 ...(options?.shellRecovery ??
357 (options?.version === undefined
358 ? []
359 : [
360 ...(options.version === "2.2.6"
361 ? [out("job.list", { kind: "shell" }), reply("job.list", { data: [] })]
362 : emptyShellInventory),
363 ])),
364 ...withInstructions([
365 ...(options?.supervised === true
366 ? [
367 out("agent.list", "<any>"),
368 reply("agent.list", agentList),
369 out("session.update", { sessionID: SESSION, permissions: supervisedRules }),
370 reply("session.update", null),
371 ]
372 : []),
373 ...entries,
374 ]),
375 ],
376 {
377 ...(options?.version === undefined ? {} : { version: options.version }),
378 ...(options?.borrowers === undefined ? {} : { borrowers: options.borrowers }),
379 ...(options?.fileSystem === undefined ? {} : { fileSystem: options.fileSystem }),
380 ...(options?.onPrompt === undefined ? {} : { onPrompt: options.onPrompt }),
381 ...(options?.external === undefined ? {} : { external: options.external }),
382 ...(options?.processExit === undefined ? {} : { processExit: options.processExit }),
383 ...(options?.beforeResponse === undefined
384 ? {}
385 : { beforeResponse: options.beforeResponse }),
386 ...(options?.replayGate === undefined ? {} : { replayGate: options.replayGate }),
387 ...(options?.attachmentsDir === undefined
388 ? {}
389 : { attachmentsDir: options.attachmentsDir }),
390 ...(options?.resolveExtractedTextPath === undefined
391 ? {}
392 : { resolveExtractedTextPath: options.resolveExtractedTextPath }),
393 },
394 );
395 const thread = yield* runtime.resumeThread({
396 providerThread: {
397 ...providerThread(yield* DateTime.now),
398 ...(options?.lastRunOrdinal === undefined
399 ? {}
400 : { lastRunOrdinal: options.lastRunOrdinal }),
401 ...(options?.goal === undefined ? {} : { goal: options.goal }),
402 ...(options?.contextUsage === undefined ? {} : { contextUsage: options.contextUsage }),
403 ...(options?.pendingBackgroundTasks === undefined
404 ? {}
405 : { pendingBackgroundTasks: options.pendingBackgroundTasks }),
406 },
407 threadId,
408 modelSelection: bigPickle,
409 runtimePolicy: policy(options?.supervised === true ? "approval-required" : "full-access"),
410 });
411 return { runtime, thread };
412 });
413
414 const requestOf = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime) =>
415 runtime.events.pipe(
416 Stream.filter(
417 (
418 event,
419 ): event is Extract<
420 ProviderAdapter.ProviderAdapterV2Event,
421 { type: "runtime_request.updated" }
422 > => event.type === "runtime_request.updated",
423 ),
424 Stream.map((event) => event.runtimeRequest),
425 Stream.runHead,
426 Effect.map(Option.getOrUndefined),
427 );
428
429 const terminalOf = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime) =>
430 runtime.events.pipe(
431 Stream.filter(
432 (
433 event,
434 ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
435 event.type === "turn.terminal",
436 ),
437 Stream.runHead,
438 Effect.map(Option.getOrUndefined),
439 );
440
441 const history = {
442 data: [
443 {
444 id: "msg_0eb732081001RntUJfRtTXOAjd",
445 time: { created: 1790656585885 },
446 text: "Think carefully step by step about whether 391 is prime, showing your reasoning, then answer in one short sentence.",
447 type: "user",
448 },
449 {
450 id: "msg_0eb7320a9001vve3OV5uNi2HRT",
451 time: { created: 1790656585925, streamed: 1790656590719, completed: 1790656590736 },
452 type: "assistant",
453 agent: "build",
454 model: { id: "space-bunny-free", providerID: "opencode", variant: "high" },
455 content: [
456 { type: "reasoning", text: "Check divisibility up to sqrt(391)." },
457 { type: "text", text: "391 is not prime: it's the product 17 × 23." },
458 ],
459 finish: "stop",
460 cost: 0,
461 tokens: { input: 8701, output: 113, reasoning: 147, cache: { read: 489, write: 0 } },
462 },
463 {
464 id: "msg_0eb733399001NhwTrB32UU6d6H",
465 time: { created: 1790656590745 },
466 type: "idle",
467 outcome: "succeeded",
468 },
469 ],
470 cursor: {},
471 };
472
473 const nativeGoal = (status: "active" | "paused" | "complete") => ({
474 id: "goal-1",
475 objective: "Write proof.txt",
476 status,
477 rounds: 2,
478 maxRounds: 100,
479 boot: "boot-1",
480 updatedAt: 1,
481 reason: "Checked proof.txt",
482 });
483
484 it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
485 it.effect("switches the session's model and variant before a turn that changed them", () =>
486 Effect.gen(function* () {
487 const { runtime, thread } = yield* resumed([
488 out("session.switchModel", {
489 sessionID: SESSION,
490 model: { providerID: "openrouter", id: "deepseek/deepseek-v4-flash", variant: "high" },
491 }),
492 reply("session.switchModel", null),
493 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
494 promptAccepted,
495 event("session.execution.succeeded", { sessionID: SESSION }),
496 ]);
497 assert.deepEqual(thread.nativeMetadata?.modelSelection, {
498 ...bigPickle,
499 options: [{ id: "variant", value: "default" }],
500 });
501 assert.equal(bigPickle.options, undefined);
502 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
503 yield* runtime.startTurn(
504 turnInput(thread, {
505 instanceId,
506 model: "openrouter/deepseek/deepseek-v4-flash",
507 options: [{ id: "variant", value: "high" }],
508 }),
509 );
510 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
511 }),
512 );
513
514 it.effect("drops context usage carried over from before a completed compaction", () =>
515 Effect.gen(function* () {
516 const { runtime, thread } = yield* resumed(
517 [
518 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
519 promptAccepted,
520 event("session.step.ended", {
521 sessionID: SESSION,
522 assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z",
523 finish: "stop",
524 cost: 0,
525 tokens: { input: 150_000, output: 40, reasoning: 0, cache: { read: 0, write: 0 } },
526 }),
527 event("session.compaction.started", { sessionID: SESSION, reason: "manual", recent: "" }),
528 event("session.compaction.ended", {
529 sessionID: SESSION,
530 reason: "manual",
531 text: "Summary",
532 recent: "",
533 }),
534 event("session.execution.succeeded", { sessionID: SESSION }),
535 ],
536 { contextUsage: { usedTokens: 150_000, maxTokens: 160_000 } },
537 );
538 assert.equal(thread.contextUsage?.usedTokens, 150_000);
539 const collected = yield* runtime.events.pipe(
540 Stream.takeUntil((event) => event.type === "turn.terminal"),
541 Stream.runCollect,
542 Effect.forkScoped,
543 );
544 yield* runtime.startTurn(turnInput(thread));
545 const seen = yield* Fiber.join(collected);
546 const usage = seen.flatMap((event) =>
547 event.type === "provider_thread.updated" ? [event.providerThread.contextUsage] : [],
548 );
549 assert.isNull(usage.at(-1));
550 const settled = seen.findLast(
551 (event) =>
552 event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null,
553 );
554 assert.isUndefined(
555 settled?.type === "provider_turn.updated" ? settled.providerTurn.tokenUsage : "missing",
556 );
557 }),
558 );
559
560 it.effect("never sends a saved variant the catalog model does not list", () =>
561 Effect.gen(function* () {
562 const { runtime, thread } = yield* resumed([
563 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
564 promptAccepted,
565 event("session.execution.succeeded", { sessionID: SESSION }),
566 ]);
567 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
568 yield* runtime.startTurn(
569 turnInput(thread, { ...bigPickle, options: [{ id: "variant", value: "medium" }] }),
570 );
571 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
572 }),
573 );
574
575 it.effect("resumes through OpenCode with an empty native prompt", () =>
576 Effect.gen(function* () {
577 const { runtime, thread } = yield* resumed([
578 out("session.prompt", { sessionID: SESSION, text: "" }),
579 promptAccepted,
580 event("session.execution.succeeded", { sessionID: SESSION }),
581 ]);
582 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
583 const { message, ...input } = turnInput(thread);
584 yield* runtime.resumeTurn!({ ...input, messageId: message.messageId });
585 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
586 }).pipe(Effect.scoped),
587 );
588
589 it.effect("renames the session before the first turn after the thread was renamed", () =>
590 Effect.gen(function* () {
591 const { runtime, thread } = yield* resumed([
592 out("session.update", { sessionID: SESSION, title: "Prime factors of 391" }),
593 reply("session.update", null),
594 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
595 promptAccepted,
596 event("session.execution.succeeded", { sessionID: SESSION }),
597 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
598 promptAccepted,
599 event("session.execution.succeeded", { sessionID: SESSION }),
600 ]);
601 const renamed = {
602 ...turnInput(thread),
603 appThread: { title: "Prime factors of 391" } as OrchestrationV2AppThread,
604 };
605 const first = yield* terminalOf(runtime).pipe(Effect.forkScoped);
606 yield* runtime.startTurn(renamed);
607 assert.equal((yield* Fiber.join(first))?.status, "completed");
608 const second = yield* terminalOf(runtime).pipe(Effect.forkScoped);
609 yield* runtime.startTurn({
610 ...renamed,
611 runId: RunId.make("run:opencode2-adapter:2"),
612 attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"),
613 });
614 assert.equal((yield* Fiber.join(second))?.status, "completed");
615 }),
616 );
617
618 it.effect("ends a turn on the provider thread it started on", () =>
619 Effect.gen(function* () {
620 const { runtime, thread } = yield* resumed([
621 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
622 promptAccepted,
623 event("session.execution.succeeded", { sessionID: SESSION }),
624 ]);
625 const forkedRow = {
626 ...thread,
627 id: ProviderThreadId.make("provider-thread:opencode2-adapter:forked-run-row"),
628 };
629 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
630 yield* runtime.startTurn(turnInput(forkedRow));
631 assert.equal((yield* Fiber.join(terminal))?.providerThreadId, forkedRow.id);
632 }),
633 );
634
635 // regression: #18315 OpenCode Go quota stops were not shown as usage limits
636 it.effect.each([
637 ["provider.quota", "usage_limit"],
638 ["provider.rate-limit", "usage_limit"],
639 ["provider", "provider_error"],
640 ] as const)("classifies a %s execution failure as %s", ([code, failureClass]) =>
641 Effect.gen(function* () {
642 const { runtime, thread } = yield* resumed([
643 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
644 promptAccepted,
645 event("session.execution.failed", {
646 sessionID: SESSION,
647 error: { type: code, message: "Provider rejected the request" },
648 }),
649 ]);
650 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
651 yield* runtime.startTurn(turnInput(thread));
652 const ended = yield* Fiber.join(terminal);
653 assert.equal(ended?.status, "failed");
654 assert.deepEqual(ended?.failure, {
655 class: failureClass,
656 code,
657 message: "Provider rejected the request",
658 retryable: null,
659 });
660 }),
661 );
662
663 // OpenCode types an empty balance as provider.quota too, but answers it with
664 // HTTP 402 and it never resets. Usage windows and budgets arrive as 429.
665 it.effect.each([
666 {
667 name: "an out-of-funds provider.quota (402)",
668 failureClass: "provider_error",
669 error: {
670 type: "provider.quota",
671 message: "Upstream request failed: Insufficient account funds",
672 status: 402,
673 },
674 },
675 {
676 name: "a provider.quota usage window (429)",
677 failureClass: "usage_limit",
678 error: {
679 type: "provider.quota",
680 message: "Subscription quota exceeded.",
681 status: 429,
682 response: {
683 body: JSON.stringify({
684 type: "error",
685 error: { type: "GoUsageLimitError", message: "Subscription quota exceeded." },
686 }),
687 },
688 },
689 },
690 {
691 name: "a provider.quota account budget (429)",
692 failureClass: "usage_limit",
693 error: {
694 type: "provider.quota",
695 message: "Upstream request failed: Account budget exceeded",
696 status: 429,
697 },
698 },
699 {
700 name: "a provider.rate-limit failure (429)",
701 failureClass: "usage_limit",
702 error: {
703 type: "provider.rate-limit",
704 message: "Rate limit exceeded: free-models-per-min.",
705 status: 429,
706 },
707 },
708 {
709 name: "a Claude limit without a reset timestamp",
710 failureClass: "usage_limit",
711 error: {
712 type: "provider.unknown",
713 message: "You've hit your session limit · resets 5:20pm (Europe/Berlin)",
714 },
715 },
716 {
717 name: "an unrelated provider.unknown failure",
718 failureClass: "provider_error",
719 error: {
720 type: "provider.unknown",
721 message: "Request failed. Resets at 2026-11-02T20:00:00Z.",
722 },
723 },
724 ] as const)("classifies $name as $failureClass", ({ error, failureClass }) =>
725 Effect.gen(function* () {
726 const { runtime, thread } = yield* resumed([
727 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
728 promptAccepted,
729 event("session.retry.scheduled", {
730 sessionID: SESSION,
731 assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z",
732 attempt: 2,
733 at: 2_001,
734 error,
735 }),
736 event("session.execution.failed", { sessionID: SESSION, error }),
737 ]);
738 const collected = yield* runtime.events.pipe(
739 Stream.takeUntil((event) => event.type === "turn.terminal"),
740 Stream.runCollect,
741 Effect.forkScoped,
742 );
743 yield* runtime.startTurn(turnInput(thread));
744 const seen = yield* Fiber.join(collected);
745 assert.deepInclude(errorRows(seen)[0], {
746 status: "running",
747 failure: { class: failureClass, code: error.type, message: error.message, retryable: true },
748 });
749 const ended = seen.find((event) => event.type === "turn.terminal");
750 assert.equal(ended?.status, "failed");
751 assert.deepEqual(ended?.failure, {
752 class: failureClass,
753 code: error.type,
754 message: error.message,
755 retryable: null,
756 });
757 }),
758 );
759
760 // regression: #29289 Claude weekly limits through claude-agent lost their usage-limit reset
761 it.effect(
762 "classifies a Claude weekly limit as a usage limit that resets at its reported time",
763 () =>
764 Effect.gen(function* () {
765 const message =
766 "You've hit your weekly limit · resets 9pm (Europe/Paris) Resets at 2026-11-02T20:00:00.000Z.";
767 const { runtime, thread } = yield* resumed([
768 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
769 promptAccepted,
770 event("session.execution.failed", {
771 sessionID: SESSION,
772 error: { type: "provider.unknown", message },
773 }),
774 ]);
775 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
776 yield* runtime.startTurn(turnInput(thread));
777 const ended = yield* Fiber.join(terminal);
778 assert.equal(ended?.status, "failed");
779 assert.deepEqual(ended?.failure, {
780 class: "usage_limit",
781 code: "provider.unknown",
782 message,
783 retryable: null,
784 resetAt: "2026-11-02T20:00:00.000Z",
785 });
786 }),
787 );
788
789 it.effect("ends the turn when its terminal event is one this build cannot decode", () =>
790 Effect.gen(function* () {
791 const { runtime, thread } = yield* resumed([
792 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
793 promptAccepted,
794 event("session.execution.interrupted", { sessionID: SESSION, reason: "budget" }),
795 ]);
796 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
797 yield* runtime.startTurn(turnInput(thread));
798 assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
799 }),
800 );
801
802 it.effect("keeps a turn running through a start event this build cannot decode", () =>
803 Effect.gen(function* () {
804 const { runtime, thread } = yield* resumed([
805 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
806 promptAccepted,
807 {
808 type: "emit_inbound",
809 frame: {
810 type: "sdk.event",
811 event: {
812 id: "evt_executionstartedx",
813 created: 1,
814 type: "session.execution.started",
815 data: { sessionID: SESSION },
816 durable: "not-an-envelope",
817 },
818 },
819 },
820 event("session.text.started", {
821 sessionID: SESSION,
822 assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z",
823 ordinal: 0,
824 }),
825 event("session.text.ended", {
826 sessionID: SESSION,
827 assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z",
828 ordinal: 0,
829 text: "DONE",
830 }),
831 event("session.execution.succeeded", { sessionID: SESSION }),
832 ]);
833 const collected = yield* runtime.events.pipe(
834 Stream.takeUntil((event) => event.type === "turn.terminal"),
835 Stream.runCollect,
836 Effect.forkScoped,
837 );
838 yield* runtime.startTurn(turnInput(thread));
839 const seen = yield* Fiber.join(collected);
840 const terminals = seen.filter((event) => event.type === "turn.terminal");
841 assert.deepEqual(
842 terminals.map((event) => event.type === "turn.terminal" && event.status),
843 ["completed"],
844 );
845 assert.isTrue(
846 seen.some(
847 (event) =>
848 event.type === "turn_item.updated" &&
849 event.turnItem.type === "assistant_message" &&
850 event.turnItem.text === "DONE",
851 ),
852 );
853 }),
854 );
855
856 it.effect("stops running turns on an external server when the session closes", () =>
857 Effect.gen(function* () {
858 const scope = yield* Scope.make();
859 const { runtime, thread } = yield* resumed(
860 [
861 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
862 promptAccepted,
863 out("session.interrupt", { sessionID: SESSION }),
864 reply("session.interrupt", { interrupted: true }),
865 ],
866 { external: true },
867 ).pipe(Scope.provide(scope));
868 yield* runtime.startTurn(turnInput(thread));
869 yield* Scope.close(scope, Exit.void);
870 }),
871 );
872
873 it.effect("sends nothing for a turn stopped while extracting document text", () =>
874 Effect.gen(function* () {
875 const resolving = yield* Deferred.make<void>();
876 const release = yield* Deferred.make<void>();
877 const prompts: Array<unknown> = [];
878 const { runtime, thread } = yield* resumed(
879 [
880 out("session.instructions.entry.put", {
881 sessionID: SESSION,
882 key: "t3-code",
883 value: "<any>",
884 }),
885 reply("session.instructions.entry.put", null),
886 out("session.interrupt", { sessionID: SESSION }),
887 reply("session.interrupt", { interrupted: false }),
888 ],
889 {
890 attachmentsDir: "/attachments",
891 onPrompt: (input) => prompts.push(input),
892 resolveExtractedTextPath: () =>
893 Effect.gen(function* () {
894 yield* Deferred.succeed(resolving, undefined);
895 yield* Deferred.await(release);
896 return undefined;
897 }),
898 },
899 );
900 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
901 const started = yield* runtime
902 .startTurn({
903 ...turnInput(thread),
904 message: {
905 ...turnInput(thread).message,
906 attachments: [
907 ChatFileAttachment.make({
908 type: "file",
909 id: ChatAttachmentId.make(
910 "thread-opencode2-adapter-12345678-1234-1234-1234-123456789abc",
911 ),
912 name: "report.rtf",
913 mimeType: "application/rtf",
914 sizeBytes: 4,
915 }),
916 ],
917 },
918 })
919 .pipe(Effect.forkScoped);
920 yield* Deferred.await(resolving);
921 yield* runtime.interruptTurn({
922 providerThread: thread,
923 providerTurnId: yield* providerTurnId,
924 });
925 yield* Deferred.succeed(release, undefined);
926 yield* Fiber.join(started);
927 assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
928 assert.lengthOf(prompts, 0);
929 }),
930 );
931
932 const childCreated = (child: string) => ({
933 sessionID: child,
934 slug: "proud-canyon",
935 version: "2.0.18",
936 projectID: "global",
937 parentID: SESSION,
938 location: { directory: WORK },
939 subpath: "",
940 title: "Sleep",
941 agent: "general",
942 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
943 });
944 const backgroundLaunch = (child: string): ReadonlyArray<ProviderReplayEntry> => {
945 const call = "call-background";
946 const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: call };
947 return [
948 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
949 promptAccepted,
950 event("session.execution.started", { sessionID: SESSION }),
951 event("session.tool.input.started", { ...tool, name: "subagent" }),
952 event("session.tool.called", {
953 ...tool,
954 name: "subagent",
955 input: { description: "Sleep", prompt: "sleep", background: true },
956 executed: false,
957 }),
958 event("session.created", childCreated(child)),
959 event("session.tool.progress", {
960 ...tool,
961 metadata: { sessionID: child, status: "running" },
962 }),
963 ];
964 };
965 const withLineage = (thread: OrchestrationV2ProviderThread) => ({
966 ...turnInput(thread),
967 appThread: {
968 id: threadId,
969 title: TITLE,
970 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
971 } as OrchestrationV2AppThread,
972 });
973 const continuationTurn = (
974 thread: OrchestrationV2ProviderThread,
975 offer: ProviderContinuationRequests.ProviderContinuationRequest,
976 suffix = "wake",
977 ) => ({
978 ...withLineage(thread),
979 runId: RunId.make(`run:opencode2-adapter:${suffix}`),
980 runOrdinal: 2,
981 providerTurnOrdinal: 2,
982 attemptId: RunAttemptId.make(`attempt:opencode2-adapter:${suffix}`),
983 message: {
984 ...turnInput(thread).message,
985 messageId: offer.messageId!,
986 text: offer.detail ?? "",
987 createdBy: "agent" as const,
988 creationSource: "provider" as const,
989 },
990 });
991 const CHILD = "ses_f1485c529ffea4URrYruwEg0Ja";
992 const watchBackgroundTurn = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime) =>
993 Effect.gen(function* () {
994 const attached = yield* Deferred.make<void>();
995 const terminal = yield* runtime.events.pipe(
996 Stream.tap((event) =>
997 event.type === "subagent.updated" && event.subagent.childThreadId !== null
998 ? Deferred.succeed(attached, undefined)
999 : Effect.void,
1000 ),
1001 Stream.filter(
1002 (
1003 event,
1004 ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
1005 event.type === "turn.terminal",
1006 ),
1007 Stream.runHead,
1008 Effect.map(Option.getOrUndefined),
1009 Effect.forkScoped,
1010 );
1011 return { attached: Deferred.await(attached), terminal: Fiber.join(terminal) };
1012 });
1013 it.effect.each([false, true, "thread", "failed", "burst", "poll"] as const)(
1014 "tracks native background shells through launch, retained output, stop=%s",
1015 (stop) =>
1016 Effect.gen(function* () {
1017 const stopped = stop === true || stop === "thread" || stop === "poll";
1018 const exitCode = stop === "failed" ? 7 : 0;
1019 const shellID = "sh_background";
1020 const tool = {
1021 sessionID: SESSION,
1022 assistantMessageID: "msg_assistant",
1023 id: "call-shell",
1024 };
1025 const gate = makeProviderReplayGate(["shell-exit"]);
1026 const { runtime, thread } = yield* resumed(
1027 [
1028 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1029 promptAccepted,
1030 event("session.execution.started", { sessionID: SESSION }),
1031 event("session.tool.input.started", { ...tool, name: "shell" }),
1032 event("session.tool.called", {
1033 ...tool,
1034 name: "shell",
1035 input: { command: "echo retained", background: true },
1036 executed: false,
1037 }),
1038 event(
1039 "session.tool.success",
1040 {
1041 ...tool,
1042 content: [{ type: "text", text: "Launched" }],
1043 metadata: { shellID },
1044 executed: false,
1045 },
1046 undefined,
1047 2,
1048 ),
1049 out("shell.output", "<any>"),
1050 reply("shell.output", {
1051 location: { directory: WORK },
1052 data: { output: "retained\n", cursor: 9, size: 9, truncated: false },
1053 }),
1054 ...(stop === "poll"
1055 ? [out("shell.output", "<any>"), reply("shell.output", "<hang>")]
1056 : []),
1057 event("session.execution.succeeded", { sessionID: SESSION }),
1058 ...(stopped
1059 ? []
1060 : [
1061 event(
1062 "shell.exited",
1063 { id: shellID, exit: exitCode, status: "exited" },
1064 "shell-exit",
1065 ),
1066 ]),
1067 ...(stop === "burst"
1068 ? Array.from({ length: 5 }, (_, page) => [
1069 out("shell.output", { cursor: String(9 + page * 65536) }),
1070 reply("shell.output", {
1071 location: { directory: WORK },
1072 data: {
1073 output:
1074 page === 4 ? "x".repeat(65519) + "FINAL DIAGNOSTIC\n" : "x".repeat(65536),
1075 cursor: 9 + (page + 1) * 65536,
1076 size: 9 + 5 * 65536,
1077 truncated: false,
1078 },
1079 }),
1080 ]).flat()
1081 : [
1082 out("shell.output", "<any>"),
1083 reply("shell.output", {
1084 location: { directory: WORK },
1085 data: { output: "", cursor: 9, size: 9, truncated: false },
1086 }),
1087 ]),
1088 ...(stopped
1089 ? [
1090 out("shell.remove", { id: shellID, "location[directory]": WORK }),
1091 event("shell.exited", { id: shellID, exit: 143, status: "exited" }),
1092 reply("shell.remove", null),
1093 ]
1094 : []),
1095 ],
1096 { replayGate: gate },
1097 );
1098 const items: Array<import("@t3tools/contracts").OrchestrationV2TurnItem> = [];
1099 const shellStarted = yield* Deferred.make<void>();
1100 const terminal = yield* runtime.events.pipe(
1101 Stream.tap((e) =>
1102 Effect.gen(function* () {
1103 if (e.type === "provider_thread.updated") {
1104 for (const task of e.providerThread.pendingBackgroundTasks ?? [])
1105 assert.isUndefined(task.awaited);
1106 }
1107 if (e.type !== "turn_item.updated") return;
1108 items.push(e.turnItem);
1109 if (e.turnItem.type === "command_execution" && e.turnItem.output === "retained\n")
1110 yield* Deferred.succeed(shellStarted, undefined);
1111 }),
1112 ),
1113 Stream.filter((e) => e.type === "turn.terminal"),
1114 Stream.runHead,
1115 Effect.forkScoped,
1116 );
1117 yield* runtime.startTurn(withLineage(thread));
1118 if (stop === "poll") {
1119 yield* Deferred.await(shellStarted);
1120 yield* TestClock.adjust("2 seconds");
1121 }
1122 yield* Fiber.join(terminal);
1123 assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1124 for (const awaited of [true, false, true]) {
1125 const roster = yield* runtime.events.pipe(
1126 Stream.filter(
1127 (e) =>
1128 e.type === "provider_thread.updated" &&
1129 e.providerThread.pendingBackgroundTasks?.some(
1130 (task) => task.taskId === shellID && (task.awaited === true) === awaited,
1131 ) === true,
1132 ),
1133 Stream.runHead,
1134 Effect.forkScoped,
1135 );
1136 assert.deepEqual(
1137 yield* runtime.awaitBackgroundTasks!({
1138 providerThread: thread,
1139 taskIds: [shellID, shellID, "sh_unknown"],
1140 awaited,
1141 }),
1142 { matched: [shellID] },
1143 );
1144 yield* Fiber.join(roster);
1145 }
1146 assert.deepEqual(
1147 yield* runtime.awaitBackgroundTasks!({
1148 providerThread: {
1149 ...thread,
1150 nativeThreadRef: {
1151 driver: OPENCODE_PROVIDER,
1152 nativeId: "ses_foreign",
1153 strength: "strong",
1154 },
1155 },
1156 taskIds: [shellID],
1157 awaited: false,
1158 }),
1159 { matched: [] },
1160 );
1161 const settled = yield* runtime.events.pipe(
1162 Stream.tap((e) =>
1163 Effect.sync(() => {
1164 if (e.type === "turn_item.updated") items.push(e.turnItem);
1165 }),
1166 ),
1167 Stream.filter(
1168 (e) =>
1169 e.type === "provider_thread.updated" &&
1170 e.providerThread.pendingBackgroundTasks?.length === 0,
1171 ),
1172 Stream.runHead,
1173 Effect.forkScoped,
1174 );
1175 if (stop === "thread")
1176 yield* runtime.interruptTurn({
1177 providerThread: thread,
1178 providerTurnId: yield* providerTurnId,
1179 requestRuntimeRestart: true,
1180 });
1181 else if (stopped) yield* runtime.stopTask!({ providerThread: thread, taskId: shellID });
1182 else gate.release("shell-exit");
1183 yield* Fiber.join(settled);
1184 assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1185 assert.deepEqual(
1186 yield* runtime.awaitBackgroundTasks!({
1187 providerThread: thread,
1188 taskIds: [shellID],
1189 awaited: true,
1190 }),
1191 { matched: [] },
1192 );
1193 assert.deepInclude(items.filter((i) => i.type === "command_execution").at(-1), {
1194 type: "command_execution",
1195 status: stopped ? "interrupted" : stop === "failed" ? "failed" : "completed",
1196 ...(stop === "failed" ? { exitCode: 7 } : {}),
1197 output: stop === "burst" ? "x".repeat(262127) + "FINAL DIAGNOSTIC\n" : "retained\n",
1198 });
1199 assert.isFalse(items.some((i) => i.type === "subagent"));
1200 }),
1201 );
1202
1203 it.effect.each([
1204 "shell",
1205 "job",
1206 "fallback",
1207 "descendant",
1208 "settled",
1209 "exited",
1210 "anchored",
1211 "awaited",
1212 ] as const)("recovers only owned native shells using %s inventory", (discovery) =>
1213 Effect.gen(function* () {
1214 const awaited = discovery === "awaited";
1215 const idAllocator = yield* IdAllocator.IdAllocatorV2.pipe(Effect.provide(IdAllocator.layer));
1216 const id = "sh_recovered";
1217 const info = {
1218 id,
1219 command: "sleep 600",
1220 status: discovery === "settled" ? "exited" : "running",
1221 ...(discovery === "settled" ? { exit: 0 } : {}),
1222 cwd: WORK,
1223 shell: "/bin/sh",
1224 file: "/remote/output",
1225 metadata: { sessionID: SESSION },
1226 time: { started: 1 },
1227 };
1228 const response = (data: unknown) => ({ location: { directory: WORK }, data });
1229 const inventory: Array<ProviderReplayEntry> =
1230 discovery === "shell"
1231 ? []
1232 : [
1233 out("job.list", { sessionID: SESSION, kind: "shell", descendants: "true" }),
1234 reply(
1235 "job.list",
1236 discovery === "fallback"
1237 ? { status: 404, body: {} }
1238 : {
1239 data: [
1240 {
1241 kind: "shell",
1242 shellID: id,
1243 sessionID: discovery === "descendant" ? "ses_descendant" : SESSION,
1244 command: info.command,
1245 status: discovery === "settled" ? "completed" : "running",
1246 },
1247 ],
1248 },
1249 ),
1250 ];
1251 if (discovery === "shell" || discovery === "fallback")
1252 inventory.push(
1253 out("shell.list", "<any>"),
1254 reply(
1255 "shell.list",
1256 response([info, { ...info, id: "sh_other", metadata: { sessionID: "ses_other" } }]),
1257 ),
1258 );
1259 inventory.push(
1260 out("shell.get", { id }),
1261 reply("shell.get", response(info)),
1262 out("shell.output", { id, cursor: "0" }),
1263 reply(
1264 "shell.output",
1265 response({ output: "retained", cursor: 8, size: 8, truncated: false }),
1266 ),
1267 );
1268 const gate = makeProviderReplayGate(["recovered-exit"]);
1269 const { runtime, thread } = yield* resumed(
1270 discovery === "settled"
1271 ? []
1272 : [
1273 ...(discovery === "exited"
1274 ? [event("shell.exited", { id, exit: 0, status: "exited" }, "recovered-exit")]
1275 : []),
1276 out("shell.output", { id, cursor: "8" }),
1277 reply(
1278 "shell.output",
1279 response({
1280 output: discovery === "exited" ? " finished" : "",
1281 cursor: discovery === "exited" ? 17 : 8,
1282 size: discovery === "exited" ? 17 : 8,
1283 truncated: false,
1284 }),
1285 ),
1286 ...(discovery === "exited"
1287 ? []
1288 : [out("shell.remove", { id }), reply("shell.remove", null)]),
1289 ],
1290 {
1291 version: discovery === "shell" ? "2.2.1" : "2.2.6",
1292 shellRecovery: inventory,
1293 external: true,
1294 ...(discovery === "anchored" ? { lastRunOrdinal: 7 } : {}),
1295 ...(awaited
1296 ? {
1297 pendingBackgroundTasks: [
1298 {
1299 taskId: id,
1300 kind: "command" as const,
1301 description: info.command,
1302 awaited: true,
1303 },
1304 ],
1305 }
1306 : {}),
1307 replayGate: gate,
1308 },
1309 );
1310 const items: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
1311 const shellEnded = yield* Deferred.make<void>();
1312 const rosterEnded = yield* Deferred.make<void>();
1313 yield* runtime.events.pipe(
1314 Stream.runForEach((event) =>
1315 Effect.gen(function* () {
1316 if (
1317 event.type === "provider_thread.updated" &&
1318 event.sessionScoped === true &&
1319 event.providerThread.pendingBackgroundTasks?.length === 0
1320 )
1321 yield* Deferred.succeed(rosterEnded, undefined);
1322 if (event.type !== "turn_item.updated" || event.turnItem.type !== "command_execution")
1323 return;
1324 items.push(event);
1325 if (event.turnItem.status !== "running") yield* Deferred.succeed(shellEnded, undefined);
1326 }),
1327 ),
1328 Effect.forkScoped,
1329 );
1330 assert.deepEqual(
1331 thread.pendingBackgroundTasks ?? [],
1332 discovery === "settled"
1333 ? []
1334 : [
1335 {
1336 taskId: id,
1337 kind: "command",
1338 description: info.command,
1339 ...(awaited ? { awaited: true } : {}),
1340 },
1341 ],
1342 );
1343 assert.equal(
1344 yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1345 discovery !== "settled",
1346 );
1347 yield* runtime.stopTask!({ providerThread: thread, taskId: "sh_other" });
1348 assert.deepEqual(
1349 yield* runtime.awaitBackgroundTasks!({
1350 providerThread: thread,
1351 taskIds: [id, "sh_other"],
1352 awaited: true,
1353 }),
1354 { matched: discovery === "settled" ? [] : [id] },
1355 );
1356 assert.equal(
1357 yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1358 discovery !== "settled",
1359 );
1360 if (discovery === "exited") gate.release("recovered-exit");
1361 else yield* runtime.stopTask!({ providerThread: thread, taskId: id });
1362 yield* Deferred.await(shellEnded);
1363 yield* Deferred.await(rosterEnded);
1364 assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1365 const item = items;
1366 const projected = item.at(0);
1367 const stopped = item.at(-1);
1368 if (stopped?.type === "turn_item.updated" && stopped.turnItem.type === "command_execution") {
1369 assert.equal(
1370 stopped.turnItem.status,
1371 discovery === "settled" || discovery === "exited" ? "completed" : "interrupted",
1372 );
1373 assert.equal(
1374 stopped.turnItem.output,
1375 discovery === "exited" ? "retained finished" : "retained",
1376 );
1377 assert.equal(
1378 stopped.turnItem.id,
1379 projected?.type === "turn_item.updated" ? projected.turnItem.id : undefined,
1380 );
1381 }
1382 assert.equal(projected?.type, "turn_item.updated");
1383 if (projected?.type === "turn_item.updated") {
1384 assert.isTrue(
1385 item.every(
1386 (event) =>
1387 event.type === "turn_item.updated" &&
1388 event.turnItem.runId ===
1389 (discovery === "anchored"
1390 ? idAllocator.derive.run({ threadId, ordinal: 7 })
1391 : null),
1392 ),
1393 );
1394 assert.deepInclude(projected.turnItem, {
1395 type: "command_execution",
1396 input: info.command,
1397 output: "retained",
1398 });
1399 }
1400 }),
1401 );
1402
1403 it.effect.each(["remove", "lookup", "output", "timeout"] as const)(
1404 "continues recovering and stopping native work when shell %s fails",
1405 (failure) =>
1406 Effect.gen(function* () {
1407 const ids = ["sh_unreachable", "sh_stoppable"];
1408 const info = (id: string) => ({
1409 id,
1410 command: "sleep 600",
1411 status: "running",
1412 cwd: WORK,
1413 shell: "/bin/sh",
1414 file: "/remote/output",
1415 metadata: { sessionID: SESSION },
1416 time: { started: 1 },
1417 });
1418 const response = (data: unknown) => ({ location: { directory: WORK }, data });
1419 const output = (id: string) => [
1420 out("shell.output", { id }),
1421 reply("shell.output", response({ output: "", cursor: 0, size: 0, truncated: false })),
1422 ];
1423 const gate = makeProviderReplayGate(["recovery-pending", "polled"]);
1424 const recovery = yield* resumed(
1425 [
1426 ...backgroundLaunch(CHILD),
1427 ...output(ids[0]!),
1428 out("shell.remove", { id: ids[0] }),
1429 reply("shell.remove", failure === "remove" ? { status: 500, body: {} } : null),
1430 ...output(ids[1]!),
1431 out("shell.remove", { id: ids[1] }),
1432 reply("shell.remove", null),
1433 out("session.interrupt", { sessionID: CHILD }),
1434 reply("session.interrupt", { interrupted: true }),
1435 out("session.interrupt", { sessionID: SESSION }),
1436 reply("session.interrupt", { interrupted: true }),
1437 event("session.execution.interrupted", { sessionID: SESSION }),
1438 ...(failure === "remove"
1439 ? [
1440 ...output(ids[0]!),
1441 out("shell.remove", { id: ids[0] }),
1442 reply("shell.remove", null),
1443 ]
1444 : []),
1445 ],
1446 {
1447 version: "2.2.1",
1448 replayGate: gate,
1449 shellRecovery: [
1450 out("shell.list", "<any>"),
1451 reply("shell.list", response(ids.map(info))),
1452 ...(failure === "timeout"
1453 ? [
1454 out("shell.get", { id: ids[0] }),
1455 reply("shell.get", "<hang>"),
1456 event(
1457 "session.execution.succeeded",
1458 { sessionID: "ses_unrelated" },
1459 "recovery-pending",
1460 ),
1461 ...ids.map((id) => out("shell.output", { id })),
1462 ...ids.map(() =>
1463 reply(
1464 "shell.output",
1465 response({ output: "", cursor: 0, size: 0, truncated: false }),
1466 ),
1467 ),
1468 event("session.execution.succeeded", { sessionID: "ses_unrelated" }, "polled"),
1469 ]
1470 : ids.flatMap((id) => [
1471 out("shell.get", { id }),
1472 reply(
1473 "shell.get",
1474 id === ids[0] && failure === "lookup"
1475 ? { status: 500, body: {} }
1476 : response(info(id)),
1477 ),
1478 ...(id === ids[0] && failure === "lookup"
1479 ? []
1480 : id === ids[0] && failure === "output"
1481 ? [
1482 out("shell.output", { id }),
1483 reply("shell.output", { status: 500, body: {} }),
1484 ]
1485 : output(id)),
1486 ])),
1487 ],
1488 },
1489 ).pipe(Effect.forkScoped);
1490 if (failure === "timeout") {
1491 yield* Effect.promise(() => gate.waitForReached("recovery-pending"));
1492 yield* TestClock.adjust("5 seconds");
1493 }
1494 const { runtime, thread } = yield* Fiber.join(recovery);
1495 const recovered = yield* runtime.events.pipe(
1496 Stream.takeUntil(
1497 (event) =>
1498 event.type === "provider_thread.updated" &&
1499 event.providerThread.pendingBackgroundTasks?.length === 2,
1500 ),
1501 Stream.runCollect,
1502 );
1503 assert.sameMembers(
1504 recovered.flatMap((event) =>
1505 event.type === "turn_item.updated" && event.turnItem.type === "command_execution"
1506 ? [event.turnItem.nativeItemRef?.nativeId]
1507 : [],
1508 ),
1509 ids,
1510 );
1511 if (failure === "timeout") {
1512 gate.release("recovery-pending");
1513 yield* Effect.promise(() => gate.waitForReached("polled"));
1514 gate.release("polled");
1515 }
1516 const watch = yield* watchBackgroundTurn(runtime);
1517 yield* runtime.startTurn(withLineage(thread));
1518 yield* watch.attached;
1519 yield* runtime.interruptTurn({
1520 providerThread: thread,
1521 providerTurnId: yield* providerTurnId,
1522 requestRuntimeRestart: true,
1523 });
1524 assert.equal((yield* watch.terminal)?.status, "interrupted");
1525 assert.equal(
1526 yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1527 failure === "remove",
1528 );
1529 if (failure === "remove")
1530 yield* runtime.stopTask!({ providerThread: thread, taskId: ids[0]! });
1531 assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1532 }),
1533 );
1534
1535 it.effect("keeps background subagents running when a turn is interrupted to restart it", () =>
1536 Effect.gen(function* () {
1537 const { runtime, thread } = yield* resumed([
1538 ...backgroundLaunch(CHILD),
1539 out("session.interrupt", { sessionID: SESSION }),
1540 reply("session.interrupt", { interrupted: true }),
1541 event("session.execution.interrupted", { sessionID: SESSION }),
1542 ]);
1543 const watch = yield* watchBackgroundTurn(runtime);
1544 yield* runtime.startTurn(withLineage(thread));
1545 yield* watch.attached;
1546 yield* runtime.interruptTurn({
1547 providerThread: thread,
1548 providerTurnId: yield* providerTurnId,
1549 });
1550 assert.equal((yield* watch.terminal)?.status, "interrupted");
1551 assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
1552 }),
1553 );
1554
1555 it.effect("stops background subagents on a user Stop", () =>
1556 Effect.gen(function* () {
1557 const { runtime, thread } = yield* resumed([
1558 ...backgroundLaunch(CHILD),
1559 out("session.interrupt", { sessionID: CHILD }),
1560 reply("session.interrupt", { interrupted: true }),
1561 out("session.interrupt", { sessionID: SESSION }),
1562 reply("session.interrupt", { interrupted: true }),
1563 event("session.execution.interrupted", { sessionID: SESSION }),
1564 ]);
1565 const watch = yield* watchBackgroundTurn(runtime);
1566 yield* runtime.startTurn(withLineage(thread));
1567 yield* watch.attached;
1568 yield* runtime.interruptTurn({
1569 providerThread: thread,
1570 providerTurnId: yield* providerTurnId,
1571 requestRuntimeRestart: true,
1572 });
1573 assert.equal((yield* watch.terminal)?.status, "interrupted");
1574 assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1575 }),
1576 );
1577
1578 it.effect("gives a background subagent the rules of a mode changed while it runs", () =>
1579 Effect.gen(function* () {
1580 const { runtime, thread } = yield* resumed([
1581 ...backgroundLaunch(CHILD),
1582 event("session.execution.succeeded", { sessionID: SESSION }),
1583 out("agent.list", "<any>"),
1584 reply("agent.list", agentList),
1585 out("session.update", { sessionID: SESSION, permissions: supervisedRules }),
1586 reply("session.update", null),
1587 out("session.update", {
1588 sessionID: CHILD,
1589 permissions: [...supervisedRules.slice(0, 3), ...mcpRules],
1590 }),
1591 reply("session.update", null),
1592 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1593 promptAccepted,
1594 event("session.execution.succeeded", { sessionID: SESSION }),
1595 ]);
1596 const firstEnded = yield* Deferred.make<void>();
1597 const ended = yield* runtime.events.pipe(
1598 Stream.filter(
1599 (
1600 event,
1601 ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
1602 event.type === "turn.terminal",
1603 ),
1604 Stream.tap(() => Deferred.succeed(firstEnded, undefined)),
1605 Stream.take(2),
1606 Stream.runCollect,
1607 Effect.forkScoped,
1608 );
1609 yield* runtime.startTurn(withLineage(thread));
1610 yield* Deferred.await(firstEnded);
1611 yield* runtime.startTurn({
1612 ...withLineage(thread),
1613 runId: RunId.make("run:opencode2-adapter:2"),
1614 runOrdinal: 2,
1615 providerTurnOrdinal: 2,
1616 attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"),
1617 runtimePolicy: policy("approval-required"),
1618 });
1619 assert.deepEqual(
1620 [...(yield* Fiber.join(ended))].map((terminal) => terminal.status),
1621 ["completed", "completed"],
1622 );
1623 }),
1624 );
1625
1626 it.effect(
1627 "keeps a finished background subagent's queued report pending until its native continuation ends",
1628 () =>
1629 Effect.gen(function* () {
1630 const gate = makeProviderReplayGate(["continue"]);
1631 const { runtime, thread } = yield* resumed(
1632 [
1633 ...nestedLaunch,
1634 event("session.execution.succeeded", { sessionID: DEEP }),
1635 deepReport("completed"),
1636 event("session.model.selected", {
1637 sessionID: SESSION,
1638 model: { providerID: "opencode", id: "big-pickle", variant: "thinking" },
1639 }),
1640 event("session.execution.started", { sessionID: MIDDLE }, "continue"),
1641 event("session.inbox.delivered", { sessionID: MIDDLE, inboxID: "msg_deep_report" }),
1642 event("session.text.ended", {
1643 sessionID: MIDDLE,
1644 assistantMessageID: "msg_native_continuation",
1645 ordinal: 0,
1646 text: "GRANDCHILD_OK",
1647 }),
1648 event("session.execution.succeeded", { sessionID: MIDDLE }),
1649 event("session.model.selected", {
1650 sessionID: SESSION,
1651 model: { providerID: "opencode", id: "big-pickle", variant: "none" },
1652 }),
1653 ],
1654 { replayGate: gate },
1655 );
1656 const queued = yield* Deferred.make<void>();
1657 const drained = yield* Deferred.make<void>();
1658 const timeline: Array<boolean | string> = [];
1659 yield* runtime.events.pipe(
1660 Stream.runForEach((event) =>
1661 Effect.gen(function* () {
1662 if (event.type === "provider_thread.updated") {
1663 if (
1664 event.providerThread.nativeThreadRef?.nativeId === MIDDLE &&
1665 event.pendingBackgroundWork !== undefined
1666 ) {
1667 timeline.push(event.pendingBackgroundWork);
1668 }
1669 if (event.providerThread.id === thread.id) {
1670 const variant =
1671 event.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value;
1672 if (variant === "thinking") yield* Deferred.succeed(queued, undefined);
1673 if (variant === "none") yield* Deferred.succeed(drained, undefined);
1674 }
1675 }
1676 if (
1677 event.type === "provider_turn.updated" &&
1678 event.providerTurn.nativeTurnRef?.nativeId === `${MIDDLE}:turn:2`
1679 ) {
1680 timeline.push(event.providerTurn.status);
1681 }
1682 if (event.type === "message.updated" && event.message.text === "GRANDCHILD_OK") {
1683 timeline.push(event.message.text);
1684 }
1685 }),
1686 ),
1687 Effect.forkScoped,
1688 );
1689 yield* runtime.startTurn(withLineage(thread));
1690 yield* Deferred.await(queued);
1691 assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
1692 assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1693 assert.strictEqual(timeline.at(-1), true);
1694 timeline.length = 0;
1695 gate.release("continue");
1696 yield* Deferred.await(drained);
1697 assert.deepEqual(
1698 timeline.filter((entry) => typeof entry === "string"),
1699 ["running", "GRANDCHILD_OK", "completed"],
1700 );
1701 assert.isAbove(timeline.indexOf(false), timeline.indexOf("completed"));
1702 assert.strictEqual(timeline.at(-1), false);
1703 assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1704 }),
1705 );
1706
1707 const returnedRunning = (id: string): ProviderReplayEntry => ({
1708 type: "emit_inbound",
1709 frame: {
1710 type: "sdk.event",
1711 event: {
1712 id: `evt_toolsuccess_${id}`,
1713 created: 1,
1714 type: "session.tool.success",
1715 data: {
1716 sessionID: SESSION,
1717 assistantMessageID: "msg_assistant",
1718 id,
1719 content: [{ type: "text", text: "The subagent is working in the background." }],
1720 metadata: { sessionID: CHILD, status: "running" },
1721 executed: true,
1722 },
1723 durable: { aggregateID: SESSION, seq: 1, version: 2 },
1724 },
1725 },
1726 });
1727 const callAgain = (
1728 input: Record<string, unknown>,
1729 { id = "call-again", writesRules = true } = {},
1730 ): ReadonlyArray<ProviderReplayEntry> => {
1731 const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id };
1732 return [
1733 event("session.tool.input.started", { ...tool, name: "subagent" }),
1734 event("session.tool.called", {
1735 ...tool,
1736 name: "subagent",
1737 input: { description: "Again", prompt: "also this", sessionID: CHILD, ...input },
1738 executed: false,
1739 }),
1740 event("session.tool.progress", {
1741 ...tool,
1742 metadata: { sessionID: CHILD, status: "running" },
1743 }),
1744 // The adapter writes a child's rules only when they changed.
1745 ...(writesRules
1746 ? [
1747 out("session.update", { sessionID: CHILD, permissions: "<any>" }),
1748 reply("session.update", null),
1749 ]
1750 : []),
1751 returnedRunning(tool.id),
1752 ];
1753 };
1754 const childReport = (inboxID: string, text: string, description = "Sleep") =>
1755 event("session.inbox.enqueued", {
1756 inboxID,
1757 sessionID: SESSION,
1758 item: {
1759 type: "synthetic",
1760 payload: {
1761 text: `<subagent sessionID="${CHILD}" state="completed" description="${description}">\n${text}\n</subagent>`,
1762 description,
1763 metadata: { source: "subagent", childID: CHILD, agent: "General", state: "completed" },
1764 },
1765 delivery: "steer",
1766 },
1767 });
1768 const watchCalls = (
1769 runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime,
1770 thread: OrchestrationV2ProviderThread,
1771 ) =>
1772 Effect.gen(function* () {
1773 const calls = new Map<string, { status: string; result: string | null }>();
1774 const callsById = new Map<string, { status: string; result: string | null }>();
1775 const childTurns = new Map<string, string>();
1776 const callsAtChildTurnStart = new Map<
1777 string,
1778 Record<string, { status: string; result: string | null }>
1779 >();
1780 const state: { roster: ReadonlyArray<unknown> | undefined } = { roster: undefined };
1781 let wake = yield* Deferred.make<void>();
1782 yield* runtime.events.pipe(
1783 Stream.tap((event) =>
1784 Effect.gen(function* () {
1785 if (event.type === "subagent.updated") {
1786 callsById.set(event.subagent.nativeTaskRef?.nativeId ?? "", {
1787 status: event.subagent.status,
1788 result: event.subagent.result,
1789 });
1790 }
1791 if (event.type === "subagent.updated" && event.subagent.title !== null) {
1792 calls.set(event.subagent.title, {
1793 status: event.subagent.status,
1794 result: event.subagent.result,
1795 });
1796 }
1797 if (event.type === "provider_thread.updated" && event.providerThread.id === thread.id) {
1798 state.roster = event.providerThread.pendingBackgroundTasks;
1799 }
1800 const id =
1801 event.type === "provider_turn.updated"
1802 ? event.providerTurn.nativeTurnRef?.nativeId
1803 : undefined;
1804 if (
1805 event.type === "provider_turn.updated" &&
1806 id?.startsWith(`${CHILD}:turn:`) === true
1807 ) {
1808 if (!childTurns.has(id)) {
1809 callsAtChildTurnStart.set(id, Object.fromEntries(calls));
1810 }
1811 childTurns.set(id, event.providerTurn.status);
1812 }
1813 yield* Deferred.succeed(wake, undefined);
1814 }),
1815 ),
1816 Stream.runDrain,
1817 Effect.forkScoped,
1818 );
1819 const until = (check: () => boolean): Effect.Effect<void> =>
1820 Effect.suspend(() => {
1821 if (check()) return Effect.void;
1822 return Effect.gen(function* () {
1823 wake = yield* Deferred.make<void>();
1824 if (check()) return;
1825 yield* Deferred.await(wake);
1826 yield* until(check);
1827 });
1828 });
1829 return { calls, callsById, callsAtChildTurnStart, childTurns, state, until };
1830 });
1831 const launchedAndRunning = [
1832 ...backgroundLaunch(CHILD),
1833 returnedRunning("call-background"),
1834 event("session.execution.started", { sessionID: CHILD }),
1835 ];
1836
1837 it.effect.each([false, true])(
1838 "settles a failed background subagent with recovered child=%s",
1839 (recoveredChild) =>
1840 Effect.gen(function* () {
1841 const ids = yield* IdAllocator.IdAllocatorV2.pipe(Effect.provide(IdAllocator.layer));
1842 const childThreadId = ids.derive.subagentThread({
1843 driver: OPENCODE_PROVIDER,
1844 nativeThreadId: CHILD,
1845 providerInstanceId: instanceId,
1846 });
1847 const childProviderThread = {
1848 ...providerThread(yield* DateTime.now),
1849 id: ids.derive.providerThread({
1850 driver: OPENCODE_PROVIDER,
1851 nativeThreadId: CHILD,
1852 providerInstanceId: instanceId,
1853 }),
1854 appThreadId: childThreadId,
1855 nativeThreadRef: {
1856 driver: OPENCODE_PROVIDER,
1857 nativeId: CHILD,
1858 strength: "strong" as const,
1859 },
1860 };
1861 const shell = {
1862 id: "sh_old_child",
1863 command: "echo done",
1864 status: "exited",
1865 exit: 0,
1866 cwd: WORK,
1867 shell: "/bin/sh",
1868 file: "/remote/output",
1869 metadata: { sessionID: CHILD },
1870 time: { started: 1, completed: 2 },
1871 };
1872 const response = (data: unknown) => ({ location: { directory: WORK }, data });
1873 const { runtime, thread } = yield* resumed(
1874 [
1875 ...(recoveredChild
1876 ? [
1877 out("session.get", { sessionID: CHILD }),
1878 replyData("session.get", sessionInfo({ id: CHILD })),
1879 out("permission.list", { sessionID: CHILD }),
1880 replyData("permission.list", []),
1881 out("session.form.list", { sessionID: CHILD }),
1882 replyData("session.form.list", []),
1883 out("shell.list", "<any>"),
1884 reply("shell.list", response([shell])),
1885 out("shell.get", { id: shell.id }),
1886 reply("shell.get", response(shell)),
1887 out("shell.output", { id: shell.id }),
1888 reply(
1889 "shell.output",
1890 response({ output: "done", cursor: 4, size: 4, truncated: false }),
1891 ),
1892 out("session.update", { sessionID: CHILD, permissions: "<any>" }),
1893 reply("session.update", null),
1894 ]
1895 : []),
1896 ...launchedAndRunning,
1897 // The parent turn ends, and the background child fails: it reports
1898 // nothing back, so its call has to end with the failure.
1899 event("session.execution.succeeded", { sessionID: SESSION }),
1900 event("session.execution.failed", {
1901 sessionID: CHILD,
1902 error: { type: "provider.quota", message: "Rate limit exceeded." },
1903 }),
1904 ],
1905 recoveredChild ? { version: "2.2.1" } : undefined,
1906 );
1907 if (recoveredChild)
1908 yield* runtime.resumeThread({
1909 providerThread: childProviderThread,
1910 threadId: childThreadId,
1911 modelSelection: bigPickle,
1912 runtimePolicy: policy(),
1913 });
1914 const childUpdates: Array<
1915 Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "provider_thread.updated" }>
1916 > = [];
1917 const watch = yield* watchCalls(
1918 {
1919 ...runtime,
1920 events: runtime.events.pipe(
1921 Stream.tap((event) =>
1922 Effect.sync(() => {
1923 if (
1924 event.type === "provider_thread.updated" &&
1925 event.providerThread.id === childProviderThread.id &&
1926 event.providerThread.ownerNodeId !== null
1927 )
1928 childUpdates.push(event);
1929 }),
1930 ),
1931 ),
1932 },
1933 thread,
1934 );
1935 yield* runtime.startTurn(withLineage(thread));
1936 yield* watch.until(
1937 () => watch.calls.get("Sleep")?.status === "failed" && watch.state.roster?.length === 0,
1938 );
1939 assert.includeMembers(
1940 childUpdates.map((event) => event.providerThread.status),
1941 ["active", "idle"],
1942 );
1943 assert.isFalse(
1944 childUpdates.some((event) => event.sessionScoped === true),
1945 "reattached child status must route through the parent run",
1946 );
1947 assert.deepEqual(watch.state.roster, []);
1948 assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1949 }),
1950 );
1951
1952 // regression: #21979 a failed background subagent pinned its thread as busy
1953 it.effect("settles the background call a foreground call joined to a failed child", () =>
1954 Effect.gen(function* () {
1955 const again = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-again" };
1956 const { runtime, thread } = yield* resumed([
1957 ...launchedAndRunning,
1958 // A foreground call joins the running background child. It is only
1959 // marked background once its own tool call returns, so the child can
1960 // fail while this call is still the foreground one.
1961 event("session.tool.input.started", { ...again, name: "subagent" }),
1962 event("session.tool.called", {
1963 ...again,
1964 name: "subagent",
1965 input: { description: "Again", prompt: "also this", sessionID: CHILD },
1966 executed: false,
1967 }),
1968 event("session.tool.progress", {
1969 ...again,
1970 metadata: { sessionID: CHILD, status: "running" },
1971 }),
1972 out("session.update", { sessionID: CHILD, permissions: "<any>" }),
1973 reply("session.update", null),
1974 // The child fails while the joined call is still the foreground one.
1975 event("session.execution.failed", {
1976 sessionID: CHILD,
1977 error: { type: "provider.quota", message: "Rate limit exceeded." },
1978 }),
1979 event("session.execution.succeeded", { sessionID: SESSION }),
1980 ]);
1981 const watch = yield* watchCalls(runtime, thread);
1982 yield* runtime.startTurn(withLineage(thread));
1983 yield* watch.until(
1984 () =>
1985 watch.calls.get("Sleep")?.status === "failed" &&
1986 watch.calls.get("Again")?.status === "failed" &&
1987 watch.state.roster?.length === 0,
1988 );
1989 assert.deepEqual(watch.state.roster, []);
1990 assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1991 }),
1992 );
1993
1994 it.effect("settles every call that joined a running subagent with its one report", () =>
1995 Effect.gen(function* () {
1996 const { runtime, thread } = yield* resumed([
1997 ...launchedAndRunning,
1998 ...callAgain({ background: true }),
1999 event("session.execution.succeeded", { sessionID: SESSION }),
2000 event("session.execution.succeeded", { sessionID: CHILD }),
2001 childReport("msg_report", "CHILD_OK"),
2002 ]);
2003 const watch = yield* watchCalls(runtime, thread);
2004 yield* runtime.startTurn(withLineage(thread));
2005 yield* watch.until(
2006 () =>
2007 watch.calls.get("Again")?.status === "completed" &&
2008 watch.calls.get("Sleep")?.status === "completed" &&
2009 watch.state.roster?.length === 0,
2010 );
2011 assert.deepEqual(Object.fromEntries(watch.calls), {
2012 Sleep: { status: "completed", result: "CHILD_OK" },
2013 Again: { status: "completed", result: "CHILD_OK" },
2014 });
2015 }),
2016 );
2017
2018 it.effect("keeps a call to a finished subagent for its own run's report", () =>
2019 Effect.gen(function* () {
2020 const { runtime, thread } = yield* resumed([
2021 ...launchedAndRunning,
2022 event("session.execution.succeeded", { sessionID: CHILD }),
2023 ...callAgain({ background: true }),
2024 childReport("msg_report_1", "FIRST_OK"),
2025 event("session.execution.started", { sessionID: CHILD }),
2026 event("session.execution.succeeded", { sessionID: CHILD }),
2027 event("session.execution.succeeded", { sessionID: SESSION }),
2028 childReport("msg_report_2", "SECOND_OK"),
2029 ]);
2030 const watch = yield* watchCalls(runtime, thread);
2031 yield* runtime.startTurn(withLineage(thread));
2032 yield* watch.until(() => watch.childTurns.has(`${CHILD}:turn:2`));
2033 assert.deepEqual(watch.callsAtChildTurnStart.get(`${CHILD}:turn:2`), {
2034 Sleep: { status: "completed", result: "FIRST_OK" },
2035 Again: { status: "running", result: null },
2036 });
2037 yield* watch.until(() => watch.calls.get("Again")?.status === "completed");
2038 assert.deepEqual(watch.calls.get("Again"), { status: "completed", result: "SECOND_OK" });
2039 }),
2040 );
2041
2042 const childSaid = (text: string, run = 1) =>
2043 event("session.text.ended", {
2044 sessionID: CHILD,
2045 assistantMessageID: `msg_child_${run}`,
2046 ordinal: 0,
2047 text,
2048 });
2049 it.effect.each([
2050 {
2051 // regression: #26319 the report settled the older run and left the resumed call running
2052 name: "an earlier run's report never arrived",
2053 replay: [
2054 ...launchedAndRunning,
2055 ...callAgain({ background: true }),
2056 childSaid("FIRST_OK"),
2057 event("session.execution.succeeded", { sessionID: CHILD }),
2058 ...callAgain({ background: true }, { id: "call-later", writesRules: false }),
2059 event("session.execution.started", { sessionID: CHILD }),
2060 childSaid("SECOND_OK", 2),
2061 event("session.execution.succeeded", { sessionID: CHILD }),
2062 event("session.execution.succeeded", { sessionID: SESSION }),
2063 childReport("msg_report_2", "SECOND_OK", "Again"),
2064 ],
2065 expected: {
2066 "call-background": { status: "completed", result: "FIRST_OK" },
2067 "call-again": { status: "completed", result: "FIRST_OK" },
2068 "call-later": { status: "completed", result: "SECOND_OK" },
2069 },
2070 },
2071 {
2072 name: "both runs' reports arrive after the runs ended",
2073 replay: [
2074 ...launchedAndRunning,
2075 event("session.execution.succeeded", { sessionID: CHILD }),
2076 ...callAgain({ background: true, description: "Sleep" }),
2077 event("session.execution.started", { sessionID: CHILD }),
2078 event("session.execution.succeeded", { sessionID: CHILD }),
2079 childReport("msg_report_1", "FIRST_OK"),
2080 childReport("msg_report_2", "SECOND_OK"),
2081 event("session.execution.succeeded", { sessionID: SESSION }),
2082 ],
2083 expected: {
2084 "call-background": { status: "completed", result: "FIRST_OK" },
2085 "call-again": { status: "completed", result: "SECOND_OK" },
2086 },
2087 },
2088 {
2089 name: "two runs with the same answer report late",
2090 replay: [
2091 ...launchedAndRunning,
2092 childSaid("DONE"),
2093 event("session.execution.succeeded", { sessionID: CHILD }),
2094 ...callAgain({ background: true }),
2095 event("session.execution.started", { sessionID: CHILD }),
2096 childSaid("DONE", 2),
2097 event("session.execution.succeeded", { sessionID: CHILD }),
2098 childReport("msg_report_1", "DONE"),
2099 ...callAgain({ background: true }, { id: "call-later", writesRules: false }),
2100 event("session.execution.started", { sessionID: CHILD }),
2101 childReport("msg_report_2", "DONE", "Again"),
2102 childSaid("THIRD_OK", 3),
2103 event("session.execution.succeeded", { sessionID: CHILD }),
2104 event("session.execution.succeeded", { sessionID: SESSION }),
2105 childReport("msg_report_3", "THIRD_OK", "Again"),
2106 ],
2107 expected: {
2108 "call-background": { status: "completed", result: "DONE" },
2109 "call-again": { status: "completed", result: "DONE" },
2110 "call-later": { status: "completed", result: "THIRD_OK" },
2111 },
2112 },
2113 {
2114 name: "the call it joined already returned",
2115 replay: [
2116 ...backgroundLaunch(CHILD),
2117 event("session.execution.started", { sessionID: CHILD }),
2118 ...callAgain({ background: true }),
2119 event("session.execution.succeeded", { sessionID: CHILD }),
2120 event(
2121 "session.tool.success",
2122 {
2123 sessionID: SESSION,
2124 assistantMessageID: "msg_assistant",
2125 id: "call-background",
2126 content: [{ type: "text", text: "FIRST_OK" }],
2127 metadata: { sessionID: CHILD, status: "completed" },
2128 executed: true,
2129 },
2130 undefined,
2131 2,
2132 ),
2133 event("session.execution.succeeded", { sessionID: SESSION }),
2134 childReport("msg_report", "CHILD_OK", "Again"),
2135 ],
2136 expected: {
2137 "call-background": { status: "completed", result: "FIRST_OK" },
2138 "call-again": { status: "completed", result: "CHILD_OK" },
2139 },
2140 },
2141 ])("settles a resumed subagent's calls when $name", ({ replay, expected }) =>
2142 Effect.gen(function* () {
2143 const { runtime, thread } = yield* resumed(replay);
2144 const watch = yield* watchCalls(runtime, thread);
2145 yield* runtime.startTurn(withLineage(thread));
2146 yield* watch.until(
2147 () =>
2148 watch.state.roster?.length === 0 &&
2149 Object.keys(expected).every((id) => watch.callsById.get(id)?.status === "completed"),
2150 );
2151 assert.deepEqual(Object.fromEntries(watch.callsById), expected);
2152 }),
2153 );
2154
2155 const MIDDLE = "ses_middle0000000000000000000";
2156 const DEEP = "ses_grandchild00000000000000";
2157 const toolOf = (session: string, id: string) => ({
2158 sessionID: session,
2159 assistantMessageID: `msg_assistant_${id}`,
2160 id,
2161 });
2162 const deepReport = (state: "completed" | "cancelled") =>
2163 event("session.inbox.enqueued", {
2164 inboxID: "msg_deep_report",
2165 sessionID: MIDDLE,
2166 item: {
2167 type: "synthetic",
2168 payload: {
2169 text: `<subagent sessionID="${DEEP}" state="${state}" description="Deep">\nDEEP_OK\n</subagent>`,
2170 description: "Deep",
2171 metadata: { source: "subagent", childID: DEEP, agent: "General", state },
2172 },
2173 delivery: "steer",
2174 },
2175 });
2176 const nestedLaunch: ReadonlyArray<ProviderReplayEntry> = [
2177 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2178 promptAccepted,
2179 event("session.execution.started", { sessionID: SESSION }),
2180 event("session.tool.input.started", { ...toolOf(SESSION, "call-middle"), name: "subagent" }),
2181 event("session.tool.called", {
2182 ...toolOf(SESSION, "call-middle"),
2183 name: "subagent",
2184 input: { description: "Middle", prompt: "delegate" },
2185 executed: false,
2186 }),
2187 event("session.created", { ...childCreated(MIDDLE), title: "Middle" }),
2188 event("session.tool.progress", {
2189 ...toolOf(SESSION, "call-middle"),
2190 metadata: { sessionID: MIDDLE, status: "running" },
2191 }),
2192 event("session.execution.started", { sessionID: MIDDLE }),
2193 event("session.tool.input.started", { ...toolOf(MIDDLE, "call-deep"), name: "subagent" }),
2194 event("session.tool.called", {
2195 ...toolOf(MIDDLE, "call-deep"),
2196 name: "subagent",
2197 input: { description: "Deep", prompt: "sleep", background: true },
2198 executed: false,
2199 }),
2200 event("session.created", { ...childCreated(DEEP), parentID: MIDDLE, title: "Deep" }),
2201 event("session.tool.progress", {
2202 ...toolOf(MIDDLE, "call-deep"),
2203 metadata: { sessionID: DEEP, status: "running" },
2204 }),
2205 event("session.tool.success", {
2206 ...toolOf(MIDDLE, "call-deep"),
2207 content: [{ type: "text", text: "The subagent is working in the background." }],
2208 metadata: { sessionID: DEEP, status: "running", truncated: false },
2209 executed: false,
2210 }),
2211 event("session.execution.started", { sessionID: DEEP }),
2212 event("session.execution.succeeded", { sessionID: MIDDLE }),
2213 event("session.tool.success", {
2214 ...toolOf(SESSION, "call-middle"),
2215 content: [{ type: "text", text: `<subagent sessionID="${MIDDLE}" state="completed">` }],
2216 metadata: { sessionID: MIDDLE, status: "completed", truncated: false },
2217 executed: false,
2218 }),
2219 event("session.execution.succeeded", { sessionID: SESSION }),
2220 ];
2221 const watchNested = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime) =>
2222 Effect.gen(function* () {
2223 const deep: Array<string> = [];
2224 const middleTurns = new Map<string, string>();
2225 const pendingSnapshots = new Map<string, boolean>();
2226 const variants = new Map<string, unknown>();
2227 let rootVariant: unknown;
2228 const terminals: Array<string> = [];
2229 const changed = yield* Deferred.make<void>();
2230 let wake = changed;
2231 yield* runtime.events.pipe(
2232 Stream.tap((event) =>
2233 Effect.gen(function* () {
2234 if (event.type === "turn.terminal") terminals.push(event.status);
2235 if (event.type === "provider_thread.updated") {
2236 const nativeId = event.providerThread.nativeThreadRef?.nativeId;
2237 if (nativeId != null && event.pendingBackgroundWork !== undefined) {
2238 pendingSnapshots.set(nativeId, event.pendingBackgroundWork);
2239 }
2240 const variant =
2241 event.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value;
2242 if (nativeId != null) variants.set(nativeId, variant);
2243 if (nativeId === SESSION) rootVariant = variant;
2244 }
2245 if (event.type === "subagent.updated" && event.subagent.title === "Deep") {
2246 deep.push(event.subagent.status);
2247 }
2248 const native = event.type === "provider_turn.updated" ? event.providerTurn : undefined;
2249 const id = native?.nativeTurnRef?.nativeId;
2250 if (native !== undefined && id?.startsWith(`${MIDDLE}:turn:`) === true) {
2251 middleTurns.set(id, native.status);
2252 }
2253 yield* Deferred.succeed(wake, undefined);
2254 }),
2255 ),
2256 Stream.runDrain,
2257 Effect.forkScoped,
2258 );
2259 const until = (check: () => boolean): Effect.Effect<void> =>
2260 Effect.suspend(() => {
2261 if (check()) return Effect.void;
2262 return Effect.gen(function* () {
2263 wake = yield* Deferred.make<void>();
2264 if (check()) return;
2265 yield* Deferred.await(wake);
2266 yield* until(check);
2267 });
2268 });
2269 return {
2270 deep,
2271 middleTurns,
2272 terminals,
2273 pendingSnapshots,
2274 variants,
2275 get rootVariant() {
2276 return rootVariant;
2277 },
2278 until,
2279 };
2280 });
2281
2282 it.effect("clears a nested report cancelled during a held wake", () =>
2283 Effect.gen(function* () {
2284 const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
2285 const gate = makeProviderReplayGate(["drained"]);
2286 const { runtime, thread } = yield* resumed(
2287 [
2288 ...backgroundLaunch(CHILD),
2289 event("session.execution.succeeded", { sessionID: SESSION }),
2290 event("session.execution.succeeded", { sessionID: CHILD }),
2291 childReport("msg_report", "CHILD_OK"),
2292 event("session.execution.started", { sessionID: SESSION }),
2293 ...nestedLaunch.slice(3, -2),
2294 event(
2295 "session.tool.success",
2296 {
2297 ...toolOf(SESSION, "call-middle"),
2298 content: [{ type: "text", text: "MIDDLE_OK" }],
2299 metadata: { sessionID: MIDDLE, status: "completed", truncated: false },
2300 executed: false,
2301 },
2302 undefined,
2303 2,
2304 ),
2305 event("session.execution.succeeded", { sessionID: DEEP }),
2306 deepReport("completed"),
2307 event("session.inbox.cancelled", { sessionID: MIDDLE, inboxID: "msg_deep_report" }),
2308 event("session.execution.succeeded", { sessionID: SESSION }),
2309 event("session.model.selected", {
2310 sessionID: SESSION,
2311 model: { providerID: "opencode", id: "big-pickle", variant: "thinking" },
2312 }),
2313 event(
2314 "session.model.selected",
2315 {
2316 sessionID: SESSION,
2317 model: { providerID: "opencode", id: "big-pickle", variant: "none" },
2318 },
2319 "drained",
2320 ),
2321 ],
2322 { replayGate: gate },
2323 ).pipe(
2324 Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
2325 offer: (request) =>
2326 Effect.sync(() => {
2327 offers.push(request);
2328 }),
2329 take: Effect.never,
2330 }),
2331 );
2332 const watch = yield* watchNested(runtime);
2333 yield* runtime.startTurn(withLineage(thread));
2334 assert.isTrue(yield* Effect.promise(() => gate.waitForReached("drained")));
2335 yield* watch.until(() => watch.rootVariant === "thinking");
2336 assert.lengthOf(offers, 1);
2337 yield* runtime.startTurn(continuationTurn(thread, offers[0]!));
2338 gate.release("drained");
2339 yield* watch.until(() => watch.rootVariant === "none");
2340 assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
2341 assert.strictEqual(watch.pendingSnapshots.get(MIDDLE), false);
2342 }),
2343 );
2344
2345 it.effect.each(["running", "exited", "timeout", "held", "sync"] as const)(
2346 "marks a shell OpenCode started on its own before T3 runs the wake, shell %s",
2347 (shell) =>
2348 Effect.gen(function* () {
2349 const shellID = "sh_wake";
2350 const tool = { sessionID: SESSION, assistantMessageID: "msg_wake", id: "call-wake-shell" };
2351 const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
2352 const shellReport = (state: string, extra: Record<string, unknown> = {}) =>
2353 event("session.inbox.enqueued", {
2354 inboxID: "msg_shell_report",
2355 sessionID: SESSION,
2356 item: {
2357 type: "synthetic",
2358 payload: {
2359 text: `<shell id="${shellID}" state="${state}">done</shell>`,
2360 description: "vp test",
2361 metadata: { source: "shell", shellID, state, ...extra },
2362 },
2363 delivery: "steer",
2364 },
2365 });
2366 const { runtime, thread } = yield* resumed([
2367 ...backgroundLaunch(CHILD),
2368 event("session.execution.succeeded", { sessionID: SESSION }),
2369 event("session.execution.succeeded", { sessionID: CHILD }),
2370 childReport("msg_report", "CHILD_OK"),
2371 event("session.execution.started", { sessionID: SESSION }),
2372 event("session.tool.input.started", { ...tool, name: "shell" }),
2373 event("session.tool.called", {
2374 ...tool,
2375 name: "shell",
2376 input: { command: "vp test", background: true },
2377 executed: false,
2378 }),
2379 event(
2380 "session.tool.success",
2381 {
2382 ...tool,
2383 content: [{ type: "text", text: "Launched" }],
2384 // A foreground shell's result already carries its exit.
2385 metadata: shell === "sync" ? { shellID, exit: 0 } : { shellID },
2386 executed: false,
2387 },
2388 undefined,
2389 2,
2390 ),
2391 event("shell.created", {
2392 info: {
2393 id: shellID,
2394 status: "running",
2395 command: "vp test",
2396 cwd: WORK,
2397 shell: "bash",
2398 file: "/tmp/sh_wake.log",
2399 metadata: { sessionID: SESSION },
2400 time: { started: 1 },
2401 },
2402 }),
2403 ...(shell === "held" ? [shellReport("completed")] : []),
2404 event("session.execution.succeeded", { sessionID: SESSION }),
2405 ...(shell === "exited"
2406 ? [
2407 event("shell.exited", { id: shellID, exit: 7, status: "exited" }),
2408 shellReport("error"),
2409 ]
2410 : []),
2411 ...(shell === "timeout"
2412 ? [
2413 event("shell.exited", { id: shellID, status: "timeout" }),
2414 shellReport("completed", { timeout: true }),
2415 ]
2416 : []),
2417 // Routed once the held execution ended, so its update proves the launch reached the adapter.
2418 event("session.model.selected", {
2419 sessionID: SESSION,
2420 model: { providerID: "opencode", id: "big-pickle", variant: "thinking" },
2421 }),
2422 ...Array.from({ length: shell === "held" ? 2 : shell === "sync" ? 0 : 1 }, () => [
2423 out("shell.output", "<any>"),
2424 reply("shell.output", {
2425 location: { directory: WORK },
2426 data: { output: "", cursor: 0, size: 0, truncated: false },
2427 }),
2428 ]).flat(),
2429 ]).pipe(
2430 Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
2431 offer: (request) =>
2432 Effect.sync(() => {
2433 offers.push(request);
2434 }),
2435 take: Effect.never,
2436 }),
2437 );
2438 // One reader: the runtime's event queue hands each event to only one taker.
2439 const launchSeen = yield* Deferred.make<void>();
2440 const marked = yield* Deferred.make<boolean | undefined>();
2441 const settled =
2442 yield* Deferred.make<import("@t3tools/contracts").OrchestrationV2TurnItem>();
2443 yield* runtime.events.pipe(
2444 Stream.tap((e) =>
2445 e.type === "turn_item.updated" &&
2446 e.turnItem.type === "command_execution" &&
2447 e.turnItem.status !== "running"
2448 ? Deferred.succeed(settled, e.turnItem)
2449 : e.type !== "provider_thread.updated"
2450 ? Effect.void
2451 : Effect.gen(function* () {
2452 const variant =
2453 e.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value;
2454 if (variant === "thinking") yield* Deferred.succeed(launchSeen, undefined);
2455 const listed = e.providerThread.pendingBackgroundTasks?.find(
2456 (task) => task.taskId === shellID,
2457 );
2458 // The first roster that lists the shell must hold the thread already.
2459 if (listed !== undefined) yield* Deferred.succeed(marked, listed.awaited);
2460 }),
2461 ),
2462 Stream.runDrain,
2463 Effect.forkScoped,
2464 );
2465 yield* runtime.startTurn(withLineage(thread));
2466 yield* Deferred.await(launchSeen);
2467 assert.deepEqual(
2468 yield* runtime.awaitBackgroundTasks!({
2469 providerThread: thread,
2470 taskIds: [shellID],
2471 awaited: true,
2472 }),
2473 { matched: shell === "running" ? [shellID] : [] },
2474 );
2475 if (shell === "sync") return;
2476 yield* runtime.startTurn(continuationTurn(thread, offers[0]!));
2477 if (shell === "running") return assert.isTrue(yield* Deferred.await(marked));
2478 // A shell that ended before the wake ran never holds the thread.
2479 assert.deepInclude(
2480 yield* Deferred.await(settled),
2481 shell === "exited"
2482 ? { status: "failed", exitCode: 7 }
2483 : { status: shell === "timeout" ? "failed" : "completed" },
2484 );
2485 const listed = yield* Deferred.poll(marked);
2486 if (Option.isSome(listed)) assert.notStrictEqual(yield* listed.value, true);
2487 }),
2488 );
2489
2490 it.effect("clears the caller's pending work when a called session's held wake runs", () =>
2491 Effect.gen(function* () {
2492 const OTHER = "ses_other00000000000000000000";
2493 const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
2494 const gate = makeProviderReplayGate(["drained"]);
2495 const { runtime, thread } = yield* resumed(
2496 [
2497 out("session.get", { sessionID: OTHER }),
2498 replyData("session.get", sessionInfo({ id: OTHER })),
2499 out("permission.list", { sessionID: OTHER }),
2500 replyData("permission.list", []),
2501 out("session.form.list", { sessionID: OTHER }),
2502 replyData("session.form.list", []),
2503 event("session.execution.started", { sessionID: OTHER }),
2504 event("session.execution.succeeded", { sessionID: OTHER }),
2505 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2506 promptAccepted,
2507 event("session.execution.started", { sessionID: SESSION }),
2508 event("session.tool.input.started", {
2509 ...toolOf(SESSION, "call-other"),
2510 name: "subagent",
2511 }),
2512 event("session.tool.called", {
2513 ...toolOf(SESSION, "call-other"),
2514 name: "subagent",
2515 input: { description: "Other", prompt: "again" },
2516 executed: false,
2517 }),
2518 event("session.tool.progress", {
2519 ...toolOf(SESSION, "call-other"),
2520 metadata: { sessionID: OTHER, status: "running" },
2521 }),
2522 event("session.tool.success", {
2523 ...toolOf(SESSION, "call-other"),
2524 content: [{ type: "text", text: "OTHER_OK" }],
2525 metadata: { sessionID: OTHER, status: "completed", truncated: false },
2526 executed: false,
2527 }),
2528 event("session.execution.succeeded", { sessionID: SESSION }),
2529 event(
2530 "session.model.selected",
2531 {
2532 sessionID: OTHER,
2533 model: { providerID: "opencode", id: "big-pickle", variant: "none" },
2534 },
2535 "drained",
2536 ),
2537 ],
2538 { replayGate: gate },
2539 ).pipe(
2540 Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
2541 offer: (request) =>
2542 Effect.sync(() => {
2543 offers.push(request);
2544 }),
2545 take: Effect.never,
2546 }),
2547 );
2548 const other = yield* runtime.resumeThread({
2549 providerThread: {
2550 ...thread,
2551 id: ProviderThreadId.make("provider-thread:opencode2-adapter:other"),
2552 nativeThreadRef: { driver: OPENCODE_PROVIDER, nativeId: OTHER, strength: "strong" },
2553 },
2554 threadId,
2555 modelSelection: bigPickle,
2556 runtimePolicy: policy(),
2557 });
2558 const watch = yield* watchNested(runtime);
2559 yield* watch.until(() => offers.length === 1);
2560 yield* runtime.startTurn(withLineage(thread));
2561 assert.isTrue(yield* Effect.promise(() => gate.waitForReached("drained")));
2562 // The called session's held wake is its caller's pending work too.
2563 yield* watch.until(() => watch.pendingSnapshots.get(SESSION) === true);
2564 yield* runtime.startTurn(continuationTurn(other, offers[0]!));
2565 gate.release("drained");
2566 yield* watch.until(() => watch.variants.get(OTHER) === "none");
2567 assert.isFalse(watch.pendingSnapshots.get(OTHER));
2568 assert.isFalse(watch.pendingSnapshots.get(SESSION));
2569 }),
2570 );
2571
2572 it.effect("stops a foreground subagent's background subagent after the turn ended", () =>
2573 Effect.gen(function* () {
2574 const offered = yield* Deferred.make<void>();
2575 const { runtime, thread } = yield* resumed([
2576 ...nestedLaunch,
2577 out("session.interrupt", { sessionID: DEEP }),
2578 reply("session.interrupt", { interrupted: true }),
2579 event("session.execution.interrupted", { sessionID: DEEP }),
2580 deepReport("cancelled"),
2581 event("session.execution.started", { sessionID: MIDDLE }),
2582 out("session.interrupt", { sessionID: MIDDLE }),
2583 reply("session.interrupt", { interrupted: true }),
2584 event("session.execution.interrupted", { sessionID: MIDDLE }),
2585 event("session.execution.started", { sessionID: SESSION }),
2586 ]).pipe(
2587 Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
2588 offer: () => Deferred.succeed(offered, undefined).pipe(Effect.asVoid),
2589 take: Effect.never,
2590 }),
2591 );
2592 const watch = yield* watchNested(runtime);
2593 yield* runtime.startTurn(withLineage(thread));
2594 yield* watch.until(() => watch.terminals.length > 0);
2595 assert.deepEqual(watch.terminals, ["completed"]);
2596 assert.equal(watch.deep.at(-1), "running");
2597 assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
2598 yield* runtime.interruptTurn({
2599 providerThread: thread,
2600 providerTurnId: yield* providerTurnId,
2601 requestRuntimeRestart: true,
2602 });
2603 yield* Deferred.await(offered);
2604 assert.equal(watch.deep.at(-1), "interrupted");
2605 assert.deepEqual([...watch.middleTurns.keys()], [`${MIDDLE}:turn:1`]);
2606 }),
2607 );
2608
2609 it.effect("stops the turn a foreground subagent runs to answer its background subagent", () =>
2610 Effect.gen(function* () {
2611 const { runtime, thread } = yield* resumed([
2612 ...nestedLaunch,
2613 event("session.execution.succeeded", { sessionID: DEEP }),
2614 deepReport("completed"),
2615 event("session.execution.started", { sessionID: MIDDLE }),
2616 event("session.text.ended", {
2617 sessionID: MIDDLE,
2618 assistantMessageID: "msg_assistant_answer",
2619 ordinal: 0,
2620 text: "Noted.",
2621 }),
2622 out("session.interrupt", { sessionID: MIDDLE }),
2623 reply("session.interrupt", { interrupted: true }),
2624 event("session.execution.interrupted", { sessionID: MIDDLE }),
2625 ]);
2626 const watch = yield* watchNested(runtime);
2627 yield* runtime.startTurn(withLineage(thread));
2628 yield* watch.until(() => watch.middleTurns.get(`${MIDDLE}:turn:2`) === "running");
2629 assert.equal(watch.deep.at(-1), "completed");
2630 assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
2631 yield* runtime.interruptTurn({
2632 providerThread: thread,
2633 providerTurnId: yield* providerTurnId,
2634 requestRuntimeRestart: true,
2635 });
2636 yield* watch.until(() => watch.middleTurns.get(`${MIDDLE}:turn:2`) === "interrupted");
2637 assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
2638 }),
2639 );
2640
2641 const stopTimedOut: ReadonlyArray<ProviderReplayEntry> = [
2642 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2643 promptAccepted,
2644 out("session.interrupt", { sessionID: SESSION }),
2645 reply("session.interrupt", "<hang>"),
2646 ];
2647 const secondTurn = (thread: OrchestrationV2ProviderThread) => ({
2648 ...turnInput(thread),
2649 runId: RunId.make("run:opencode2-adapter:2"),
2650 runOrdinal: 2,
2651 providerTurnOrdinal: 2,
2652 attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"),
2653 });
2654 const stopFirstTurn = (
2655 runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime,
2656 thread: OrchestrationV2ProviderThread,
2657 ) =>
2658 Effect.gen(function* () {
2659 yield* runtime.startTurn(turnInput(thread));
2660 const interrupt = yield* runtime
2661 .interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId })
2662 .pipe(Effect.forkScoped);
2663 yield* TestClock.adjust("11 seconds");
2664 yield* Fiber.join(interrupt).pipe(Effect.flip);
2665 });
2666 const terminals = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime, count: number) =>
2667 runtime.events.pipe(
2668 Stream.filter(
2669 (
2670 event,
2671 ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
2672 event.type === "turn.terminal",
2673 ),
2674 Stream.take(count),
2675 Stream.runCollect,
2676 Effect.forkScoped,
2677 );
2678
2679 // regression: #30193 an unanswered Stop showed the turn interrupted while its tool kept running
2680 it.effect("reports a Stop OpenCode never answers as an interrupt timeout", () =>
2681 Effect.gen(function* () {
2682 const { runtime, thread } = yield* resumed(stopTimedOut);
2683 yield* runtime.startTurn(turnInput(thread));
2684 const interrupt = yield* runtime
2685 .interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId })
2686 .pipe(Effect.exit, Effect.forkScoped);
2687 yield* TestClock.adjust("11 seconds");
2688 const exit = yield* Fiber.join(interrupt);
2689 assert.propertyVal(
2690 Exit.isFailure(exit) ? Cause.squash(exit.cause) : { _tag: "interrupt succeeded" },
2691 "_tag",
2692 "ProviderAdapterInterruptTimeoutError",
2693 );
2694 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
2695 );
2696
2697 it.effect("never lets a timed-out Stop's late end finish the next turn", () =>
2698 Effect.gen(function* () {
2699 const gate = makeProviderReplayGate(["late-end"]);
2700 const { runtime, thread } = yield* resumed(
2701 [
2702 ...stopTimedOut,
2703 event("session.execution.succeeded", { sessionID: SESSION }, "late-end"),
2704 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2705 promptAccepted,
2706 event("session.execution.started", { sessionID: SESSION }),
2707 event("session.execution.failed", {
2708 sessionID: SESSION,
2709 error: { type: "provider", message: "second turn failed" },
2710 }),
2711 ],
2712 { replayGate: gate },
2713 );
2714 const lateEnd = yield* Deferred.make<void>();
2715 const ended = yield* runtime.events.pipe(
2716 Stream.filter(
2717 (
2718 event,
2719 ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
2720 event.type === "turn.terminal",
2721 ),
2722 Stream.tap(() => Deferred.succeed(lateEnd, undefined)),
2723 Stream.take(2),
2724 Stream.runCollect,
2725 Effect.forkScoped,
2726 );
2727 yield* stopFirstTurn(runtime, thread);
2728 gate.release("late-end");
2729 yield* Deferred.await(lateEnd);
2730 yield* runtime.startTurn(secondTurn(thread));
2731 const [first, second] = yield* Fiber.join(ended);
2732 assert.equal(first?.status, "interrupted");
2733 assert.equal(second?.status, "failed");
2734 assert.equal(second?.failure?.message, "second turn failed");
2735 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
2736 );
2737
2738 it.effect("checks the server before prompting again after a prompt request failed", () =>
2739 Effect.gen(function* () {
2740 const { runtime, thread } = yield* resumed([
2741 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2742 reply("session.prompt", {
2743 status: 502,
2744 body: { _tag: "UnknownError", message: "bad gateway" },
2745 }),
2746 out("session.active"),
2747 reply("session.active", { data: { [SESSION]: { type: "running" } } }),
2748 out("session.interrupt", { sessionID: SESSION }),
2749 reply("session.interrupt", { interrupted: true }),
2750 ]);
2751 const ended = yield* terminals(runtime, 2);
2752 yield* runtime.startTurn(turnInput(thread)).pipe(Effect.ignore);
2753 yield* runtime.startTurn(secondTurn(thread));
2754 const [first, second] = yield* Fiber.join(ended);
2755 assert.equal(first?.status, "failed");
2756 assert.equal(second?.failure?.message, OPENCODE_2_STILL_STOPPING);
2757 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
2758 );
2759
2760 // regression: #14744 continuations hung after a reconnect took a Stop's end
2761 it.effect("still checks the server when a failed prompt's execution starts late", () =>
2762 Effect.gen(function* () {
2763 const offered = yield* Deferred.make<void>();
2764 const { runtime, thread } = yield* resumed([
2765 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2766 reply("session.prompt", {
2767 status: 502,
2768 body: { _tag: "UnknownError", message: "bad gateway" },
2769 }),
2770 event("session.execution.started", { sessionID: SESSION }),
2771 out("session.active"),
2772 reply("session.active", { data: { [SESSION]: { type: "running" } } }),
2773 out("session.interrupt", { sessionID: SESSION }),
2774 reply("session.interrupt", { interrupted: true }),
2775 ]).pipe(
2776 Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
2777 offer: () => Deferred.succeed(offered, undefined).pipe(Effect.asVoid),
2778 take: Effect.never,
2779 }),
2780 );
2781 const ended = yield* terminals(runtime, 2);
2782 yield* runtime.startTurn(turnInput(thread)).pipe(Effect.ignore);
2783 yield* Deferred.await(offered);
2784 yield* runtime.startTurn(secondTurn(thread));
2785 const [first, second] = yield* Fiber.join(ended);
2786 assert.equal(first?.status, "failed");
2787 assert.equal(second?.failure?.message, OPENCODE_2_STILL_STOPPING);
2788 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
2789 );
2790
2791 it.effect("ends a background reply's continuation after a lost stream took a Stop's end", () =>
2792 Effect.gen(function* () {
2793 const offered =
2794 yield* Deferred.make<ProviderContinuationRequests.ProviderContinuationRequest>();
2795 const gate = makeProviderReplayGate(["drop", "reply"]);
2796 const { runtime, thread } = yield* resumed(
2797 [
2798 ...backgroundLaunch(CHILD),
2799 out("session.interrupt", { sessionID: SESSION }),
2800 reply("session.interrupt", "<hang>"),
2801 out("session.interrupt", { sessionID: SESSION }),
2802 reply("session.interrupt", { interrupted: true }),
2803 event("session.usage.updated", { sessionID: SESSION }, "drop"),
2804 { type: "runtime_exit", status: "success" } as const,
2805 out("event.subscribe"),
2806 out("session.active"),
2807 replyData("session.active", { [CHILD]: { type: "running" } }),
2808 out("message.list", "<any>"),
2809 reply("message.list", { data: [], cursor: {} }),
2810 out("permission.list", { sessionID: CHILD }),
2811 replyData("permission.list", []),
2812 out("session.form.list", { sessionID: CHILD }),
2813 replyData("session.form.list", []),
2814 event("session.execution.succeeded", { sessionID: CHILD }),
2815 event("session.inbox.enqueued", {
2816 inboxID: "msg_report",
2817 sessionID: SESSION,
2818 item: {
2819 type: "synthetic",
2820 payload: {
2821 text: `<subagent sessionID="${CHILD}" state="completed" description="Sleep">\nCHILD_OK\n</subagent>`,
2822 description: "Sleep",
2823 metadata: {
2824 source: "subagent",
2825 childID: CHILD,
2826 agent: "General",
2827 state: "completed",
2828 },
2829 },
2830 delivery: "steer",
2831 },
2832 }),
2833 event("session.execution.started", { sessionID: SESSION }),
2834 event(
2835 "session.text.ended",
2836 {
2837 sessionID: SESSION,
2838 assistantMessageID: "msg_followup",
2839 ordinal: 0,
2840 text: "CHILD_OK",
2841 },
2842 "reply",
2843 ),
2844 event("session.execution.succeeded", { sessionID: SESSION }),
2845 event("session.execution.started", { sessionID: CHILD }),
2846 ],
2847 { replayGate: gate },
2848 ).pipe(
2849 Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
2850 offer: (request) => Deferred.succeed(offered, request).pipe(Effect.asVoid),
2851 take: Effect.never,
2852 }),
2853 );
2854 const attached = yield* Deferred.make<void>();
2855 const collected = yield* runtime.events.pipe(
2856 Stream.tap((event) =>
2857 event.type === "subagent.updated" && event.subagent.childThreadId !== null
2858 ? Deferred.succeed(attached, undefined)
2859 : Effect.void,
2860 ),
2861 Stream.takeUntil(
2862 (event) =>
2863 event.type === "provider_turn.updated" &&
2864 event.providerTurn.nativeTurnRef?.nativeId?.startsWith(`${CHILD}:turn:`) === true,
2865 ),
2866 Stream.runCollect,
2867 Effect.forkScoped,
2868 );
2869 yield* runtime.startTurn(withLineage(thread));
2870 yield* Deferred.await(attached);
2871 const stop = { providerThread: thread, providerTurnId: yield* providerTurnId };
2872 const interrupt = yield* runtime.interruptTurn(stop).pipe(Effect.flip, Effect.forkScoped);
2873 yield* TestClock.adjust("11 seconds");
2874 yield* Fiber.join(interrupt);
2875 yield* runtime.interruptTurn(stop);
2876 gate.release("drop");
2877 yield* runtime.startTurn({
2878 ...continuationTurn(thread, yield* Deferred.await(offered)),
2879 runOrdinal: 2,
2880 providerTurnOrdinal: 2,
2881 });
2882 gate.release("reply");
2883 const events = [...(yield* Fiber.join(collected))];
2884 assert.deepEqual(
2885 events.flatMap((event) => (event.type === "turn.terminal" ? [event.status] : [])),
2886 ["interrupted", "completed"],
2887 );
2888 assert.include(
2889 events.flatMap((event) =>
2890 event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
2891 ? [event.turnItem.text]
2892 : [],
2893 ),
2894 "CHILD_OK",
2895 );
2896 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
2897 );
2898
2899 const replyAfterUnclearFailure = (endedFirst: boolean) =>
2900 Effect.gen(function* () {
2901 const offered =
2902 yield* Deferred.make<ProviderContinuationRequests.ProviderContinuationRequest>();
2903 const gate = makeProviderReplayGate(endedFirst ? ["wake"] : ["wake", "reply"]);
2904 const { runtime, thread } = yield* resumed(
2905 [
2906 ...backgroundLaunch(CHILD),
2907 event("session.execution.succeeded", { sessionID: SESSION }),
2908 out("session.update", { sessionID: CHILD, permissions: t3Rules }),
2909 reply("session.update", null),
2910 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2911 reply("session.prompt", {
2912 status: 502,
2913 body: { _tag: "UnknownError", message: "bad gateway" },
2914 }),
2915 event("session.execution.succeeded", { sessionID: CHILD }, "wake"),
2916 event("session.inbox.enqueued", {
2917 inboxID: "msg_report",
2918 sessionID: SESSION,
2919 item: {
2920 type: "synthetic",
2921 payload: {
2922 text: `<subagent sessionID="${CHILD}" state="completed" description="Sleep">\nCHILD_OK\n</subagent>`,
2923 description: "Sleep",
2924 metadata: {
2925 source: "subagent",
2926 childID: CHILD,
2927 agent: "General",
2928 state: "completed",
2929 },
2930 },
2931 delivery: "steer",
2932 },
2933 }),
2934 event("session.execution.started", { sessionID: SESSION }),
2935 event(
2936 "session.text.ended",
2937 {
2938 sessionID: SESSION,
2939 assistantMessageID: "msg_followup",
2940 ordinal: 0,
2941 text: "CHILD_OK",
2942 },
2943 endedFirst ? undefined : "reply",
2944 ),
2945 event("session.execution.succeeded", { sessionID: SESSION }),
2946 event("session.execution.started", { sessionID: CHILD }),
2947 ],
2948 { replayGate: gate },
2949 ).pipe(
2950 Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
2951 offer: (request) => Deferred.succeed(offered, request).pipe(Effect.asVoid),
2952 take: Effect.never,
2953 }),
2954 );
2955 const launched = yield* Deferred.make<void>();
2956 const childRan = yield* Deferred.make<void>();
2957 const ended: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
2958 const allEnded = yield* Deferred.make<void>();
2959 yield* runtime.events.pipe(
2960 Stream.tap((event) =>
2961 Effect.gen(function* () {
2962 if (
2963 event.type === "provider_turn.updated" &&
2964 event.providerTurn.nativeTurnRef?.nativeId?.startsWith(`${CHILD}:turn:`) === true
2965 ) {
2966 yield* Deferred.succeed(childRan, undefined);
2967 }
2968 if (event.type !== "turn_item.updated" && event.type !== "turn.terminal") return;
2969 ended.push(event);
2970 if (event.type === "turn.terminal") yield* Deferred.succeed(launched, undefined);
2971 if (ended.filter((entry) => entry.type === "turn.terminal").length === 3) {
2972 yield* Deferred.succeed(allEnded, undefined);
2973 }
2974 }),
2975 ),
2976 Stream.runDrain,
2977 Effect.forkScoped,
2978 );
2979 yield* runtime.startTurn(withLineage(thread));
2980 yield* Deferred.await(launched);
2981 yield* runtime
2982 .startTurn({ ...secondTurn(thread), appThread: withLineage(thread).appThread })
2983 .pipe(Effect.ignore);
2984 gate.release("wake");
2985 if (endedFirst) yield* Deferred.await(childRan);
2986 yield* runtime.startTurn({
2987 ...continuationTurn(thread, yield* Deferred.await(offered)),
2988 runOrdinal: 3,
2989 providerTurnOrdinal: 3,
2990 });
2991 if (!endedFirst) gate.release("reply");
2992 yield* Deferred.await(allEnded);
2993 assert.deepEqual(
2994 ended.flatMap((event) => (event.type === "turn.terminal" ? [event.status] : [])),
2995 ["completed", "failed", "completed"],
2996 );
2997 assert.include(
2998 ended.flatMap((event) =>
2999 event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
3000 ? [event.turnItem.text]
3001 : [],
3002 ),
3003 "CHILD_OK",
3004 );
3005 }).pipe(Effect.scoped, Effect.provide(TestClock.layer()));
3006
3007 // regression: #14744 continuations hung after a reconnect took a Stop's end
3008 it.effect("ends a background reply's continuation after a prompt failed unclearly", () =>
3009 replyAfterUnclearFailure(false),
3010 );
3011
3012 it.effect("reports a turn as completed when its Stop request failed", () =>
3013 Effect.gen(function* () {
3014 const { runtime, thread } = yield* resumed([
3015 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3016 promptAccepted,
3017 out("session.interrupt", { sessionID: SESSION }),
3018 reply("session.interrupt", {
3019 status: 500,
3020 body: { _tag: "UnknownError", message: "interrupt failed" },
3021 }),
3022 event("session.execution.succeeded", { sessionID: SESSION }),
3023 ]);
3024 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3025 yield* runtime.startTurn(turnInput(thread));
3026 const failed = yield* runtime
3027 .interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId })
3028 .pipe(Effect.flip);
3029 assert.equal(failed._tag, "ProviderAdapterInterruptError");
3030 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3031 }),
3032 );
3033
3034 it.effect("gives a resumed session T3's rules when it was made with others", () =>
3035 Effect.gen(function* () {
3036 const runtime = yield* openCode2ReplayRuntimeWithInstructions([
3037 ...opening,
3038 out("session.get", { sessionID: SESSION }),
3039 replyData(
3040 "session.get",
3041 sessionInfo({
3042 permissions: [
3043 { action: "*", resource: "*", effect: "allow" },
3044 { action: "subagent", resource: "*", effect: "deny" },
3045 ],
3046 }),
3047 ),
3048 ...noOpenRequests,
3049 out("session.update", { sessionID: SESSION, permissions: t3Rules }),
3050 reply("session.update", null),
3051 ]);
3052 yield* runtime.resumeThread({
3053 providerThread: providerThread(yield* DateTime.now),
3054 threadId,
3055 modelSelection: bigPickle,
3056 runtimePolicy: policy(),
3057 });
3058 }),
3059 );
3060
3061 it.effect("moves the session when the thread's worktree changed", () =>
3062 Effect.gen(function* () {
3063 const runtime = yield* openCode2ReplayRuntimeWithInstructions([
3064 ...opening,
3065 ...directoryModels("/work/opencode2-feature"),
3066 out("session.get", { sessionID: SESSION }),
3067 replyData("session.get", sessionInfo()),
3068 ...noOpenRequests,
3069 out("session.move", { sessionID: SESSION, directory: "/work/opencode2-feature" }),
3070 reply("session.move", null),
3071 ]);
3072 yield* runtime.resumeThread({
3073 providerThread: providerThread(yield* DateTime.now),
3074 threadId,
3075 modelSelection: bigPickle,
3076 runtimePolicy: { ...policy(), cwd: "/work/opencode2-feature" },
3077 });
3078 }),
3079 );
3080
3081 it.effect("breaks the thread and forgets it when the session was deleted outside T3", () =>
3082 Effect.gen(function* () {
3083 const { runtime, thread } = yield* resumed([
3084 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3085 reply("session.prompt", {
3086 status: 404,
3087 body: {
3088 _tag: "SessionNotFoundError",
3089 sessionID: SESSION,
3090 message: `Session not found: ${SESSION}`,
3091 },
3092 }),
3093 ]);
3094 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3095 yield* runtime.startTurn(turnInput(thread)).pipe(Effect.ignore);
3096 const ended = yield* Fiber.join(terminal);
3097 assert.equal(ended?.status, "failed");
3098 assert.equal(ended?.threadDisposition, "broken");
3099 const again = yield* runtime.startTurn(turnInput(thread)).pipe(Effect.flip);
3100 assert.equal(again._tag, "ProviderAdapterProtocolError");
3101 assert.include(again.message, "not registered");
3102 }),
3103 );
3104
3105 it.effect("stops the requests a session still waits on when a restarted T3 loads it", () =>
3106 Effect.gen(function* () {
3107 const runtime = yield* openCode2ReplayRuntimeWithInstructions(
3108 [
3109 ...opening,
3110 out("session.get", { sessionID: SESSION }),
3111 replyData("session.get", sessionInfo()),
3112 out("permission.list", { sessionID: SESSION }),
3113 replyData("permission.list", [shellAsk.data]),
3114 out("session.form.list", { sessionID: SESSION }),
3115 replyData("session.form.list", [colorForm]),
3116 out("permission.reply", {
3117 sessionID: SESSION,
3118 requestID: shellAsk.data.id,
3119 decision: "reject",
3120 }),
3121 reply("permission.reply", null),
3122 out("session.form.cancel", { sessionID: SESSION, formID: colorForm.id }),
3123 reply("session.form.cancel", null),
3124 out("session.active"),
3125 reply("session.active", { data: {} }),
3126 event("session.execution.interrupted", { sessionID: SESSION, reason: "user" }),
3127 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3128 promptAccepted,
3129 event("session.execution.started", { sessionID: SESSION }),
3130 event("session.execution.succeeded", { sessionID: SESSION }),
3131 ],
3132 { external: true },
3133 );
3134 const thread = yield* runtime.resumeThread({
3135 providerThread: providerThread(yield* DateTime.now),
3136 threadId,
3137 modelSelection: bigPickle,
3138 runtimePolicy: policy(),
3139 });
3140 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3141 yield* runtime.startTurn(turnInput(thread));
3142 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3143 }),
3144 );
3145
3146 it.effect("ends the turn when an answer to its request cannot be delivered", () =>
3147 Effect.gen(function* () {
3148 const failedReply = reply("permission.reply", {
3149 status: 500,
3150 body: { _tag: "UnknownError", message: "reply failed" },
3151 });
3152 const replyOut = out("permission.reply", {
3153 sessionID: SESSION,
3154 requestID: shellAsk.data.id,
3155 decision: "once",
3156 });
3157 const { runtime, thread } = yield* resumed(
3158 [
3159 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3160 promptAccepted,
3161 shellAskEvent,
3162 replyOut,
3163 failedReply,
3164 replyOut,
3165 failedReply,
3166 out("session.interrupt", { sessionID: SESSION }),
3167 reply("session.interrupt", { interrupted: true }),
3168 ],
3169 { supervised: true },
3170 );
3171 const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
3172 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3173 yield* runtime.startTurn(turnInput(thread, bigPickle, "approval-required"));
3174 const request = yield* Fiber.join(requested);
3175 yield* runtime.respondToRuntimeRequest({ requestId: request!.id, decision: "accept" });
3176 const ended = yield* Fiber.join(terminal);
3177 assert.equal(ended?.status, "failed");
3178 assert.equal(
3179 ended?.status === "failed" ? ended.failure.message : undefined,
3180 "OpenCode is waiting on a request T3 Code couldn't answer.",
3181 );
3182 }),
3183 );
3184
3185 it.effect("counts an answer to a request OpenCode already dropped as delivered", () =>
3186 Effect.gen(function* () {
3187 const { runtime, thread } = yield* resumed(
3188 [
3189 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3190 promptAccepted,
3191 shellAskEvent,
3192 out("permission.reply", {
3193 sessionID: SESSION,
3194 requestID: shellAsk.data.id,
3195 decision: "once",
3196 }),
3197 reply("permission.reply", {
3198 status: 404,
3199 body: {
3200 _tag: "PermissionNotFoundError",
3201 requestID: shellAsk.data.id,
3202 message: "Permission request not found",
3203 },
3204 }),
3205 event("session.execution.succeeded", { sessionID: SESSION }),
3206 ],
3207 { supervised: true },
3208 );
3209 const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
3210 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3211 yield* runtime.startTurn(turnInput(thread, bigPickle, "approval-required"));
3212 const request = yield* Fiber.join(requested);
3213 yield* runtime.respondToRuntimeRequest({ requestId: request!.id, decision: "accept" });
3214 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3215 }),
3216 );
3217
3218 it.effect("declines a form T3 cannot show with the reason, instead of leaving it open", () =>
3219 Effect.gen(function* () {
3220 const { runtime, thread } = yield* resumed([
3221 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3222 promptAccepted,
3223 event("form.created", {
3224 form: {
3225 id: "frm_0eb79ab35001fkvFECSh3wYNVD",
3226 sessionID: SESSION,
3227 title: "MCP authorization",
3228 metadata: { kind: "mcp" },
3229 fields: [
3230 {
3231 key: "authorization",
3232 type: "external",
3233 url: "https://example.com/authorize",
3234 title: "Authorize",
3235 },
3236 ],
3237 },
3238 }),
3239 out("session.form.cancel", {
3240 sessionID: SESSION,
3241 formID: "frm_0eb79ab35001fkvFECSh3wYNVD",
3242 }),
3243 reply("session.form.cancel", null),
3244 ]);
3245 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3246 yield* runtime.startTurn(turnInput(thread));
3247 const ended = yield* Fiber.join(terminal);
3248 assert.equal(ended?.status, "failed");
3249 assert.include(
3250 ended?.status === "failed" ? ended.failure.message : "",
3251 "asked for a link to open",
3252 );
3253 }),
3254 );
3255
3256 it.effect("asks a subagent's permission request on the parent thread's turn", () =>
3257 Effect.gen(function* () {
3258 const child = "ses_f0e5aa64cffelFnoQRL0DAA9BH";
3259 const { runtime, thread } = yield* resumed(
3260 [
3261 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3262 promptAccepted,
3263 event("session.created", {
3264 sessionID: child,
3265 slug: "stellar-garden",
3266 version: "2.0.18",
3267 projectID: "global",
3268 parentID: SESSION,
3269 location: { directory: WORK },
3270 subpath: "",
3271 title: "Echo test command",
3272 agent: "general",
3273 permissions: supervisedRules,
3274 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
3275 }),
3276 event("permission.asked", { ...shellAsk.data, sessionID: child }),
3277 out("permission.reply", {
3278 sessionID: child,
3279 requestID: shellAsk.data.id,
3280 decision: "once",
3281 }),
3282 reply("permission.reply", null),
3283 event("permission.replied", {
3284 sessionID: child,
3285 requestID: shellAsk.data.id,
3286 reply: "once",
3287 }),
3288 event("session.execution.succeeded", { sessionID: SESSION }),
3289 ],
3290 { supervised: true },
3291 );
3292 const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
3293 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3294 yield* runtime.startTurn(turnInput(thread, bigPickle, "approval-required"));
3295 const request = yield* Fiber.join(requested);
3296 assert.equal(request?.nativeRequestRef?.nativeId, shellAsk.data.id);
3297 yield* runtime.respondToRuntimeRequest({ requestId: request!.id, decision: "accept" });
3298 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3299 }),
3300 );
3301
3302 it.effect("keeps 'allow this session' in the session's rules, not OpenCode's saved grants", () =>
3303 Effect.gen(function* () {
3304 const { runtime, thread } = yield* resumed(
3305 [
3306 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3307 promptAccepted,
3308 shellAskEvent,
3309 out("session.update", {
3310 sessionID: SESSION,
3311 permissions: [
3312 ...supervisedRules.slice(0, 3),
3313 { action: "shell", resource: "echo *", effect: "allow" },
3314 ...supervisedRules.slice(3),
3315 ],
3316 }),
3317 reply("session.update", null),
3318 out("permission.reply", {
3319 sessionID: SESSION,
3320 requestID: shellAsk.data.id,
3321 decision: "once",
3322 }),
3323 reply("permission.reply", null),
3324 event("session.execution.succeeded", { sessionID: SESSION }),
3325 ],
3326 { supervised: true },
3327 );
3328 const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
3329 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3330 yield* runtime.startTurn(turnInput(thread, bigPickle, "approval-required"));
3331 const request = yield* Fiber.join(requested);
3332 yield* runtime.respondToRuntimeRequest({
3333 requestId: request!.id,
3334 decision: "acceptForSession",
3335 });
3336 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3337 }),
3338 );
3339
3340 it.effect("reads the agents again while a fresh server still lists none", () =>
3341 Effect.gen(function* () {
3342 // OpenCode 2.0.18 briefly returns no agents on startup; using that response drops agent paths.
3343 const runtime = yield* openCode2ReplayRuntime([
3344 ...opening,
3345 out("agent.list", "<any>"),
3346 reply("agent.list", { location: { directory: WORK }, data: [] }),
3347 out("agent.list", "<any>"),
3348 reply("agent.list", agentList),
3349 out("session.create", {
3350 location: { directory: WORK },
3351 model: { providerID: "opencode", id: "big-pickle" },
3352 permissions: supervisedRules,
3353 }),
3354 replyData("session.create", sessionInfo({ permissions: supervisedRules })),
3355 ]);
3356 const created = yield* runtime
3357 .ensureThread({
3358 threadId,
3359 modelSelection: bigPickle,
3360 runtimePolicy: policy("approval-required"),
3361 })
3362 .pipe(Effect.forkScoped);
3363 yield* TestClock.adjust("250 millis");
3364 assert.equal((yield* Fiber.join(created)).nativeThreadRef?.nativeId, SESSION);
3365 }),
3366 );
3367 const reconnected = (
3368 active: Record<string, unknown>,
3369 ended?: "succeeded",
3370 assistant: Record<string, unknown> = {},
3371 deliveredSteer?: string,
3372 ) => [
3373 { type: "runtime_exit", status: "success" } as const,
3374 out("event.subscribe"),
3375 out("session.active"),
3376 replyData("session.active", active),
3377 out("message.list", { sessionID: SESSION, order: "desc", limit: "50" }),
3378 reply("message.list", {
3379 data: [
3380 ...(ended === undefined
3381 ? []
3382 : [{ id: "msg_idle_gap", time: { created: 3 }, type: "idle", outcome: ended }]),
3383 {
3384 id: "msg_assistant_gap",
3385 time: { created: 2 },
3386 type: "assistant",
3387 agent: "build",
3388 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
3389 content: [
3390 { type: "text", text: "Sent while the stream was down." },
3391 {
3392 type: "tool",
3393 id: "call_gap",
3394 name: "shell",
3395 executed: true,
3396 state: {
3397 status: "completed",
3398 input: { command: "echo GAP" },
3399 content: [{ type: "text", text: "GAP" }],
3400 metadata: {},
3401 },
3402 time: { created: 2, ran: 2, completed: 2 },
3403 },
3404 ],
3405 finish: "stop",
3406 ...assistant,
3407 },
3408 ...(deliveredSteer === undefined
3409 ? []
3410 : [{ id: deliveredSteer, time: { created: 2 }, text: "steered", type: "user" }]),
3411 {
3412 id: "msg_0eb735d41001NJee1EvVePJAK5",
3413 time: { created: 1 },
3414 text: "hi",
3415 type: "user",
3416 },
3417 ],
3418 cursor: {},
3419 }),
3420 ];
3421 const openRequests = (
3422 permissions: ReadonlyArray<unknown>,
3423 forms: ReadonlyArray<unknown> = [],
3424 ): ReadonlyArray<ProviderReplayEntry> => [
3425 out("permission.list", { sessionID: SESSION }),
3426 replyData("permission.list", permissions),
3427 out("session.form.list", { sessionID: SESSION }),
3428 replyData("session.form.list", forms),
3429 ];
3430
3431 const turnItems = (collected: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>) =>
3432 collected.flatMap((event) =>
3433 event.type === "turn_item.updated" ? [`${event.turnItem.type}:${event.turnItem.status}`] : [],
3434 );
3435
3436 it.effect.each(["delivered", "pending"] as const)(
3437 "reconciles a %s steer after reconnect without losing its execution",
3438 (delivery) =>
3439 Effect.gen(function* () {
3440 const steerId = `msg_t3_steer_${SESSION}:message:opencode2-adapter:steer`;
3441 const reconnect = reconnected(
3442 {},
3443 "succeeded",
3444 {},
3445 delivery === "delivered" ? steerId : undefined,
3446 );
3447 const { runtime, thread } = yield* resumed(
3448 [
3449 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
3450 promptAccepted,
3451 ...(delivery === "pending"
3452 ? [
3453 event("rpc.opencode.goal.changed", {
3454 sessionID: SESSION,
3455 goal: nativeGoal("active"),
3456 }),
3457 ]
3458 : []),
3459 out("session.prompt", "<any>"),
3460 replyData("session.prompt", {
3461 id: steerId,
3462 sessionID: SESSION,
3463 time: { created: 2 },
3464 type: "user",
3465 payload: { text: "steered" },
3466 delivery: "steer",
3467 }),
3468 ...reconnect.slice(0, 2),
3469 ...(delivery === "pending"
3470 ? [out("rpc.call", "<any>"), reply("rpc.call", { output: { unreadable: true } })]
3471 : []),
3472 ...(delivery === "pending" ? emptyShellInventory : []),
3473 ...reconnect.slice(2),
3474 ...(delivery === "pending"
3475 ? [
3476 event("session.execution.started", { sessionID: SESSION }),
3477 event("session.inbox.delivered", { sessionID: SESSION, inboxID: steerId }),
3478 event("session.text.ended", {
3479 sessionID: SESSION,
3480 assistantMessageID: "msg_delayed_steer",
3481 ordinal: 0,
3482 text: "Steer processed",
3483 }),
3484 event("session.execution.succeeded", { sessionID: SESSION }),
3485 ]
3486 : [event("session.execution.interrupted", { sessionID: SESSION, reason: "user" })]),
3487 ],
3488 delivery === "pending" ? { version: "2.2.5" } : undefined,
3489 );
3490 const events = yield* runtime.events.pipe(
3491 Stream.takeUntil((e) => e.type === "turn.terminal"),
3492 Stream.runCollect,
3493 Effect.forkScoped,
3494 );
3495 yield* runtime.startTurn(turnInput(thread));
3496 yield* runtime.steerTurn({
3497 providerThread: thread,
3498 providerTurnId: yield* providerTurnId,
3499 threadId,
3500 runId: turnInput(thread).runId,
3501 message: {
3502 ...turnInput(thread).message,
3503 messageId: MessageId.make("message:opencode2-adapter:steer"),
3504 text: "steered",
3505 },
3506 });
3507 const collected = yield* Fiber.join(events);
3508 assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
3509 if (delivery === "pending")
3510 assert.isTrue(
3511 collected.some(
3512 (e) =>
3513 e.type === "turn_item.updated" &&
3514 e.turnItem.type === "assistant_message" &&
3515 e.turnItem.text === "Steer processed",
3516 ),
3517 );
3518 }),
3519 );
3520
3521 it.effect("does not end a turn from an earlier turn's history when its prompt is not there", () =>
3522 Effect.gen(function* () {
3523 const { runtime, thread } = yield* resumed([
3524 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3525 promptAccepted,
3526 { type: "runtime_exit", status: "success" } as const,
3527 out("event.subscribe"),
3528 out("session.active"),
3529 replyData("session.active", {}),
3530 out("message.list", { sessionID: SESSION, order: "desc", limit: "50" }),
3531 reply("message.list", {
3532 data: [
3533 { id: "msg_idle_earlier", time: { created: 3 }, type: "idle", outcome: "succeeded" },
3534 {
3535 id: "msg_assistant_earlier",
3536 time: { created: 2 },
3537 type: "assistant",
3538 agent: "build",
3539 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
3540 content: [{ type: "text", text: "An earlier turn's answer." }],
3541 finish: "stop",
3542 },
3543 { id: "msg_user_earlier", time: { created: 1 }, text: "earlier", type: "user" },
3544 ],
3545 cursor: {},
3546 }),
3547 ]);
3548 const events = yield* runtime.events.pipe(
3549 Stream.takeUntil((event) => event.type === "turn.terminal"),
3550 Stream.runCollect,
3551 Effect.forkScoped,
3552 );
3553 yield* runtime.startTurn(turnInput(thread));
3554 const collected = yield* Fiber.join(events);
3555 assert.notInclude(
3556 collected.flatMap((event) =>
3557 event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
3558 ? [event.turnItem.text]
3559 : [],
3560 ),
3561 "An earlier turn's answer.",
3562 );
3563 assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "interrupted" });
3564 }),
3565 );
3566
3567 it.effect("ends a turn that finished while the stream was down with the server's outcome", () =>
3568 Effect.gen(function* () {
3569 const { runtime, thread } = yield* resumed([
3570 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
3571 promptAccepted,
3572 event("session.step.started", {
3573 sessionID: SESSION,
3574 assistantMessageID: "msg_before_gap",
3575 agent: "build",
3576 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
3577 started: 1,
3578 }),
3579 event("session.step.ended", {
3580 sessionID: SESSION,
3581 assistantMessageID: "msg_before_gap",
3582 finish: "tool-calls",
3583 cost: 0,
3584 tokens: { input: 100, output: 10, reasoning: 0, cache: { read: 0, write: 0 } },
3585 }),
3586 ...reconnected({}, "succeeded"),
3587 ]);
3588 const events = yield* runtime.events.pipe(
3589 Stream.takeUntil((event) => event.type === "turn.terminal"),
3590 Stream.runCollect,
3591 Effect.forkScoped,
3592 );
3593 yield* runtime.startTurn(turnInput(thread));
3594 const collected = yield* Fiber.join(events);
3595 assert.includeMembers(turnItems(collected), [
3596 "assistant_message:completed",
3597 "command_execution:completed",
3598 ]);
3599 assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
3600 // Steps that ended during the gap sent no tokens or models, so both stay incomplete.
3601 const settled = collected.findLast(
3602 (event) =>
3603 event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null,
3604 );
3605 const usage =
3606 settled?.type === "provider_turn.updated" ? settled.providerTurn.turnTokenUsage : undefined;
3607 assert.deepInclude(usage, { usageStatus: "partial", inputTokens: 100, outputTokens: 10 });
3608 assert.notProperty(usage, "models");
3609 }),
3610 );
3611
3612 it.effect("finishes a workspace command whose stream dropped before its inbox event", () =>
3613 Effect.gen(function* () {
3614 // session.command returns 204 without an inbox id; the stream drops before session.inbox.enqueued provides it.
3615 const { runtime, thread } = yield* resumed([
3616 out("command.list", "<any>"),
3617 reply("command.list", { location: { directory: WORK }, data: [{ name: "git/hello" }] }),
3618 out("message.list", { sessionID: SESSION, order: "desc", limit: "1" }),
3619 reply("message.list", {
3620 data: [
3621 { id: "msg_idle_before", time: { created: 1 }, type: "idle", outcome: "succeeded" },
3622 ],
3623 cursor: {},
3624 }),
3625 out("session.command", { sessionID: SESSION, name: "git/hello", text: "WORLD" }),
3626 reply("session.command", null),
3627 { type: "runtime_exit", status: "success" } as const,
3628 out("event.subscribe"),
3629 out("session.active"),
3630 replyData("session.active", {}),
3631 out("message.list", { sessionID: SESSION, order: "desc", limit: "50" }),
3632 reply("message.list", {
3633 data: [
3634 { id: "msg_idle_cmd", time: { created: 4 }, type: "idle", outcome: "succeeded" },
3635 {
3636 id: "msg_assistant_cmd",
3637 time: { created: 3 },
3638 type: "assistant",
3639 agent: "build",
3640 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
3641 content: [{ type: "text", text: "HELLO WORLD" }],
3642 finish: "stop",
3643 },
3644 {
3645 id: "msg_user_cmd",
3646 time: { created: 2 },
3647 text: "Reply with exactly: HELLO WORLD",
3648 type: "user",
3649 },
3650 { id: "msg_idle_before", time: { created: 1 }, type: "idle", outcome: "succeeded" },
3651 ],
3652 cursor: {},
3653 }),
3654 ]);
3655 const events = yield* runtime.events.pipe(
3656 Stream.takeUntil((event) => event.type === "turn.terminal"),
3657 Stream.runCollect,
3658 Effect.forkScoped,
3659 );
3660 yield* runtime.startTurn({
3661 ...turnInput(thread),
3662 message: { ...turnInput(thread).message, text: "/git/hello WORLD" },
3663 });
3664 const collected = yield* Fiber.join(events);
3665 const texts = collected.flatMap((event) =>
3666 event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
3667 ? [event.turnItem.text]
3668 : [],
3669 );
3670 assert.include(texts, "HELLO WORLD");
3671 assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
3672 }),
3673 );
3674
3675 it.effect("sends a $skill that appears once OpenCode finishes scanning the directory", () =>
3676 Effect.gen(function* () {
3677 const prompts: Array<unknown> = [];
3678 const greet = {
3679 id: "greet",
3680 name: "greet",
3681 path: `${WORK}/.opencode/skills/greet/SKILL.md`,
3682 content: "Say hello.",
3683 };
3684 const { runtime, thread } = yield* resumed(
3685 [
3686 out("skill.list", { "location[directory]": WORK }),
3687 reply("skill.list", { location: { directory: WORK }, data: [] }),
3688 // OpenCode answers the model list only once the directory scan has ended.
3689 ...directoryModels(WORK),
3690 out("skill.list", { "location[directory]": WORK }),
3691 reply("skill.list", { location: { directory: WORK }, data: [greet] }),
3692 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3693 promptAccepted,
3694 event("session.execution.succeeded", { sessionID: SESSION }),
3695 ],
3696 { onPrompt: (input) => prompts.push(input) },
3697 );
3698 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3699 const started = yield* runtime
3700 .startTurn({
3701 ...turnInput(thread),
3702 message: { ...turnInput(thread).message, text: "$greet again please" },
3703 })
3704 .pipe(Effect.exit);
3705 assert.deepInclude(prompts[0], { skills: [{ id: "greet" }] });
3706 assert.isTrue(Exit.isSuccess(started));
3707 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3708 }),
3709 );
3710
3711 it.effect("keeps owned work through a stalled reconciliation without releasing its server", () =>
3712 Effect.gen(function* () {
3713 const reading = yield* Deferred.make<void>();
3714 const resume = yield* Deferred.make<void>();
3715 const borrowers = { current: 0 };
3716 const { runtime, thread } = yield* resumed(
3717 [
3718 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
3719 promptAccepted,
3720 ...reconnected({ [SESSION]: { type: "running" } }),
3721 ...openRequests([]),
3722 event("session.execution.succeeded", { sessionID: SESSION }),
3723 ],
3724 {
3725 borrowers,
3726 beforeResponse: (path) =>
3727 path.endsWith("/message")
3728 ? Deferred.succeed(reading, undefined).pipe(Effect.andThen(Deferred.await(resume)))
3729 : Effect.void,
3730 },
3731 );
3732 const collected: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
3733 const ended = yield* runtime.events.pipe(
3734 Stream.tap((event) => Effect.sync(() => collected.push(event))),
3735 Stream.takeUntil((event) => event.type === "turn.terminal"),
3736 Stream.runDrain,
3737 Effect.forkScoped,
3738 );
3739 yield* runtime.startTurn(turnInput(thread));
3740 yield* Deferred.await(reading);
3741 yield* TestClock.adjust("3 minutes");
3742 assert.isFalse(collected.some((event) => event.type === "turn.terminal"));
3743 assert.equal(borrowers.current, 1);
3744 yield* Deferred.succeed(resume, undefined);
3745 yield* Fiber.join(ended);
3746 assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
3747 }),
3748 );
3749
3750 // regression: #39120 a live owned server failed after five stalled event subscriptions
3751 it.effect("keeps owned work through more than five stalled event subscriptions", () =>
3752 Effect.gen(function* () {
3753 let subscriptions = 0;
3754 const [exit, ...restored] = reconnected({}, "succeeded");
3755 const { runtime, thread } = yield* resumed(
3756 [
3757 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
3758 promptAccepted,
3759 exit!,
3760 ...Array.from({ length: 5 }, () => out("event.subscribe")),
3761 ...restored,
3762 ],
3763 {
3764 beforeResponse: (path) =>
3765 path === "/api/event"
3766 ? Effect.suspend(() => {
3767 subscriptions += 1;
3768 return subscriptions >= 2 && subscriptions <= 6 ? Effect.never : Effect.void;
3769 })
3770 : Effect.void,
3771 },
3772 );
3773 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3774 yield* runtime.startTurn(turnInput(thread));
3775 // Each stalled subscription waits out its 10s deadline before the next attempt.
3776 for (let attempt = 0; attempt < 8; attempt++) yield* TestClock.adjust("15 seconds");
3777 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3778 assert.equal(subscriptions, 7);
3779 }),
3780 );
3781
3782 it.effect("reconciles a session deleted after the active snapshot", () =>
3783 Effect.gen(function* () {
3784 const otherId = "ses_other_stalled_session";
3785 const otherPrompt = "msg_other_stalled_prompt";
3786 const history = (sessionID: string, id: string) => [
3787 out("message.list", { sessionID, order: "desc", limit: "50" }),
3788 reply("message.list", {
3789 data: [{ id, time: { created: 1 }, text: "hi", type: "user" }],
3790 cursor: {},
3791 }),
3792 ];
3793 const requests = (sessionID: string) => [
3794 out("permission.list", { sessionID }),
3795 replyData("permission.list", []),
3796 out("session.form.list", { sessionID }),
3797 replyData("session.form.list", []),
3798 ];
3799 const { runtime, thread } = yield* resumed([
3800 out("session.get", { sessionID: otherId }),
3801 replyData("session.get", sessionInfo({ id: otherId })),
3802 ...requests(otherId),
3803 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
3804 promptAccepted,
3805 out("session.instructions.entry.put", {
3806 sessionID: otherId,
3807 key: "t3-code",
3808 value: "<any>",
3809 }),
3810 reply("session.instructions.entry.put", null),
3811 out("session.prompt", { sessionID: otherId, id: otherPrompt, text: "<any>" }),
3812 replyData("session.prompt", {
3813 id: otherPrompt,
3814 sessionID: otherId,
3815 time: { created: 1 },
3816 type: "user",
3817 payload: { text: "hi" },
3818 delivery: "steer",
3819 }),
3820 { type: "runtime_exit", status: "success" },
3821 out("event.subscribe"),
3822 out("session.active"),
3823 replyData("session.active", {
3824 [SESSION]: { type: "running" },
3825 [otherId]: { type: "running" },
3826 }),
3827 out("message.list", { sessionID: SESSION, order: "desc", limit: "50" }),
3828 reply("message.list", {
3829 status: 404,
3830 body: {
3831 _tag: "SessionNotFoundError",
3832 sessionID: SESSION,
3833 message: "Deleted during recovery",
3834 },
3835 }),
3836 ...history(otherId, otherPrompt),
3837 ...requests(otherId),
3838 event("session.execution.succeeded", { sessionID: otherId }),
3839 ]);
3840 const other = yield* runtime.resumeThread({
3841 providerThread: {
3842 ...providerThread(yield* DateTime.now),
3843 id: ProviderThreadId.make("provider-thread:other"),
3844 nativeThreadRef: { driver: OPENCODE_PROVIDER, nativeId: otherId, strength: "strong" },
3845 },
3846 threadId,
3847 modelSelection: bigPickle,
3848 runtimePolicy: policy(),
3849 });
3850 const terminals = yield* runtime.events.pipe(
3851 Stream.filter((event) => event.type === "turn.terminal"),
3852 Stream.take(2),
3853 Stream.runCollect,
3854 Effect.forkScoped,
3855 );
3856 yield* runtime.startTurn(turnInput(thread));
3857 yield* runtime.startTurn({
3858 ...turnInput(other),
3859 runId: RunId.make("run:other"),
3860 attemptId: RunAttemptId.make("attempt:other"),
3861 });
3862 const ended = yield* Fiber.join(terminals);
3863 assert.deepEqual(
3864 ended.map((event) => event.status),
3865 ["interrupted", "completed"],
3866 );
3867 assert.equal(ended[0]?.threadDisposition, "broken");
3868 assert.sameMembers(
3869 ended.map((event) => event.providerThreadId),
3870 [thread.id, other.id],
3871 );
3872 }),
3873 );
3874
3875 it.effect.each([503, 429])(
3876 "recovers an owned server after more than five HTTP %s reconciliation replies",
3877 (status) =>
3878 Effect.gen(function* () {
3879 const allowRecovery = yield* Deferred.make<void>();
3880 const attempts = yield* Queue.unbounded<void>();
3881 let attempt = 0;
3882 const { runtime, thread } = yield* resumed(
3883 [
3884 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3885 promptAccepted,
3886 { type: "runtime_exit", status: "success" },
3887 out("event.subscribe"),
3888 ...Array.from({ length: 6 }, () => [
3889 out("session.active"),
3890 reply("session.active", { status, body: { message: "Recovering" } }),
3891 ]).flat(),
3892 ...reconnected({ [SESSION]: { type: "running" } }).slice(2),
3893 ...openRequests([]),
3894 event("session.execution.succeeded", { sessionID: SESSION }),
3895 ],
3896 {
3897 beforeResponse: (path) =>
3898 path === "/api/session/active"
3899 ? Effect.gen(function* () {
3900 attempt += 1;
3901 yield* Queue.offer(attempts, undefined);
3902 if (attempt === 7) yield* Deferred.await(allowRecovery);
3903 })
3904 : Effect.void,
3905 },
3906 );
3907 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3908 yield* runtime.startTurn(turnInput(thread));
3909 for (let retry = 0; retry < 6; retry += 1) {
3910 yield* Queue.take(attempts);
3911 yield* TestClock.adjust("30 seconds");
3912 }
3913 yield* Queue.take(attempts);
3914 yield* Deferred.succeed(allowRecovery, undefined);
3915 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3916 }),
3917 );
3918
3919 it.effect(
3920 "keeps a $skill found on the first read when the reread after the scan comes back empty",
3921 () =>
3922 Effect.gen(function* () {
3923 const prompts: Array<unknown> = [];
3924 const greet = {
3925 id: "greet",
3926 name: "greet",
3927 path: `${WORK}/.opencode/skills/greet/SKILL.md`,
3928 content: "Say hello.",
3929 };
3930 const { runtime, thread } = yield* resumed(
3931 [
3932 out("skill.list", { "location[directory]": WORK }),
3933 reply("skill.list", { location: { directory: WORK }, data: [greet] }),
3934 ...directoryModels(WORK),
3935 out("skill.list", { "location[directory]": WORK }),
3936 reply("skill.list", { location: { directory: WORK }, data: [] }),
3937 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3938 promptAccepted,
3939 event("session.execution.succeeded", { sessionID: SESSION }),
3940 ],
3941 { onPrompt: (input) => prompts.push(input) },
3942 );
3943 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3944 yield* runtime.startTurn({
3945 ...turnInput(thread),
3946 message: { ...turnInput(thread).message, text: "$greet then echo $HOME" },
3947 });
3948 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3949 assert.deepInclude(prompts[0], { skills: [{ id: "greet" }] });
3950 }),
3951 );
3952
3953 it.effect.each([
3954 {
3955 server: "an external server keeps rejecting requests",
3956 external: true,
3957 status: 503,
3958 tries: 5,
3959 },
3960 { server: "an owned server rejects its credentials", external: false, status: 401, tries: 1 },
3961 ])("bounds recovery when $server", ({ external, status, tries }) =>
3962 Effect.gen(function* () {
3963 const attempts = yield* Queue.unbounded<void>();
3964 const { runtime, thread } = yield* resumed(
3965 [
3966 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3967 promptAccepted,
3968 { type: "runtime_exit", status: "success" },
3969 ...Array.from({ length: tries }, () => [
3970 out("event.subscribe"),
3971 out("session.active"),
3972 reply("session.active", { status, body: { message: "Unavailable" } }),
3973 ]).flat(),
3974 ],
3975 {
3976 external,
3977 beforeResponse: (path) =>
3978 path === "/api/session/active"
3979 ? Queue.offer(attempts, undefined).pipe(Effect.asVoid)
3980 : Effect.void,
3981 },
3982 );
3983 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
3984 yield* runtime.startTurn(turnInput(thread));
3985 for (let attempt = 1; attempt < tries; attempt += 1) {
3986 yield* Queue.take(attempts);
3987 yield* TestClock.adjust("2 seconds");
3988 }
3989 yield* Queue.take(attempts);
3990 assert.equal((yield* Fiber.join(terminal))?.status, "failed");
3991 }),
3992 );
3993
3994 it.effect.each(["lists", "stream"] as const)(
3995 "restores approvals and questions from %s after slow recovery",
3996 (source) =>
3997 Effect.gen(function* () {
3998 const gate = makeProviderReplayGate(["late-permission"]);
3999 let holdReads = false;
4000 const reading = yield* Deferred.make<void>();
4001 const resume = yield* Deferred.make<void>();
4002 const requests = yield* Queue.unbounded<RuntimeRequestId>();
4003 const { runtime, thread } = yield* resumed(
4004 [
4005 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
4006 promptAccepted,
4007 ...reconnected({ [SESSION]: { type: "running" } }),
4008 ...openRequests(
4009 source === "lists" ? [shellAsk.data] : [],
4010 source === "lists" ? [colorForm] : [],
4011 ),
4012 ...(source === "stream"
4013 ? [
4014 event("permission.asked", shellAsk.data, "late-permission"),
4015 event("form.created", { form: colorForm }),
4016 ]
4017 : []),
4018 out("permission.reply", {
4019 sessionID: SESSION,
4020 requestID: shellAsk.data.id,
4021 decision: "once",
4022 }),
4023 reply("permission.reply", null),
4024 out("session.form.reply", {
4025 sessionID: SESSION,
4026 formID: colorForm.id,
4027 answer: { q0: "Red" },
4028 }),
4029 reply("session.form.reply", null),
4030 event("session.execution.succeeded", { sessionID: SESSION }),
4031 ],
4032 {
4033 supervised: true,
4034 replayGate: gate,
4035 beforeResponse: (path) =>
4036 holdReads && path.endsWith(source === "stream" ? "/form" : "/message")
4037 ? Deferred.succeed(reading, undefined).pipe(Effect.andThen(Deferred.await(resume)))
4038 : Effect.void,
4039 },
4040 );
4041 const ended = yield* Deferred.make<string>();
4042 yield* runtime.events.pipe(
4043 Stream.runForEach((event) =>
4044 Effect.gen(function* () {
4045 if (
4046 event.type === "runtime_request.updated" &&
4047 event.runtimeRequest.status === "pending"
4048 ) {
4049 yield* Queue.offer(requests, event.runtimeRequest.id);
4050 }
4051 if (event.type === "turn.terminal") {
4052 yield* Deferred.succeed(ended, event.status);
4053 }
4054 }),
4055 ),
4056 Effect.forkScoped,
4057 );
4058 holdReads = true;
4059 yield* runtime.startTurn(turnInput(thread, bigPickle, "approval-required"));
4060 yield* Deferred.await(reading);
4061 if (source === "stream") {
4062 yield* Effect.promise(() => gate.waitForReached("late-permission"));
4063 gate.release("late-permission");
4064 }
4065 yield* TestClock.adjust("2 minutes");
4066 assert.equal(yield* Queue.size(requests), 0);
4067 yield* Deferred.succeed(resume, undefined);
4068 yield* runtime.respondToRuntimeRequest({
4069 requestId: yield* Queue.take(requests),
4070 decision: "accept",
4071 });
4072 yield* runtime.respondToRuntimeRequest({
4073 requestId: yield* Queue.take(requests),
4074 answers: { q0: "Red" },
4075 });
4076 assert.equal(yield* Deferred.await(ended), "completed");
4077 }),
4078 );
4079
4080 it.effect(
4081 "recovers through a restarted server when the process exits during a history read",
4082 () =>
4083 Effect.gen(function* () {
4084 const reading = yield* Deferred.make<void>();
4085 const cancelled = yield* Deferred.make<void>();
4086 let restarted = false;
4087 let held = false;
4088 const { runtime, thread } = yield* resumed(
4089 [
4090 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
4091 promptAccepted,
4092 ...reconnected({ [SESSION]: { type: "running" } }),
4093 ...reconnected({}).slice(1),
4094 ],
4095 {
4096 // The replay lends one connection; only the first borrow's process exits.
4097 processExit: Effect.suspend(() =>
4098 restarted
4099 ? Effect.never
4100 : Effect.sleep("1 second").pipe(
4101 Effect.tap(() =>
4102 Effect.sync(() => {
4103 restarted = true;
4104 }),
4105 ),
4106 ),
4107 ),
4108 beforeResponse: (path) =>
4109 path.endsWith("/message") && !held
4110 ? Effect.sync(() => (held = true)).pipe(
4111 Effect.andThen(Deferred.succeed(reading, undefined)),
4112 Effect.andThen(Effect.never),
4113 Effect.onInterrupt(() => Deferred.succeed(cancelled, undefined)),
4114 )
4115 : Effect.void,
4116 },
4117 );
4118 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
4119 yield* runtime.startTurn(turnInput(thread));
4120 yield* Deferred.await(reading);
4121 // The exit at 1s cuts the stalled read; the retry 2s later borrows the restarted server.
4122 yield* TestClock.adjust("3 seconds");
4123 yield* Deferred.await(cancelled);
4124 assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
4125 assert.equal(runtime.providerSession.status, "ready");
4126 }),
4127 );
4128
4129 it.effect("releases a recovering session on shutdown without waiting for its HTTP read", () =>
4130 Effect.gen(function* () {
4131 const sessionScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
4132 Scope.close(scope, Exit.void),
4133 );
4134 const reading = yield* Deferred.make<void>();
4135 const cancelled = yield* Deferred.make<void>();
4136 const borrowers = { current: 0 };
4137 const { runtime, thread } = yield* resumed(
4138 [
4139 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
4140 promptAccepted,
4141 ...reconnected({ [SESSION]: { type: "running" } }),
4142 ],
4143 {
4144 borrowers,
4145 beforeResponse: (path) =>
4146 path.endsWith("/message")
4147 ? Deferred.succeed(reading, undefined).pipe(
4148 Effect.andThen(Effect.never),
4149 Effect.onInterrupt(() => Deferred.succeed(cancelled, undefined)),
4150 )
4151 : Effect.void,
4152 },
4153 ).pipe(Effect.provideService(Scope.Scope, sessionScope));
4154 yield* runtime.startTurn(turnInput(thread));
4155 yield* Deferred.await(reading);
4156 assert.equal(borrowers.current, 1);
4157 yield* Scope.close(sessionScope, Exit.void);
4158 yield* Deferred.await(cancelled);
4159 assert.equal(borrowers.current, 0);
4160 }),
4161 );
4162
4163 it.effect("honors a confirmed Stop during recovery and ignores its late backfill", () =>
4164 Effect.gen(function* () {
4165 const recovered = yield* Deferred.make<void>();
4166 const reading = yield* Deferred.make<void>();
4167 const resume = yield* Deferred.make<void>();
4168 const { runtime, thread } = yield* resumed(
4169 [
4170 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
4171 promptAccepted,
4172 ...reconnected({ [SESSION]: { type: "running" } }),
4173 out("session.interrupt", { sessionID: SESSION }),
4174 reply("session.interrupt", { interrupted: true }),
4175 ...openRequests([]),
4176 event("session.execution.interrupted", { sessionID: SESSION }),
4177 event("session.model.selected", {
4178 sessionID: SESSION,
4179 model: { providerID: "opencode", id: "recovered" },
4180 }),
4181 ],
4182 {
4183 beforeResponse: (path) =>
4184 path.endsWith("/message")
4185 ? Deferred.succeed(reading, undefined).pipe(Effect.andThen(Deferred.await(resume)))
4186 : Effect.void,
4187 },
4188 );
4189 const collected: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
4190 const stopped = yield* Deferred.make<void>();
4191 yield* runtime.events.pipe(
4192 Stream.runForEach((event) =>
4193 Effect.gen(function* () {
4194 collected.push(event);
4195 if (
4196 event.type === "provider_thread.updated" &&
4197 event.providerThread.nativeMetadata?.modelSelection?.model === "opencode/recovered"
4198 ) {
4199 yield* Deferred.succeed(recovered, undefined);
4200 }
4201 if (event.type === "turn.terminal") yield* Deferred.succeed(stopped, undefined);
4202 }),
4203 ),
4204 Effect.forkScoped,
4205 );
4206 yield* runtime.startTurn(turnInput(thread));
4207 yield* Deferred.await(reading);
4208 const stopping = yield* runtime
4209 .interruptTurn({
4210 providerThread: thread,
4211 providerTurnId: yield* providerTurnId,
4212 })
4213 .pipe(Effect.forkScoped);
4214 yield* Fiber.join(stopping);
4215 assert.equal(runtime.providerSession.status, "ready");
4216 yield* Deferred.await(stopped);
4217 yield* Deferred.succeed(resume, undefined);
4218 yield* Deferred.await(recovered);
4219 assert.deepEqual(
4220 collected.filter((event) => event.type === "turn.terminal").map((event) => event.status),
4221 ["interrupted"],
4222 );
4223 assert.isFalse(
4224 collected.some(
4225 (event) =>
4226 event.type === "turn_item.updated" && event.turnItem.type === "assistant_message",
4227 ),
4228 );
4229 }),
4230 );
4231
4232 it.effect("keeps a background child's question open past its parent's turn end", () =>
4233 Effect.gen(function* () {
4234 const form = { ...colorForm, sessionID: CHILD };
4235 const { runtime, thread } = yield* resumed([
4236 ...launchedAndRunning,
4237 event("form.created", { form }),
4238 event("session.execution.succeeded", { sessionID: SESSION }),
4239 ]);
4240 const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
4241 const ended = yield* runtime.events.pipe(
4242 Stream.filter(
4243 (event) =>
4244 event.type === "turn.terminal" ||
4245 (event.type === "provider_turn.updated" && event.providerTurn.status === "completed"),
4246 ),
4247 Stream.take(2),
4248 Stream.runCollect,
4249 Effect.forkScoped,
4250 );
4251 yield* runtime.startTurn(withLineage(thread));
4252 const request = yield* Fiber.join(requested);
4253 assert.equal(request?.nativeRequestRef?.nativeId, form.id);
4254 for (const terminal of yield* Fiber.join(ended)) {
4255 assert.deepEqual(
4256 "retainedRuntimeRequestIds" in terminal ? terminal.retainedRuntimeRequestIds : undefined,
4257 [request!.id],
4258 );
4259 }
4260 }),
4261 );
4262
4263 // A cancel without a message aborts the asking session's step, so the child would never report.
4264 it.effect.each(["cancel", "decline"] as const)(
4265 "lets a background child carry on when its question is dismissed with %s",
4266 (decision) =>
4267 Effect.gen(function* () {
4268 const form = { ...colorForm, sessionID: CHILD };
4269 const { runtime, thread } = yield* resumed([
4270 ...launchedAndRunning,
4271 event("form.created", { form }),
4272 event("session.execution.succeeded", { sessionID: SESSION }),
4273 out("session.form.cancel", { sessionID: CHILD, formID: form.id, message: "<string>" }),
4274 reply("session.form.cancel", null),
4275 ]);
4276 const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
4277 yield* runtime.startTurn(withLineage(thread));
4278 const request = yield* Fiber.join(requested);
4279 yield* runtime.respondToRuntimeRequest({ requestId: request!.id, decision });
4280 }),
4281 );
4282
4283 it.effect("keeps a background child's requests when its parent stops during reconciliation", () =>
4284 Effect.gen(function* () {
4285 const reading = yield* Deferred.make<void>();
4286 const resume = yield* Deferred.make<void>();
4287 const recovered = yield* Deferred.make<void>();
4288 const permission = { ...shellAsk.data, sessionID: CHILD };
4289 const form = { ...colorForm, sessionID: CHILD };
4290 const { runtime, thread } = yield* resumed(
4291 [
4292 ...backgroundLaunch(CHILD),
4293 event("permission.asked", permission),
4294 event("form.created", { form }),
4295 ...reconnected({ [SESSION]: { type: "running" }, [CHILD]: { type: "running" } }),
4296 ...openRequests([]),
4297 out("permission.list", { sessionID: CHILD }),
4298 replyData("permission.list", [permission]),
4299 out("session.form.list", { sessionID: CHILD }),
4300 replyData("session.form.list", [form]),
4301 out("session.interrupt", { sessionID: SESSION }),
4302 reply("session.interrupt", { interrupted: true }),
4303 event("session.model.selected", {
4304 sessionID: SESSION,
4305 model: { providerID: "opencode", id: "recovered" },
4306 }),
4307 out("permission.reply", { sessionID: CHILD, requestID: permission.id, decision: "once" }),
4308 reply("permission.reply", null),
4309 out("session.form.reply", { sessionID: CHILD, formID: form.id, answer: { q0: "Red" } }),
4310 reply("session.form.reply", null),
4311 ],
4312 {
4313 beforeResponse: (path) =>
4314 path === `/api/session/${CHILD}/form`
4315 ? Deferred.succeed(reading, undefined).pipe(Effect.andThen(Deferred.await(resume)))
4316 : Effect.void,
4317 },
4318 );
4319 const requests = new Map<
4320 string,
4321 { readonly id: RuntimeRequestId; readonly status: string }
4322 >();
4323 yield* runtime.events.pipe(
4324 Stream.runForEach((event) =>
4325 Effect.gen(function* () {
4326 if (event.type === "runtime_request.updated") {
4327 const nativeId = event.runtimeRequest.nativeRequestRef?.nativeId;
4328 if (nativeId != null) requests.set(nativeId, event.runtimeRequest);
4329 }
4330 if (
4331 event.type === "provider_thread.updated" &&
4332 event.providerThread.nativeMetadata?.modelSelection?.model === "opencode/recovered"
4333 ) {
4334 yield* Deferred.succeed(recovered, undefined);
4335 }
4336 }),
4337 ),
4338 Effect.forkScoped,
4339 );
4340 yield* runtime.startTurn(withLineage(thread));
4341 yield* Deferred.await(reading);
4342 const stopping = yield* runtime
4343 .interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId })
4344 .pipe(Effect.forkScoped);
4345 yield* Fiber.join(stopping);
4346 yield* Deferred.succeed(resume, undefined);
4347 yield* Deferred.await(recovered);
4348 assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
4349 assert.equal(requests.get(permission.id)?.status, "pending");
4350 assert.equal(requests.get(form.id)?.status, "pending");
4351 yield* runtime.respondToRuntimeRequest({
4352 requestId: requests.get(permission.id)!.id,
4353 decision: "accept",
4354 });
4355 yield* runtime.respondToRuntimeRequest({
4356 requestId: requests.get(form.id)!.id,
4357 answers: { q0: "Red" },
4358 });
4359 }),
4360 );
4361
4362 it.effect("keeps a turn still running after a reconnect open for its next events", () =>
4363 Effect.gen(function* () {
4364 const { runtime, thread } = yield* resumed([
4365 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
4366 promptAccepted,
4367 ...reconnected({ [SESSION]: { type: "running" } }),
4368 ...openRequests([]),
4369 event("session.text.ended", {
4370 sessionID: SESSION,
4371 assistantMessageID: "msg_assistant_after",
4372 ordinal: 0,
4373 text: "Arrived on the new stream.",
4374 }),
4375 event("session.execution.succeeded", { sessionID: SESSION }),
4376 ]);
4377 const events = yield* runtime.events.pipe(
4378 Stream.takeUntil((event) => event.type === "turn.terminal"),
4379 Stream.runCollect,
4380 Effect.forkScoped,
4381 );
4382 yield* runtime.startTurn(turnInput(thread));
4383 const collected = yield* Fiber.join(events);
4384 const texts = collected.flatMap((event) =>
4385 event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
4386 ? [event.turnItem.text]
4387 : [],
4388 );
4389 assert.includeMembers(texts, [
4390 "Sent while the stream was down.",
4391 "Arrived on the new stream.",
4392 ]);
4393 assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
4394 }),
4395 );
4396
4397 it.effect("continues a reply still streaming at reconnect from the text already shown", () =>
4398 Effect.gen(function* () {
4399 const delta = (text: string) =>
4400 event("session.text.delta", {
4401 sessionID: SESSION,
4402 assistantMessageID: "msg_assistant_gap",
4403 ordinal: 0,
4404 delta: text,
4405 });
4406 const { runtime, thread } = yield* resumed([
4407 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
4408 promptAccepted,
4409 delta("Sent before the stream dropped"),
4410 // OpenCode saves a block's text only when the block ends.
4411 ...reconnected({ [SESSION]: { type: "running" } }, undefined, {
4412 content: [{ type: "text", text: "" }],
4413 finish: undefined,
4414 }),
4415 ...openRequests([]),
4416 delta(" and after it came back."),
4417 event("session.execution.succeeded", { sessionID: SESSION }),
4418 ]);
4419 const events = yield* runtime.events.pipe(
4420 Stream.takeUntil((event) => event.type === "turn.terminal"),
4421 Stream.runCollect,
4422 Effect.forkScoped,
4423 );
4424 yield* runtime.startTurn(turnInput(thread));
4425 const collected = yield* Fiber.join(events);
4426 const texts = collected.flatMap((event) =>
4427 event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
4428 ? [event.turnItem.text]
4429 : [],
4430 );
4431 assert.deepEqual(texts, [
4432 "Sent before the stream dropped",
4433 "Sent before the stream dropped",
4434 "Sent before the stream dropped and after it came back.",
4435 "Sent before the stream dropped and after it came back.",
4436 ]);
4437 }),
4438 );
4439
4440 it.effect("shows a permission asked while the stream was down, and answers it", () =>
4441 Effect.gen(function* () {
4442 const { runtime, thread } = yield* resumed(
4443 [
4444 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
4445 promptAccepted,
4446 ...reconnected({ [SESSION]: { type: "running" } }),
4447 ...openRequests([shellAsk.data]),
4448 out("permission.reply", {
4449 sessionID: SESSION,
4450 requestID: shellAsk.data.id,
4451 decision: "once",
4452 }),
4453 reply("permission.reply", null),
4454 event("session.execution.succeeded", { sessionID: SESSION }),
4455 ],
4456 { supervised: true },
4457 );
4458 const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
4459 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
4460 yield* runtime.startTurn(turnInput(thread, bigPickle, "approval-required"));
4461 const request = yield* Fiber.join(requested);
4462 assert.equal(request?.nativeRequestRef?.nativeId, shellAsk.data.id);
4463 yield* runtime.respondToRuntimeRequest({ requestId: request!.id, decision: "accept" });
4464 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
4465 }),
4466 );
4467
4468 it.effect("settles a request OpenCode no longer lists after the stream came back", () =>
4469 Effect.gen(function* () {
4470 const { runtime, thread } = yield* resumed(
4471 [
4472 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
4473 promptAccepted,
4474 shellAskEvent,
4475 ...reconnected({ [SESSION]: { type: "running" } }),
4476 ...openRequests([]),
4477 event("session.execution.succeeded", { sessionID: SESSION }),
4478 ],
4479 { supervised: true },
4480 );
4481 const events = yield* runtime.events.pipe(
4482 Stream.takeUntil((event) => event.type === "turn.terminal"),
4483 Stream.runCollect,
4484 Effect.forkScoped,
4485 );
4486 yield* runtime.startTurn(turnInput(thread, bigPickle, "approval-required"));
4487 const collected = yield* Fiber.join(events);
4488 const statuses = collected.flatMap((event) =>
4489 event.type === "runtime_request.updated" ? [event.runtimeRequest.status] : [],
4490 );
4491 assert.deepEqual(statuses, ["pending", "cancelled"]);
4492 assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
4493 }),
4494 );
4495
4496 it.effect.each(["delegate_task", "html_preview", "mcp__acme__edit_document"])(
4497 "keeps MCP %s as a dynamic tool through its lifecycle",
4498 (toolName) =>
4499 Effect.gen(function* () {
4500 const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-wait" };
4501 const name = toolName.startsWith("mcp__") ? toolName : `t3-code-web_${toolName}`;
4502 const input =
4503 toolName !== "delegate_task"
4504 ? { html: "<p>Preview</p>" }
4505 : { task: "Review", mode: "wait" };
4506 const { runtime, thread } = yield* resumed([
4507 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
4508 promptAccepted,
4509 event("session.tool.input.started", { ...tool, name }),
4510 event("session.tool.called", { ...tool, name, input, executed: true }),
4511 event(
4512 "session.tool.success",
4513 {
4514 ...tool,
4515 content: [
4516 { type: "text", text: "Reviewed" },
4517 ...(toolName !== "delegate_task"
4518 ? [{ type: "file", uri: "data:image/png;base64,iVBORw0KGgo=", mime: "image/png" }]
4519 : []),
4520 ],
4521 metadata: {},
4522 executed: true,
4523 },
4524 undefined,
4525 2,
4526 ),
4527 event("session.execution.succeeded", { sessionID: SESSION }),
4528 ]);
4529 const events = yield* runtime.events.pipe(
4530 Stream.takeUntil((event) => event.type === "turn.terminal"),
4531 Stream.runCollect,
4532 Effect.forkScoped,
4533 );
4534 yield* runtime.startTurn(turnInput(thread));
4535 const items = (yield* Fiber.join(events)).flatMap((event) =>
4536 event.type === "turn_item.updated" &&
4537 event.turnItem.nativeItemRef?.nativeId?.endsWith(tool.id)
4538 ? [event.turnItem]
4539 : [],
4540 );
4541 assert.deepEqual(
4542 items.map((item) => item.type),
4543 ["dynamic_tool", "dynamic_tool", "dynamic_tool"],
4544 );
4545 assert.deepEqual(
4546 items.map((item) => item.status),
4547 ["running", "running", "completed"],
4548 );
4549 const last = items.at(-1);
4550 assert.equal(last?.type === "dynamic_tool" ? last.toolName : null, name);
4551 assert.deepEqual(last?.type === "dynamic_tool" ? last.input : null, input);
4552 assert.deepEqual(
4553 toolOutputImages(last?.type === "dynamic_tool" ? last.output : null),
4554 toolName !== "delegate_task" ? [{ mimeType: "image/png", data: "iVBORw0KGgo=" }] : [],
4555 );
4556 }),
4557 );
4558
4559 it.effect.each(["completed", "error", "cancelled"] as const)(
4560 "retains native image job %s after its launch returns",
4561 (outcome) =>
4562 Effect.gen(function* () {
4563 const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-image" };
4564 const notice = (sessionID: string) =>
4565 event("session.inbox.enqueued", {
4566 sessionID,
4567 inboxID: `msg_image_${sessionID}`,
4568 item: {
4569 type: "synthetic",
4570 delivery: "steer",
4571 payload: {
4572 description: "Image generation",
4573 text:
4574 outcome === "completed"
4575 ? "Image outcome retained. Saved image: /work/opencode2/image.png (test/image)."
4576 : "Image outcome retained",
4577 metadata: {
4578 source: "experimental_image_generate",
4579 jobID: "image_test",
4580 state: outcome,
4581 path: "/work/opencode2/image",
4582 },
4583 },
4584 },
4585 });
4586 const { runtime, thread } = yield* resumed(
4587 [
4588 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
4589 promptAccepted,
4590 event("session.tool.input.started", { ...tool, name: "experimental_image_generate" }),
4591 event("session.tool.called", { ...tool, input: { prompt: "A tree" }, executed: false }),
4592 event(
4593 "session.tool.success",
4594 {
4595 ...tool,
4596 content: [{ type: "text", text: "Job launched" }],
4597 metadata: {
4598 jobID: "image_test",
4599 path: "/work/opencode2/image",
4600 model: "test/image",
4601 },
4602 executed: false,
4603 },
4604 undefined,
4605 2,
4606 ),
4607 event("session.execution.succeeded", { sessionID: SESSION }),
4608 notice("ses_other"),
4609 notice(SESSION),
4610 ...(outcome === "completed"
4611 ? [
4612 out("image.read", {
4613 path: "/api/fs/read/image.png",
4614 "location[directory]": WORK,
4615 }),
4616 reply("image.read", { imageBase64: "iVBORw0KGgo=" }),
4617 ]
4618 : []),
4619 ],
4620 { external: true },
4621 );
4622 let launched = false;
4623 const events = yield* runtime.events.pipe(
4624 Stream.takeUntil((e) => {
4625 if (e.type !== "provider_thread.updated") return false;
4626 if (
4627 e.providerThread.pendingBackgroundTasks?.some((task) => task.taskId === "image_test")
4628 )
4629 launched = true;
4630 return launched && e.pendingBackgroundWork === false;
4631 }),
4632 Stream.runCollect,
4633 Effect.forkScoped,
4634 );
4635 yield* runtime.startTurn(turnInput(thread));
4636 const collected = yield* Fiber.join(events);
4637 const items = collected.flatMap((e) =>
4638 e.type === "turn_item.updated" && e.turnItem.nativeItemRef?.nativeId === "call-image"
4639 ? [e.turnItem]
4640 : [],
4641 );
4642 assert.deepEqual(
4643 items.map((item) => item.status),
4644 [
4645 "running",
4646 "running",
4647 "running",
4648 outcome === "error" ? "failed" : outcome === "cancelled" ? "interrupted" : "completed",
4649 ],
4650 );
4651 assert.include(JSON.stringify(items.at(-1)), "Image outcome retained");
4652 if (outcome === "completed") {
4653 const item = items.at(-1);
4654 assert.deepEqual(item?.type === "dynamic_tool" ? toolOutputImages(item.output) : [], [
4655 { mimeType: "image/png", data: "iVBORw0KGgo=" },
4656 ]);
4657 }
4658 const rosters = collected.flatMap((e) =>
4659 e.type === "provider_thread.updated"
4660 ? [e.providerThread.pendingBackgroundTasks ?? []]
4661 : [],
4662 );
4663 assert.isTrue(rosters.some((tasks) => tasks.some((task) => task.taskId === "image_test")));
4664 assert.deepEqual(rosters.at(-1), []);
4665 }),
4666 );
4667
4668 it.effect.each(["history", "list", "late-preview"] as const)(
4669 "recovers native image job outcomes from %s after reconnect",
4670 (source) =>
4671 Effect.gen(function* () {
4672 const { runtime, thread } = yield* resumed(
4673 [
4674 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
4675 promptAccepted,
4676 ...(() => {
4677 const frames: Array<ProviderReplayEntry> = reconnected({}, "succeeded", {
4678 content: [
4679 {
4680 type: "tool",
4681 id: "call-image-gap",
4682 name: "experimental_image_generate",
4683 executed: false,
4684 state: {
4685 status: "completed",
4686 input: { prompt: "A tree" },
4687 content: [{ type: "text", text: "Job launched" }],
4688 metadata: { jobID: "image_gap", path: "/tmp/image", model: "test/image" },
4689 },
4690 time: { created: 2, ran: 2, completed: 2 },
4691 },
4692 ],
4693 });
4694 if (source !== "history")
4695 frames.splice(
4696 2,
4697 0,
4698 out("rpc.call", "<any>"),
4699 reply("rpc.call", { output: null }),
4700 out("job.list", { kind: "shell" }),
4701 reply("job.list", { data: [] }),
4702 );
4703 return frames;
4704 })(),
4705 out("message.list", { sessionID: SESSION, type: "synthetic", limit: "100" }),
4706 reply("message.list", {
4707 data:
4708 source !== "history"
4709 ? []
4710 : [
4711 {
4712 id: "msg_image_gap",
4713 time: { created: 3 },
4714 type: "synthetic",
4715 text: "Recovered image failure",
4716 description: "Image generation",
4717 metadata: {
4718 source: "experimental_image_generate",
4719 jobID: "image_gap",
4720 state: "error",
4721 path: "/tmp/image",
4722 },
4723 },
4724 ],
4725 cursor: {},
4726 }),
4727 ...(source !== "history"
4728 ? [
4729 out("imageJobs", { sessionID: SESSION, kind: "image" }),
4730 reply("imageJobs", {
4731 data: [
4732 {
4733 kind: "image",
4734 id: "image_gap",
4735 sessionID: SESSION,
4736 status: source === "late-preview" ? "completed" : "error",
4737 path: "/tmp/image",
4738 model: "test/image",
4739 time: { started: 2, completed: 3 },
4740 },
4741 ],
4742 }),
4743 ]
4744 : []),
4745 ...(source === "late-preview"
4746 ? [
4747 event("session.inbox.enqueued", {
4748 sessionID: SESSION,
4749 inboxID: "msg_image_late",
4750 item: {
4751 type: "synthetic",
4752 delivery: "steer",
4753 payload: {
4754 description: "Image generation",
4755 text: "Image request finished. Saved image: /tmp/image.png (test/image).",
4756 metadata: {
4757 source: "experimental_image_generate",
4758 jobID: "image_gap",
4759 state: "completed",
4760 path: "/tmp/image",
4761 },
4762 },
4763 },
4764 }),
4765 out("image.read", {
4766 path: "/api/fs/read/image.png",
4767 "location[directory]": "/tmp",
4768 }),
4769 reply("image.read", { imageBase64: "iVBORw0KGgo=" }),
4770 ]
4771 : []),
4772 ],
4773 { ...(source !== "history" ? { version: "2.2.6" as const } : {}), external: true },
4774 );
4775 const events = yield* runtime.events.pipe(
4776 Stream.takeUntil(
4777 (e) =>
4778 e.type === "turn_item.updated" &&
4779 e.turnItem.nativeItemRef?.nativeId === "call-image-gap" &&
4780 (source === "late-preview"
4781 ? e.turnItem.type === "dynamic_tool" &&
4782 toolOutputImages(e.turnItem.output).length > 0
4783 : e.turnItem.status === "failed"),
4784 ),
4785 Stream.runCollect,
4786 Effect.forkScoped,
4787 );
4788 yield* runtime.startTurn(turnInput(thread));
4789 const collected = yield* Fiber.join(events);
4790 assert.include(
4791 JSON.stringify(collected.at(-1)),
4792 source === "late-preview"
4793 ? "Saved image: /tmp/image.png"
4794 : source !== "history"
4795 ? "Image generation error"
4796 : "Recovered image failure",
4797 );
4798 assert.isTrue(
4799 collected.some(
4800 (e) =>
4801 e.type === "provider_thread.updated" &&
4802 e.providerThread.pendingBackgroundTasks?.some((task) => task.taskId === "image_gap"),
4803 ),
4804 );
4805 }),
4806 );
4807
4808 it.effect("settles a recovered image outcome when preview I/O is interrupted", () =>
4809 Effect.gen(function* () {
4810 const reading = yield* Deferred.make<void>();
4811 const interrupted = yield* Deferred.make<void>();
4812 const fs = yield* FileSystem.FileSystem;
4813 const { runtime, thread } = yield* resumed(
4814 [
4815 out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
4816 promptAccepted,
4817 ...reconnected({}, "succeeded", {
4818 content: [
4819 {
4820 type: "tool",
4821 id: "call-image-slow",
4822 name: "experimental_image_generate",
4823 executed: false,
4824 state: {
4825 status: "completed",
4826 input: { prompt: "A tree" },
4827 content: [{ type: "text", text: "Launched" }],
4828 metadata: { jobID: "image_slow", path: "/tmp/image", model: "test/image" },
4829 },
4830 time: { created: 2, ran: 2, completed: 2 },
4831 },
4832 ],
4833 }),
4834 out("message.list", { sessionID: SESSION, type: "synthetic", limit: "100" }),
4835 reply("message.list", {
4836 data: [
4837 {
4838 id: "msg_image_slow",
4839 type: "synthetic",
4840 time: { created: 3 },
4841 text: "Image request finished. Saved image: /tmp/image.png (test/image).",
4842 description: "Image generation",
4843 metadata: {
4844 source: "experimental_image_generate",
4845 jobID: "image_slow",
4846 state: "completed",
4847 path: "/tmp/image",
4848 },
4849 },
4850 ],
4851 cursor: {},
4852 }),
4853 event("session.model.selected", {
4854 sessionID: SESSION,
4855 model: { providerID: "opencode", id: "big-pickle", variant: "recovery-observed" },
4856 }),
4857 ],
4858 {
4859 fileSystem: {
4860 ...fs,
4861 stat: (path) =>
4862 path === "/tmp/image.png"
4863 ? Deferred.succeed(reading, undefined).pipe(
4864 Effect.andThen(Effect.never),
4865 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
4866 )
4867 : fs.stat(path),
4868 },
4869 },
4870 );
4871 const events = yield* runtime.events.pipe(
4872 Stream.takeUntil(
4873 (e) =>
4874 e.type === "provider_thread.updated" &&
4875 e.providerThread.nativeMetadata?.modelSelection?.options?.some(
4876 (option) => option.value === "recovery-observed",
4877 ) === true,
4878 ),
4879 Stream.runCollect,
4880 Effect.forkScoped,
4881 );
4882 yield* runtime.startTurn(turnInput(thread));
4883 yield* Deferred.await(reading);
4884 yield* TestClock.adjust("5 seconds");
4885 yield* Deferred.await(interrupted);
4886 const collected = yield* Fiber.join(events);
4887 assert.isTrue(
4888 collected.some(
4889 (e) =>
4890 e.type === "turn_item.updated" &&
4891 e.turnItem.nativeItemRef?.nativeId === "call-image-slow" &&
4892 e.turnItem.status === "completed",
4893 ),
4894 );
4895 assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
4896 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
4897 );
4898
4899 it.effect.each(["root", "child"] as const)(
4900 "settles %s native image tasks when reconnect attempts fail",
4901 (owner) =>
4902 Effect.gen(function* () {
4903 const attempts = yield* Effect.forEach([0, 1, 2, 3, 4], () => Deferred.make<void>());
4904 let count = 0;
4905 let failures = 0;
4906 const borrowers = {
4907 get current() {
4908 return count;
4909 },
4910 set current(next: number) {
4911 if (next < count && count === 2) {
4912 const attempt = attempts[failures++];
4913 if (attempt !== undefined) Deferred.doneUnsafe(attempt, Effect.void);
4914 }
4915 count = next;
4916 },
4917 };
4918 const tool = {
4919 sessionID: owner === "root" ? SESSION : CHILD,
4920 assistantMessageID: "msg_assistant",
4921 id: "call-image-lost",
4922 };
4923 const { runtime, thread } = yield* resumed(
4924 [
4925 ...(owner === "root"
4926 ? [out("session.prompt", { sessionID: SESSION, text: "<any>" }), promptAccepted]
4927 : [
4928 ...backgroundLaunch(CHILD),
4929 event("session.execution.started", { sessionID: CHILD }),
4930 ]),
4931 event("session.tool.input.started", { ...tool, name: "experimental_image_generate" }),
4932 event(
4933 "session.tool.success",
4934 {
4935 ...tool,
4936 content: [{ type: "text", text: "Launched" }],
4937 metadata: { jobID: "image_lost", path: "/tmp/image", model: "test/image" },
4938 executed: false,
4939 },
4940 undefined,
4941 2,
4942 ),
4943 ...(owner === "child"
4944 ? [event("session.execution.succeeded", { sessionID: CHILD })]
4945 : []),
4946 event("session.execution.succeeded", { sessionID: SESSION }),
4947 { type: "runtime_exit", status: "success" },
4948 ],
4949 // A live owned server is retried until it answers; only an external one runs out of attempts.
4950 { borrowers, external: true },
4951 );
4952 const events = yield* runtime.events.pipe(Stream.runCollect, Effect.forkScoped);
4953 yield* runtime.startTurn(withLineage(thread));
4954 yield* Deferred.await(attempts[0]!);
4955 for (const attempt of attempts.slice(1)) {
4956 yield* TestClock.adjust("2 seconds");
4957 yield* Deferred.await(attempt);
4958 }
4959 const collected = yield* Fiber.join(events);
4960 assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
4961 assert.isTrue(
4962 collected.some(
4963 (e) =>
4964 e.type === "turn_item.updated" &&
4965 e.turnItem.nativeItemRef?.nativeId ===
4966 (owner === "root" ? tool.id : `${CHILD}:${tool.id}`) &&
4967 e.turnItem.status === "failed",
4968 ),
4969 );
4970 const rootSnapshots = collected.flatMap((e) =>
4971 e.type === "provider_thread.updated" && e.providerThread.id === thread.id ? [e] : [],
4972 );
4973 assert.isFalse(rootSnapshots.at(-1)?.pendingBackgroundWork);
4974 assert.deepEqual(rootSnapshots.at(-1)?.providerThread.pendingBackgroundTasks, []);
4975 assert.isTrue(
4976 rootSnapshots.some((e) =>
4977 e.providerThread.pendingBackgroundTasks?.some((task) => task.taskId === "image_lost"),
4978 ),
4979 );
4980 }),
4981 );
4982
4983 it.effect("projects successful native todo updates into one checklist", () =>
4984 Effect.gen(function* () {
4985 const updates = [
4986 [
4987 { content: " Inspect code ", status: "completed" },
4988 { content: "Implement", status: "in_progress" },
4989 { content: "Verify", status: "pending" },
4990 { content: "Abandoned", status: "cancelled" },
4991 ],
4992 [{ content: "Inspect code", status: "completed" }],
4993 [{ content: "Abandoned", status: "cancelled" }],
4994 [],
4995 [{ content: "Follow up", status: "pending" }],
4996 ];
4997 const tool = (id: string) => ({
4998 sessionID: SESSION,
4999 assistantMessageID: "msg_assistant",
5000 id,
Showing first 5,000 of 8,734 lines. View raw