sailfork / t3code-github / apps/ server/ src/ orchestration-v2/ Adapters/ OpenCode2AdapterV2.test.ts

import * as NodeURL from "node:url";
import { toolOutputImages } from "@t3tools/shared/toolOutput";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import {
  ChatAttachmentId,
  ChatFileAttachment,
  ChatImageAttachment,
  CheckpointId,
  EnvironmentId,
  MessageId,
  NodeId,
  ProviderInstanceId,
  ProviderSessionId,
  ProviderThreadId,
  ProviderTurnId,
  RunAttemptId,
  RunId,
  ThreadId,
  type ModelSelection,
  type OrchestrationV2AppThread,
  type OrchestrationV2ProviderFailure,
  type OrchestrationV2ProviderThread,
  type OrchestrationV2ProviderTurn,
  type ProviderReplayEntry,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as Exit from "effect/Exit";
import { TestClock } from "effect/testing";

import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import {
  OPENCODE_2_STILL_STOPPING,
  OPENCODE_PROVIDER,
  t3McpServerName,
} from "@t3tools/provider-opencode/testing";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { openCode2ReplayRuntime } from "./OpenCode2AdapterV2.testkit.ts";
import {
  makeProviderReplayGate,
  type ProviderReplayGate,
} from "@t3tools/provider-testing/replayGate";

const SESSION = "ses_f148ca2deffeJcwCnRQtb0YFNX";
const WORK = "/work/opencode2";
const instanceId = ProviderInstanceId.make("opencode");
const threadId = ThreadId.make("thread:opencode2-adapter");

const out = (type: string, input?: unknown): ProviderReplayEntry => ({
  type: "expect_outbound",
  frame: input === undefined ? { type } : { type, input },
});
const reply = (operation: string, data: unknown): ProviderReplayEntry => ({
  type: "emit_inbound",
  frame: { type: "sdk.response", operation, data },
});
const replyData = (operation: string, data: unknown) => reply(operation, { data });
const event = (
  type: string,
  data: Record<string, unknown>,
  label?: string,
  version = 1,
): ProviderReplayEntry => ({
  type: "emit_inbound",
  frame: {
    type: "sdk.event",
    event: {
      id: `evt_${type.replaceAll(".", "")}0000`,
      created: 1,
      type,
      data,
      durable: { ...durable.durable, version },
    },
  },
  ...(label === undefined ? {} : { label }),
});
const durable = { durable: { aggregateID: SESSION, seq: 1, version: 1 } };

const mcpRules = [
  { action: "t3-code-*", resource: "*", effect: "deny" },
  { action: "t3-code-thread_opencode2-adapter_*", resource: "*", effect: "allow" },
];
const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, ...mcpRules];
const TITLE = "Prime check";
const sessionInfo = (overrides: Record<string, unknown> = {}) => ({
  id: SESSION,
  title: TITLE,
  permissions: t3Rules,
  projectID: "global",
  model: { id: "big-pickle", providerID: "opencode", variant: "default" },
  cost: 0,
  tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  time: { created: 1790656601394, updated: 1790656601394 },
  location: { directory: WORK },
  ...overrides,
});
const modelCatalog = {
  location: { directory: WORK },
  data: [
    {
      id: "big-pickle",
      modelID: "big-pickle",
      providerID: "opencode",
      family: "big-pickle",
      name: "Big Pickle",
      compatibility: { reasoningField: "reasoning_content" },
      package: "@opencode/ai/providers/openai-compatible",
      settings: { apiKey: "public", baseURL: "https://opencode.ai/zen/v1", provider: "opencode" },
      capabilities: { tools: true, input: ["text"], output: ["text"] },
      variants: [],
      time: { released: 1760659200000 },
      cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }],
      status: "active",
      enabled: true,
      limit: { context: 200000, input: 160000, output: 32000 },
    },
  ],
};

const PROMPT_ID = "msg_0eb735d41001NJee1EvVePJAK5";
const promptAccepted = replyData("session.prompt", {
  id: PROMPT_ID,
  sessionID: SESSION,
  time: { created: 1790656601410 },
  type: "user",
  payload: { text: "hi" },
  delivery: "steer",
});

const noOpenRequests: ReadonlyArray<ProviderReplayEntry> = [
  out("permission.list", { sessionID: SESSION }),
  replyData("permission.list", []),
  out("session.form.list", { sessionID: SESSION }),
  replyData("session.form.list", []),
];

const withInstructions = (
  entries: ReadonlyArray<ProviderReplayEntry>,
): ReadonlyArray<ProviderReplayEntry> => {
  const first = entries.findIndex(
    (entry) =>
      entry.type === "expect_outbound" &&
      typeof entry.frame === "object" &&
      entry.frame !== null &&
      "type" in entry.frame &&
      [
        "session.prompt",
        "session.command",
        "session.compact",
        "command.list",
        "skill.list",
      ].includes(String(entry.frame.type)),
  );
  const after = entries.findIndex(
    (entry, index) =>
      index < first &&
      entry.type === "emit_inbound" &&
      typeof entry.frame === "object" &&
      entry.frame !== null &&
      "operation" in entry.frame &&
      entry.frame.operation === "mcp.add",
  );
  const at = after < 0 ? first : after + 1;
  return first < 0
    ? entries
    : [
        ...entries.slice(0, at),
        out("session.instructions.entry.put", {
          sessionID: SESSION,
          key: "t3-code",
          value: "<any>",
        }),
        reply("session.instructions.entry.put", null),
        ...entries.slice(at),
      ];
};

const openCode2ReplayRuntimeWithInstructions = (
  entries: ReadonlyArray<ProviderReplayEntry>,
  options?: { readonly external?: boolean },
) => openCode2ReplayRuntime(withInstructions(entries), options);

const opening: ReadonlyArray<ProviderReplayEntry> = [
  out("event.subscribe"),
  out("model.list", "<any>"),
  reply("model.list", modelCatalog),
];
const directoryModels = (directory: string): ReadonlyArray<ProviderReplayEntry> => [
  out("model.list", { "location[directory]": directory }),
  reply("model.list", { ...modelCatalog, location: { directory } }),
];

const bigPickle: ModelSelection = { instanceId, model: "opencode/big-pickle" };
const policy = (runtimeMode: "full-access" | "approval-required" = "full-access") => ({
  runtimeMode,
  interactionMode: "default" as const,
  cwd: WORK,
});

const providerThread = (now: DateTime.Utc): OrchestrationV2ProviderThread => ({
  id: ProviderThreadId.make("provider-thread:opencode2-adapter"),
  driver: OPENCODE_PROVIDER,
  providerInstanceId: instanceId,
  providerSessionId: ProviderSessionId.make("provider-session:opencode2-adapter"),
  appThreadId: threadId,
  ownerNodeId: null,
  nativeThreadRef: { driver: OPENCODE_PROVIDER, nativeId: SESSION, strength: "strong" },
  nativeConversationHeadRef: null,
  status: "idle",
  firstRunOrdinal: null,
  lastRunOrdinal: null,
  handoffIds: [],
  forkedFrom: null,
  createdAt: now,
  updatedAt: now,
});

