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