const turnInput = (
  thread: OrchestrationV2ProviderThread,
  modelSelection: ModelSelection = bigPickle,
  runtimeMode: "full-access" | "approval-required" = "full-access",
) => ({
  appThread: { title: TITLE } as OrchestrationV2AppThread,
  threadId,
  runId: RunId.make("run:opencode2-adapter"),
  runOrdinal: 1,
  providerTurnOrdinal: 1,
  attemptId: RunAttemptId.make("attempt:opencode2-adapter"),
  rootNodeId: NodeId.make("node:opencode2-adapter"),
  providerThread: thread,
  message: {
    messageId: MessageId.make("message:opencode2-adapter"),
    text: "hi",
    attachments: [],
    createdBy: "user" as const,
    creationSource: "web" as const,
    scheduledTaskId: undefined,
    senderThreadId: undefined,
  },
  modelSelection,
  runtimePolicy: policy(runtimeMode),
});

const buildPaths = [
  {
    action: "external_directory",
    resource: "/home/.local/share/opencode/tool-output/*",
    effect: "allow",
  },
];
const agentList = {
  location: { directory: WORK },
  data: [
    {
      id: "build",
      name: "Build",
      request: { settings: {}, headers: {}, body: {} },
      description: "The default agent.",
      mode: "primary",
      hidden: false,
      permissions: [{ action: "*", resource: "*", effect: "allow" }, ...buildPaths],
    },
  ],
};
const supervisedRules = [
  { action: "shell", resource: "*", effect: "ask" },
  { action: "edit", resource: "*", effect: "ask" },
  { action: "external_directory", resource: "*", effect: "ask" },
  ...buildPaths,
  ...mcpRules,
];

const shellAsk = {
  data: {
    id: "per_0eb7c4d7e001Pyt8o50Vi4KrOO",
    sessionID: SESSION,
    action: "shell",
    resources: ["echo FIRST"],
    save: ["echo *"],
    source: { type: "tool", messageID: "msg_0eb7c4330001dYFQKuTpfD780v", id: "call_1" },
  },
};
const shellAskEvent = event("permission.asked", shellAsk.data);
const colorForm = {
  id: "frm_0eb79ab35001fkvFECSh3wYNVD",
  sessionID: SESSION,
  title: "Questions",
  metadata: { kind: "question" },
  fields: [
    {
      key: "q0",
      title: "Color preference",
      description: "Which color do you prefer?",
      type: "string",
      options: [{ value: "Red", label: "Red" }],
      custom: true,
    },
  ],
};

const resumed = (
  entries: ReadonlyArray<ProviderReplayEntry>,
  options?: {
    readonly external?: boolean;
    readonly supervised?: boolean;
    readonly replayGate?: ProviderReplayGate;
    readonly attachmentsDir?: string;
    readonly resolveExtractedTextPath?: (path: string) => Effect.Effect<string | undefined>;
    readonly fileSystem?: FileSystem.FileSystem;
    readonly onPrompt?: (input: unknown) => void;
  },
) =>
  Effect.gen(function* () {
    const runtime = yield* openCode2ReplayRuntime(
      withInstructions([
        ...opening,
        out("session.get", { sessionID: SESSION }),
        replyData("session.get", sessionInfo()),
        ...noOpenRequests,
        ...(options?.supervised === true
          ? [
              out("agent.list", "<any>"),
              reply("agent.list", agentList),
              out("session.update", { sessionID: SESSION, permissions: supervisedRules }),
              reply("session.update", null),
            ]
          : []),
        ...entries,
      ]),
      {
        ...(options?.fileSystem === undefined ? {} : { fileSystem: options.fileSystem }),
        ...(options?.onPrompt === undefined ? {} : { onPrompt: options.onPrompt }),
        ...(options?.external === undefined ? {} : { external: options.external }),
        ...(options?.replayGate === undefined ? {} : { replayGate: options.replayGate }),
        ...(options?.attachmentsDir === undefined
          ? {}
          : { attachmentsDir: options.attachmentsDir }),
        ...(options?.resolveExtractedTextPath === undefined
          ? {}
          : { resolveExtractedTextPath: options.resolveExtractedTextPath }),
      },
    );
    const thread = yield* runtime.resumeThread({
      providerThread: providerThread(yield* DateTime.now),
      threadId,
      modelSelection: bigPickle,
      runtimePolicy: policy(options?.supervised === true ? "approval-required" : "full-access"),
    });
    return { runtime, thread };
  });

const requestOf = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime) =>
  runtime.events.pipe(
    Stream.filter(
      (
        event,
      ): event is Extract<
        ProviderAdapter.ProviderAdapterV2Event,
        { type: "runtime_request.updated" }
      > => event.type === "runtime_request.updated",
    ),
    Stream.map((event) => event.runtimeRequest),
    Stream.runHead,
    Effect.map(Option.getOrUndefined),
  );

const terminalOf = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime) =>
  runtime.events.pipe(
    Stream.filter(
      (
        event,
      ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
        event.type === "turn.terminal",
    ),
    Stream.runHead,
    Effect.map(Option.getOrUndefined),
  );

const history = {
  data: [
    {
      id: "msg_0eb732081001RntUJfRtTXOAjd",
      time: { created: 1790656585885 },
      text: "Think carefully step by step about whether 391 is prime, showing your reasoning, then answer in one short sentence.",
      type: "user",
    },
    {
      id: "msg_0eb7320a9001vve3OV5uNi2HRT",
      time: { created: 1790656585925, streamed: 1790656590719, completed: 1790656590736 },
      type: "assistant",
      agent: "build",
      model: { id: "space-bunny-free", providerID: "opencode", variant: "high" },
      content: [
        { type: "reasoning", text: "Check divisibility up to sqrt(391)." },
        { type: "text", text: "391 is not prime: it's the product 17 × 23." },
      ],
      finish: "stop",
      cost: 0,
      tokens: { input: 8701, output: 113, reasoning: 147, cache: { read: 489, write: 0 } },
    },
    {
      id: "msg_0eb733399001NhwTrB32UU6d6H",
      time: { created: 1790656590745 },
      type: "idle",
      outcome: "succeeded",
    },
  ],
  cursor: {},
};

it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
  it.effect("switches the session's model and variant before a turn that changed them", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        out("session.switchModel", {
          sessionID: SESSION,
          model: { providerID: "openrouter", id: "deepseek/deepseek-v4-flash", variant: "high" },
        }),
        reply("session.switchModel", null),
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        promptAccepted,
        event("session.execution.succeeded", { sessionID: SESSION }),
      ]);
      assert.deepEqual(thread.nativeMetadata?.modelSelection, {
        ...bigPickle,
        options: [{ id: "variant", value: "default" }],
      });
      assert.equal(bigPickle.options, undefined);
      const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
      yield* runtime.startTurn(
        turnInput(thread, {
          instanceId,
          model: "openrouter/deepseek/deepseek-v4-flash",
          options: [{ id: "variant", value: "high" }],
        }),
      );
      assert.equal((yield* Fiber.join(terminal))?.status, "completed");
    }).pipe(Effect.scoped),
  );

  it.effect("renames the session before the first turn after the thread was renamed", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        out("session.update", { sessionID: SESSION, title: "Prime factors of 391" }),
        reply("session.update", null),
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        promptAccepted,
        event("session.execution.succeeded", { sessionID: SESSION }),
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        promptAccepted,
        event("session.execution.succeeded", { sessionID: SESSION }),
      ]);
      const renamed = {
        ...turnInput(thread),
        appThread: { title: "Prime factors of 391" } as OrchestrationV2AppThread,
      };
      const first = yield* terminalOf(runtime).pipe(Effect.forkScoped);
      yield* runtime.startTurn(renamed);
      assert.equal((yield* Fiber.join(first))?.status, "completed");
      const second = yield* terminalOf(runtime).pipe(Effect.forkScoped);
      yield* runtime.startTurn({
        ...renamed,
        runId: RunId.make("run:opencode2-adapter:2"),
        attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"),
      });
      assert.equal((yield* Fiber.join(second))?.status, "completed");
    }).pipe(Effect.scoped),
  );

  it.effect("ends a turn on the provider thread it started on", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        promptAccepted,
        event("session.execution.succeeded", { sessionID: SESSION }),
      ]);
      const forkedRow = {
        ...thread,
        id: ProviderThreadId.make("provider-thread:opencode2-adapter:forked-run-row"),
      };
      const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
      yield* runtime.startTurn(turnInput(forkedRow));
      assert.equal((yield* Fiber.join(terminal))?.providerThreadId, forkedRow.id);
    }).pipe(Effect.scoped),
  );

  // regression: #18315 OpenCode Go quota stops were not shown as usage limits
  it.effect.each([
    ["provider.quota", "usage_limit"],
    ["provider.rate-limit", "usage_limit"],
    ["provider", "provider_error"],
  ] as const)("classifies a %s execution failure as %s", ([code, failureClass]) =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        promptAccepted,
        event("session.execution.failed", {
          sessionID: SESSION,
          error: { type: code, message: "Provider rejected the request" },
        }),
      ]);
      const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
      yield* runtime.startTurn(turnInput(thread));
      const ended = yield* Fiber.join(terminal);
      assert.equal(ended?.status, "failed");
      assert.deepEqual(ended?.failure, {
        class: failureClass,
        code,
        message: "Provider rejected the request",
        retryable: null,
      });
    }).pipe(Effect.scoped),
  );

  // OpenCode types an empty balance as provider.quota too, but answers it with
  // HTTP 402 and it never resets. Usage windows and budgets arrive as 429.
  it.effect.each([
    {
      name: "an out-of-funds provider.quota (402)",
      failureClass: "provider_error",
      error: {
        type: "provider.quota",
        message: "Upstream request failed: Insufficient account funds",
        status: 402,
      },
    },
    {
      name: "a provider.quota usage window (429)",
      failureClass: "usage_limit",
      error: {
        type: "provider.quota",
        message: "Subscription quota exceeded.",
        status: 429,
        response: {
          body: JSON.stringify({
            type: "error",
            error: { type: "GoUsageLimitError", message: "Subscription quota exceeded." },
          }),
        },
      },
    },
    {
      name: "a provider.quota account budget (429)",
      failureClass: "usage_limit",
      error: {
        type: "provider.quota",
        message: "Upstream request failed: Account budget exceeded",
        status: 429,
      },
    },
    {
      name: "a provider.rate-limit failure (429)",
      failureClass: "usage_limit",
      error: {
        type: "provider.rate-limit",
        message: "Rate limit exceeded: free-models-per-min.",
        status: 429,
      },
    },
    {
      name: "a Claude limit without a reset timestamp",
      failureClass: "usage_limit",
      error: {
        type: "provider.unknown",
        message: "You've hit your session limit · resets 5:20pm (Europe/Berlin)",
      },
    },
    {
      name: "an unrelated provider.unknown failure",
      failureClass: "provider_error",
      error: {
        type: "provider.unknown",
        message: "Request failed. Resets at 2026-11-02T20:00:00Z.",
      },
    },
  ] as const)("classifies $name as $failureClass", ({ error, failureClass }) =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        promptAccepted,
        event("session.execution.failed", { sessionID: SESSION, error }),
      ]);
      const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
      yield* runtime.startTurn(turnInput(thread));
      const ended = yield* Fiber.join(terminal);
      assert.equal(ended?.status, "failed");
      assert.deepEqual(ended?.failure, {
        class: failureClass,
        code: error.type,
        message: error.message,
        retryable: null,
      });
    }).pipe(Effect.scoped),
  );

  // regression: #29289 Claude weekly limits through claude-agent lost their usage-limit reset
  it.effect(
    "classifies a Claude weekly limit as a usage limit that resets at its reported time",
    () =>
      Effect.gen(function* () {
        const message =
          "You've hit your weekly limit · resets 9pm (Europe/Paris) Resets at 2026-11-02T20:00:00.000Z.";
        const { runtime, thread } = yield* resumed([
          out("session.prompt", { sessionID: SESSION, text: "<any>" }),
          promptAccepted,
          event("session.execution.failed", {
            sessionID: SESSION,
            error: { type: "provider.unknown", message },
          }),
        ]);
        const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
        yield* runtime.startTurn(turnInput(thread));
        const ended = yield* Fiber.join(terminal);
        assert.equal(ended?.status, "failed");
        assert.deepEqual(ended?.failure, {
          class: "usage_limit",
          code: "provider.unknown",
          message,
          retryable: null,
          resetAt: "2026-11-02T20:00:00.000Z",
        });
      }).pipe(Effect.scoped),
  );

  it.effect("ends the turn when its terminal event is one this build cannot decode", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        promptAccepted,
        event("session.execution.interrupted", { sessionID: SESSION, reason: "budget" }),
      ]);
      const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
      yield* runtime.startTurn(turnInput(thread));
      assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
    }).pipe(Effect.scoped),
  );

  it.effect("keeps a turn running through a start event this build cannot decode", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        promptAccepted,
        {
          type: "emit_inbound",
          frame: {
            type: "sdk.event",
            event: {
              id: "evt_executionstartedx",
              created: 1,
              type: "session.execution.started",
              data: { sessionID: SESSION },
              durable: "not-an-envelope",
            },
          },
        },
        event("session.text.started", {
          sessionID: SESSION,
          assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z",
          ordinal: 0,
        }),
        event("session.text.ended", {
          sessionID: SESSION,
          assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z",
          ordinal: 0,
          text: "DONE",
        }),
        event("session.execution.succeeded", { sessionID: SESSION }),
      ]);
      const collected = yield* runtime.events.pipe(
        Stream.takeUntil((event) => event.type === "turn.terminal"),
        Stream.runCollect,
        Effect.forkScoped,
      );
      yield* runtime.startTurn(turnInput(thread));
      const seen = yield* Fiber.join(collected);
      const terminals = seen.filter((event) => event.type === "turn.terminal");
      assert.deepEqual(
        terminals.map((event) => event.type === "turn.terminal" && event.status),
        ["completed"],
      );
      assert.isTrue(
        seen.some(
          (event) =>
            event.type === "turn_item.updated" &&
            event.turnItem.type === "assistant_message" &&
            event.turnItem.text === "DONE",
        ),
      );
    }).pipe(Effect.scoped),
  );

  it.effect("stops running turns on an external server when the session closes", () =>
    Effect.gen(function* () {
      const scope = yield* Scope.make();
      const { runtime, thread } = yield* resumed(
        [
          out("session.prompt", { sessionID: SESSION, text: "<any>" }),
          promptAccepted,
          out("session.interrupt", { sessionID: SESSION }),
          reply("session.interrupt", { interrupted: true }),
        ],
        { external: true },
      ).pipe(Scope.provide(scope));
      yield* runtime.startTurn(turnInput(thread));
      yield* Scope.close(scope, Exit.void);
    }),
  );

  it.effect("sends nothing for a turn stopped while extracting document text", () =>
    Effect.gen(function* () {
      const resolving = yield* Deferred.make<void>();
      const release = yield* Deferred.make<void>();
      const prompts: Array<unknown> = [];
      const { runtime, thread } = yield* resumed(
        [
          out("session.instructions.entry.put", {
            sessionID: SESSION,
            key: "t3-code",
            value: "<any>",
          }),
          reply("session.instructions.entry.put", null),
          out("session.interrupt", { sessionID: SESSION }),
          reply("session.interrupt", { interrupted: false }),
        ],
        {
          attachmentsDir: "/attachments",
          onPrompt: (input) => prompts.push(input),
          resolveExtractedTextPath: () =>
            Effect.gen(function* () {
              yield* Deferred.succeed(resolving, undefined);
              yield* Deferred.await(release);
              return undefined;
            }),
        },
      );
      const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
      const started = yield* runtime
        .startTurn({
          ...turnInput(thread),
          message: {
            ...turnInput(thread).message,
            attachments: [
              ChatFileAttachment.make({
                type: "file",
                id: ChatAttachmentId.make(
                  "thread-opencode2-adapter-12345678-1234-1234-1234-123456789abc",
                ),
                name: "report.rtf",
                mimeType: "application/rtf",
                sizeBytes: 4,
              }),
            ],
          },
        })
        .pipe(Effect.forkScoped);
      yield* Deferred.await(resolving);
      yield* runtime.interruptTurn({
        providerThread: thread,
        providerTurnId: yield* providerTurnId,
      });
      yield* Deferred.succeed(release, undefined);
      yield* Fiber.join(started);
      assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
      assert.lengthOf(prompts, 0);
    }).pipe(Effect.scoped),
  );

  const childCreated = (child: string) => ({
    sessionID: child,
    slug: "proud-canyon",
    version: "2.0.18",
    projectID: "global",
    parentID: SESSION,
    location: { directory: WORK },
    subpath: "",
    title: "Sleep",
    agent: "general",
    model: { id: "big-pickle", providerID: "opencode", variant: "default" },
  });
  const backgroundLaunch = (child: string): ReadonlyArray<ProviderReplayEntry> => {
    const call = "call-background";
    const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: call };
    return [
      out("session.prompt", { sessionID: SESSION, text: "<any>" }),
      promptAccepted,
      event("session.execution.started", { sessionID: SESSION }),
      event("session.tool.input.started", { ...tool, name: "subagent" }),
      event("session.tool.called", {
        ...tool,
        name: "subagent",
        input: { description: "Sleep", prompt: "sleep", background: true },
        executed: false,
      }),
      event("session.created", childCreated(child)),
      event("session.tool.progress", {
        ...tool,
        metadata: { sessionID: child, status: "running" },
      }),
    ];
  };
  const withLineage = (thread: OrchestrationV2ProviderThread) => ({
    ...turnInput(thread),
    appThread: {
      id: threadId,
      title: TITLE,
      lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
    } as OrchestrationV2AppThread,
  });
  const continuationTurn = (
    thread: OrchestrationV2ProviderThread,
    offer: ProviderContinuationRequests.ProviderContinuationRequest,
    suffix = "wake",
  ) => ({
    ...withLineage(thread),
    runId: RunId.make(`run:opencode2-adapter:${suffix}`),
    runOrdinal: 2,
    providerTurnOrdinal: 2,
    attemptId: RunAttemptId.make(`attempt:opencode2-adapter:${suffix}`),
    message: {
      ...turnInput(thread).message,
      messageId: offer.messageId!,
      text: offer.detail ?? "",
      createdBy: "agent" as const,
      creationSource: "provider" as const,
    },
  });
  const CHILD = "ses_f1485c529ffea4URrYruwEg0Ja";
  const watchBackgroundTurn = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime) =>
    Effect.gen(function* () {
      const attached = yield* Deferred.make<void>();
      const terminal = yield* runtime.events.pipe(
        Stream.tap((event) =>
          event.type === "subagent.updated" && event.subagent.childThreadId !== null
            ? Deferred.succeed(attached, undefined)
            : Effect.void,
        ),
        Stream.filter(
          (
            event,
          ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
            event.type === "turn.terminal",
        ),
        Stream.runHead,
        Effect.map(Option.getOrUndefined),
        Effect.forkScoped,
      );
      return { attached: Deferred.await(attached), terminal: Fiber.join(terminal) };
    });
  it.effect("keeps background subagents running when a turn is interrupted to restart it", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        ...backgroundLaunch(CHILD),
        out("session.interrupt", { sessionID: SESSION }),
        reply("session.interrupt", { interrupted: true }),
        event("session.execution.interrupted", { sessionID: SESSION }),
      ]);
      const watch = yield* watchBackgroundTurn(runtime);
      yield* runtime.startTurn(withLineage(thread));
      yield* watch.attached;
      yield* runtime.interruptTurn({
        providerThread: thread,
        providerTurnId: yield* providerTurnId,
      });
      assert.equal((yield* watch.terminal)?.status, "interrupted");
      assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
    }).pipe(Effect.scoped),
  );

  it.effect("stops background subagents on a user Stop", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        ...backgroundLaunch(CHILD),
        out("session.interrupt", { sessionID: CHILD }),
        reply("session.interrupt", { interrupted: true }),
        out("session.interrupt", { sessionID: SESSION }),
        reply("session.interrupt", { interrupted: true }),
        event("session.execution.interrupted", { sessionID: SESSION }),
      ]);
      const watch = yield* watchBackgroundTurn(runtime);
      yield* runtime.startTurn(withLineage(thread));
      yield* watch.attached;
      yield* runtime.interruptTurn({
        providerThread: thread,
        providerTurnId: yield* providerTurnId,
        requestRuntimeRestart: true,
      });
      assert.equal((yield* watch.terminal)?.status, "interrupted");
      assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
    }).pipe(Effect.scoped),
  );

  it.effect("gives a background subagent the rules of a mode changed while it runs", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        ...backgroundLaunch(CHILD),
        event("session.execution.succeeded", { sessionID: SESSION }),
        out("agent.list", "<any>"),
        reply("agent.list", agentList),
        out("session.update", { sessionID: SESSION, permissions: supervisedRules }),
        reply("session.update", null),
        out("session.update", {
          sessionID: CHILD,
          permissions: [...supervisedRules.slice(0, 3), ...mcpRules],
        }),
        reply("session.update", null),
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        promptAccepted,
        event("session.execution.succeeded", { sessionID: SESSION }),
      ]);
      const firstEnded = yield* Deferred.make<void>();
      const ended = yield* runtime.events.pipe(
        Stream.filter(
          (
            event,
          ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
            event.type === "turn.terminal",
        ),
        Stream.tap(() => Deferred.succeed(firstEnded, undefined)),
        Stream.take(2),
        Stream.runCollect,
        Effect.forkScoped,
      );
      yield* runtime.startTurn(withLineage(thread));
      yield* Deferred.await(firstEnded);
      yield* runtime.startTurn({
        ...withLineage(thread),
        runId: RunId.make("run:opencode2-adapter:2"),
        runOrdinal: 2,
        providerTurnOrdinal: 2,
        attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"),
        runtimePolicy: policy("approval-required"),
      });
      assert.deepEqual(
        [...(yield* Fiber.join(ended))].map((terminal) => terminal.status),
        ["completed", "completed"],
      );
    }).pipe(Effect.scoped),
  );

  it.effect(
    "keeps a finished background subagent's queued report pending until its native continuation ends",
    () =>
      Effect.gen(function* () {
        const gate = makeProviderReplayGate(["continue"]);
        const { runtime, thread } = yield* resumed(
          [
            ...nestedLaunch,
            event("session.execution.succeeded", { sessionID: DEEP }),
            deepReport("completed"),
            event("session.model.selected", {
              sessionID: SESSION,
              model: { providerID: "opencode", id: "big-pickle", variant: "thinking" },
            }),
            event("session.execution.started", { sessionID: MIDDLE }, "continue"),
            event("session.inbox.delivered", { sessionID: MIDDLE, inboxID: "msg_deep_report" }),
            event("session.text.ended", {
              sessionID: MIDDLE,
              assistantMessageID: "msg_native_continuation",
              ordinal: 0,
              text: "GRANDCHILD_OK",
            }),
            event("session.execution.succeeded", { sessionID: MIDDLE }),
            event("session.model.selected", {
              sessionID: SESSION,
              model: { providerID: "opencode", id: "big-pickle", variant: "none" },
            }),
          ],
          { replayGate: gate },
        );
        const queued = yield* Deferred.make<void>();
        const drained = yield* Deferred.make<void>();
        const timeline: Array<boolean | string> = [];
        yield* runtime.events.pipe(
          Stream.runForEach((event) =>
            Effect.gen(function* () {
              if (event.type === "provider_thread.updated") {
                if (
                  event.providerThread.nativeThreadRef?.nativeId === MIDDLE &&
                  event.pendingBackgroundWork !== undefined
                ) {
                  timeline.push(event.pendingBackgroundWork);
                }
                if (event.providerThread.id === thread.id) {
                  const variant =
                    event.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value;
                  if (variant === "thinking") yield* Deferred.succeed(queued, undefined);
                  if (variant === "none") yield* Deferred.succeed(drained, undefined);
                }
              }
              if (
                event.type === "provider_turn.updated" &&
                event.providerTurn.nativeTurnRef?.nativeId === `${MIDDLE}:turn:2`
              ) {
                timeline.push(event.providerTurn.status);
              }
              if (event.type === "message.updated" && event.message.text === "GRANDCHILD_OK") {
                timeline.push(event.message.text);
              }
            }),
          ),
          Effect.forkScoped,
        );
        yield* runtime.startTurn(withLineage(thread));
        yield* Deferred.await(queued);
        assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
        assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
        assert.strictEqual(timeline.at(-1), true);
        timeline.length = 0;
        gate.release("continue");
        yield* Deferred.await(drained);
        assert.deepEqual(
          timeline.filter((entry) => typeof entry === "string"),
          ["running", "GRANDCHILD_OK", "completed"],
        );
        assert.isAbove(timeline.indexOf(false), timeline.indexOf("completed"));
        assert.strictEqual(timeline.at(-1), false);
        assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
      }).pipe(Effect.scoped),
  );

  const returnedRunning = (id: string): ProviderReplayEntry => ({
    type: "emit_inbound",
    frame: {
      type: "sdk.event",
      event: {
        id: `evt_toolsuccess_${id}`,
        created: 1,
        type: "session.tool.success",
        data: {
          sessionID: SESSION,
          assistantMessageID: "msg_assistant",
          id,
          content: [{ type: "text", text: "The subagent is working in the background." }],
          metadata: { sessionID: CHILD, status: "running" },
          executed: true,
        },
        durable: { aggregateID: SESSION, seq: 1, version: 2 },
      },
    },
  });
  const callAgain = (input: Record<string, unknown>): ReadonlyArray<ProviderReplayEntry> => {
    const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-again" };
    return [
      event("session.tool.input.started", { ...tool, name: "subagent" }),
      event("session.tool.called", {
        ...tool,
        name: "subagent",
        input: { description: "Again", prompt: "also this", sessionID: CHILD, ...input },
        executed: false,
      }),
      event("session.tool.progress", {
        ...tool,
        metadata: { sessionID: CHILD, status: "running" },
      }),
      out("session.update", { sessionID: CHILD, permissions: "<any>" }),
      reply("session.update", null),
      returnedRunning(tool.id),
    ];
  };
  const childReport = (inboxID: string, text: string) =>
    event("session.inbox.enqueued", {
      inboxID,
      sessionID: SESSION,
      item: {
        type: "synthetic",
        payload: {
          text: `<subagent sessionID="${CHILD}" state="completed" description="Sleep">\n${text}\n</subagent>`,
          description: "Sleep",
          metadata: { source: "subagent", childID: CHILD, agent: "General", state: "completed" },
        },
        delivery: "steer",
      },
    });
  const watchCalls = (
    runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime,
    thread: OrchestrationV2ProviderThread,
  ) =>
    Effect.gen(function* () {
      const calls = new Map<string, { status: string; result: string | null }>();
      const childTurns = new Map<string, string>();
      const callsAtChildTurnStart = new Map<
        string,
        Record<string, { status: string; result: string | null }>
      >();
      const state: { roster: ReadonlyArray<unknown> | undefined } = { roster: undefined };
      let wake = yield* Deferred.make<void>();
      yield* runtime.events.pipe(
        Stream.tap((event) =>
          Effect.gen(function* () {
            if (event.type === "subagent.updated" && event.subagent.title !== null) {
              calls.set(event.subagent.title, {
                status: event.subagent.status,
                result: event.subagent.result,
              });
            }
            if (event.type === "provider_thread.updated" && event.providerThread.id === thread.id) {
              state.roster = event.providerThread.pendingBackgroundTasks;
            }
            const id =
              event.type === "provider_turn.updated"
                ? event.providerTurn.nativeTurnRef?.nativeId
                : undefined;
            if (
              event.type === "provider_turn.updated" &&
              id?.startsWith(`${CHILD}:turn:`) === true
            ) {
              if (!childTurns.has(id)) {
                callsAtChildTurnStart.set(id, Object.fromEntries(calls));
              }
              childTurns.set(id, event.providerTurn.status);
            }
            yield* Deferred.succeed(wake, undefined);
          }),
        ),
        Stream.runDrain,
        Effect.forkScoped,
      );
      const until = (check: () => boolean): Effect.Effect<void> =>
        Effect.suspend(() => {
          if (check()) return Effect.void;
          return Effect.gen(function* () {
            wake = yield* Deferred.make<void>();
            if (check()) return;
            yield* Deferred.await(wake);
            yield* until(check);
          });
        });
      return { calls, callsAtChildTurnStart, childTurns, state, until };
    });
  const launchedAndRunning = [
    ...backgroundLaunch(CHILD),
    returnedRunning("call-background"),
    event("session.execution.started", { sessionID: CHILD }),
  ];

  it.effect("settles a background subagent that fails, so no work is left pending", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        ...launchedAndRunning,
        // The parent turn ends, and the background child fails: it reports
        // nothing back, so its call has to end with the failure.
        event("session.execution.succeeded", { sessionID: SESSION }),
        event("session.execution.failed", {
          sessionID: CHILD,
          error: { type: "provider.quota", message: "Rate limit exceeded." },
        }),
      ]);
      const watch = yield* watchCalls(runtime, thread);
      yield* runtime.startTurn(withLineage(thread));
      yield* watch.until(
        () => watch.calls.get("Sleep")?.status === "failed" && watch.state.roster?.length === 0,
      );
      assert.deepEqual(watch.state.roster, []);
      assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
    }).pipe(Effect.scoped),
  );

  // regression: #21979 a failed background subagent pinned its thread as busy
  it.effect("settles the background call a foreground call joined to a failed child", () =>
    Effect.gen(function* () {
      const again = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-again" };
      const { runtime, thread } = yield* resumed([
        ...launchedAndRunning,
        // A foreground call joins the running background child. It is only
        // marked background once its own tool call returns, so the child can
        // fail while this call is still the foreground one.
        event("session.tool.input.started", { ...again, name: "subagent" }),
        event("session.tool.called", {
          ...again,
          name: "subagent",
          input: { description: "Again", prompt: "also this", sessionID: CHILD },
          executed: false,
        }),
        event("session.tool.progress", {
          ...again,
          metadata: { sessionID: CHILD, status: "running" },
        }),
        out("session.update", { sessionID: CHILD, permissions: "<any>" }),
        reply("session.update", null),
        // The child fails while the joined call is still the foreground one.
        event("session.execution.failed", {
          sessionID: CHILD,
          error: { type: "provider.quota", message: "Rate limit exceeded." },
        }),
        event("session.execution.succeeded", { sessionID: SESSION }),
      ]);
      const watch = yield* watchCalls(runtime, thread);
      yield* runtime.startTurn(withLineage(thread));
      yield* watch.until(
        () =>
          watch.calls.get("Sleep")?.status === "failed" &&
          watch.calls.get("Again")?.status === "failed" &&
          watch.state.roster?.length === 0,
      );
      assert.deepEqual(watch.state.roster, []);
      assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
    }).pipe(Effect.scoped),
  );

  it.effect("settles every call that joined a running subagent with its one report", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        ...launchedAndRunning,
        ...callAgain({ background: true }),
        event("session.execution.succeeded", { sessionID: SESSION }),
        event("session.execution.succeeded", { sessionID: CHILD }),
        childReport("msg_report", "CHILD_OK"),
      ]);
      const watch = yield* watchCalls(runtime, thread);
      yield* runtime.startTurn(withLineage(thread));
      yield* watch.until(
        () =>
          watch.calls.get("Again")?.status === "completed" &&
          watch.calls.get("Sleep")?.status === "completed" &&
          watch.state.roster?.length === 0,
      );
      assert.deepEqual(Object.fromEntries(watch.calls), {
        Sleep: { status: "completed", result: "CHILD_OK" },
        Again: { status: "completed", result: "CHILD_OK" },
      });
    }).pipe(Effect.scoped),
  );

  it.effect("keeps a call to a finished subagent for its own run's report", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        ...launchedAndRunning,
        event("session.execution.succeeded", { sessionID: CHILD }),
        ...callAgain({ background: true }),
        childReport("msg_report_1", "FIRST_OK"),
        event("session.execution.started", { sessionID: CHILD }),
        event("session.execution.succeeded", { sessionID: CHILD }),
        event("session.execution.succeeded", { sessionID: SESSION }),
        childReport("msg_report_2", "SECOND_OK"),
      ]);
      const watch = yield* watchCalls(runtime, thread);
      yield* runtime.startTurn(withLineage(thread));
      yield* watch.until(() => watch.childTurns.has(`${CHILD}:turn:2`));
      assert.deepEqual(watch.callsAtChildTurnStart.get(`${CHILD}:turn:2`), {
        Sleep: { status: "completed", result: "FIRST_OK" },
        Again: { status: "running", result: null },
      });
      yield* watch.until(() => watch.calls.get("Again")?.status === "completed");
      assert.deepEqual(watch.calls.get("Again"), { status: "completed", result: "SECOND_OK" });
    }).pipe(Effect.scoped),
  );

  const MIDDLE = "ses_middle0000000000000000000";
  const DEEP = "ses_grandchild00000000000000";
  const toolOf = (session: string, id: string) => ({
    sessionID: session,
    assistantMessageID: `msg_assistant_${id}`,
    id,
  });
  const deepReport = (state: "completed" | "cancelled") =>
    event("session.inbox.enqueued", {
      inboxID: "msg_deep_report",
      sessionID: MIDDLE,
      item: {
        type: "synthetic",
        payload: {
          text: `<subagent sessionID="${DEEP}" state="${state}" description="Deep">\nDEEP_OK\n</subagent>`,
          description: "Deep",
          metadata: { source: "subagent", childID: DEEP, agent: "General", state },
        },
        delivery: "steer",
      },
    });
  const nestedLaunch: ReadonlyArray<ProviderReplayEntry> = [
    out("session.prompt", { sessionID: SESSION, text: "<any>" }),
    promptAccepted,
    event("session.execution.started", { sessionID: SESSION }),
    event("session.tool.input.started", { ...toolOf(SESSION, "call-middle"), name: "subagent" }),
    event("session.tool.called", {
      ...toolOf(SESSION, "call-middle"),
      name: "subagent",
      input: { description: "Middle", prompt: "delegate" },
      executed: false,
    }),
    event("session.created", { ...childCreated(MIDDLE), title: "Middle" }),
    event("session.tool.progress", {
      ...toolOf(SESSION, "call-middle"),
      metadata: { sessionID: MIDDLE, status: "running" },
    }),
    event("session.execution.started", { sessionID: MIDDLE }),
    event("session.tool.input.started", { ...toolOf(MIDDLE, "call-deep"), name: "subagent" }),
    event("session.tool.called", {
      ...toolOf(MIDDLE, "call-deep"),
      name: "subagent",
      input: { description: "Deep", prompt: "sleep", background: true },
      executed: false,
    }),
    event("session.created", { ...childCreated(DEEP), parentID: MIDDLE, title: "Deep" }),
    event("session.tool.progress", {
      ...toolOf(MIDDLE, "call-deep"),
      metadata: { sessionID: DEEP, status: "running" },
    }),
    event("session.tool.success", {
      ...toolOf(MIDDLE, "call-deep"),
      content: [{ type: "text", text: "The subagent is working in the background." }],
      metadata: { sessionID: DEEP, status: "running", truncated: false },
      executed: false,
    }),
    event("session.execution.started", { sessionID: DEEP }),
    event("session.execution.succeeded", { sessionID: MIDDLE }),
    event("session.tool.success", {
      ...toolOf(SESSION, "call-middle"),
      content: [{ type: "text", text: `<subagent sessionID="${MIDDLE}" state="completed">` }],
      metadata: { sessionID: MIDDLE, status: "completed", truncated: false },
      executed: false,
    }),
    event("session.execution.succeeded", { sessionID: SESSION }),
  ];
  const watchNested = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime) =>
    Effect.gen(function* () {
      const deep: Array<string> = [];
      const middleTurns = new Map<string, string>();
      const pendingSnapshots = new Map<string, boolean>();
      const variants = new Map<string, unknown>();
      let rootVariant: unknown;
      const terminals: Array<string> = [];
      const changed = yield* Deferred.make<void>();
      let wake = changed;
      yield* runtime.events.pipe(
        Stream.tap((event) =>
          Effect.gen(function* () {
            if (event.type === "turn.terminal") terminals.push(event.status);
            if (event.type === "provider_thread.updated") {
              const nativeId = event.providerThread.nativeThreadRef?.nativeId;
              if (nativeId != null && event.pendingBackgroundWork !== undefined) {
                pendingSnapshots.set(nativeId, event.pendingBackgroundWork);
              }
              const variant =
                event.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value;
              if (nativeId != null) variants.set(nativeId, variant);
              if (nativeId === SESSION) rootVariant = variant;
            }
            if (event.type === "subagent.updated" && event.subagent.title === "Deep") {
              deep.push(event.subagent.status);
            }
            const native = event.type === "provider_turn.updated" ? event.providerTurn : undefined;
            const id = native?.nativeTurnRef?.nativeId;
            if (native !== undefined && id?.startsWith(`${MIDDLE}:turn:`) === true) {
              middleTurns.set(id, native.status);
            }
            yield* Deferred.succeed(wake, undefined);
          }),
        ),
        Stream.runDrain,
        Effect.forkScoped,
      );
      const until = (check: () => boolean): Effect.Effect<void> =>
        Effect.suspend(() => {
          if (check()) return Effect.void;
          return Effect.gen(function* () {
            wake = yield* Deferred.make<void>();
            if (check()) return;
            yield* Deferred.await(wake);
            yield* until(check);
          });
        });
      return {
        deep,
        middleTurns,
        terminals,
        pendingSnapshots,
        variants,
        get rootVariant() {
          return rootVariant;
        },
        until,
      };
    });

  it.effect("clears a nested report cancelled during a held wake", () =>
    Effect.gen(function* () {
      const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
      const gate = makeProviderReplayGate(["drained"]);
      const { runtime, thread } = yield* resumed(
        [
          ...backgroundLaunch(CHILD),
          event("session.execution.succeeded", { sessionID: SESSION }),
          event("session.execution.succeeded", { sessionID: CHILD }),
          childReport("msg_report", "CHILD_OK"),
          event("session.execution.started", { sessionID: SESSION }),
          ...nestedLaunch.slice(3, -2),
          event(
            "session.tool.success",
            {
              ...toolOf(SESSION, "call-middle"),
              content: [{ type: "text", text: "MIDDLE_OK" }],
              metadata: { sessionID: MIDDLE, status: "completed", truncated: false },
              executed: false,
            },
            undefined,
            2,
          ),
          event("session.execution.succeeded", { sessionID: DEEP }),
          deepReport("completed"),
          event("session.inbox.cancelled", { sessionID: MIDDLE, inboxID: "msg_deep_report" }),
          event("session.execution.succeeded", { sessionID: SESSION }),
          event("session.model.selected", {
            sessionID: SESSION,
            model: { providerID: "opencode", id: "big-pickle", variant: "thinking" },
          }),
          event(
            "session.model.selected",
            {
              sessionID: SESSION,
              model: { providerID: "opencode", id: "big-pickle", variant: "none" },
            },
            "drained",
          ),
        ],
        { replayGate: gate },
      ).pipe(
        Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
          offer: (request) =>
            Effect.sync(() => {
              offers.push(request);
            }),
          take: Effect.never,
        }),
      );
      const watch = yield* watchNested(runtime);
      yield* runtime.startTurn(withLineage(thread));
      assert.isTrue(yield* Effect.promise(() => gate.waitForReached("drained")));
      yield* watch.until(() => watch.rootVariant === "thinking");
      assert.lengthOf(offers, 1);
      yield* runtime.startTurn(continuationTurn(thread, offers[0]!));
      gate.release("drained");
      yield* watch.until(() => watch.rootVariant === "none");
      assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
      assert.strictEqual(watch.pendingSnapshots.get(MIDDLE), false);
    }).pipe(Effect.scoped),
  );

  it.effect("clears the caller's pending work when a called session's held wake runs", () =>
    Effect.gen(function* () {
      const OTHER = "ses_other00000000000000000000";
      const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
      const gate = makeProviderReplayGate(["drained"]);
      const { runtime, thread } = yield* resumed(
        [
          out("session.get", { sessionID: OTHER }),
          replyData("session.get", sessionInfo({ id: OTHER })),
          out("permission.list", { sessionID: OTHER }),
          replyData("permission.list", []),
          out("session.form.list", { sessionID: OTHER }),
          replyData("session.form.list", []),
          event("session.execution.started", { sessionID: OTHER }),
          event("session.execution.succeeded", { sessionID: OTHER }),
          out("session.prompt", { sessionID: SESSION, text: "<any>" }),
          promptAccepted,
          event("session.execution.started", { sessionID: SESSION }),
          event("session.tool.input.started", {
            ...toolOf(SESSION, "call-other"),
            name: "subagent",
          }),
          event("session.tool.called", {
            ...toolOf(SESSION, "call-other"),
            name: "subagent",
            input: { description: "Other", prompt: "again" },
            executed: false,
          }),
          event("session.tool.progress", {
            ...toolOf(SESSION, "call-other"),
            metadata: { sessionID: OTHER, status: "running" },
          }),
          event("session.tool.success", {
            ...toolOf(SESSION, "call-other"),
            content: [{ type: "text", text: "OTHER_OK" }],
            metadata: { sessionID: OTHER, status: "completed", truncated: false },
            executed: false,
          }),
          event("session.execution.succeeded", { sessionID: SESSION }),
          event(
            "session.model.selected",
            {
              sessionID: OTHER,
              model: { providerID: "opencode", id: "big-pickle", variant: "none" },
            },
            "drained",
          ),
        ],
        { replayGate: gate },
      ).pipe(
        Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
          offer: (request) =>
            Effect.sync(() => {
              offers.push(request);
            }),
          take: Effect.never,
        }),
      );
      const other = yield* runtime.resumeThread({
        providerThread: {
          ...thread,
          id: ProviderThreadId.make("provider-thread:opencode2-adapter:other"),
          nativeThreadRef: { driver: OPENCODE_PROVIDER, nativeId: OTHER, strength: "strong" },
        },
        threadId,
        modelSelection: bigPickle,
        runtimePolicy: policy(),
      });
      const watch = yield* watchNested(runtime);
      yield* watch.until(() => offers.length === 1);
      yield* runtime.startTurn(withLineage(thread));
      assert.isTrue(yield* Effect.promise(() => gate.waitForReached("drained")));
      // The called session's held wake is its caller's pending work too.
      yield* watch.until(() => watch.pendingSnapshots.get(SESSION) === true);
      yield* runtime.startTurn(continuationTurn(other, offers[0]!));
      gate.release("drained");
      yield* watch.until(() => watch.variants.get(OTHER) === "none");
      assert.isFalse(watch.pendingSnapshots.get(OTHER));
      assert.isFalse(watch.pendingSnapshots.get(SESSION));
    }).pipe(Effect.scoped),
  );

  it.effect("stops a foreground subagent's background subagent after the turn ended", () =>
    Effect.gen(function* () {
      const offered = yield* Deferred.make<void>();
      const { runtime, thread } = yield* resumed([
        ...nestedLaunch,
        out("session.interrupt", { sessionID: DEEP }),
        reply("session.interrupt", { interrupted: true }),
        event("session.execution.interrupted", { sessionID: DEEP }),
        deepReport("cancelled"),
        event("session.execution.started", { sessionID: MIDDLE }),
        out("session.interrupt", { sessionID: MIDDLE }),
        reply("session.interrupt", { interrupted: true }),
        event("session.execution.interrupted", { sessionID: MIDDLE }),
        event("session.execution.started", { sessionID: SESSION }),
      ]).pipe(
        Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
          offer: () => Deferred.succeed(offered, undefined).pipe(Effect.asVoid),
          take: Effect.never,
        }),
      );
      const watch = yield* watchNested(runtime);
      yield* runtime.startTurn(withLineage(thread));
      yield* watch.until(() => watch.terminals.length > 0);
      assert.deepEqual(watch.terminals, ["completed"]);
      assert.equal(watch.deep.at(-1), "running");
      assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
      yield* runtime.interruptTurn({
        providerThread: thread,
        providerTurnId: yield* providerTurnId,
        requestRuntimeRestart: true,
      });
      yield* Deferred.await(offered);
      assert.equal(watch.deep.at(-1), "interrupted");
      assert.deepEqual([...watch.middleTurns.keys()], [`${MIDDLE}:turn:1`]);
    }).pipe(Effect.scoped),
  );

  it.effect("stops the turn a foreground subagent runs to answer its background subagent", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        ...nestedLaunch,
        event("session.execution.succeeded", { sessionID: DEEP }),
        deepReport("completed"),
        event("session.execution.started", { sessionID: MIDDLE }),
        event("session.text.ended", {
          sessionID: MIDDLE,
          assistantMessageID: "msg_assistant_answer",
          ordinal: 0,
          text: "Noted.",
        }),
        out("session.interrupt", { sessionID: MIDDLE }),
        reply("session.interrupt", { interrupted: true }),
        event("session.execution.interrupted", { sessionID: MIDDLE }),
      ]);
      const watch = yield* watchNested(runtime);
      yield* runtime.startTurn(withLineage(thread));
      yield* watch.until(() => watch.middleTurns.get(`${MIDDLE}:turn:2`) === "running");
      assert.equal(watch.deep.at(-1), "completed");
      assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
      yield* runtime.interruptTurn({
        providerThread: thread,
        providerTurnId: yield* providerTurnId,
        requestRuntimeRestart: true,
      });
      yield* watch.until(() => watch.middleTurns.get(`${MIDDLE}:turn:2`) === "interrupted");
      assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
    }).pipe(Effect.scoped),
  );

  const stopTimedOut: ReadonlyArray<ProviderReplayEntry> = [
    out("session.prompt", { sessionID: SESSION, text: "<any>" }),
    promptAccepted,
    out("session.interrupt", { sessionID: SESSION }),
    reply("session.interrupt", "<hang>"),
  ];
  const secondTurn = (thread: OrchestrationV2ProviderThread) => ({
    ...turnInput(thread),
    runId: RunId.make("run:opencode2-adapter:2"),
    runOrdinal: 2,
    providerTurnOrdinal: 2,
    attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"),
  });
  const stopFirstTurn = (
    runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime,
    thread: OrchestrationV2ProviderThread,
  ) =>
    Effect.gen(function* () {
      yield* runtime.startTurn(turnInput(thread));
      const interrupt = yield* runtime
        .interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId })
        .pipe(Effect.forkScoped);
      yield* TestClock.adjust("11 seconds");
      yield* Fiber.join(interrupt);
    });
  const terminals = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime, count: number) =>
    runtime.events.pipe(
      Stream.filter(
        (
          event,
        ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
          event.type === "turn.terminal",
      ),
      Stream.take(count),
      Stream.runCollect,
      Effect.forkScoped,
    );

  it.effect("never lets a timed-out Stop's late end finish the next turn", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        ...stopTimedOut,
        out("session.active"),
        reply("session.active", { data: {} }),
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        promptAccepted,
        event("session.execution.succeeded", { sessionID: SESSION }),
        event("session.execution.started", { sessionID: SESSION }),
        event("session.execution.failed", {
          sessionID: SESSION,
          error: { type: "provider", message: "second turn failed" },
        }),
      ]);
      const ended = yield* terminals(runtime, 2);
      yield* stopFirstTurn(runtime, thread);
      yield* runtime.startTurn(secondTurn(thread));
      const [first, second] = yield* Fiber.join(ended);
      assert.equal(first?.status, "interrupted");
      assert.equal(second?.status, "failed");
      assert.equal(second?.failure?.message, "second turn failed");
    }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
  );

  it.effect("checks the server before prompting again after a prompt request failed", () =>
    Effect.gen(function* () {
      const { runtime, thread } = yield* resumed([
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        reply("session.prompt", {
          status: 502,
          body: { _tag: "UnknownError", message: "bad gateway" },
        }),
        out("session.active"),
        reply("session.active", { data: { [SESSION]: { type: "running" } } }),
        out("session.interrupt", { sessionID: SESSION }),
        reply("session.interrupt", { interrupted: true }),
      ]);
      const ended = yield* terminals(runtime, 2);
      yield* runtime.startTurn(turnInput(thread)).pipe(Effect.ignore);
      yield* runtime.startTurn(secondTurn(thread));
      const [first, second] = yield* Fiber.join(ended);
      assert.equal(first?.status, "failed");
      assert.equal(second?.failure?.message, OPENCODE_2_STILL_STOPPING);
    }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
  );

  // regression: #14744 continuations hung after a reconnect took a Stop's end
  it.effect("still checks the server when a failed prompt's execution starts late", () =>
    Effect.gen(function* () {
      const offered = yield* Deferred.make<void>();
      const { runtime, thread } = yield* resumed([
        out("session.prompt", { sessionID: SESSION, text: "<any>" }),
        reply("session.prompt", {
          status: 502,
          body: { _tag: "UnknownError", message: "bad gateway" },
        }),
        event("session.execution.started", { sessionID: SESSION }),
        out("session.active"),
        reply("session.active", { data: { [SESSION]: { type: "running" } } }),
        out("session.interrupt", { sessionID: SESSION }),
        reply("session.interrupt", { interrupted: true }),
      ]).pipe(
        Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
          offer: () => Deferred.succeed(offered, undefined).pipe(Effect.asVoid),
          take: Effect.never,
        }),
      );