The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import { assert, describe, it } from "@effect/vitest"; |
| 4 | import { |
| 5 | CommandId, |
| 6 | ContextTransferId, |
| 7 | EnvironmentId, |
| 8 | GitCommandError, |
| 9 | isLiveSubagentShell, |
| 10 | MessageId, |
| 11 | NodeId, |
| 12 | ORCHESTRATOR_MCP_RUNNING_TASK_NEXT, |
| 13 | type OrchestratorMcpCapabilitiesResult, |
| 14 | type OrchestratorMcpListScheduledTasksInput, |
| 15 | type Project, |
| 16 | OrchestratorMcpTarget, |
| 17 | type OrchestrationV2ThreadShell, |
| 18 | type ScheduledTask, |
| 19 | type ScheduledTaskUpsertInput, |
| 20 | ScheduledTaskId, |
| 21 | ProjectId, |
| 22 | ProviderDriverKind, |
| 23 | ProviderInstanceId, |
| 24 | ProviderThreadId, |
| 25 | ProviderTurnId, |
| 26 | RunId, |
| 27 | ThreadId, |
| 28 | type OrchestrationV2ServerCommand, |
| 29 | type OrchestrationV2StoredEvent, |
| 30 | type OrchestrationV2ThreadProjection, |
| 31 | type ServerProvider, |
| 32 | } from "@t3tools/contracts"; |
| 33 | import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; |
| 34 | import { formatThreadLink, hostedThreadLink } from "@t3tools/shared/threadLinks"; |
| 35 | import * as DateTime from "effect/DateTime"; |
| 36 | import * as Deferred from "effect/Deferred"; |
| 37 | import * as Duration from "effect/Duration"; |
| 38 | import * as Effect from "effect/Effect"; |
| 39 | import * as Fiber from "effect/Fiber"; |
| 40 | import * as Layer from "effect/Layer"; |
| 41 | import * as Option from "effect/Option"; |
| 42 | import * as Queue from "effect/Queue"; |
| 43 | import * as Ref from "effect/Ref"; |
| 44 | import * as Result from "effect/Result"; |
| 45 | import * as Schema from "effect/Schema"; |
| 46 | import * as Stream from "effect/Stream"; |
| 47 | import * as TestClock from "effect/testing/TestClock"; |
| 48 | |
| 49 | import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; |
| 50 | import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts"; |
| 51 | import * as EffectWorker from "../orchestration-v2/EffectWorker.ts"; |
| 52 | import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts"; |
| 53 | import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; |
| 54 | import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; |
| 55 | import * as SqlitePersistence from "../persistence/Sqlite.ts"; |
| 56 | import { |
| 57 | DispatchModeLimit, |
| 58 | type DispatchModeRefusal, |
| 59 | } from "../orchestration-v2/DispatchModeLimit.ts"; |
| 60 | import { |
| 61 | OrchestratorDispatchError, |
| 62 | OrchestratorProjectionError, |
| 63 | OrchestratorThreadAboveModeLimitError, |
| 64 | } from "../orchestration-v2/Orchestrator.ts"; |
| 65 | import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; |
| 66 | import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; |
| 67 | import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; |
| 68 | import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; |
| 69 | import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; |
| 70 | import { buildUnavailableProviderSnapshot } from "../provider/unavailableProviderSnapshot.ts"; |
| 71 | import * as ProjectService from "../project/ProjectService.ts"; |
| 72 | import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; |
| 73 | import * as ServerSettings from "../serverSettings.ts"; |
| 74 | import * as SecretRequests from "../secrets/SecretRequests.ts"; |
| 75 | import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; |
| 76 | import type { McpInvocationScope } from "./McpInvocationContext.ts"; |
| 77 | import { idleThreadProjection, liveThreadShell } from "./McpToolAccess.testkit.ts"; |
| 78 | import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; |
| 79 | import { resolveRuntimeMode } from "./delegatedTaskModes.ts"; |
| 80 | import type { ProjectionRecordFilter } from "../orchestration-v2/ProjectionStore.ts"; |
| 81 | import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; |
| 82 | |
| 83 | const decodeTarget = Schema.decodeUnknownEffect(OrchestratorMcpTarget); |
| 84 | |
| 85 | const layerOrchestratorService = OrchestratorMcpService.layer.pipe( |
| 86 | Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), |
| 87 | Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), |
| 88 | ); |
| 89 | |
| 90 | describe("OrchestratorMcpService", () => { |
| 91 | it.effect("retries terminal acknowledgement with a fresh command id", () => |
| 92 | Effect.gen(function* () { |
| 93 | const parentThreadId = ThreadId.make("thread:mcp-ack-parent"); |
| 94 | const childThreadId = ThreadId.make("thread:mcp-ack-child"); |
| 95 | const childRunId = RunId.make("run:mcp-ack-child"); |
| 96 | const taskId = NodeId.make("node:mcp-ack-task"); |
| 97 | const resultTransferId = ContextTransferId.make("transfer:mcp-ack-result"); |
| 98 | const acknowledgementCommandIds = yield* Ref.make<ReadonlyArray<string>>([]); |
| 99 | const acknowledgementAttempts = yield* Ref.make(0); |
| 100 | const parentProjection = { |
| 101 | thread: { id: parentThreadId }, |
| 102 | runs: [], |
| 103 | subagents: [ |
| 104 | { |
| 105 | id: taskId, |
| 106 | threadId: parentThreadId, |
| 107 | origin: "app_owned", |
| 108 | childThreadId, |
| 109 | driver: "codex", |
| 110 | model: "gpt-5.6-terra", |
| 111 | result: "terminal result", |
| 112 | completionDelivery: { state: "pending" }, |
| 113 | }, |
| 114 | ], |
| 115 | } as unknown as OrchestrationV2ThreadProjection; |
| 116 | const childProjection = { |
| 117 | thread: { id: childThreadId, title: "Child" }, |
| 118 | runs: [ |
| 119 | { |
| 120 | id: childRunId, |
| 121 | ordinal: 1, |
| 122 | status: "completed", |
| 123 | startedAt: DateTime.makeUnsafe("2026-10-03T10:00:00Z"), |
| 124 | completedAt: DateTime.makeUnsafe("2026-10-03T10:10:00Z"), |
| 125 | }, |
| 126 | { |
| 127 | id: RunId.make("run:mcp-ack-continuation"), |
| 128 | ordinal: 2, |
| 129 | status: "failed", |
| 130 | startedAt: DateTime.makeUnsafe("2026-10-03T10:02:00Z"), |
| 131 | completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00Z"), |
| 132 | }, |
| 133 | ], |
| 134 | contextTransfers: [ |
| 135 | { |
| 136 | id: resultTransferId, |
| 137 | type: "subagent_result", |
| 138 | sourceThreadId: childThreadId, |
| 139 | targetThreadId: parentThreadId, |
| 140 | sourcePoint: { runId: childRunId }, |
| 141 | }, |
| 142 | ], |
| 143 | messages: [ |
| 144 | { |
| 145 | id: MessageId.make("message:mcp-ack-result"), |
| 146 | runId: childRunId, |
| 147 | role: "assistant", |
| 148 | text: "terminal result", |
| 149 | createdAt: DateTime.makeUnsafe("2026-10-03T10:10:00Z"), |
| 150 | updatedAt: DateTime.makeUnsafe("2026-10-03T10:10:00Z"), |
| 151 | }, |
| 152 | ], |
| 153 | turnItems: [], |
| 154 | subagents: [], |
| 155 | providerThreads: [], |
| 156 | providerTurns: [], |
| 157 | runtimeRequests: [], |
| 158 | } as unknown as OrchestrationV2ThreadProjection; |
| 159 | let hasNestedWork = true; |
| 160 | let settleAfterTaskRead = false; |
| 161 | const layerDependencies = Layer.mergeAll( |
| 162 | NodeServices.layer, |
| 163 | NodeCrypto.layer, |
| 164 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 165 | getThreadRecords: (threadId) => |
| 166 | Effect.sync(() => { |
| 167 | if (threadId !== parentThreadId) { |
| 168 | return hasNestedWork |
| 169 | ? { |
| 170 | ...childProjection, |
| 171 | contextTransfers: [], |
| 172 | subagents: [ |
| 173 | { ...parentProjection.subagents[0]!, status: "running" as const }, |
| 174 | ], |
| 175 | } |
| 176 | : childProjection; |
| 177 | } |
| 178 | const snapshot = hasNestedWork |
| 179 | ? { |
| 180 | ...parentProjection, |
| 181 | subagents: parentProjection.subagents.map((task) => ({ |
| 182 | ...task, |
| 183 | result: null, |
| 184 | status: "running" as const, |
| 185 | })), |
| 186 | } |
| 187 | : parentProjection; |
| 188 | if (settleAfterTaskRead) { |
| 189 | settleAfterTaskRead = false; |
| 190 | hasNestedWork = false; |
| 191 | } |
| 192 | return snapshot; |
| 193 | }), |
| 194 | delegatedTaskResultPending: () => Effect.succeed(false), |
| 195 | dispatch: (command) => |
| 196 | Ref.update(acknowledgementCommandIds, (commandIds) => [ |
| 197 | ...commandIds, |
| 198 | String(command.commandId), |
| 199 | ]).pipe( |
| 200 | Effect.andThen(Ref.updateAndGet(acknowledgementAttempts, (count) => count + 1)), |
| 201 | Effect.flatMap((attempt) => |
| 202 | attempt === 1 |
| 203 | ? Effect.fail(new Error("simulated acknowledgement failure") as never) |
| 204 | : Effect.succeed({} as never), |
| 205 | ), |
| 206 | ), |
| 207 | }), |
| 208 | ServerSettings.layerTest(), |
| 209 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 210 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 211 | list: () => Effect.succeed([]), |
| 212 | }), |
| 213 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 214 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 215 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 216 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 217 | ); |
| 218 | const scope: McpInvocationScope = { |
| 219 | environmentId: EnvironmentId.make("environment:mcp-ack"), |
| 220 | requestNamespace: "provider-session:mcp-ack", |
| 221 | thread: { |
| 222 | threadId: parentThreadId, |
| 223 | providerSessionId: "provider-session:mcp-ack", |
| 224 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 225 | }, |
| 226 | client: undefined, |
| 227 | capabilities: new Set(["orchestration"]), |
| 228 | issuedAt: 1, |
| 229 | }; |
| 230 | |
| 231 | yield* Effect.gen(function* () { |
| 232 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 233 | const pending = yield* service.taskStatus(scope, taskId); |
| 234 | assert.equal(pending.status, "running"); |
| 235 | assert.equal(pending.workState, "waiting_for_children"); |
| 236 | assert.isNull(pending.summary); |
| 237 | assert.isNull(pending.resultContextTransferId); |
| 238 | assert.equal(yield* Ref.get(acknowledgementAttempts), 0); |
| 239 | hasNestedWork = false; |
| 240 | const error = yield* service.taskStatus(scope, taskId).pipe(Effect.flip); |
| 241 | assert.equal(error.code, "orchestration_error"); |
| 242 | |
| 243 | // Completion lands after task selection, before the remaining parent/child reads. |
| 244 | hasNestedWork = true; |
| 245 | settleAfterTaskRead = true; |
| 246 | const result = yield* service.taskStatus(scope, taskId); |
| 247 | assert.equal(result.status, "completed"); |
| 248 | assert.equal(result.summary, "terminal result"); |
| 249 | assert.equal(result.latestTerminalRunId, childRunId); |
| 250 | assert.equal(result.latestTerminalStatus, "completed"); |
| 251 | assert.equal(result.resultContextTransferId, resultTransferId); |
| 252 | const commandIds = yield* Ref.get(acknowledgementCommandIds); |
| 253 | assert.equal(commandIds.length, 2); |
| 254 | assert.notEqual(commandIds[0], commandIds[1]); |
| 255 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 256 | }), |
| 257 | ); |
| 258 | |
| 259 | it.effect("reports a restart-cut child as working until its continuation settles", () => |
| 260 | Effect.gen(function* () { |
| 261 | const parentThreadId = ThreadId.make("thread:mcp-restart-parent"); |
| 262 | const childThreadId = ThreadId.make("thread:mcp-restart-child"); |
| 263 | const taskId = NodeId.make("node:mcp-restart-task"); |
| 264 | const cutRunId = RunId.make("run:mcp-restart-child"); |
| 265 | const continuationRunId = RunId.make("run:mcp-restart-continuation"); |
| 266 | const dispatched = yield* Ref.make(0); |
| 267 | let awaitsRestart = true; |
| 268 | let readFails = true; |
| 269 | const parentProjection = { |
| 270 | thread: { id: parentThreadId }, |
| 271 | runs: [], |
| 272 | contextTransfers: [], |
| 273 | subagents: [ |
| 274 | { |
| 275 | id: taskId, |
| 276 | threadId: parentThreadId, |
| 277 | origin: "app_owned", |
| 278 | childThreadId, |
| 279 | driver: "codex", |
| 280 | model: "gpt-5.6-terra", |
| 281 | status: "running", |
| 282 | result: null, |
| 283 | completionDelivery: { state: "pending" }, |
| 284 | }, |
| 285 | ], |
| 286 | } as unknown as OrchestrationV2ThreadProjection; |
| 287 | const childProjection = { |
| 288 | thread: { id: childThreadId, title: "Child" }, |
| 289 | runs: [ |
| 290 | { |
| 291 | id: cutRunId, |
| 292 | ordinal: 1, |
| 293 | status: "cancelled", |
| 294 | delegatedTaskId: taskId, |
| 295 | startedAt: DateTime.makeUnsafe("2026-10-03T10:00:00Z"), |
| 296 | completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00Z"), |
| 297 | }, |
| 298 | { id: RunId.make("run:mcp-restart-later"), ordinal: 2, status: "running" }, |
| 299 | ], |
| 300 | contextTransfers: [], |
| 301 | messages: [], |
| 302 | subagents: [], |
| 303 | providerThreads: [], |
| 304 | providerTurns: [], |
| 305 | runtimeRequests: [], |
| 306 | turnItems: [], |
| 307 | } as unknown as OrchestrationV2ThreadProjection; |
| 308 | let childRuns = childProjection.runs; |
| 309 | const layerDependencies = Layer.mergeAll( |
| 310 | NodeServices.layer, |
| 311 | NodeCrypto.layer, |
| 312 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 313 | getThreadRecords: (threadId) => |
| 314 | Effect.succeed( |
| 315 | threadId === parentThreadId |
| 316 | ? parentProjection |
| 317 | : { ...childProjection, runs: childRuns }, |
| 318 | ), |
| 319 | delegatedTaskResultPending: () => |
| 320 | readFails |
| 321 | ? Effect.fail(new OrchestratorProjectionError({ threadId: childThreadId })) |
| 322 | : Effect.succeed(awaitsRestart), |
| 323 | dispatch: () => Ref.update(dispatched, (count) => count + 1).pipe(Effect.as({} as never)), |
| 324 | }), |
| 325 | ServerSettings.layerTest(), |
| 326 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 327 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 328 | list: () => Effect.succeed([]), |
| 329 | }), |
| 330 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 331 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 332 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 333 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 334 | ); |
| 335 | const scope: McpInvocationScope = { |
| 336 | environmentId: EnvironmentId.make("environment:mcp-restart"), |
| 337 | requestNamespace: "provider-session:mcp-restart", |
| 338 | thread: { |
| 339 | threadId: parentThreadId, |
| 340 | providerSessionId: "provider-session:mcp-restart", |
| 341 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 342 | }, |
| 343 | client: undefined, |
| 344 | capabilities: new Set(["orchestration"]), |
| 345 | issuedAt: 1, |
| 346 | }; |
| 347 | |
| 348 | yield* Effect.gen(function* () { |
| 349 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 350 | const failed = yield* service.taskStatus(scope, taskId).pipe(Effect.flip); |
| 351 | assert.equal(failed.code, "orchestration_error"); |
| 352 | assert.equal(yield* Ref.get(dispatched), 0); |
| 353 | readFails = false; |
| 354 | const held = yield* service.taskStatus(scope, taskId); |
| 355 | assert.equal(held.status, "running"); |
| 356 | assert.equal(held.workState, "working"); |
| 357 | assert.isNull(held.summary); |
| 358 | assert.isNull(held.latestTerminalRunId); |
| 359 | assert.isNull(held.latestTerminalStatus); |
| 360 | assert.equal(yield* Ref.get(dispatched), 0); |
| 361 | |
| 362 | const continuationRun = { |
| 363 | id: continuationRunId, |
| 364 | ordinal: 3, |
| 365 | status: "running", |
| 366 | delegatedTaskId: taskId, |
| 367 | startedAt: DateTime.makeUnsafe("2026-10-03T10:06:00Z"), |
| 368 | restartContinuationOfRunId: cutRunId, |
| 369 | } as unknown as (typeof childRuns)[number]; |
| 370 | childRuns = [...childProjection.runs, continuationRun]; |
| 371 | const continuing = yield* service.taskStatus(scope, taskId); |
| 372 | assert.equal(continuing.status, "running"); |
| 373 | assert.isNull(continuing.latestTerminalRunId); |
| 374 | assert.isNull(continuing.latestTerminalStatus); |
| 375 | |
| 376 | // A second restart cut the continuation, and its own continuation declined. |
| 377 | childRuns = [ |
| 378 | ...childProjection.runs, |
| 379 | { |
| 380 | ...continuationRun, |
| 381 | status: "cancelled", |
| 382 | completedAt: DateTime.makeUnsafe("2026-10-03T10:10:00Z"), |
| 383 | }, |
| 384 | ]; |
| 385 | awaitsRestart = false; |
| 386 | const settled = yield* service.taskStatus(scope, taskId); |
| 387 | assert.equal(settled.status, "cancelled"); |
| 388 | assert.equal(settled.latestTerminalRunId, continuationRunId); |
| 389 | assert.equal(settled.latestTerminalStatus, "cancelled"); |
| 390 | assert.equal(yield* Ref.get(dispatched), 1); |
| 391 | |
| 392 | // A continuation cancelled before it started leaves the cut run as the result. |
| 393 | childRuns = [ |
| 394 | ...childProjection.runs, |
| 395 | { ...continuationRun, status: "cancelled", startedAt: null }, |
| 396 | ]; |
| 397 | const unstarted = yield* service.taskStatus(scope, taskId); |
| 398 | assert.equal(unstarted.latestTerminalRunId, cutRunId); |
| 399 | assert.equal(unstarted.latestTerminalStatus, "cancelled"); |
| 400 | |
| 401 | // That unstarted continuation was itself continued, so the whole chain is still live. |
| 402 | childRuns = [ |
| 403 | ...childProjection.runs, |
| 404 | { ...continuationRun, status: "cancelled", startedAt: null }, |
| 405 | { |
| 406 | ...continuationRun, |
| 407 | id: RunId.make("run:mcp-restart-continuation-2"), |
| 408 | ordinal: 4, |
| 409 | restartContinuationOfRunId: continuationRunId, |
| 410 | }, |
| 411 | ]; |
| 412 | const chained = yield* service.taskStatus(scope, taskId); |
| 413 | assert.isNull(chained.latestTerminalRunId); |
| 414 | assert.isNull(chained.latestTerminalStatus); |
| 415 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 416 | }), |
| 417 | ); |
| 418 | |
| 419 | it.effect("reports a child run the provider has not started yet as starting", () => |
| 420 | Effect.gen(function* () { |
| 421 | const parentThreadId = ThreadId.make("thread:mcp-starting-parent"); |
| 422 | const childThreadId = ThreadId.make("thread:mcp-starting-child"); |
| 423 | const childRunId = RunId.make("run:mcp-starting-child"); |
| 424 | const taskId = NodeId.make("node:mcp-starting-task"); |
| 425 | const parentProjection = { |
| 426 | thread: { id: parentThreadId }, |
| 427 | runs: [], |
| 428 | contextTransfers: [], |
| 429 | subagents: [ |
| 430 | { |
| 431 | id: taskId, |
| 432 | threadId: parentThreadId, |
| 433 | origin: "app_owned", |
| 434 | childThreadId, |
| 435 | driver: "codex", |
| 436 | model: "gpt-5.6-terra", |
| 437 | status: "running", |
| 438 | result: null, |
| 439 | completionDelivery: null, |
| 440 | }, |
| 441 | ], |
| 442 | } as unknown as OrchestrationV2ThreadProjection; |
| 443 | let providerStarted = false; |
| 444 | const childProjection = () => |
| 445 | ({ |
| 446 | thread: { id: childThreadId, title: "Child task" }, |
| 447 | runs: [ |
| 448 | { |
| 449 | id: childRunId, |
| 450 | ordinal: 1, |
| 451 | status: providerStarted ? "running" : "starting", |
| 452 | startedAt: providerStarted ? DateTime.makeUnsafe("2026-10-24T10:00:00Z") : null, |
| 453 | delegatedTaskId: taskId, |
| 454 | }, |
| 455 | ], |
| 456 | contextTransfers: [], |
| 457 | messages: [], |
| 458 | subagents: [], |
| 459 | providerThreads: [{ status: "not_loaded", pendingBackgroundTasks: [] }], |
| 460 | providerTurns: [], |
| 461 | runtimeRequests: [], |
| 462 | turnItems: [], |
| 463 | }) as unknown as OrchestrationV2ThreadProjection; |
| 464 | const layerDependencies = Layer.mergeAll( |
| 465 | NodeServices.layer, |
| 466 | NodeCrypto.layer, |
| 467 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 468 | getThreadRecords: (threadId) => |
| 469 | Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection()), |
| 470 | }), |
| 471 | ServerSettings.layerTest(), |
| 472 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 473 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 474 | list: () => Effect.succeed([]), |
| 475 | }), |
| 476 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 477 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 478 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 479 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 480 | ); |
| 481 | const scope: McpInvocationScope = { |
| 482 | environmentId: EnvironmentId.make("environment:mcp-starting"), |
| 483 | requestNamespace: "provider-session:mcp-starting", |
| 484 | thread: { |
| 485 | threadId: parentThreadId, |
| 486 | providerSessionId: "provider-session:mcp-starting", |
| 487 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 488 | }, |
| 489 | client: undefined, |
| 490 | capabilities: new Set(["orchestration"]), |
| 491 | issuedAt: 1, |
| 492 | }; |
| 493 | |
| 494 | yield* Effect.gen(function* () { |
| 495 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 496 | const waiting = yield* service.taskStatus(scope, taskId); |
| 497 | assert.equal(waiting.status, "starting"); |
| 498 | assert.equal(waiting.workState, "working"); |
| 499 | assert.equal(waiting.childRunId, childRunId); |
| 500 | providerStarted = true; |
| 501 | const started = yield* service.taskStatus(scope, taskId); |
| 502 | assert.equal(started.status, "running"); |
| 503 | assert.equal(started.workState, "working"); |
| 504 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 505 | }), |
| 506 | ); |
| 507 | |
| 508 | it.effect("takes a silent run's report only from the same task's earlier runs", () => |
| 509 | Effect.gen(function* () { |
| 510 | const parentThreadId = ThreadId.make("thread:mcp-report-parent"); |
| 511 | const childThreadId = ThreadId.make("thread:mcp-report-child"); |
| 512 | const taskA = NodeId.make("node:mcp-report-task-a"); |
| 513 | const taskB = NodeId.make("node:mcp-report-task-b"); |
| 514 | const silent = "Child task completed without an assistant result."; |
| 515 | const parentProjection = { |
| 516 | thread: { id: parentThreadId }, |
| 517 | runs: [], |
| 518 | contextTransfers: [], |
| 519 | subagents: [taskA, taskB].map((id) => ({ |
| 520 | id, |
| 521 | threadId: parentThreadId, |
| 522 | origin: "app_owned", |
| 523 | childThreadId, |
| 524 | driver: "codex", |
| 525 | model: "gpt-5.6-terra", |
| 526 | status: "running", |
| 527 | result: null, |
| 528 | completionDelivery: null, |
| 529 | })), |
| 530 | } as unknown as OrchestrationV2ThreadProjection; |
| 531 | const run = (ordinal: number, delegatedTaskId: NodeId) => ({ |
| 532 | id: RunId.make(`run:mcp-report-${ordinal}`), |
| 533 | ordinal, |
| 534 | status: "completed", |
| 535 | delegatedTaskId, |
| 536 | startedAt: DateTime.makeUnsafe(`2026-10-24T10:0${ordinal}:00Z`), |
| 537 | completedAt: DateTime.makeUnsafe(`2026-10-24T10:0${ordinal}:30Z`), |
| 538 | }); |
| 539 | const runs = [run(1, taskA), run(2, taskA), run(3, taskB)]; |
| 540 | let reports: ReadonlyArray<readonly [number, string]> = []; |
| 541 | // The mock ignores run filters, so every report is loaded whichever runs are asked for. |
| 542 | const childProjection = () => |
| 543 | ({ |
| 544 | thread: { id: childThreadId, title: "Child task" }, |
| 545 | runs, |
| 546 | contextTransfers: [], |
| 547 | messages: reports.map(([ordinal, text]) => ({ |
| 548 | id: MessageId.make(`message:mcp-report-${ordinal}`), |
| 549 | runId: runs[ordinal - 1]!.id, |
| 550 | role: "assistant", |
| 551 | text, |
| 552 | createdAt: runs[ordinal - 1]!.completedAt, |
| 553 | updatedAt: runs[ordinal - 1]!.completedAt, |
| 554 | })), |
| 555 | subagents: [], |
| 556 | providerThreads: [], |
| 557 | providerTurns: [], |
| 558 | runtimeRequests: [], |
| 559 | turnItems: [], |
| 560 | }) as unknown as OrchestrationV2ThreadProjection; |
| 561 | const layerDependencies = Layer.mergeAll( |
| 562 | NodeServices.layer, |
| 563 | NodeCrypto.layer, |
| 564 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 565 | getThreadRecords: (threadId) => |
| 566 | Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection()), |
| 567 | delegatedTaskResultPending: () => Effect.succeed(false), |
| 568 | dispatch: () => Effect.succeed({} as never), |
| 569 | }), |
| 570 | ServerSettings.layerTest(), |
| 571 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 572 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 573 | list: () => Effect.succeed([]), |
| 574 | }), |
| 575 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 576 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 577 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 578 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 579 | ); |
| 580 | const scope: McpInvocationScope = { |
| 581 | environmentId: EnvironmentId.make("environment:mcp-report"), |
| 582 | requestNamespace: "provider-session:mcp-report", |
| 583 | thread: { |
| 584 | threadId: parentThreadId, |
| 585 | providerSessionId: "provider-session:mcp-report", |
| 586 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 587 | }, |
| 588 | client: undefined, |
| 589 | capabilities: new Set(["orchestration"]), |
| 590 | issuedAt: 1, |
| 591 | }; |
| 592 | |
| 593 | yield* Effect.gen(function* () { |
| 594 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 595 | // Task A reported, then a run queued behind the report ended without text. |
| 596 | reports = [[1, "REPORT-A"]]; |
| 597 | const reported = yield* service.taskStatus(scope, taskA); |
| 598 | assert.equal(reported.status, "completed"); |
| 599 | assert.equal(reported.summary, "REPORT-A"); |
| 600 | assert.equal(reported.latestTerminalRunId, runs[2]!.id); |
| 601 | assert.equal(reported.latestTerminalSummary, silent); |
| 602 | assert.equal((yield* service.taskStatus(scope, taskB)).summary, silent); |
| 603 | |
| 604 | // A later task's report is not the result of a task that said nothing. |
| 605 | reports = [[3, "REPORT-B"]]; |
| 606 | const quiet = yield* service.taskStatus(scope, taskA); |
| 607 | assert.equal(quiet.summary, silent); |
| 608 | assert.equal(quiet.latestTerminalSummary, "REPORT-B"); |
| 609 | assert.equal((yield* service.taskStatus(scope, taskB)).summary, "REPORT-B"); |
| 610 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 611 | }), |
| 612 | ); |
| 613 | |
| 614 | it.effect("tells the parent to end its turn only while its task still runs", () => |
| 615 | Effect.gen(function* () { |
| 616 | const parentThreadId = ThreadId.make("thread:mcp-next-parent"); |
| 617 | const childThreadId = ThreadId.make("thread:mcp-next-child"); |
| 618 | const taskId = NodeId.make("node:mcp-next-task"); |
| 619 | let finished = false; |
| 620 | let pendingRequest = false; |
| 621 | const parentProjection = () => |
| 622 | ({ |
| 623 | thread: { id: parentThreadId }, |
| 624 | runs: [], |
| 625 | contextTransfers: [], |
| 626 | subagents: [ |
| 627 | { |
| 628 | id: taskId, |
| 629 | threadId: parentThreadId, |
| 630 | origin: "app_owned", |
| 631 | childThreadId, |
| 632 | driver: "codex", |
| 633 | model: "gpt-5.6-terra", |
| 634 | status: finished ? "completed" : "running", |
| 635 | result: finished ? "done" : null, |
| 636 | completionDelivery: { state: "pending" }, |
| 637 | }, |
| 638 | ], |
| 639 | }) as unknown as OrchestrationV2ThreadProjection; |
| 640 | const childRun = () => ({ |
| 641 | id: RunId.make("run:mcp-next-child"), |
| 642 | ordinal: 1, |
| 643 | status: finished ? ("completed" as const) : ("running" as const), |
| 644 | delegatedTaskId: taskId, |
| 645 | }); |
| 646 | const childProjection = () => |
| 647 | ({ |
| 648 | thread: { id: childThreadId, title: "Child task" }, |
| 649 | runs: [childRun()], |
| 650 | contextTransfers: [], |
| 651 | messages: [], |
| 652 | subagents: [], |
| 653 | providerThreads: [], |
| 654 | providerTurns: [], |
| 655 | runtimeRequests: pendingRequest ? [{ status: "pending" }] : [], |
| 656 | nodes: [], |
| 657 | turnItems: [], |
| 658 | }) as unknown as OrchestrationV2ThreadProjection; |
| 659 | const layerDependencies = Layer.mergeAll( |
| 660 | NodeServices.layer, |
| 661 | NodeCrypto.layer, |
| 662 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 663 | getThreadRecords: (threadId) => |
| 664 | Effect.succeed(threadId === parentThreadId ? parentProjection() : childProjection()), |
| 665 | getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), |
| 666 | getProjectThreadRecords: () => Effect.succeed(childProjection()), |
| 667 | waitForThread: () => |
| 668 | Effect.succeed({ |
| 669 | threadId: childThreadId, |
| 670 | run: childRun() as unknown as OrchestrationV2ThreadProjection["runs"][number], |
| 671 | timedOut: !finished, |
| 672 | }), |
| 673 | dispatch: () => Effect.succeed({} as never), |
| 674 | }), |
| 675 | ServerSettings.layerTest(), |
| 676 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 677 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 678 | list: () => Effect.succeed([]), |
| 679 | }), |
| 680 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 681 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 682 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 683 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 684 | ); |
| 685 | const scope: McpInvocationScope = { |
| 686 | environmentId: EnvironmentId.make("environment:mcp-next"), |
| 687 | requestNamespace: "provider-session:mcp-next", |
| 688 | thread: { |
| 689 | threadId: parentThreadId, |
| 690 | providerSessionId: "provider-session:mcp-next", |
| 691 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 692 | }, |
| 693 | client: undefined, |
| 694 | capabilities: new Set(["orchestration"]), |
| 695 | issuedAt: 1, |
| 696 | }; |
| 697 | |
| 698 | yield* Effect.gen(function* () { |
| 699 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 700 | const running = yield* service.taskStatus(scope, taskId); |
| 701 | assert.equal(running.status, "running"); |
| 702 | assert.equal(running.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); |
| 703 | const waiting = yield* service.waitForThread(scope, { threadId: childThreadId }); |
| 704 | assert.isTrue(waiting.timedOut); |
| 705 | assert.equal(waiting.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); |
| 706 | |
| 707 | // A child waiting on a question or approval needs an answer, not a wake. |
| 708 | pendingRequest = true; |
| 709 | const asking = yield* service.waitForThread(scope, { threadId: childThreadId }); |
| 710 | assert.isTrue(asking.timedOut); |
| 711 | assert.notProperty(asking, "next"); |
| 712 | pendingRequest = false; |
| 713 | |
| 714 | finished = true; |
| 715 | const completed = yield* service.taskStatus(scope, taskId); |
| 716 | assert.equal(completed.status, "completed"); |
| 717 | assert.notProperty(completed, "next"); |
| 718 | const waited = yield* service.waitForThread(scope, { threadId: childThreadId }); |
| 719 | assert.equal(waited.status, "completed"); |
| 720 | assert.notProperty(waited, "next"); |
| 721 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 722 | }), |
| 723 | ); |
| 724 | |
| 725 | it.effect("does not dispose delivery when a nonterminal task has no active child run", () => |
| 726 | Effect.gen(function* () { |
| 727 | const parentThreadId = ThreadId.make("thread:mcp-cancel-parent"); |
| 728 | const childThreadId = ThreadId.make("thread:mcp-cancel-child"); |
| 729 | const taskId = NodeId.make("node:mcp-cancel-task"); |
| 730 | const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]); |
| 731 | const parentProjection = { |
| 732 | thread: { id: parentThreadId }, |
| 733 | runs: [], |
| 734 | contextTransfers: [], |
| 735 | subagents: [ |
| 736 | { |
| 737 | id: taskId, |
| 738 | threadId: parentThreadId, |
| 739 | origin: "app_owned", |
| 740 | childThreadId, |
| 741 | driver: "codex", |
| 742 | model: "gpt-5.6-terra", |
| 743 | result: null, |
| 744 | completionDelivery: { state: "pending" }, |
| 745 | }, |
| 746 | ], |
| 747 | } as unknown as OrchestrationV2ThreadProjection; |
| 748 | const childProjection = { |
| 749 | thread: { id: childThreadId, title: "Child" }, |
| 750 | runs: [], |
| 751 | contextTransfers: [], |
| 752 | messages: [], |
| 753 | subagents: [], |
| 754 | providerThreads: [], |
| 755 | providerTurns: [], |
| 756 | runtimeRequests: [], |
| 757 | } as unknown as OrchestrationV2ThreadProjection; |
| 758 | const layerDependencies = Layer.mergeAll( |
| 759 | NodeServices.layer, |
| 760 | NodeCrypto.layer, |
| 761 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 762 | getThreadRecords: (threadId) => |
| 763 | Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), |
| 764 | getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), |
| 765 | listAppOwnedChildThreadIds: () => Effect.succeed([]), |
| 766 | dispatch: (command) => |
| 767 | Ref.update(dispatched, (commands) => [...commands, command]).pipe( |
| 768 | Effect.as({} as never), |
| 769 | ), |
| 770 | }), |
| 771 | ServerSettings.layerTest(), |
| 772 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 773 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 774 | list: () => Effect.succeed([]), |
| 775 | }), |
| 776 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 777 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 778 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 779 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 780 | ); |
| 781 | const scope: McpInvocationScope = { |
| 782 | environmentId: EnvironmentId.make("environment:mcp-cancel"), |
| 783 | requestNamespace: "provider-session:mcp-cancel", |
| 784 | thread: { |
| 785 | threadId: parentThreadId, |
| 786 | providerSessionId: "provider-session:mcp-cancel", |
| 787 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 788 | }, |
| 789 | client: undefined, |
| 790 | capabilities: new Set(["orchestration"]), |
| 791 | issuedAt: 1, |
| 792 | }; |
| 793 | |
| 794 | yield* Effect.gen(function* () { |
| 795 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 796 | const error = yield* service |
| 797 | .cancelTask(scope, { taskId, clientRequestId: "cancel-unstarted-task" }) |
| 798 | .pipe(Effect.flip); |
| 799 | assert.equal(error.code, "task_not_cancellable"); |
| 800 | assert.deepEqual(yield* Ref.get(dispatched), []); |
| 801 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 802 | }), |
| 803 | ); |
| 804 | |
| 805 | it.effect.each(["no runs", "a finished run"] as const)( |
| 806 | "cancels an orphaned follow-up through its parent when the child has %s", |
| 807 | (childState) => |
| 808 | Effect.gen(function* () { |
| 809 | const parentThreadId = ThreadId.make("thread:mcp-orphan-parent"); |
| 810 | const childThreadId = ThreadId.make("thread:mcp-orphan-child"); |
| 811 | const taskId = NodeId.make("node:mcp-orphan-task"); |
| 812 | const parentRunId = RunId.make("run:mcp-orphan-parent"); |
| 813 | const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationV2ServerCommand>>([]); |
| 814 | const status = yield* Ref.make("running"); |
| 815 | const parentProjection = (taskStatus: string) => |
| 816 | ({ |
| 817 | thread: { id: parentThreadId }, |
| 818 | runs: [], |
| 819 | contextTransfers: [], |
| 820 | subagents: [ |
| 821 | { |
| 822 | id: taskId, |
| 823 | threadId: parentThreadId, |
| 824 | runId: parentRunId, |
| 825 | origin: "app_owned", |
| 826 | childThreadId, |
| 827 | driver: "codex", |
| 828 | model: "gpt-5.6-terra", |
| 829 | status: taskStatus, |
| 830 | result: null, |
| 831 | completionDelivery: { state: "pending" }, |
| 832 | }, |
| 833 | ], |
| 834 | }) as unknown as OrchestrationV2ThreadProjection; |
| 835 | // A finished run whose binding to the follow-up was lost. |
| 836 | const childProjection = { |
| 837 | thread: { id: childThreadId, title: "Child" }, |
| 838 | runs: |
| 839 | childState === "no runs" |
| 840 | ? [] |
| 841 | : [{ id: RunId.make("run:mcp-orphan-child"), ordinal: 1, status: "completed" }], |
| 842 | contextTransfers: [], |
| 843 | messages: [], |
| 844 | subagents: [], |
| 845 | providerThreads: [], |
| 846 | providerTurns: [], |
| 847 | runtimeRequests: [], |
| 848 | turnItems: [], |
| 849 | } as unknown as OrchestrationV2ThreadProjection; |
| 850 | const layerDependencies = Layer.mergeAll( |
| 851 | NodeServices.layer, |
| 852 | NodeCrypto.layer, |
| 853 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 854 | getThreadRecords: (threadId) => |
| 855 | threadId === parentThreadId |
| 856 | ? Effect.map(Ref.get(status), parentProjection) |
| 857 | : Effect.succeed(childProjection), |
| 858 | getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), |
| 859 | listAppOwnedChildThreadIds: () => Effect.succeed([]), |
| 860 | delegatedTaskResultPending: () => Effect.succeed(false), |
| 861 | stopDelegatedTasks: () => Effect.void, |
| 862 | cancelDelegatedTask: ({ command }) => |
| 863 | Ref.update(dispatched, (commands) => [...commands, command]), |
| 864 | // The orchestrator's subagent.stop repair is covered in ThreadStop.test.ts. |
| 865 | dispatch: (command) => |
| 866 | Ref.update(dispatched, (commands) => [...commands, command]).pipe( |
| 867 | Effect.andThen( |
| 868 | command.type === "subagent.stop" ? Ref.set(status, "cancelled") : Effect.void, |
| 869 | ), |
| 870 | Effect.as({} as never), |
| 871 | ), |
| 872 | }), |
| 873 | ServerSettings.layerTest(), |
| 874 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 875 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 876 | list: () => Effect.succeed([]), |
| 877 | }), |
| 878 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 879 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 880 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 881 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 882 | ); |
| 883 | const scope: McpInvocationScope = { |
| 884 | environmentId: EnvironmentId.make("environment:mcp-orphan"), |
| 885 | requestNamespace: "provider-session:mcp-orphan", |
| 886 | thread: { |
| 887 | threadId: parentThreadId, |
| 888 | providerSessionId: "provider-session:mcp-orphan", |
| 889 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 890 | }, |
| 891 | client: undefined, |
| 892 | capabilities: new Set(["orchestration"]), |
| 893 | issuedAt: 1, |
| 894 | }; |
| 895 | |
| 896 | yield* Effect.gen(function* () { |
| 897 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 898 | const result = yield* service.cancelTask(scope, { |
| 899 | taskId, |
| 900 | clientRequestId: "cancel-orphan-task", |
| 901 | }); |
| 902 | assert.deepEqual(result, { taskId, status: "cancelled" }); |
| 903 | const commands = yield* Ref.get(dispatched); |
| 904 | // A child whose run finished can still run another turn's work, so it is stopped too. |
| 905 | assert.deepEqual( |
| 906 | commands.flatMap((command) => |
| 907 | command.type === "thread.stop" ? [command.threadId] : [], |
| 908 | ), |
| 909 | childState === "a finished run" ? [childThreadId] : [], |
| 910 | ); |
| 911 | const stop = commands.find((command) => command.type === "subagent.stop"); |
| 912 | if (stop?.type !== "subagent.stop") return; |
| 913 | assert.deepEqual( |
| 914 | { threadId: stop.threadId, runId: stop.runId, subagentId: stop.subagentId }, |
| 915 | { threadId: parentThreadId, runId: parentRunId, subagentId: taskId }, |
| 916 | ); |
| 917 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 918 | }), |
| 919 | ); |
| 920 | |
| 921 | it.effect("does not dispose delivery when the child stop fails", () => |
| 922 | Effect.gen(function* () { |
| 923 | const parentThreadId = ThreadId.make("thread:mcp-cancel-failed-parent"); |
| 924 | const childThreadId = ThreadId.make("thread:mcp-cancel-failed-child"); |
| 925 | const childRunId = RunId.make("run:mcp-cancel-failed-child"); |
| 926 | const taskId = NodeId.make("node:mcp-cancel-failed-task"); |
| 927 | const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]); |
| 928 | const parentProjection = { |
| 929 | thread: { id: parentThreadId }, |
| 930 | runs: [], |
| 931 | contextTransfers: [], |
| 932 | subagents: [ |
| 933 | { |
| 934 | id: taskId, |
| 935 | threadId: parentThreadId, |
| 936 | origin: "app_owned", |
| 937 | childThreadId, |
| 938 | driver: "codex", |
| 939 | model: "gpt-5.6-terra", |
| 940 | result: null, |
| 941 | completionDelivery: { state: "pending" }, |
| 942 | }, |
| 943 | ], |
| 944 | } as unknown as OrchestrationV2ThreadProjection; |
| 945 | const childProjection = { |
| 946 | thread: { id: childThreadId, title: "Child" }, |
| 947 | runs: [{ id: childRunId, status: "running" }], |
| 948 | contextTransfers: [], |
| 949 | messages: [], |
| 950 | subagents: [], |
| 951 | providerThreads: [], |
| 952 | providerTurns: [], |
| 953 | runtimeRequests: [], |
| 954 | } as unknown as OrchestrationV2ThreadProjection; |
| 955 | const layerDependencies = Layer.mergeAll( |
| 956 | NodeServices.layer, |
| 957 | NodeCrypto.layer, |
| 958 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 959 | getThreadRecords: (threadId) => |
| 960 | Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), |
| 961 | getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), |
| 962 | listAppOwnedChildThreadIds: () => Effect.succeed([]), |
| 963 | dispatch: (command) => |
| 964 | Ref.update(dispatched, (commands) => [...commands, command]).pipe( |
| 965 | Effect.andThen(Effect.fail(new Error("simulated stop failure") as never)), |
| 966 | ), |
| 967 | stopDelegatedTasks: () => Effect.void, |
| 968 | cancelDelegatedTask: ({ command, stopDescendants }) => |
| 969 | stopDescendants(() => Effect.die("No remote descendants in this test")).pipe( |
| 970 | Effect.andThen(Ref.update(dispatched, (commands) => [...commands, command])), |
| 971 | Effect.andThen( |
| 972 | Effect.fail( |
| 973 | new OrchestratorDispatchError({ |
| 974 | commandId: command.commandId, |
| 975 | commandType: command.type, |
| 976 | cause: new Error("simulated stop failure"), |
| 977 | }) as never, |
| 978 | ), |
| 979 | ), |
| 980 | ), |
| 981 | }), |
| 982 | ServerSettings.layerTest(), |
| 983 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 984 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 985 | list: () => Effect.succeed([]), |
| 986 | }), |
| 987 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 988 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 989 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 990 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 991 | ); |
| 992 | const scope: McpInvocationScope = { |
| 993 | environmentId: EnvironmentId.make("environment:mcp-cancel-failed"), |
| 994 | requestNamespace: "provider-session:mcp-cancel-failed", |
| 995 | thread: { |
| 996 | threadId: parentThreadId, |
| 997 | providerSessionId: "provider-session:mcp-cancel-failed", |
| 998 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 999 | }, |
| 1000 | client: undefined, |
| 1001 | capabilities: new Set(["orchestration"]), |
| 1002 | issuedAt: 1, |
| 1003 | }; |
| 1004 | |
| 1005 | yield* Effect.gen(function* () { |
| 1006 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1007 | const error = yield* service |
| 1008 | .cancelTask(scope, { taskId, clientRequestId: "cancel-failed-task" }) |
| 1009 | .pipe(Effect.flip); |
| 1010 | assert.equal(error.code, "task_not_cancellable"); |
| 1011 | assert.equal( |
| 1012 | error.message, |
| 1013 | `Unable to stop delegated task ${taskId}: simulated stop failure`, |
| 1014 | ); |
| 1015 | assert.deepEqual( |
| 1016 | (yield* Ref.get(dispatched)).map((command) => (command as { type: string }).type), |
| 1017 | ["thread.stop"], |
| 1018 | ); |
| 1019 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 1020 | }), |
| 1021 | ); |
| 1022 | |
| 1023 | it.effect("returns cancel requested when post-stop disposal fails", () => |
| 1024 | Effect.gen(function* () { |
| 1025 | const parentThreadId = ThreadId.make("thread:mcp-cancel-dispose-failed-parent"); |
| 1026 | const childThreadId = ThreadId.make("thread:mcp-cancel-dispose-failed-child"); |
| 1027 | const childRunId = RunId.make("run:mcp-cancel-dispose-failed-child"); |
| 1028 | const taskId = NodeId.make("node:mcp-cancel-dispose-failed-task"); |
| 1029 | const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]); |
| 1030 | const parentProjection = { |
| 1031 | thread: { id: parentThreadId }, |
| 1032 | runs: [], |
| 1033 | contextTransfers: [], |
| 1034 | subagents: [ |
| 1035 | { |
| 1036 | id: taskId, |
| 1037 | threadId: parentThreadId, |
| 1038 | origin: "app_owned", |
| 1039 | childThreadId, |
| 1040 | driver: "codex", |
| 1041 | model: "gpt-5.6-terra", |
| 1042 | result: null, |
| 1043 | completionDelivery: { state: "pending" }, |
| 1044 | }, |
| 1045 | ], |
| 1046 | } as unknown as OrchestrationV2ThreadProjection; |
| 1047 | const childProjection = { |
| 1048 | thread: { id: childThreadId, title: "Child" }, |
| 1049 | runs: [{ id: childRunId, status: "running" }], |
| 1050 | contextTransfers: [], |
| 1051 | messages: [], |
| 1052 | subagents: [], |
| 1053 | providerThreads: [], |
| 1054 | providerTurns: [], |
| 1055 | runtimeRequests: [], |
| 1056 | } as unknown as OrchestrationV2ThreadProjection; |
| 1057 | const layerDependencies = Layer.mergeAll( |
| 1058 | NodeServices.layer, |
| 1059 | NodeCrypto.layer, |
| 1060 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1061 | getThreadRecords: (threadId) => |
| 1062 | Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), |
| 1063 | getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), |
| 1064 | listAppOwnedChildThreadIds: () => Effect.succeed([]), |
| 1065 | dispatch: (command) => |
| 1066 | Ref.update(dispatched, (commands) => [...commands, command]).pipe( |
| 1067 | Effect.andThen( |
| 1068 | command.type === "delegated_task.completion-delivery.dispose" |
| 1069 | ? Effect.fail(new Error("simulated disposal failure") as never) |
| 1070 | : Effect.succeed({} as never), |
| 1071 | ), |
| 1072 | ), |
| 1073 | stopDelegatedTasks: () => Effect.void, |
| 1074 | cancelDelegatedTask: ({ command, stopDescendants }) => |
| 1075 | stopDescendants(() => Effect.die("No remote descendants in this test")).pipe( |
| 1076 | Effect.andThen(Ref.update(dispatched, (commands) => [...commands, command])), |
| 1077 | ), |
| 1078 | }), |
| 1079 | ServerSettings.layerTest(), |
| 1080 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 1081 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 1082 | list: () => Effect.succeed([]), |
| 1083 | }), |
| 1084 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 1085 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 1086 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 1087 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 1088 | ); |
| 1089 | const scope: McpInvocationScope = { |
| 1090 | environmentId: EnvironmentId.make("environment:mcp-cancel-dispose-failed"), |
| 1091 | requestNamespace: "provider-session:mcp-cancel-dispose-failed", |
| 1092 | thread: { |
| 1093 | threadId: parentThreadId, |
| 1094 | providerSessionId: "provider-session:mcp-cancel-dispose-failed", |
| 1095 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 1096 | }, |
| 1097 | client: undefined, |
| 1098 | capabilities: new Set(["orchestration"]), |
| 1099 | issuedAt: 1, |
| 1100 | }; |
| 1101 | |
| 1102 | yield* Effect.gen(function* () { |
| 1103 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1104 | const result = yield* service.cancelTask(scope, { |
| 1105 | taskId, |
| 1106 | clientRequestId: "cancel-dispose-failed-task", |
| 1107 | }); |
| 1108 | assert.equal(result.status, "cancel_requested"); |
| 1109 | assert.deepEqual( |
| 1110 | (yield* Ref.get(dispatched)).map((command) => (command as { type: string }).type), |
| 1111 | ["thread.stop", "delegated_task.completion-delivery.dispose"], |
| 1112 | ); |
| 1113 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 1114 | }), |
| 1115 | ); |
| 1116 | |
| 1117 | it.effect( |
| 1118 | "reports the dispatch cause instead of the generic wrapper when disposing a finished task's completion delivery fails", |
| 1119 | () => |
| 1120 | Effect.gen(function* () { |
| 1121 | const parentThreadId = ThreadId.make("thread:mcp-cancel-dispose-cause-parent"); |
| 1122 | const childThreadId = ThreadId.make("thread:mcp-cancel-dispose-cause-child"); |
| 1123 | const taskId = NodeId.make("node:mcp-cancel-dispose-cause-task"); |
| 1124 | const parentProjection = { |
| 1125 | thread: { id: parentThreadId }, |
| 1126 | runs: [], |
| 1127 | contextTransfers: [], |
| 1128 | subagents: [ |
| 1129 | { |
| 1130 | id: taskId, |
| 1131 | threadId: parentThreadId, |
| 1132 | origin: "app_owned", |
| 1133 | childThreadId, |
| 1134 | driver: "codex", |
| 1135 | model: "gpt-5.6-terra", |
| 1136 | status: "completed", |
| 1137 | result: "Done.", |
| 1138 | completionDelivery: { state: "pending" }, |
| 1139 | }, |
| 1140 | ], |
| 1141 | } as unknown as OrchestrationV2ThreadProjection; |
| 1142 | const childProjection = { |
| 1143 | thread: { id: childThreadId, title: "Child" }, |
| 1144 | runs: [], |
| 1145 | contextTransfers: [], |
| 1146 | messages: [], |
| 1147 | subagents: [], |
| 1148 | providerThreads: [], |
| 1149 | providerTurns: [], |
| 1150 | runtimeRequests: [], |
| 1151 | } as unknown as OrchestrationV2ThreadProjection; |
| 1152 | const layerDependencies = Layer.mergeAll( |
| 1153 | NodeServices.layer, |
| 1154 | NodeCrypto.layer, |
| 1155 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1156 | getThreadRecords: (threadId) => |
| 1157 | Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), |
| 1158 | getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), |
| 1159 | listAppOwnedChildThreadIds: () => Effect.succeed([]), |
| 1160 | stopDelegatedTasks: () => Effect.void, |
| 1161 | cancelDelegatedTask: () => Effect.void, |
| 1162 | dispatch: (command) => |
| 1163 | command.type === "delegated_task.completion-delivery.dispose" |
| 1164 | ? Effect.fail( |
| 1165 | new OrchestratorDispatchError({ |
| 1166 | commandId: command.commandId, |
| 1167 | commandType: command.type, |
| 1168 | cause: new Error("refused by the orchestrator"), |
| 1169 | }) as never, |
| 1170 | ) |
| 1171 | : Effect.succeed({} as never), |
| 1172 | }), |
| 1173 | ServerSettings.layerTest(), |
| 1174 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 1175 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 1176 | list: () => Effect.succeed([]), |
| 1177 | }), |
| 1178 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 1179 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 1180 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 1181 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 1182 | ); |
| 1183 | const scope: McpInvocationScope = { |
| 1184 | environmentId: EnvironmentId.make("environment:mcp-cancel-dispose-cause"), |
| 1185 | requestNamespace: "provider-session:mcp-cancel-dispose-cause", |
| 1186 | thread: { |
| 1187 | threadId: parentThreadId, |
| 1188 | providerSessionId: "provider-session:mcp-cancel-dispose-cause", |
| 1189 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 1190 | }, |
| 1191 | client: undefined, |
| 1192 | capabilities: new Set(["orchestration"]), |
| 1193 | issuedAt: 1, |
| 1194 | }; |
| 1195 | const error = yield* Effect.gen(function* () { |
| 1196 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1197 | return yield* service |
| 1198 | .cancelTask(scope, { taskId, clientRequestId: "cancel-dispose-dispatch-cause" }) |
| 1199 | .pipe(Effect.flip); |
| 1200 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 1201 | assert.equal(error.code, "orchestration_error"); |
| 1202 | assert.equal( |
| 1203 | error.message, |
| 1204 | `Unable to dispose delegated task ${taskId} completion delivery: refused by the orchestrator`, |
| 1205 | ); |
| 1206 | }), |
| 1207 | ); |
| 1208 | |
| 1209 | it.effect("refuses to cancel a task whose child now runs above the parent's modes", () => |
| 1210 | Effect.gen(function* () { |
| 1211 | const parentThreadId = ThreadId.make("thread:mcp-cancel-dispose-failed-parent"); |
| 1212 | const childThreadId = ThreadId.make("thread:mcp-cancel-dispose-failed-child"); |
| 1213 | const childRunId = RunId.make("run:mcp-cancel-dispose-failed-child"); |
| 1214 | const taskId = NodeId.make("node:mcp-cancel-dispose-failed-task"); |
| 1215 | const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]); |
| 1216 | const parentProjection = { |
| 1217 | thread: { id: parentThreadId, runtimeMode: "approval-required", interactionMode: "plan" }, |
| 1218 | runs: [], |
| 1219 | contextTransfers: [], |
| 1220 | subagents: [ |
| 1221 | { |
| 1222 | id: taskId, |
| 1223 | threadId: parentThreadId, |
| 1224 | origin: "app_owned", |
| 1225 | childThreadId, |
| 1226 | driver: "codex", |
| 1227 | model: "gpt-5.6-terra", |
| 1228 | result: null, |
| 1229 | completionDelivery: { state: "pending" }, |
| 1230 | }, |
| 1231 | ], |
| 1232 | } as unknown as OrchestrationV2ThreadProjection; |
| 1233 | const childProjection = { |
| 1234 | thread: { id: childThreadId, title: "Child" }, |
| 1235 | runs: [{ id: childRunId, status: "running" }], |
| 1236 | contextTransfers: [], |
| 1237 | messages: [], |
| 1238 | subagents: [], |
| 1239 | providerThreads: [], |
| 1240 | providerTurns: [], |
| 1241 | runtimeRequests: [], |
| 1242 | } as unknown as OrchestrationV2ThreadProjection; |
| 1243 | const layerDependencies = Layer.mergeAll( |
| 1244 | NodeServices.layer, |
| 1245 | NodeCrypto.layer, |
| 1246 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1247 | getThreadRecords: (threadId) => |
| 1248 | Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), |
| 1249 | getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), |
| 1250 | listAppOwnedChildThreadIds: () => Effect.succeed([]), |
| 1251 | dispatch: (command) => |
| 1252 | Ref.update(dispatched, (commands) => [...commands, command]).pipe( |
| 1253 | Effect.andThen( |
| 1254 | command.type === "delegated_task.completion-delivery.dispose" |
| 1255 | ? Effect.fail(new Error("simulated disposal failure") as never) |
| 1256 | : Effect.succeed({} as never), |
| 1257 | ), |
| 1258 | ), |
| 1259 | stopDelegatedTasks: () => Effect.void, |
| 1260 | cancelDelegatedTask: ({ command, stopDescendants }) => |
| 1261 | stopDescendants(() => Effect.die("No remote descendants in this test")).pipe( |
| 1262 | Effect.andThen(Ref.update(dispatched, (commands) => [...commands, command])), |
| 1263 | ), |
| 1264 | }), |
| 1265 | ServerSettings.layerTest(), |
| 1266 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 1267 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 1268 | list: () => Effect.succeed([]), |
| 1269 | }), |
| 1270 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 1271 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 1272 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 1273 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 1274 | ); |
| 1275 | const scope: McpInvocationScope = { |
| 1276 | environmentId: EnvironmentId.make("environment:mcp-cancel-dispose-failed"), |
| 1277 | requestNamespace: "provider-session:mcp-cancel-dispose-failed", |
| 1278 | thread: { |
| 1279 | threadId: parentThreadId, |
| 1280 | providerSessionId: "provider-session:mcp-cancel-dispose-failed", |
| 1281 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 1282 | }, |
| 1283 | client: undefined, |
| 1284 | capabilities: new Set(["orchestration"]), |
| 1285 | issuedAt: 1, |
| 1286 | }; |
| 1287 | |
| 1288 | yield* Effect.gen(function* () { |
| 1289 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1290 | const error = yield* service |
| 1291 | .cancelTask(scope, { taskId, clientRequestId: "cancel-above-modes" }) |
| 1292 | .pipe(Effect.flip); |
| 1293 | assert.equal(error.code, "runtime_mode_escalation_denied"); |
| 1294 | assert.deepEqual(yield* Ref.get(dispatched), []); |
| 1295 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 1296 | }), |
| 1297 | ); |
| 1298 | |
| 1299 | const cancelOverRaisedGrandchild = (child: { |
| 1300 | readonly deleted: boolean; |
| 1301 | readonly raisedDuringStop?: boolean; |
| 1302 | }) => |
| 1303 | Effect.gen(function* () { |
| 1304 | const parentThreadId = ThreadId.make("thread:mcp-cancel-grandchild-parent"); |
| 1305 | const childThreadId = ThreadId.make("thread:mcp-cancel-grandchild-child"); |
| 1306 | const grandchildThreadId = ThreadId.make("thread:mcp-cancel-grandchild-grandchild"); |
| 1307 | const taskId = NodeId.make("node:mcp-cancel-grandchild-task"); |
| 1308 | const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]); |
| 1309 | const stoppedBelow = yield* Ref.make(false); |
| 1310 | const subagentReads = yield* Ref.make<ReadonlyArray<ProjectionRecordFilter | undefined>>([]); |
| 1311 | const appOwnedTask = ( |
| 1312 | id: string, |
| 1313 | threadId: ThreadId, |
| 1314 | childId: ThreadId, |
| 1315 | settled?: "settled", |
| 1316 | ) => ({ |
| 1317 | id: NodeId.make(id), |
| 1318 | threadId, |
| 1319 | origin: "app_owned", |
| 1320 | childThreadId: childId, |
| 1321 | driver: "codex", |
| 1322 | model: "gpt-5.6-terra", |
| 1323 | status: settled === undefined ? "running" : "completed", |
| 1324 | result: settled === undefined ? null : "Done.", |
| 1325 | completionDelivery: { state: settled === undefined ? "pending" : "delivered" }, |
| 1326 | }); |
| 1327 | // Older tasks the parent and child dispatched and that have long settled. |
| 1328 | const settledThreadId = ThreadId.make("thread:mcp-cancel-grandchild-settled"); |
| 1329 | const projections = new Map([ |
| 1330 | [ |
| 1331 | parentThreadId, |
| 1332 | { |
| 1333 | thread: { |
| 1334 | id: parentThreadId, |
| 1335 | runtimeMode: "approval-required", |
| 1336 | interactionMode: "default", |
| 1337 | }, |
| 1338 | runs: [], |
| 1339 | contextTransfers: [], |
| 1340 | subagents: [ |
| 1341 | appOwnedTask( |
| 1342 | "node:mcp-cancel-grandchild-old", |
| 1343 | parentThreadId, |
| 1344 | settledThreadId, |
| 1345 | "settled", |
| 1346 | ), |
| 1347 | appOwnedTask(taskId, parentThreadId, childThreadId), |
| 1348 | ], |
| 1349 | }, |
| 1350 | ], |
| 1351 | [ |
| 1352 | childThreadId, |
| 1353 | { |
| 1354 | thread: { id: childThreadId, title: "Child" }, |
| 1355 | runs: [{ id: RunId.make("run:mcp-cancel-grandchild-child"), status: "running" }], |
| 1356 | contextTransfers: [], |
| 1357 | messages: [], |
| 1358 | subagents: [ |
| 1359 | appOwnedTask( |
| 1360 | "node:mcp-cancel-grandchild-done", |
| 1361 | childThreadId, |
| 1362 | settledThreadId, |
| 1363 | "settled", |
| 1364 | ), |
| 1365 | appOwnedTask("node:mcp-cancel-grandchild-below", childThreadId, grandchildThreadId), |
| 1366 | ], |
| 1367 | providerThreads: [], |
| 1368 | providerTurns: [], |
| 1369 | runtimeRequests: [], |
| 1370 | }, |
| 1371 | ], |
| 1372 | [ |
| 1373 | settledThreadId, |
| 1374 | { |
| 1375 | thread: { id: settledThreadId }, |
| 1376 | runs: [], |
| 1377 | contextTransfers: [], |
| 1378 | messages: [], |
| 1379 | subagents: [], |
| 1380 | providerThreads: [], |
| 1381 | runtimeRequests: [], |
| 1382 | }, |
| 1383 | ], |
| 1384 | [ |
| 1385 | grandchildThreadId, |
| 1386 | { |
| 1387 | thread: { id: grandchildThreadId }, |
| 1388 | runs: [], |
| 1389 | contextTransfers: [], |
| 1390 | messages: [], |
| 1391 | subagents: [], |
| 1392 | providerThreads: [], |
| 1393 | providerTurns: [], |
| 1394 | runtimeRequests: [], |
| 1395 | }, |
| 1396 | ], |
| 1397 | ]) as unknown as ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection>; |
| 1398 | const layerDependencies = Layer.mergeAll( |
| 1399 | NodeServices.layer, |
| 1400 | NodeCrypto.layer, |
| 1401 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1402 | getThreadRecords: (threadId, fields, filter) => |
| 1403 | ((fields as ReadonlyArray<string>).includes("subagents") |
| 1404 | ? Ref.update(subagentReads, (reads) => [...reads, filter]) |
| 1405 | : Effect.void |
| 1406 | ).pipe(Effect.as(projections.get(threadId)!)), |
| 1407 | listAppOwnedChildThreadIds: (threadId) => |
| 1408 | Effect.succeed( |
| 1409 | projections |
| 1410 | .get(threadId)! |
| 1411 | .subagents.flatMap((task) => |
| 1412 | task.origin === "app_owned" && task.childThreadId !== null |
| 1413 | ? [task.childThreadId] |
| 1414 | : [], |
| 1415 | ), |
| 1416 | ), |
| 1417 | getThreadShell: (threadId) => |
| 1418 | Effect.succeed( |
| 1419 | threadId === grandchildThreadId && child.raisedDuringStop !== true |
| 1420 | ? liveThreadShell(threadId) |
| 1421 | : threadId === childThreadId && child.deleted |
| 1422 | ? null |
| 1423 | : liveThreadShell(threadId, { runtimeMode: "approval-required" }), |
| 1424 | ), |
| 1425 | dispatch: (command) => |
| 1426 | Ref.update(dispatched, (commands) => [...commands, command]).pipe( |
| 1427 | Effect.as({} as never), |
| 1428 | ), |
| 1429 | cancelDelegatedTask: ({ command, stopDescendants }) => |
| 1430 | stopDescendants(() => Effect.die("No remote descendants in this test")).pipe( |
| 1431 | Effect.andThen(Ref.update(dispatched, (commands) => [...commands, command])), |
| 1432 | ), |
| 1433 | stopDelegatedTasks: () => |
| 1434 | Effect.gen(function* () { |
| 1435 | const limit = yield* DispatchModeLimit; |
| 1436 | if (child.raisedDuringStop === true && limit?.refused !== undefined) { |
| 1437 | const refusal: DispatchModeRefusal = { |
| 1438 | threadId: grandchildThreadId, |
| 1439 | mode: "runtime", |
| 1440 | runtimeMode: "full-access", |
| 1441 | interactionMode: "default", |
| 1442 | }; |
| 1443 | yield* Ref.set(limit.refused, refusal); |
| 1444 | return yield* new OrchestratorThreadAboveModeLimitError({ |
| 1445 | commandId: CommandId.make("stop-grandchild"), |
| 1446 | threadId: grandchildThreadId, |
| 1447 | mode: "runtime", |
| 1448 | runtimeMode: "full-access", |
| 1449 | interactionMode: "default", |
| 1450 | }); |
| 1451 | } |
| 1452 | yield* Ref.set(stoppedBelow, true); |
| 1453 | }), |
| 1454 | }), |
| 1455 | ServerSettings.layerTest(), |
| 1456 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 1457 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 1458 | list: () => Effect.succeed([]), |
| 1459 | }), |
| 1460 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 1461 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 1462 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 1463 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 1464 | ); |
| 1465 | const scope: McpInvocationScope = { |
| 1466 | environmentId: EnvironmentId.make("environment:mcp-cancel-grandchild"), |
| 1467 | requestNamespace: "provider-session:mcp-cancel-grandchild", |
| 1468 | thread: { |
| 1469 | threadId: parentThreadId, |
| 1470 | providerSessionId: "provider-session:mcp-cancel-grandchild", |
| 1471 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 1472 | }, |
| 1473 | client: undefined, |
| 1474 | capabilities: new Set(["orchestration"]), |
| 1475 | issuedAt: 1, |
| 1476 | }; |
| 1477 | |
| 1478 | return yield* Effect.gen(function* () { |
| 1479 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1480 | const error = yield* service |
| 1481 | .cancelTask(scope, { taskId, clientRequestId: "cancel-grandchild-above-modes" }) |
| 1482 | .pipe(Effect.flip); |
| 1483 | // No read decodes every task a thread has dispatched. |
| 1484 | for (const filter of yield* Ref.get(subagentReads)) { |
| 1485 | assert.isTrue( |
| 1486 | filter?.subagentIds !== undefined || filter?.omitSettledSubagents !== undefined, |
| 1487 | ); |
| 1488 | } |
| 1489 | return { |
| 1490 | code: error.code, |
| 1491 | dispatched: yield* Ref.get(dispatched), |
| 1492 | stoppedBelow: yield* Ref.get(stoppedBelow), |
| 1493 | }; |
| 1494 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 1495 | }); |
| 1496 | |
| 1497 | it.effect("refuses to cancel a task when a task under it now runs above the parent's modes", () => |
| 1498 | Effect.gen(function* () { |
| 1499 | assert.deepEqual(yield* cancelOverRaisedGrandchild({ deleted: false }), { |
| 1500 | code: "runtime_mode_escalation_denied", |
| 1501 | dispatched: [], |
| 1502 | stoppedBelow: false, |
| 1503 | }); |
| 1504 | }), |
| 1505 | ); |
| 1506 | |
| 1507 | it.effect("reports a task under the child that its user raises while it is being stopped", () => |
| 1508 | Effect.gen(function* () { |
| 1509 | const outcome = yield* cancelOverRaisedGrandchild({ deleted: false, raisedDuringStop: true }); |
| 1510 | assert.equal(outcome.code, "runtime_mode_escalation_denied"); |
| 1511 | assert.isFalse(outcome.stoppedBelow); |
| 1512 | }), |
| 1513 | ); |
| 1514 | |
| 1515 | it.effect("checks the tasks under a deleted child before cancelling it", () => |
| 1516 | Effect.gen(function* () { |
| 1517 | assert.deepEqual(yield* cancelOverRaisedGrandchild({ deleted: true }), { |
| 1518 | code: "runtime_mode_escalation_denied", |
| 1519 | dispatched: [], |
| 1520 | stoppedBelow: false, |
| 1521 | }); |
| 1522 | }), |
| 1523 | ); |
| 1524 | }); |
| 1525 | |
| 1526 | describe("OrchestratorMcpService provider resolution", () => { |
| 1527 | const parentThreadId = ThreadId.make("thread:mcp-providers-parent"); |
| 1528 | const childThreadId = ThreadId.make("thread:mcp-providers-child"); |
| 1529 | const parentRunId = RunId.make("run:mcp-providers-parent"); |
| 1530 | const parentNodeId = NodeId.make("node:mcp-providers-root"); |
| 1531 | const taskId = NodeId.make("node:mcp-providers-task"); |
| 1532 | const projectId = ProjectId.make("project:mcp-providers"); |
| 1533 | const codexInstanceId = ProviderInstanceId.make("codex"); |
| 1534 | const antigravityInstanceId = ProviderInstanceId.make("antigravity"); |
| 1535 | |
| 1536 | const scope: McpInvocationScope = { |
| 1537 | environmentId: EnvironmentId.make("environment:mcp-providers"), |
| 1538 | requestNamespace: "provider-session:mcp-providers", |
| 1539 | thread: { |
| 1540 | threadId: parentThreadId, |
| 1541 | providerSessionId: "provider-session:mcp-providers", |
| 1542 | providerInstanceId: codexInstanceId, |
| 1543 | }, |
| 1544 | client: undefined, |
| 1545 | capabilities: new Set(["orchestration"]), |
| 1546 | issuedAt: 1, |
| 1547 | }; |
| 1548 | |
| 1549 | const providerSnapshot = (input: { |
| 1550 | readonly instanceId: ProviderInstanceId; |
| 1551 | readonly driver: ProviderDriverKind; |
| 1552 | readonly model?: string; |
| 1553 | readonly enabled?: boolean; |
| 1554 | }): ServerProvider => ({ |
| 1555 | instanceId: input.instanceId, |
| 1556 | driver: input.driver, |
| 1557 | enabled: input.enabled ?? true, |
| 1558 | installed: input.enabled !== false, |
| 1559 | version: input.enabled === false ? null : "test", |
| 1560 | status: input.enabled === false ? "disabled" : "ready", |
| 1561 | auth: { status: input.enabled === false ? "unknown" : "authenticated" }, |
| 1562 | ...(input.enabled === false ? { message: "Provider is disabled in T3 Code settings." } : {}), |
| 1563 | checkedAt: "2026-09-13T00:00:00.000Z", |
| 1564 | models: |
| 1565 | input.model === undefined |
| 1566 | ? [] |
| 1567 | : [{ slug: input.model, name: input.model, isCustom: false, capabilities: null }], |
| 1568 | slashCommands: [], |
| 1569 | skills: [], |
| 1570 | }); |
| 1571 | |
| 1572 | const providerRegistryLayer = (providers: ReadonlyArray<ServerProvider>) => |
| 1573 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 1574 | getProviders: Effect.succeed(providers), |
| 1575 | refreshInstance: () => Effect.succeed(providers), |
| 1576 | }); |
| 1577 | |
| 1578 | const adapterRegistryLayer = (instanceIds: ReadonlyArray<ProviderInstanceId>) => |
| 1579 | Layer.succeed( |
| 1580 | ProviderAdapterRegistry.ProviderAdapterRegistryV2, |
| 1581 | ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({ |
| 1582 | list: () => Effect.succeed(instanceIds), |
| 1583 | get: (instanceId) => |
| 1584 | instanceIds.includes(instanceId) |
| 1585 | ? Effect.succeed({ |
| 1586 | instanceId, |
| 1587 | } as unknown as ProviderAdapter.ProviderAdapterV2["Service"]) |
| 1588 | : Effect.fail( |
| 1589 | new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({ instanceId }), |
| 1590 | ), |
| 1591 | }), |
| 1592 | ); |
| 1593 | |
| 1594 | const parentProjection = ( |
| 1595 | subagents: ReadonlyArray<unknown>, |
| 1596 | modelSelection: { |
| 1597 | readonly instanceId: ProviderInstanceId; |
| 1598 | readonly model: string; |
| 1599 | readonly options?: ReadonlyArray<{ readonly id: string; readonly value: unknown }>; |
| 1600 | } = { instanceId: codexInstanceId, model: "gpt-5.4" }, |
| 1601 | ): OrchestrationV2ThreadProjection => |
| 1602 | ({ |
| 1603 | thread: { |
| 1604 | id: parentThreadId, |
| 1605 | projectId, |
| 1606 | title: "MCP parent", |
| 1607 | createdBy: "user", |
| 1608 | creationSource: "web", |
| 1609 | modelSelection, |
| 1610 | runtimeMode: "full-access", |
| 1611 | interactionMode: "default", |
| 1612 | }, |
| 1613 | runs: [ |
| 1614 | { |
| 1615 | id: parentRunId, |
| 1616 | ordinal: 1, |
| 1617 | status: "running", |
| 1618 | rootNodeId: parentNodeId, |
| 1619 | providerInstanceId: codexInstanceId, |
| 1620 | modelSelection, |
| 1621 | }, |
| 1622 | ], |
| 1623 | contextTransfers: [], |
| 1624 | subagents, |
| 1625 | }) as unknown as OrchestrationV2ThreadProjection; |
| 1626 | |
| 1627 | const childProjection = { |
| 1628 | thread: { id: childThreadId, title: "Child" }, |
| 1629 | runs: [], |
| 1630 | contextTransfers: [], |
| 1631 | messages: [], |
| 1632 | subagents: [], |
| 1633 | providerThreads: [], |
| 1634 | providerTurns: [], |
| 1635 | runtimeRequests: [], |
| 1636 | turnItems: [], |
| 1637 | } as unknown as OrchestrationV2ThreadProjection; |
| 1638 | |
| 1639 | it.effect.each([ |
| 1640 | "parent completion", |
| 1641 | "nested child completion", |
| 1642 | "child run completion", |
| 1643 | "child question", |
| 1644 | "child approval", |
| 1645 | "Node fetch's 300 s idle timeout", |
| 1646 | ] as const)("a task wait still returns on %s", (wake) => |
| 1647 | Effect.gen(function* () { |
| 1648 | const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>(); |
| 1649 | const subscribed = yield* Deferred.make<void>(); |
| 1650 | const nestedId = NodeId.make("node:mcp-wait-nested"); |
| 1651 | const childRunId = RunId.make("run:mcp-wait-child"); |
| 1652 | const childRootId = NodeId.make("node:mcp-wait-child-root"); |
| 1653 | const eventThreadId = wake === "parent completion" ? parentThreadId : childThreadId; |
| 1654 | const eventType = |
| 1655 | wake === "child run completion" |
| 1656 | ? "run.updated" |
| 1657 | : wake === "child question" || wake === "child approval" |
| 1658 | ? "runtime-request.updated" |
| 1659 | : "subagent.updated"; |
| 1660 | const terminal = wake.endsWith("completion"); |
| 1661 | let ready = false; |
| 1662 | const task = () => ({ |
| 1663 | id: taskId, |
| 1664 | threadId: parentThreadId, |
| 1665 | runId: parentRunId, |
| 1666 | parentNodeId, |
| 1667 | origin: "app_owned", |
| 1668 | providerInstanceId: codexInstanceId, |
| 1669 | driver: "codex", |
| 1670 | childThreadId, |
| 1671 | model: "gpt-5.4", |
| 1672 | status: ready && terminal ? "completed" : "running", |
| 1673 | result: ready && wake === "parent completion" ? "done" : null, |
| 1674 | }); |
| 1675 | const child = () => |
| 1676 | ({ |
| 1677 | ...childProjection, |
| 1678 | runs: [ |
| 1679 | { |
| 1680 | id: childRunId, |
| 1681 | ordinal: 1, |
| 1682 | status: |
| 1683 | wake === "nested child completion" || (ready && terminal) ? "completed" : "running", |
| 1684 | startedAt: DateTime.makeUnsafe(0), |
| 1685 | completedAt: ready && terminal ? DateTime.makeUnsafe(1) : null, |
| 1686 | }, |
| 1687 | ], |
| 1688 | subagents: |
| 1689 | wake === "nested child completion" |
| 1690 | ? [{ id: nestedId, status: ready ? "completed" : "running" }] |
| 1691 | : [], |
| 1692 | nodes: [{ id: childRootId, runId: childRunId }], |
| 1693 | runtimeRequests: |
| 1694 | ready && !terminal |
| 1695 | ? [ |
| 1696 | { |
| 1697 | id: "request:mcp-wait-answer", |
| 1698 | nodeId: childRootId, |
| 1699 | kind: wake === "child question" ? "user_input" : "command", |
| 1700 | status: "pending", |
| 1701 | responseCapability: { type: "live" }, |
| 1702 | createdAt: DateTime.makeUnsafe(0), |
| 1703 | }, |
| 1704 | ] |
| 1705 | : [], |
| 1706 | }) as unknown as OrchestrationV2ThreadProjection; |
| 1707 | const dependencies = Layer.mergeAll( |
| 1708 | NodeServices.layer, |
| 1709 | NodeCrypto.layer, |
| 1710 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1711 | hasReceipt: () => Effect.succeed(false), |
| 1712 | assertProviderInstanceEnabled: () => Effect.void, |
| 1713 | isProviderInstanceEnabledForProject: () => Effect.succeed(true), |
| 1714 | getThreadRecords: (threadId) => |
| 1715 | Effect.sync(() => (threadId === parentThreadId ? parentProjection([task()]) : child())), |
| 1716 | getThreadEventSequence: () => Effect.succeed(0), |
| 1717 | delegatedTaskResultPending: () => Effect.succeed(false), |
| 1718 | streamStoredEventsFrom: (input) => |
| 1719 | input?.threadId === eventThreadId && input.eventType === eventType |
| 1720 | ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe( |
| 1721 | Stream.drain, |
| 1722 | Stream.concat(Stream.fromQueue(events)), |
| 1723 | ) |
| 1724 | : Stream.never, |
| 1725 | dispatch: () => |
| 1726 | Effect.succeed({ |
| 1727 | sequence: 1, |
| 1728 | storedEvents: [{ event: { type: "subagent.updated", payload: task() } }], |
| 1729 | } as never), |
| 1730 | }), |
| 1731 | ServerSettings.layerTest(), |
| 1732 | providerRegistryLayer([ |
| 1733 | providerSnapshot({ |
| 1734 | instanceId: codexInstanceId, |
| 1735 | driver: ProviderDriverKind.make("codex"), |
| 1736 | model: "gpt-5.4", |
| 1737 | }), |
| 1738 | ]), |
| 1739 | adapterRegistryLayer([codexInstanceId]), |
| 1740 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 1741 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 1742 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 1743 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 1744 | ); |
| 1745 | yield* Effect.gen(function* () { |
| 1746 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1747 | const waiting = yield* service |
| 1748 | .delegateTask(scope, { task: "Review the change.", mode: "wait" }) |
| 1749 | .pipe(Effect.forkChild); |
| 1750 | yield* Deferred.await(subscribed); |
| 1751 | if (wake === "Node fetch's 300 s idle timeout") { |
| 1752 | // Nothing is written during the wait, so undici drops the call at 300 s, before any handle. |
| 1753 | const beforeClientTimeout = yield* Fiber.join(waiting).pipe( |
| 1754 | Effect.timeoutOption(Duration.seconds(299)), |
| 1755 | Effect.forkChild, |
| 1756 | ); |
| 1757 | yield* TestClock.adjust(Duration.seconds(299)); |
| 1758 | const result = yield* Fiber.join(beforeClientTimeout); |
| 1759 | assert.isTrue( |
| 1760 | Option.isSome(result), |
| 1761 | "a wait without timeoutMs was still silent at 299 s, so a Node MCP client loses the taskId", |
| 1762 | ); |
| 1763 | if (Option.isSome(result)) { |
| 1764 | assert.equal(result.value.taskId, taskId); |
| 1765 | assert.isTrue(result.value.waitTimedOut); |
| 1766 | } |
| 1767 | return; |
| 1768 | } |
| 1769 | ready = true; |
| 1770 | if (wake === "parent completion") { |
| 1771 | yield* Queue.offer(events, { |
| 1772 | sequence: 2, |
| 1773 | event: { |
| 1774 | type: "subagent.updated", |
| 1775 | threadId: parentThreadId, |
| 1776 | payload: { ...task(), id: nestedId }, |
| 1777 | }, |
| 1778 | } as unknown as OrchestrationV2StoredEvent); |
| 1779 | } |
| 1780 | yield* Queue.offer(events, { |
| 1781 | sequence: 3, |
| 1782 | event: { |
| 1783 | type: eventType, |
| 1784 | threadId: eventThreadId, |
| 1785 | payload: { id: wake === "parent completion" ? taskId : nestedId }, |
| 1786 | }, |
| 1787 | } as unknown as OrchestrationV2StoredEvent); |
| 1788 | const result = yield* Fiber.join(waiting); |
| 1789 | assert.isFalse(result.waitTimedOut); |
| 1790 | if (terminal) { |
| 1791 | assert.equal(result.status, "completed"); |
| 1792 | if (wake === "parent completion") assert.equal(result.summary, "done"); |
| 1793 | } else { |
| 1794 | assert.equal(result.status, "running"); |
| 1795 | if (wake === "child question") assert.isTrue(result.hasPendingQuestion); |
| 1796 | else { |
| 1797 | assert.deepEqual(result.pendingApproval, { |
| 1798 | requestId: "request:mcp-wait-answer", |
| 1799 | kind: "command", |
| 1800 | runId: childRunId, |
| 1801 | }); |
| 1802 | } |
| 1803 | } |
| 1804 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); |
| 1805 | }), |
| 1806 | ); |
| 1807 | |
| 1808 | it.effect.each([ |
| 1809 | { name: "default", timeoutMs: undefined, budgetMs: 30_000 }, |
| 1810 | { name: "capped", timeoutMs: 3_600_000, budgetMs: 45_000 }, |
| 1811 | { name: "shorter requested", timeoutMs: 500, budgetMs: 500 }, |
| 1812 | ])("returns task and thread handles at the $name wait budget", (scenario) => |
| 1813 | Effect.gen(function* () { |
| 1814 | const subscribed = yield* Deferred.make<void>(); |
| 1815 | const returned = yield* Deferred.make<void>(); |
| 1816 | const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]); |
| 1817 | const threadWaitBudgets = yield* Ref.make<ReadonlyArray<number | undefined>>([]); |
| 1818 | const task = { |
| 1819 | id: taskId, |
| 1820 | threadId: parentThreadId, |
| 1821 | runId: parentRunId, |
| 1822 | parentNodeId, |
| 1823 | origin: "app_owned", |
| 1824 | providerInstanceId: codexInstanceId, |
| 1825 | driver: "codex", |
| 1826 | childThreadId, |
| 1827 | model: "gpt-5.4", |
| 1828 | status: "running", |
| 1829 | result: null, |
| 1830 | }; |
| 1831 | const dependencies = Layer.mergeAll( |
| 1832 | NodeServices.layer, |
| 1833 | NodeCrypto.layer, |
| 1834 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1835 | hasReceipt: () => Effect.succeed(false), |
| 1836 | assertProviderInstanceEnabled: () => Effect.void, |
| 1837 | isProviderInstanceEnabledForProject: () => Effect.succeed(true), |
| 1838 | getThreadRecords: (threadId) => |
| 1839 | Effect.succeed( |
| 1840 | threadId === parentThreadId ? parentProjection([task]) : childProjection, |
| 1841 | ), |
| 1842 | getThreadEventSequence: () => Effect.succeed(0), |
| 1843 | delegatedTaskResultPending: () => Effect.succeed(false), |
| 1844 | streamStoredEventsFrom: () => |
| 1845 | Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe( |
| 1846 | Stream.drain, |
| 1847 | Stream.concat(Stream.never), |
| 1848 | ), |
| 1849 | waitForThread: (input) => |
| 1850 | Ref.update(threadWaitBudgets, (budgets) => [...budgets, input.timeoutMs]).pipe( |
| 1851 | Effect.as({ threadId: parentThreadId, run: null, timedOut: true }), |
| 1852 | ), |
| 1853 | dispatch: (command) => |
| 1854 | Ref.update(dispatched, (commands) => [...commands, command]).pipe( |
| 1855 | Effect.as({ |
| 1856 | sequence: 1, |
| 1857 | storedEvents: [{ event: { type: "subagent.updated", payload: task } }], |
| 1858 | } as never), |
| 1859 | ), |
| 1860 | }), |
| 1861 | ServerSettings.layerTest(), |
| 1862 | providerRegistryLayer([ |
| 1863 | providerSnapshot({ |
| 1864 | instanceId: codexInstanceId, |
| 1865 | driver: ProviderDriverKind.make("codex"), |
| 1866 | model: "gpt-5.4", |
| 1867 | }), |
| 1868 | ]), |
| 1869 | adapterRegistryLayer([codexInstanceId]), |
| 1870 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 1871 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 1872 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 1873 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 1874 | ); |
| 1875 | yield* Effect.gen(function* () { |
| 1876 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1877 | const budget = scenario.timeoutMs === undefined ? {} : { timeoutMs: scenario.timeoutMs }; |
| 1878 | const waiting = yield* service |
| 1879 | .delegateTask(scope, { task: "Review the change.", mode: "wait", ...budget }) |
| 1880 | .pipe( |
| 1881 | Effect.tap(() => Deferred.succeed(returned, undefined)), |
| 1882 | Effect.forkChild, |
| 1883 | ); |
| 1884 | yield* Deferred.await(subscribed); |
| 1885 | yield* TestClock.adjust(Duration.millis(scenario.budgetMs - 1)); |
| 1886 | assert.isFalse(yield* Deferred.isDone(returned)); |
| 1887 | yield* TestClock.adjust(Duration.millis(1)); |
| 1888 | const result = yield* Fiber.join(waiting); |
| 1889 | assert.include(result, { taskId, childThreadId, status: "running", waitTimedOut: true }); |
| 1890 | assert.include((yield* Ref.get(dispatched)).at(-1), { |
| 1891 | type: "delegated_task.wake-policy", |
| 1892 | completionWake: "always", |
| 1893 | }); |
| 1894 | |
| 1895 | yield* service.waitForThread(scope, { threadId: parentThreadId, ...budget }); |
| 1896 | assert.deepEqual(yield* Ref.get(threadWaitBudgets), [scenario.budgetMs]); |
| 1897 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); |
| 1898 | }), |
| 1899 | ); |
| 1900 | |
| 1901 | it.effect("leaves a result undelivered when the caller goes away after its wait times out", () => |
| 1902 | Effect.gen(function* () { |
| 1903 | const subscribed = yield* Deferred.make<void>(); |
| 1904 | const upgrading = yield* Deferred.make<void>(); |
| 1905 | const finishUpgrade = yield* Deferred.make<void>(); |
| 1906 | const dispatched = yield* Ref.make<ReadonlyArray<{ readonly type: string }>>([]); |
| 1907 | let task: Record<string, unknown> = { |
| 1908 | id: taskId, |
| 1909 | threadId: parentThreadId, |
| 1910 | runId: parentRunId, |
| 1911 | parentNodeId, |
| 1912 | origin: "app_owned", |
| 1913 | providerInstanceId: codexInstanceId, |
| 1914 | driver: "codex", |
| 1915 | childThreadId, |
| 1916 | model: "gpt-5.4", |
| 1917 | status: "running", |
| 1918 | result: null, |
| 1919 | }; |
| 1920 | const dependencies = Layer.mergeAll( |
| 1921 | NodeServices.layer, |
| 1922 | NodeCrypto.layer, |
| 1923 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1924 | hasReceipt: () => Effect.succeed(false), |
| 1925 | assertProviderInstanceEnabled: () => Effect.void, |
| 1926 | isProviderInstanceEnabledForProject: () => Effect.succeed(true), |
| 1927 | getThreadRecords: (threadId) => |
| 1928 | Effect.sync(() => |
| 1929 | threadId === parentThreadId ? parentProjection([task]) : childProjection, |
| 1930 | ), |
| 1931 | getThreadEventSequence: () => Effect.succeed(0), |
| 1932 | delegatedTaskResultPending: () => Effect.succeed(false), |
| 1933 | streamStoredEventsFrom: () => |
| 1934 | Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe( |
| 1935 | Stream.drain, |
| 1936 | Stream.concat(Stream.never), |
| 1937 | ), |
| 1938 | dispatch: (command) => |
| 1939 | Ref.update(dispatched, (commands) => [...commands, command]).pipe( |
| 1940 | Effect.andThen( |
| 1941 | command.type === "delegated_task.wake-policy" |
| 1942 | ? Deferred.succeed(upgrading, undefined).pipe( |
| 1943 | Effect.andThen(Deferred.await(finishUpgrade)), |
| 1944 | ) |
| 1945 | : Effect.void, |
| 1946 | ), |
| 1947 | Effect.as({ |
| 1948 | sequence: 1, |
| 1949 | storedEvents: [{ event: { type: "subagent.updated", payload: task } }], |
| 1950 | } as never), |
| 1951 | ), |
| 1952 | }), |
| 1953 | ServerSettings.layerTest(), |
| 1954 | providerRegistryLayer([ |
| 1955 | providerSnapshot({ |
| 1956 | instanceId: codexInstanceId, |
| 1957 | driver: ProviderDriverKind.make("codex"), |
| 1958 | model: "gpt-5.4", |
| 1959 | }), |
| 1960 | ]), |
| 1961 | adapterRegistryLayer([codexInstanceId]), |
| 1962 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 1963 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 1964 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 1965 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 1966 | ); |
| 1967 | yield* Effect.gen(function* () { |
| 1968 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1969 | const waiting = yield* service |
| 1970 | .delegateTask(scope, { task: "Review the change.", mode: "wait", timeoutMs: 500 }) |
| 1971 | .pipe(Effect.forkChild); |
| 1972 | yield* Deferred.await(subscribed); |
| 1973 | yield* TestClock.adjust(Duration.millis(500)); |
| 1974 | yield* Deferred.await(upgrading); |
| 1975 | yield* Effect.sync(() => waiting.interruptUnsafe()); |
| 1976 | task = { ...task, status: "completed", result: "Reviewed." }; |
| 1977 | yield* Deferred.succeed(finishUpgrade, undefined); |
| 1978 | yield* Fiber.await(waiting); |
| 1979 | assert.notInclude( |
| 1980 | (yield* Ref.get(dispatched)).map((command) => command.type), |
| 1981 | "delegated_task.completion-delivery.acknowledge", |
| 1982 | ); |
| 1983 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); |
| 1984 | }), |
| 1985 | ); |
| 1986 | |
| 1987 | it.effect.each([ |
| 1988 | { name: "ten-minute default", timeoutMs: undefined, budgetMs: 600_000 }, |
| 1989 | { name: "one-hour maximum", timeoutMs: 3_600_000, budgetMs: 3_600_000 }, |
| 1990 | ])("keeps a secret request pending for its $name", (scenario) => |
| 1991 | Effect.gen(function* () { |
| 1992 | const pending = yield* Deferred.make<void>(); |
| 1993 | const returned = yield* Deferred.make<void>(); |
| 1994 | const statuses = yield* Ref.make<ReadonlyArray<string>>([]); |
| 1995 | const dependencies = Layer.mergeAll( |
| 1996 | NodeServices.layer, |
| 1997 | NodeCrypto.layer, |
| 1998 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1999 | getThreadRecords: () => Effect.succeed({ ...parentProjection([]), turnItems: [] }), |
| 2000 | dispatch: (command) => { |
| 2001 | if (command.type !== "secret_request.record") return Effect.die("Unexpected command"); |
| 2002 | return Ref.update(statuses, (values) => [...values, command.secretStatus]).pipe( |
| 2003 | Effect.andThen(Deferred.succeed(pending, undefined)), |
| 2004 | Effect.as({} as never), |
| 2005 | ); |
| 2006 | }, |
| 2007 | }), |
| 2008 | ServerSettings.layerTest(), |
| 2009 | providerRegistryLayer([]), |
| 2010 | adapterRegistryLayer([]), |
| 2011 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 2012 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 2013 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 2014 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 2015 | ); |
| 2016 | yield* Effect.gen(function* () { |
| 2017 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 2018 | const waiting = yield* service |
| 2019 | .requestSecret(scope, { |
| 2020 | label: "Token", |
| 2021 | reason: "Connect the account.", |
| 2022 | ...(scenario.timeoutMs === undefined ? {} : { timeoutMs: scenario.timeoutMs }), |
| 2023 | }) |
| 2024 | .pipe( |
| 2025 | Effect.tap(() => Deferred.succeed(returned, undefined)), |
| 2026 | Effect.forkChild, |
| 2027 | ); |
| 2028 | yield* Deferred.await(pending); |
| 2029 | yield* TestClock.adjust(Duration.millis(scenario.budgetMs - 1)); |
| 2030 | assert.isFalse(yield* Deferred.isDone(returned)); |
| 2031 | assert.deepEqual(yield* Ref.get(statuses), ["pending"]); |
| 2032 | yield* TestClock.adjust(Duration.millis(1)); |
| 2033 | assert.include(yield* Fiber.join(waiting), { status: "timed_out" }); |
| 2034 | assert.deepEqual(yield* Ref.get(statuses), ["pending", "cancelled"]); |
| 2035 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); |
| 2036 | }), |
| 2037 | ); |
| 2038 | |
| 2039 | // Command receipts dedupe by commandId, so a later run reusing the identity gets no card. |
| 2040 | it.effect("opens a new secret card when a later run reuses a clientRequestId", () => |
| 2041 | Effect.gen(function* () { |
| 2042 | const runId = yield* Ref.make(parentRunId); |
| 2043 | const pending = yield* Queue.unbounded<{ |
| 2044 | readonly commandId: CommandId; |
| 2045 | readonly turnItemId: string; |
| 2046 | }>(); |
| 2047 | const dependencies = Layer.mergeAll( |
| 2048 | NodeServices.layer, |
| 2049 | NodeCrypto.layer, |
| 2050 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 2051 | getThreadRecords: () => |
| 2052 | Ref.get(runId).pipe( |
| 2053 | Effect.map((id) => { |
| 2054 | const projection = parentProjection([]); |
| 2055 | return { |
| 2056 | ...projection, |
| 2057 | runs: projection.runs.map((run) => ({ ...run, id })), |
| 2058 | turnItems: [], |
| 2059 | }; |
| 2060 | }), |
| 2061 | ), |
| 2062 | dispatch: (command) => { |
| 2063 | if (command.type !== "secret_request.record") return Effect.die("Unexpected command"); |
| 2064 | return ( |
| 2065 | command.secretStatus === "pending" |
| 2066 | ? Queue.offer(pending, { |
| 2067 | commandId: command.commandId, |
| 2068 | turnItemId: command.turnItemId, |
| 2069 | }) |
| 2070 | : Effect.void |
| 2071 | ).pipe(Effect.as({} as never)); |
| 2072 | }, |
| 2073 | }), |
| 2074 | ServerSettings.layerTest(), |
| 2075 | providerRegistryLayer([]), |
| 2076 | adapterRegistryLayer([]), |
| 2077 | Layer.mock(ProjectService.ProjectService)({}), |
| 2078 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 2079 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 2080 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 2081 | ); |
| 2082 | yield* Effect.gen(function* () { |
| 2083 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 2084 | const ask = Effect.gen(function* () { |
| 2085 | const call = yield* service |
| 2086 | .requestSecret(scope, { |
| 2087 | label: "Router API key", |
| 2088 | reason: "Reads the firewall rules.", |
| 2089 | clientRequestId: "router-key", |
| 2090 | timeoutMs: 1_000, |
| 2091 | }) |
| 2092 | .pipe(Effect.forkChild); |
| 2093 | const card = yield* Queue.take(pending); |
| 2094 | yield* TestClock.adjust(Duration.seconds(1)); |
| 2095 | assert.include(yield* Fiber.join(call), { status: "timed_out" }); |
| 2096 | return card; |
| 2097 | }); |
| 2098 | |
| 2099 | const first = yield* ask; |
| 2100 | assert.deepEqual(yield* ask, first); |
| 2101 | yield* Ref.set(runId, RunId.make("run:mcp-providers-parent-later")); |
| 2102 | const later = yield* ask; |
| 2103 | assert.notEqual(later.commandId, first.commandId); |
| 2104 | assert.notEqual(later.turnItemId, first.turnItemId); |
| 2105 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); |
| 2106 | }), |
| 2107 | ); |
| 2108 | |
| 2109 | it.effect( |
| 2110 | "advertises orchestration capability from registered adapters rather than a driver allowlist", |
| 2111 | () => |
| 2112 | Effect.gen(function* () { |
| 2113 | const disabledAntigravityInstanceId = ProviderInstanceId.make("antigravity-alt"); |
| 2114 | const disabledWithoutAdapterInstanceId = ProviderInstanceId.make("codex-without-adapter"); |
| 2115 | const projectDisabledInstanceId = ProviderInstanceId.make("codex-project-off"); |
| 2116 | const forkOnlyInstanceId = ProviderInstanceId.make("forkOnly"); |
| 2117 | const forkShadow = yield* buildUnavailableProviderSnapshot({ |
| 2118 | driverKind: "forkOnly", |
| 2119 | instanceId: forkOnlyInstanceId, |
| 2120 | reason: "Driver 'forkOnly' is not registered in this build.", |
| 2121 | checkedAt: "2026-09-13T00:00:00.000Z", |
| 2122 | }); |
| 2123 | let providers: ReadonlyArray<ServerProvider> = [ |
| 2124 | providerSnapshot({ |
| 2125 | instanceId: codexInstanceId, |
| 2126 | driver: ProviderDriverKind.make("codex"), |
| 2127 | model: "gpt-5.4", |
| 2128 | }), |
| 2129 | providerSnapshot({ |
| 2130 | instanceId: ProviderInstanceId.make("claudeAgent"), |
| 2131 | driver: ProviderDriverKind.make("claudeAgent"), |
| 2132 | model: "claude-sonnet-4-6", |
| 2133 | }), |
| 2134 | providerSnapshot({ |
| 2135 | instanceId: ProviderInstanceId.make("pi"), |
| 2136 | driver: ProviderDriverKind.make("pi"), |
| 2137 | model: "pi-model", |
| 2138 | }), |
| 2139 | providerSnapshot({ |
| 2140 | instanceId: ProviderInstanceId.make("acpRegistry"), |
| 2141 | driver: ProviderDriverKind.make("acpRegistry"), |
| 2142 | model: "acp-model", |
| 2143 | }), |
| 2144 | providerSnapshot({ |
| 2145 | instanceId: antigravityInstanceId, |
| 2146 | driver: ProviderDriverKind.make("antigravity"), |
| 2147 | model: "ant-model", |
| 2148 | }), |
| 2149 | providerSnapshot({ |
| 2150 | instanceId: disabledAntigravityInstanceId, |
| 2151 | driver: ProviderDriverKind.make("antigravity"), |
| 2152 | model: "ant-model", |
| 2153 | enabled: false, |
| 2154 | }), |
| 2155 | providerSnapshot({ |
| 2156 | instanceId: disabledWithoutAdapterInstanceId, |
| 2157 | driver: ProviderDriverKind.make("codex"), |
| 2158 | model: "gpt-5.4", |
| 2159 | enabled: false, |
| 2160 | }), |
| 2161 | providerSnapshot({ |
| 2162 | instanceId: projectDisabledInstanceId, |
| 2163 | driver: ProviderDriverKind.make("codex"), |
| 2164 | model: "gpt-5.4", |
| 2165 | }), |
| 2166 | forkShadow, |
| 2167 | ]; |
| 2168 | const layerDependencies = Layer.mergeAll( |
| 2169 | NodeServices.layer, |
| 2170 | NodeCrypto.layer, |
| 2171 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 2172 | getThreadRecords: () => Effect.succeed(parentProjection([])), |
| 2173 | }), |
| 2174 | ServerSettings.layerTest({ |
| 2175 | providerInstances: { |
| 2176 | [ProviderInstanceId.make("pi")]: { |
| 2177 | driver: ProviderDriverKind.make("pi"), |
| 2178 | enabled: true, |
| 2179 | }, |
| 2180 | [ProviderInstanceId.make("acpRegistry")]: { |
| 2181 | driver: ProviderDriverKind.make("acpRegistry"), |
| 2182 | enabled: true, |
| 2183 | }, |
| 2184 | [antigravityInstanceId]: { |
| 2185 | driver: ProviderDriverKind.make("antigravity"), |
| 2186 | enabled: true, |
| 2187 | }, |
| 2188 | [projectDisabledInstanceId]: { driver: ProviderDriverKind.make("codex") }, |
| 2189 | }, |
| 2190 | projectSettingsOverrides: { |
| 2191 | [projectId]: { |
| 2192 | providerInstances: { [projectDisabledInstanceId]: { enabled: false } }, |
| 2193 | }, |
| 2194 | }, |
| 2195 | }), |
| 2196 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 2197 | getProviders: Effect.sync(() => providers), |
| 2198 | }), |
| 2199 | adapterRegistryLayer([ |
| 2200 | codexInstanceId, |
| 2201 | projectDisabledInstanceId, |
| 2202 | ProviderInstanceId.make("claudeAgent"), |
| 2203 | ProviderInstanceId.make("pi"), |
| 2204 | ProviderInstanceId.make("acpRegistry"), |
| 2205 | antigravityInstanceId, |
| 2206 | disabledAntigravityInstanceId, |
| 2207 | ]), |
| 2208 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 2209 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 2210 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 2211 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 2212 | ); |
| 2213 | |
| 2214 | yield* Effect.gen(function* () { |
| 2215 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 2216 | const capabilities = yield* service.capabilities(scope); |
| 2217 | const byId = new Map( |
| 2218 | capabilities.providers.map((provider) => [provider.providerInstanceId, provider]), |
| 2219 | ); |
| 2220 | for (const provider of providers) { |
| 2221 | assert.deepEqual( |
| 2222 | byId.get(provider.instanceId)?.models.map((model) => model.id), |
| 2223 | provider.models.map((model) => model.slug), |
| 2224 | ); |
| 2225 | } |
| 2226 | |
| 2227 | providers = providers.map((provider) => ({ |
| 2228 | ...provider, |
| 2229 | models: [ |
| 2230 | ...provider.models, |
| 2231 | { |
| 2232 | slug: `${provider.driver}/custom-model-after-refresh`, |
| 2233 | name: "Custom model", |
| 2234 | isCustom: true, |
| 2235 | capabilities: null, |
| 2236 | }, |
| 2237 | ], |
| 2238 | })); |
| 2239 | const refreshed = yield* service.capabilities(scope); |
| 2240 | for (const provider of providers) { |
| 2241 | assert.deepEqual( |
| 2242 | refreshed.providers |
| 2243 | .find((entry) => entry.providerInstanceId === provider.instanceId) |
| 2244 | ?.models.map((model) => model.id), |
| 2245 | provider.models.map((model) => model.slug), |
| 2246 | ); |
| 2247 | } |
| 2248 | |
| 2249 | for (const instanceId of [ |
| 2250 | codexInstanceId, |
| 2251 | ProviderInstanceId.make("claudeAgent"), |
| 2252 | ProviderInstanceId.make("pi"), |
| 2253 | ProviderInstanceId.make("acpRegistry"), |
| 2254 | antigravityInstanceId, |
| 2255 | ]) { |
| 2256 | const entry = byId.get(instanceId); |
| 2257 | assert.isDefined(entry); |
| 2258 | assert.isTrue( |
| 2259 | entry!.canRunChildTask, |
| 2260 | `expected ${instanceId} to advertise canRunChildTask`, |
| 2261 | ); |
| 2262 | assert.isTrue(entry!.canRunCrossProviderChildTask); |
| 2263 | assert.deepEqual(entry!.constraints, []); |
| 2264 | } |
| 2265 | |
| 2266 | const disabled = byId.get(disabledAntigravityInstanceId); |
| 2267 | assert.isDefined(disabled); |
| 2268 | assert.isFalse(disabled!.canRunChildTask); |
| 2269 | assert.isFalse(disabled!.canRunCrossProviderChildTask); |
| 2270 | assert.deepEqual(disabled!.constraints, ["Provider instance is disabled."]); |
| 2271 | |
| 2272 | const projectDisabled = byId.get(projectDisabledInstanceId); |
| 2273 | assert.isDefined(projectDisabled); |
| 2274 | assert.isFalse(projectDisabled!.canRunChildTask); |
| 2275 | assert.deepEqual(projectDisabled!.constraints, ["Provider instance is disabled."]); |
| 2276 | |
| 2277 | const disabledWithoutAdapter = byId.get(disabledWithoutAdapterInstanceId); |
| 2278 | assert.isDefined(disabledWithoutAdapter); |
| 2279 | assert.isFalse(disabledWithoutAdapter!.canRunChildTask); |
| 2280 | assert.isFalse(disabledWithoutAdapter!.canRunCrossProviderChildTask); |
| 2281 | assert.deepEqual(disabledWithoutAdapter!.constraints, [ |
| 2282 | "No V2 provider adapter is registered.", |
| 2283 | "Provider instance is disabled.", |
| 2284 | ]); |
| 2285 | |
| 2286 | const fork = byId.get(forkOnlyInstanceId); |
| 2287 | assert.isDefined(fork); |
| 2288 | assert.isFalse(fork!.canRunChildTask); |
| 2289 | assert.isFalse(fork!.canRunCrossProviderChildTask); |
| 2290 | assert.deepEqual(fork!.constraints, [ |
| 2291 | "No V2 provider adapter is registered.", |
| 2292 | "Driver 'forkOnly' is not registered in this build.", |
| 2293 | "Provider instance is disabled.", |
| 2294 | ]); |
| 2295 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 2296 | }), |
| 2297 | ); |
| 2298 | |
| 2299 | describe("listed models", () => { |
| 2300 | const opencodeInstanceId = ProviderInstanceId.make("opencode"); |
| 2301 | const model = (slug: string, extra: Partial<ServerProvider["models"][number]> = {}) => ({ |
| 2302 | slug, |
| 2303 | name: slug, |
| 2304 | isCustom: false, |
| 2305 | capabilities: null, |
| 2306 | ...extra, |
| 2307 | }); |
| 2308 | const opencodeSlugs = Array.from( |
| 2309 | { length: 12 }, |
| 2310 | (_, index) => `oc/m${String(index + 1).padStart(2, "0")}`, |
| 2311 | ); |
| 2312 | const catalog: ReadonlyArray<ServerProvider> = [ |
| 2313 | { |
| 2314 | ...providerSnapshot({ |
| 2315 | instanceId: codexInstanceId, |
| 2316 | driver: ProviderDriverKind.make("codex"), |
| 2317 | }), |
| 2318 | displayName: "Codex", |
| 2319 | models: [ |
| 2320 | model("gpt-6", { |
| 2321 | name: "Sol", |
| 2322 | capabilities: { |
| 2323 | optionDescriptors: [ |
| 2324 | { |
| 2325 | id: "effort", |
| 2326 | label: "Reasoning", |
| 2327 | description: "How hard the model thinks.", |
| 2328 | type: "select", |
| 2329 | options: [ |
| 2330 | { id: "low", label: "Low", description: "Fast." }, |
| 2331 | { id: "high", label: "High", isDefault: true }, |
| 2332 | ], |
| 2333 | promptInjectedValues: ["high"], |
| 2334 | }, |
| 2335 | { id: "fastMode", label: "Fast", type: "boolean" }, |
| 2336 | { |
| 2337 | id: "agent", |
| 2338 | label: "Agent", |
| 2339 | type: "select", |
| 2340 | options: [{ id: "build", label: "Build" }], |
| 2341 | currentValue: "build", |
| 2342 | }, |
| 2343 | ], |
| 2344 | }, |
| 2345 | }), |
| 2346 | model("gpt-5", { name: "Code Legacy", isLegacy: true }), |
| 2347 | model("gpt-4", { isLegacy: true }), |
| 2348 | model("gpt-3", { name: "GPT-3", isLegacy: true }), |
| 2349 | model("my-alpha", { isCustom: true }), |
| 2350 | ], |
| 2351 | }, |
| 2352 | { |
| 2353 | ...providerSnapshot({ |
| 2354 | instanceId: opencodeInstanceId, |
| 2355 | driver: ProviderDriverKind.make("opencode"), |
| 2356 | }), |
| 2357 | models: [ |
| 2358 | ...opencodeSlugs.map((slug) => model(slug, { isLegacy: slug === "oc/m03" })), |
| 2359 | model("oc-custom", { isCustom: true }), |
| 2360 | ], |
| 2361 | }, |
| 2362 | ]; |
| 2363 | |
| 2364 | const capabilitiesWith = (search?: string) => |
| 2365 | Effect.gen(function* () { |
| 2366 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 2367 | return yield* service.capabilities(scope, search === undefined ? {} : { search }); |
| 2368 | }).pipe( |
| 2369 | Effect.provide( |
| 2370 | layerOrchestratorService.pipe( |
| 2371 | Layer.provide( |
| 2372 | Layer.mergeAll( |
| 2373 | NodeServices.layer, |
| 2374 | NodeCrypto.layer, |
| 2375 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 2376 | getThreadRecords: () => |
| 2377 | Effect.succeed( |
| 2378 | parentProjection([], { instanceId: codexInstanceId, model: "gpt-3" }), |
| 2379 | ), |
| 2380 | }), |
| 2381 | ServerSettings.layerTest({ |
| 2382 | favorites: [ |
| 2383 | { provider: codexInstanceId, model: "gpt-4" }, |
| 2384 | { provider: opencodeInstanceId, model: "oc/m10" }, |
| 2385 | ], |
| 2386 | providerModelPreferences: { |
| 2387 | [opencodeInstanceId]: { hiddenModels: ["oc/m02"], modelOrder: ["oc/m12"] }, |
| 2388 | }, |
| 2389 | }), |
| 2390 | providerRegistryLayer(catalog), |
| 2391 | adapterRegistryLayer([codexInstanceId, opencodeInstanceId]), |
| 2392 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 2393 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 2394 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 2395 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 2396 | ), |
| 2397 | ), |
| 2398 | ), |
| 2399 | ), |
| 2400 | ); |
| 2401 | |
| 2402 | const listing = (capabilities: OrchestratorMcpCapabilitiesResult) => |
| 2403 | capabilities.providers.map((provider) => ({ |
| 2404 | id: provider.providerInstanceId, |
| 2405 | models: provider.models.map((entry) => entry.id), |
| 2406 | omitted: provider.omittedModels ?? 0, |
| 2407 | })); |
| 2408 | |
| 2409 | it.effect( |
| 2410 | "skips legacy models, lists the first 8 of large catalogs, and keeps pinned models", |
| 2411 | () => |
| 2412 | Effect.gen(function* () { |
| 2413 | assert.deepEqual(listing(yield* capabilitiesWith()), [ |
| 2414 | // gpt-4 is a favorite and gpt-3 is the caller's model; legacy gpt-5 is left out. |
| 2415 | { id: codexInstanceId, models: ["gpt-6", "gpt-4", "gpt-3", "my-alpha"], omitted: 1 }, |
| 2416 | { |
| 2417 | id: opencodeInstanceId, |
| 2418 | models: [ |
| 2419 | "oc/m12", |
| 2420 | "oc/m01", |
| 2421 | "oc/m04", |
| 2422 | "oc/m05", |
| 2423 | "oc/m06", |
| 2424 | "oc/m07", |
| 2425 | "oc/m08", |
| 2426 | "oc/m09", |
| 2427 | "oc/m10", |
| 2428 | "oc-custom", |
| 2429 | ], |
| 2430 | omitted: 2, |
| 2431 | }, |
| 2432 | ]); |
| 2433 | }), |
| 2434 | ); |
| 2435 | |
| 2436 | it.effect("search matches every word and caps each provider's matches", () => |
| 2437 | Effect.gen(function* () { |
| 2438 | assert.deepEqual(listing(yield* capabilitiesWith("GPT 5")), [ |
| 2439 | { id: codexInstanceId, models: ["gpt-5"], omitted: 0 }, |
| 2440 | { id: opencodeInstanceId, models: [], omitted: 0 }, |
| 2441 | ]); |
| 2442 | const opencode = listing(yield* capabilitiesWith("oc/m"))[1]; |
| 2443 | assert.deepEqual(opencode, { |
| 2444 | id: opencodeInstanceId, |
| 2445 | models: ["oc/m12", "oc/m01", "oc/m03", "oc/m04", "oc/m05", "oc/m06", "oc/m07", "oc/m08"], |
| 2446 | omitted: 3, |
| 2447 | }); |
| 2448 | // A word naming the provider matches all its models, so legacy ones stay out. |
| 2449 | assert.deepEqual(listing(yield* capabilitiesWith("Codex")), [ |
| 2450 | { id: codexInstanceId, models: ["gpt-6", "gpt-4", "gpt-3", "my-alpha"], omitted: 1 }, |
| 2451 | { id: opencodeInstanceId, models: [], omitted: 0 }, |
| 2452 | ]); |
| 2453 | assert.deepEqual(listing(yield* capabilitiesWith(" ")), listing(yield* capabilitiesWith())); |
| 2454 | for (const search of ["code", "codex code", " CODE "]) { |
| 2455 | assert.deepEqual(listing(yield* capabilitiesWith(search))[0], { |
| 2456 | id: codexInstanceId, |
| 2457 | models: ["gpt-5"], |
| 2458 | omitted: 0, |
| 2459 | }); |
| 2460 | } |
| 2461 | assert.deepEqual( |
| 2462 | listing(yield* capabilitiesWith("open"))[1], |
| 2463 | listing(yield* capabilitiesWith())[1], |
| 2464 | ); |
| 2465 | assert.deepEqual(listing(yield* capabilitiesWith("codex gpt 5"))[0], { |
| 2466 | id: codexInstanceId, |
| 2467 | models: ["gpt-5"], |
| 2468 | omitted: 0, |
| 2469 | }); |
| 2470 | }), |
| 2471 | ); |
| 2472 | |
| 2473 | it.effect("describes models by id, distinct label, and option values", () => |
| 2474 | Effect.gen(function* () { |
| 2475 | const codex = (yield* capabilitiesWith()).providers[0]; |
| 2476 | assert.deepEqual(codex?.models.slice(0, 4), [ |
| 2477 | { |
| 2478 | id: "gpt-6", |
| 2479 | label: "Sol", |
| 2480 | options: [ |
| 2481 | { id: "effort", values: ["low", "high"], default: "high" }, |
| 2482 | { id: "fastMode", values: [false, true] }, |
| 2483 | { id: "agent", values: ["build"], default: "build" }, |
| 2484 | ], |
| 2485 | }, |
| 2486 | { id: "gpt-4" }, |
| 2487 | { id: "gpt-3" }, |
| 2488 | { id: "my-alpha" }, |
| 2489 | ]); |
| 2490 | }), |
| 2491 | ); |
| 2492 | }); |
| 2493 | |
| 2494 | it.effect.each(["already advertised", "newly advertised", "still unavailable"] as const)( |
| 2495 | "rechecks a delegated model that is %s", |
| 2496 | (availability) => |
| 2497 | Effect.gen(function* () { |
| 2498 | const museInstanceId = ProviderInstanceId.make("muse"); |
| 2499 | const model = "muse-wonder-1.0"; |
| 2500 | const provider = (advertisedModel: string) => |
| 2501 | providerSnapshot({ |
| 2502 | instanceId: museInstanceId, |
| 2503 | driver: ProviderDriverKind.make("muse"), |
| 2504 | model: advertisedModel, |
| 2505 | }); |
| 2506 | const commands: Array<unknown> = []; |
| 2507 | const refreshedInstances: Array<ProviderInstanceId> = []; |
| 2508 | const task = { |
| 2509 | id: taskId, |
| 2510 | threadId: parentThreadId, |
| 2511 | origin: "app_owned", |
| 2512 | childThreadId, |
| 2513 | providerInstanceId: museInstanceId, |
| 2514 | model, |
| 2515 | status: "running", |
| 2516 | result: null, |
| 2517 | }; |
| 2518 | const dependencies = Layer.mergeAll( |
| 2519 | NodeServices.layer, |
| 2520 | NodeCrypto.layer, |
| 2521 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 2522 | hasReceipt: () => Effect.succeed(false), |
| 2523 | getThreadRecords: (threadId) => |
| 2524 | Effect.succeed( |
| 2525 | threadId === parentThreadId |
| 2526 | ? parentProjection(commands.length > 0 ? [task] : []) |
| 2527 | : childProjection, |
| 2528 | ), |
| 2529 | dispatch: (command) => |
| 2530 | Effect.sync(() => { |
| 2531 | commands.push(command); |
| 2532 | return { |
| 2533 | sequence: 1, |
| 2534 | storedEvents: [{ event: { type: "subagent.updated", payload: task } }], |
| 2535 | } as never; |
| 2536 | }), |
| 2537 | }), |
| 2538 | ServerSettings.layerTest(), |
| 2539 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 2540 | getProviders: Effect.succeed([ |
| 2541 | provider(availability === "already advertised" ? model : "muse-spark-1.3"), |
| 2542 | ]), |
| 2543 | refreshInstance: (instanceId) => |
| 2544 | Effect.sync(() => { |
| 2545 | refreshedInstances.push(instanceId); |
| 2546 | return [provider(availability === "still unavailable" ? "muse-spark-1.3" : model)]; |
| 2547 | }), |
| 2548 | }), |
| 2549 | adapterRegistryLayer([museInstanceId]), |
| 2550 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 2551 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 2552 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 2553 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 2554 | ); |
| 2555 | yield* Effect.gen(function* () { |
| 2556 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 2557 | const delegation = service.delegateTask(scope, { |
| 2558 | task: "Review the change.", |
| 2559 | target: { providerInstanceId: museInstanceId, model }, |
| 2560 | mode: "async", |
| 2561 | clientRequestId: availability, |
| 2562 | }); |
| 2563 | if (availability === "still unavailable") { |
| 2564 | const error = yield* delegation.pipe(Effect.flip); |
| 2565 | assert.equal(error.code, "model_unavailable"); |
| 2566 | assert.deepEqual(commands, []); |
| 2567 | } else { |
| 2568 | const result = yield* delegation; |
| 2569 | assert.equal(result.model, model); |
| 2570 | assert.equal(commands.length, 1); |
| 2571 | assert.deepEqual((commands[0] as { modelSelection: unknown }).modelSelection, { |
| 2572 | instanceId: museInstanceId, |
| 2573 | model, |
| 2574 | }); |
| 2575 | } |
| 2576 | assert.deepEqual( |
| 2577 | refreshedInstances, |
| 2578 | availability === "already advertised" ? [] : [museInstanceId], |
| 2579 | ); |
| 2580 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); |
| 2581 | }), |
| 2582 | ); |
| 2583 | |
| 2584 | it.effect("delegates to a model only the parent project's folder config advertises", () => |
| 2585 | Effect.gen(function* () { |
| 2586 | const opencodeInstanceId = ProviderInstanceId.make("opencode"); |
| 2587 | const workspaceRoot = "/work/uni"; |
| 2588 | const model = "uni/medium-local"; |
| 2589 | const machineModels = [ |
| 2590 | { slug: "opencode/big-pickle", name: "Big Pickle", isCustom: false, capabilities: null }, |
| 2591 | ]; |
| 2592 | const opencode: ServerProvider = { |
| 2593 | ...providerSnapshot({ |
| 2594 | instanceId: opencodeInstanceId, |
| 2595 | driver: ProviderDriverKind.make("opencode"), |
| 2596 | }), |
| 2597 | models: machineModels, |
| 2598 | workspaceSnapshots: [ |
| 2599 | { |
| 2600 | cwd: workspaceRoot, |
| 2601 | checkedAt: "2026-09-13T00:00:00.000Z", |
| 2602 | slashCommands: [], |
| 2603 | skills: [], |
| 2604 | models: [ |
| 2605 | ...machineModels, |
| 2606 | { slug: model, name: "Medium Local", isCustom: false, capabilities: null }, |
| 2607 | ], |
| 2608 | }, |
| 2609 | ], |
| 2610 | }; |
| 2611 | const commands: Array<unknown> = []; |
| 2612 | const task = { |
| 2613 | id: taskId, |
| 2614 | threadId: parentThreadId, |
| 2615 | origin: "app_owned", |
| 2616 | childThreadId, |
| 2617 | providerInstanceId: opencodeInstanceId, |
| 2618 | model, |
| 2619 | status: "running", |
| 2620 | result: null, |
| 2621 | }; |
| 2622 | const dependencies = Layer.mergeAll( |
| 2623 | NodeServices.layer, |
| 2624 | NodeCrypto.layer, |
| 2625 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 2626 | hasReceipt: () => Effect.succeed(false), |
| 2627 | getThreadRecords: (threadId) => |
| 2628 | Effect.succeed( |
| 2629 | threadId === parentThreadId |
| 2630 | ? parentProjection(commands.length > 0 ? [task] : []) |
| 2631 | : childProjection, |
| 2632 | ), |
| 2633 | dispatch: (command) => |
| 2634 | Effect.sync(() => { |
| 2635 | commands.push(command); |
| 2636 | return { |
| 2637 | sequence: 1, |
| 2638 | storedEvents: [{ event: { type: "subagent.updated", payload: task } }], |
| 2639 | } as never; |
| 2640 | }), |
| 2641 | }), |
| 2642 | ServerSettings.layerTest(), |
| 2643 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 2644 | getProviders: Effect.succeed([opencode]), |
| 2645 | refreshInstance: () => Effect.succeed([opencode]), |
| 2646 | refreshWorkspaceSnapshot: () => Effect.succeed([opencode]), |
| 2647 | }), |
| 2648 | adapterRegistryLayer([opencodeInstanceId]), |
| 2649 | Layer.mock(ProjectService.ProjectService)({ |
| 2650 | getById: () => Effect.succeedSome({ id: projectId, workspaceRoot } as never), |
| 2651 | }), |
| 2652 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 2653 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 2654 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 2655 | ); |
| 2656 | yield* Effect.gen(function* () { |
| 2657 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 2658 | const capabilities = yield* service.capabilities(scope, { search: "local" }); |
| 2659 | assert.deepEqual( |
| 2660 | capabilities.providers |
| 2661 | .find((provider) => provider.providerInstanceId === opencodeInstanceId) |
| 2662 | ?.models.map((listed) => listed.id), |
| 2663 | [model], |
| 2664 | ); |
| 2665 | const result = yield* service.delegateTask(scope, { |
| 2666 | task: "Review the change.", |
| 2667 | target: { providerInstanceId: opencodeInstanceId, model }, |
| 2668 | mode: "async", |
| 2669 | clientRequestId: "folder-scoped-model", |
| 2670 | }); |
| 2671 | assert.equal(result.model, model); |
| 2672 | assert.deepEqual((commands[0] as { modelSelection: unknown }).modelSelection, { |
| 2673 | instanceId: opencodeInstanceId, |
| 2674 | model, |
| 2675 | }); |
| 2676 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); |
| 2677 | }), |
| 2678 | ); |
| 2679 | |
| 2680 | it.effect("rejects delegation to a provider without a registered adapter", () => |
| 2681 | Effect.gen(function* () { |
| 2682 | const forkOnlyInstanceId = ProviderInstanceId.make("forkOnly"); |
| 2683 | const forkShadow = yield* buildUnavailableProviderSnapshot({ |
| 2684 | driverKind: "forkOnly", |
| 2685 | instanceId: forkOnlyInstanceId, |
| 2686 | reason: "Driver 'forkOnly' is not registered in this build.", |
| 2687 | checkedAt: "2026-09-13T00:00:00.000Z", |
| 2688 | }); |
| 2689 | const layerDependencies = Layer.mergeAll( |
| 2690 | NodeServices.layer, |
| 2691 | NodeCrypto.layer, |
| 2692 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 2693 | hasReceipt: () => Effect.succeed(false), |
| 2694 | getThreadRecords: () => Effect.succeed(parentProjection([])), |
| 2695 | }), |
| 2696 | ServerSettings.layerTest(), |
| 2697 | providerRegistryLayer([ |
| 2698 | providerSnapshot({ |
| 2699 | instanceId: codexInstanceId, |
| 2700 | driver: ProviderDriverKind.make("codex"), |
| 2701 | model: "gpt-5.4", |
| 2702 | }), |
| 2703 | forkShadow, |
| 2704 | ]), |
| 2705 | adapterRegistryLayer([codexInstanceId]), |
| 2706 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 2707 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 2708 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 2709 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 2710 | ); |
| 2711 | |
| 2712 | yield* Effect.gen(function* () { |
| 2713 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 2714 | const byInstance = yield* service |
| 2715 | .delegateTask(scope, { |
| 2716 | task: "Summarize the diff.", |
| 2717 | target: { providerInstanceId: forkOnlyInstanceId }, |
| 2718 | mode: "async", |
| 2719 | clientRequestId: "delegate-fork-1", |
| 2720 | }) |
| 2721 | .pipe(Effect.flip); |
| 2722 | assert.equal(byInstance.code, "provider_unavailable"); |
| 2723 | assert.isTrue(byInstance.message.includes("No V2 provider adapter is registered.")); |
| 2724 | |
| 2725 | const byDriver = yield* service |
| 2726 | .delegateTask(scope, { |
| 2727 | task: "Summarize the diff.", |
| 2728 | target: { driverKind: ProviderDriverKind.make("forkOnly") }, |
| 2729 | mode: "async", |
| 2730 | clientRequestId: "delegate-fork-2", |
| 2731 | }) |
| 2732 | .pipe(Effect.flip); |
| 2733 | assert.equal(byDriver.code, "provider_unavailable"); |
| 2734 | assert.isTrue( |
| 2735 | byDriver.message.includes("No V2 provider adapter is registered for driver forkOnly."), |
| 2736 | ); |
| 2737 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 2738 | }), |
| 2739 | ); |
| 2740 | |
| 2741 | it.effect("reports the dispatch cause instead of the generic wrapper when delegating fails", () => |
| 2742 | Effect.gen(function* () { |
| 2743 | const layerDependencies = Layer.mergeAll( |
| 2744 | NodeServices.layer, |
| 2745 | NodeCrypto.layer, |
| 2746 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 2747 | hasReceipt: () => Effect.succeed(false), |
| 2748 | getThreadRecords: () => Effect.succeed(parentProjection([])), |
| 2749 | dispatch: (command) => |
| 2750 | Effect.fail( |
| 2751 | new OrchestratorDispatchError({ |
| 2752 | commandId: command.commandId, |
| 2753 | commandType: command.type, |
| 2754 | cause: new Error("refused by the orchestrator"), |
| 2755 | }) as never, |
| 2756 | ), |
| 2757 | }), |
| 2758 | ServerSettings.layerTest(), |
| 2759 | providerRegistryLayer([ |
| 2760 | providerSnapshot({ |
| 2761 | instanceId: codexInstanceId, |
| 2762 | driver: ProviderDriverKind.make("codex"), |
| 2763 | model: "gpt-5.4", |
| 2764 | }), |
| 2765 | ]), |
| 2766 | adapterRegistryLayer([codexInstanceId]), |
| 2767 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 2768 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 2769 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 2770 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 2771 | ); |
| 2772 | const error = yield* Effect.gen(function* () { |
| 2773 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 2774 | return yield* service |
| 2775 | .delegateTask(scope, { |
| 2776 | task: "Summarize the diff.", |
| 2777 | mode: "async", |
| 2778 | clientRequestId: "delegate-dispatch-cause", |
| 2779 | }) |
| 2780 | .pipe(Effect.flip); |
| 2781 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 2782 | assert.equal(error.code, "orchestration_error"); |
| 2783 | assert.equal(error.message, "Unable to create delegated task: refused by the orchestrator"); |
| 2784 | }), |
| 2785 | ); |
| 2786 | |
| 2787 | it.effect.each([ |
| 2788 | { failingType: "thread.create", prefix: "Unable to create thread 1: " }, |
| 2789 | { failingType: "message.dispatch", prefix: "Unable to start thread 1: " }, |
| 2790 | { |
| 2791 | failingType: "thread.created.record", |
| 2792 | prefix: "Unable to record thread 1 in the parent timeline: ", |
| 2793 | }, |
| 2794 | ] as const)( |
| 2795 | "reports the dispatch cause instead of the generic wrapper when create_threads' $failingType dispatch fails", |
| 2796 | ({ failingType, prefix }) => |
| 2797 | Effect.gen(function* () { |
| 2798 | const childThreadId = ThreadId.make("thread:mcp-providers-create-child"); |
| 2799 | const childShell = { |
| 2800 | thread: { |
| 2801 | id: childThreadId, |
| 2802 | title: "Child", |
| 2803 | modelSelection: { instanceId: codexInstanceId, model: "gpt-5.4" }, |
| 2804 | }, |
| 2805 | runs: [], |
| 2806 | } as unknown as OrchestrationV2ThreadProjection; |
| 2807 | const layerDependencies = Layer.mergeAll( |
| 2808 | NodeServices.layer, |
| 2809 | NodeCrypto.layer, |
| 2810 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 2811 | hasReceipt: () => Effect.succeed(false), |
| 2812 | assertProviderInstanceEnabled: () => Effect.void, |
| 2813 | getThreadRecords: (threadId) => |
| 2814 | Effect.succeed(threadId === parentThreadId ? parentProjection([]) : childShell), |
| 2815 | dispatch: (command) => |
| 2816 | command.type === failingType |
| 2817 | ? Effect.fail( |
| 2818 | new OrchestratorDispatchError({ |
| 2819 | commandId: command.commandId, |
| 2820 | commandType: command.type, |
| 2821 | cause: new Error("refused by the orchestrator"), |
| 2822 | }) as never, |
| 2823 | ) |
| 2824 | : Effect.succeed({ storedEvents: [] } as never), |
| 2825 | }), |
| 2826 | ServerSettings.layerTest(), |
| 2827 | providerRegistryLayer([ |
| 2828 | providerSnapshot({ |
| 2829 | instanceId: codexInstanceId, |
| 2830 | driver: ProviderDriverKind.make("codex"), |
| 2831 | model: "gpt-5.4", |
| 2832 | }), |
| 2833 | ]), |
| 2834 | adapterRegistryLayer([codexInstanceId]), |
| 2835 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 2836 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 2837 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 2838 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 2839 | ); |
| 2840 | const error = yield* Effect.gen(function* () { |
| 2841 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 2842 | return yield* service |
| 2843 | .createThreads(scope, { |
| 2844 | threads: [{ prompt: "Summarize the diff." }], |
| 2845 | clientRequestId: `create-threads-dispatch-cause-${failingType}`, |
| 2846 | }) |
| 2847 | .pipe(Effect.flip); |
| 2848 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 2849 | assert.equal(error.code, "orchestration_error"); |
| 2850 | assert.equal(error.message, `${prefix}refused by the orchestrator`); |
| 2851 | }), |
| 2852 | ); |
| 2853 | |
| 2854 | it.effect("an unadvertised model refusal names advertised slugs to retry with", () => |
| 2855 | Effect.gen(function* () { |
| 2856 | const codex = providerSnapshot({ |
| 2857 | instanceId: codexInstanceId, |
| 2858 | driver: ProviderDriverKind.make("codex"), |
| 2859 | }); |
| 2860 | const layerDependencies = Layer.mergeAll( |
| 2861 | NodeServices.layer, |
| 2862 | NodeCrypto.layer, |
| 2863 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 2864 | hasReceipt: () => Effect.succeed(false), |
| 2865 | getThreadRecords: () => Effect.succeed(parentProjection([])), |
| 2866 | }), |
| 2867 | ServerSettings.layerTest(), |
| 2868 | providerRegistryLayer([ |
| 2869 | { |
| 2870 | ...codex, |
| 2871 | models: [ |
| 2872 | { slug: "claude-opus-4-1", isLegacy: true }, |
| 2873 | ...Array.from({ length: 9 }, (_, index) => ({ slug: `claude-opus-5-${index + 1}` })), |
| 2874 | ].map((model) => ({ ...model, name: model.slug, isCustom: false, capabilities: null })), |
| 2875 | version: "2.1.302", |
| 2876 | updateRequiredModels: [ |
| 2877 | { slug: "claude-fable-5-2", name: "Claude Fable 5.2", minVersion: "2.1.321" }, |
| 2878 | ], |
| 2879 | }, |
| 2880 | ]), |
| 2881 | adapterRegistryLayer([codexInstanceId]), |
| 2882 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 2883 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 2884 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 2885 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 2886 | ); |
| 2887 | |
| 2888 | yield* Effect.gen(function* () { |
| 2889 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 2890 | const refuse = (model: string) => |
| 2891 | service |
| 2892 | .delegateTask(scope, { |
| 2893 | task: "Summarize the diff.", |
| 2894 | target: { providerInstanceId: codexInstanceId, model }, |
| 2895 | mode: "async", |
| 2896 | clientRequestId: `delegate-unadvertised-${model}`, |
| 2897 | }) |
| 2898 | .pipe(Effect.flip); |
| 2899 | |
| 2900 | const prefixed = yield* refuse("anthropic/claude-opus-5-3"); |
| 2901 | assert.equal(prefixed.code, "model_unavailable"); |
| 2902 | assert.equal( |
| 2903 | prefixed.message, |
| 2904 | "Model anthropic/claude-opus-5-3 is not advertised by provider codex. " + |
| 2905 | "Did you mean claude-opus-5-3?", |
| 2906 | ); |
| 2907 | |
| 2908 | const unmatched = yield* refuse("opus-5.5"); |
| 2909 | assert.equal( |
| 2910 | unmatched.message, |
| 2911 | "Model opus-5.5 is not advertised by provider codex. Advertised models: " + |
| 2912 | "claude-opus-5-1, claude-opus-5-2, claude-opus-5-3, claude-opus-5-4, claude-opus-5-5, " + |
| 2913 | "claude-opus-5-6, claude-opus-5-7, claude-opus-5-8 and 2 more; " + |
| 2914 | "orchestrator_capabilities with search finds them.", |
| 2915 | ); |
| 2916 | |
| 2917 | const updateRequired = yield* refuse("claude-fable-5-2"); |
| 2918 | assert.equal(updateRequired.code, "model_unavailable"); |
| 2919 | assert.include(updateRequired.message, "v2.1.302"); |
| 2920 | assert.include(updateRequired.message, "2.1.321"); |
| 2921 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 2922 | }), |
| 2923 | ); |
| 2924 | |
| 2925 | it.effect("driver-only delegation skips an instance the project turned off", () => |
| 2926 | Effect.gen(function* () { |
| 2927 | const altInstanceId = ProviderInstanceId.make("codex-alt"); |
| 2928 | const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]); |
| 2929 | const task = { |
| 2930 | id: taskId, |
| 2931 | threadId: parentThreadId, |
| 2932 | runId: parentRunId, |
| 2933 | parentNodeId, |
| 2934 | origin: "app_owned", |
| 2935 | createdBy: "agent", |
| 2936 | driver: ProviderDriverKind.make("codex"), |
| 2937 | providerInstanceId: altInstanceId, |
| 2938 | providerThreadId: null, |
| 2939 | childThreadId, |
| 2940 | nativeTaskRef: null, |
| 2941 | prompt: "Summarize the diff.", |
| 2942 | title: null, |
| 2943 | model: "gpt-5.4", |
| 2944 | status: "running", |
| 2945 | result: null, |
| 2946 | startedAt: null, |
| 2947 | completedAt: null, |
| 2948 | }; |
| 2949 | let delegated = false; |
| 2950 | const layerDependencies = Layer.mergeAll( |
| 2951 | NodeServices.layer, |
| 2952 | NodeCrypto.layer, |
| 2953 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 2954 | hasReceipt: () => Effect.succeed(false), |
| 2955 | getThreadRecords: (threadId) => |
| 2956 | Effect.succeed( |
| 2957 | threadId === parentThreadId |
| 2958 | ? parentProjection(delegated ? [task] : []) |
| 2959 | : childProjection, |
| 2960 | ), |
| 2961 | isProviderInstanceEnabledForProject: ({ instanceId }) => |
| 2962 | Effect.succeed(instanceId !== codexInstanceId), |
| 2963 | assertProviderInstanceEnabled: ({ projectId, instanceId }) => |
| 2964 | instanceId === codexInstanceId |
| 2965 | ? Effect.fail( |
| 2966 | new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({ |
| 2967 | projectId, |
| 2968 | instanceId, |
| 2969 | }), |
| 2970 | ) |
| 2971 | : Effect.void, |
| 2972 | dispatch: (command) => |
| 2973 | Ref.update(dispatched, (commands) => [...commands, command]).pipe( |
| 2974 | Effect.andThen( |
| 2975 | Effect.sync(() => { |
| 2976 | delegated = true; |
| 2977 | }), |
| 2978 | ), |
| 2979 | Effect.as({ |
| 2980 | sequence: 1, |
| 2981 | storedEvents: [ |
| 2982 | { |
| 2983 | sequence: 1, |
| 2984 | commandId: null, |
| 2985 | event: { type: "subagent.updated", payload: task }, |
| 2986 | }, |
| 2987 | ], |
| 2988 | } as never), |
| 2989 | ), |
| 2990 | }), |
| 2991 | providerRegistryLayer([ |
| 2992 | providerSnapshot({ |
| 2993 | instanceId: codexInstanceId, |
| 2994 | driver: ProviderDriverKind.make("codex"), |
| 2995 | model: "gpt-5.4", |
| 2996 | }), |
| 2997 | providerSnapshot({ |
| 2998 | instanceId: altInstanceId, |
| 2999 | driver: ProviderDriverKind.make("codex"), |
| 3000 | model: "gpt-5.4", |
| 3001 | }), |
| 3002 | ]), |
| 3003 | adapterRegistryLayer([codexInstanceId, altInstanceId]), |
| 3004 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 3005 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 3006 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 3007 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 3008 | ServerSettings.layerTest(), |
| 3009 | ); |
| 3010 | |
| 3011 | yield* Effect.gen(function* () { |
| 3012 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 3013 | const result = yield* service.delegateTask(scope, { |
| 3014 | task: "Summarize the diff.", |
| 3015 | target: { driverKind: ProviderDriverKind.make("codex") }, |
| 3016 | mode: "async", |
| 3017 | clientRequestId: "delegate-driver-skip-disabled-1", |
| 3018 | }); |
| 3019 | assert.equal(result.status, "running"); |
| 3020 | const commands = yield* Ref.get(dispatched); |
| 3021 | assert.equal(commands.length, 1); |
| 3022 | const request = commands[0] as { |
| 3023 | modelSelection: { instanceId: string; model: string }; |
| 3024 | }; |
| 3025 | assert.equal(request.modelSelection.instanceId, altInstanceId); |
| 3026 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 3027 | }), |
| 3028 | ); |
| 3029 | |
| 3030 | it.effect.each(["async", "wait"] as const)( |
| 3031 | "prepares a delegated child whose %s caller goes away after its run commits", |
| 3032 | (mode) => |
| 3033 | Effect.gen(function* () { |
| 3034 | const runCommitted = yield* Deferred.make<void>(); |
| 3035 | const wakePolicies = yield* Ref.make<ReadonlyArray<string>>([]); |
| 3036 | const finishDispatch = yield* Deferred.make<void>(); |
| 3037 | const prepared = yield* Deferred.make<void>(); |
| 3038 | const childRunId = RunId.make("run:mcp-delegate-caller-gone"); |
| 3039 | const task = { |
| 3040 | id: taskId, |
| 3041 | threadId: parentThreadId, |
| 3042 | runId: parentRunId, |
| 3043 | parentNodeId, |
| 3044 | origin: "app_owned", |
| 3045 | createdBy: "agent", |
| 3046 | driver: ProviderDriverKind.make("codex"), |
| 3047 | providerInstanceId: codexInstanceId, |
| 3048 | providerThreadId: null, |
| 3049 | childThreadId, |
| 3050 | nativeTaskRef: null, |
| 3051 | prompt: "Summarize the diff.", |
| 3052 | title: null, |
| 3053 | model: "gpt-5.4", |
| 3054 | status: "running", |
| 3055 | result: null, |
| 3056 | startedAt: null, |
| 3057 | completedAt: null, |
| 3058 | }; |
| 3059 | const layerDependencies = Layer.mergeAll( |
| 3060 | NodeServices.layer, |
| 3061 | NodeCrypto.layer, |
| 3062 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 3063 | hasReceipt: () => Effect.succeed(false), |
| 3064 | getThreadRecords: (threadId) => |
| 3065 | Effect.succeed(threadId === parentThreadId ? parentProjection([]) : childProjection), |
| 3066 | isProviderInstanceEnabledForProject: () => Effect.succeed(true), |
| 3067 | assertProviderInstanceEnabled: () => Effect.void, |
| 3068 | dispatch: (command) => |
| 3069 | command.type === "delegated_task.wake-policy" |
| 3070 | ? Ref.update(wakePolicies, (policies) => [ |
| 3071 | ...policies, |
| 3072 | command.completionWake, |
| 3073 | ]).pipe(Effect.as({ sequence: 3, storedEvents: [] } as never)) |
| 3074 | : Deferred.succeed(runCommitted, undefined).pipe( |
| 3075 | Effect.andThen(Deferred.await(finishDispatch)), |
| 3076 | Effect.as({ |
| 3077 | sequence: 2, |
| 3078 | storedEvents: [ |
| 3079 | { |
| 3080 | sequence: 1, |
| 3081 | commandId: null, |
| 3082 | event: { type: "subagent.updated", payload: task }, |
| 3083 | }, |
| 3084 | { |
| 3085 | sequence: 2, |
| 3086 | commandId: null, |
| 3087 | event: { |
| 3088 | type: "run.created", |
| 3089 | threadId: childThreadId, |
| 3090 | payload: { id: childRunId, workspacePreparation: { type: "root" } }, |
| 3091 | }, |
| 3092 | }, |
| 3093 | ], |
| 3094 | } as never), |
| 3095 | ), |
| 3096 | }), |
| 3097 | providerRegistryLayer([ |
| 3098 | providerSnapshot({ |
| 3099 | instanceId: codexInstanceId, |
| 3100 | driver: ProviderDriverKind.make("codex"), |
| 3101 | model: "gpt-5.4", |
| 3102 | }), |
| 3103 | ]), |
| 3104 | adapterRegistryLayer([codexInstanceId]), |
| 3105 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 3106 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 3107 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 3108 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 3109 | ServerSettings.layerTest(), |
| 3110 | ); |
| 3111 | const layerService = OrchestratorMcpService.layer.pipe( |
| 3112 | Layer.provide( |
| 3113 | Layer.mock(ThreadLaunchService.ThreadLaunchService)({ |
| 3114 | prepareRun: (input) => |
| 3115 | input.runId === childRunId ? Deferred.succeed(prepared, undefined) : Effect.void, |
| 3116 | }), |
| 3117 | ), |
| 3118 | Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), |
| 3119 | ); |
| 3120 | |
| 3121 | yield* Effect.gen(function* () { |
| 3122 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 3123 | const delegation = yield* Effect.forkChild( |
| 3124 | service.delegateTask(scope, { |
| 3125 | task: "Summarize the diff.", |
| 3126 | target: { driverKind: ProviderDriverKind.make("codex") }, |
| 3127 | mode, |
| 3128 | clientRequestId: `delegate-caller-gone-${mode}`, |
| 3129 | }), |
| 3130 | ); |
| 3131 | yield* Deferred.await(runCommitted); |
| 3132 | yield* Effect.sync(() => delegation.interruptUnsafe()); |
| 3133 | yield* Deferred.succeed(finishDispatch, undefined); |
| 3134 | yield* Fiber.await(delegation); |
| 3135 | yield* Deferred.await(prepared); |
| 3136 | assert.deepEqual(yield* Ref.get(wakePolicies), mode === "wait" ? ["always"] : []); |
| 3137 | }).pipe(Effect.provide(layerService.pipe(Layer.provide(layerDependencies)))); |
| 3138 | }), |
| 3139 | ); |
| 3140 | |
| 3141 | it.effect( |
| 3142 | "retrying an accepted driver-only delegation replays even after the project disables every candidate", |
| 3143 | () => |
| 3144 | Effect.gen(function* () { |
| 3145 | const altInstanceId = ProviderInstanceId.make("codex-alt"); |
| 3146 | const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]); |
| 3147 | const accepted = yield* Ref.make(false); |
| 3148 | const everyCandidateDisabled = yield* Ref.make(false); |
| 3149 | const task = { |
| 3150 | id: taskId, |
| 3151 | threadId: parentThreadId, |
| 3152 | runId: parentRunId, |
| 3153 | parentNodeId, |
| 3154 | origin: "app_owned", |
| 3155 | createdBy: "agent", |
| 3156 | driver: ProviderDriverKind.make("codex"), |
| 3157 | providerInstanceId: codexInstanceId, |
| 3158 | providerThreadId: null, |
| 3159 | childThreadId, |
| 3160 | nativeTaskRef: null, |
| 3161 | prompt: "Summarize the diff.", |
| 3162 | title: null, |
| 3163 | model: "gpt-5.4", |
| 3164 | status: "running", |
| 3165 | result: null, |
| 3166 | startedAt: null, |
| 3167 | completedAt: null, |
| 3168 | }; |
| 3169 | const layerDependencies = Layer.mergeAll( |
| 3170 | NodeServices.layer, |
| 3171 | NodeCrypto.layer, |
| 3172 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 3173 | getThreadRecords: (threadId) => |
| 3174 | Ref.get(accepted).pipe( |
| 3175 | Effect.map((isAccepted) => |
| 3176 | threadId === parentThreadId |
| 3177 | ? parentProjection(isAccepted ? [task] : []) |
| 3178 | : childProjection, |
| 3179 | ), |
| 3180 | ), |
| 3181 | hasReceipt: () => Ref.get(accepted), |
| 3182 | isProviderInstanceEnabledForProject: () => |
| 3183 | Ref.get(everyCandidateDisabled).pipe(Effect.map((disabled) => !disabled)), |
| 3184 | assertProviderInstanceEnabled: ({ projectId, instanceId }) => |
| 3185 | Effect.all([Ref.get(accepted), Ref.get(everyCandidateDisabled)]).pipe( |
| 3186 | Effect.flatMap(([isAccepted, disabled]) => |
| 3187 | isAccepted || !disabled |
| 3188 | ? Effect.void |
| 3189 | : Effect.fail( |
| 3190 | new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({ |
| 3191 | projectId, |
| 3192 | instanceId, |
| 3193 | }), |
| 3194 | ), |
| 3195 | ), |
| 3196 | ), |
| 3197 | dispatch: (command) => |
| 3198 | Ref.update(dispatched, (commands) => [...commands, command]).pipe( |
| 3199 | Effect.andThen(Ref.set(accepted, true)), |
| 3200 | Effect.as({ |
| 3201 | sequence: 1, |
| 3202 | storedEvents: [ |
| 3203 | { |
| 3204 | sequence: 1, |
| 3205 | commandId: null, |
| 3206 | event: { type: "subagent.updated", payload: task }, |
| 3207 | }, |
| 3208 | ], |
| 3209 | } as never), |
| 3210 | ), |
| 3211 | }), |
| 3212 | providerRegistryLayer([ |
| 3213 | providerSnapshot({ |
| 3214 | instanceId: codexInstanceId, |
| 3215 | driver: ProviderDriverKind.make("codex"), |
| 3216 | model: "gpt-5.4", |
| 3217 | }), |
| 3218 | providerSnapshot({ |
| 3219 | instanceId: altInstanceId, |
| 3220 | driver: ProviderDriverKind.make("codex"), |
| 3221 | model: "gpt-5.4", |
| 3222 | }), |
| 3223 | ]), |
| 3224 | adapterRegistryLayer([codexInstanceId, altInstanceId]), |
| 3225 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 3226 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 3227 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 3228 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 3229 | ServerSettings.layerTest(), |
| 3230 | ); |
| 3231 | |
| 3232 | yield* Effect.gen(function* () { |
| 3233 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 3234 | const first = yield* service.delegateTask(scope, { |
| 3235 | task: "Summarize the diff.", |
| 3236 | target: { driverKind: ProviderDriverKind.make("codex") }, |
| 3237 | mode: "async", |
| 3238 | clientRequestId: "delegate-driver-retry-after-disable-1", |
| 3239 | }); |
| 3240 | assert.equal(first.status, "running"); |
| 3241 | |
| 3242 | yield* Ref.set(everyCandidateDisabled, true); |
| 3243 | |
| 3244 | const retry = yield* service.delegateTask(scope, { |
| 3245 | task: "Summarize the diff.", |
| 3246 | target: { driverKind: ProviderDriverKind.make("codex") }, |
| 3247 | mode: "async", |
| 3248 | clientRequestId: "delegate-driver-retry-after-disable-1", |
| 3249 | }); |
| 3250 | assert.equal(retry.status, "running"); |
| 3251 | |
| 3252 | const commands = yield* Ref.get(dispatched); |
| 3253 | assert.equal(commands.length, 2); |
| 3254 | const retryCommand = commands[1] as { |
| 3255 | modelSelection: { instanceId: string; model: string }; |
| 3256 | }; |
| 3257 | assert.equal(retryCommand.modelSelection.instanceId, codexInstanceId); |
| 3258 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 3259 | }), |
| 3260 | ); |
| 3261 | |
| 3262 | it.effect.each([ |
| 3263 | { name: "parent instance", parentEnabled: true, model: "gpt-5.4" }, |
| 3264 | { name: "alternate instance", parentEnabled: false, model: "gpt-5.5" }, |
| 3265 | ])( |
| 3266 | "replays accepted creation on the $name without authorizing new disabled work", |
| 3267 | ({ parentEnabled, model }) => |
| 3268 | Effect.gen(function* () { |
| 3269 | const altInstanceId = ProviderInstanceId.make("codex-alt"); |
| 3270 | const driver = ProviderDriverKind.make("codex"); |
| 3271 | const cwd = yield* checkpointWorkspace("mcp-create-retry"); |
| 3272 | const layerRegistry = ProviderAdapterRegistry.layerFromAdapters( |
| 3273 | [codexInstanceId, altInstanceId].map((instanceId) => ({ |
| 3274 | instanceId, |
| 3275 | driver, |
| 3276 | getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), |
| 3277 | planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), |
| 3278 | openSession: () => |
| 3279 | Effect.die("These tests exercise committed commands before provider execution."), |
| 3280 | })), |
| 3281 | ); |
| 3282 | const layerDatabase = SqlitePersistence.layerMemory; |
| 3283 | const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( |
| 3284 | { name: "mcp-create-retry", runtimePolicyOverride: { cwd } }, |
| 3285 | layerRegistry, |
| 3286 | { databaseLayer: layerDatabase, runEffectWorker: false }, |
| 3287 | ); |
| 3288 | const layerSettings = ServerSettings.layerTest({ |
| 3289 | providerInstances: { |
| 3290 | [codexInstanceId]: { driver: "codex", enabled: true }, |
| 3291 | [altInstanceId]: { driver: "codex", enabled: true }, |
| 3292 | }, |
| 3293 | projectSettingsOverrides: { |
| 3294 | [projectId]: { providerInstances: { [codexInstanceId]: { enabled: parentEnabled } } }, |
| 3295 | }, |
| 3296 | }); |
| 3297 | const layerThreads = ThreadManagementService.layer.pipe( |
| 3298 | Layer.provideMerge(layerOrchestrator), |
| 3299 | Layer.provide( |
| 3300 | LegacyV1ThreadImporter.layer.pipe( |
| 3301 | Layer.provide(layerOrchestrator), |
| 3302 | Layer.provide(layerDatabase), |
| 3303 | ), |
| 3304 | ), |
| 3305 | Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))), |
| 3306 | Layer.provideMerge(layerSettings), |
| 3307 | ); |
| 3308 | const layerTest = layerOrchestratorService.pipe( |
| 3309 | Layer.provideMerge(layerThreads), |
| 3310 | Layer.provide( |
| 3311 | Layer.mergeAll( |
| 3312 | NodeServices.layer, |
| 3313 | NodeCrypto.layer, |
| 3314 | layerRegistry, |
| 3315 | layerSettings, |
| 3316 | providerRegistryLayer([ |
| 3317 | providerSnapshot({ instanceId: codexInstanceId, driver, model: "gpt-5.4" }), |
| 3318 | providerSnapshot({ instanceId: altInstanceId, driver, model: "gpt-5.5" }), |
| 3319 | ]), |
| 3320 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 3321 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 3322 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 3323 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 3324 | ), |
| 3325 | ), |
| 3326 | ); |
| 3327 | yield* Effect.gen(function* () { |
| 3328 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 3329 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 3330 | const settings = yield* ServerSettings.ServerSettingsService; |
| 3331 | yield* orchestrator.dispatch({ |
| 3332 | type: "thread.create", |
| 3333 | createdBy: "user", |
| 3334 | creationSource: "web", |
| 3335 | commandId: CommandId.make("parent:create"), |
| 3336 | threadId: parentThreadId, |
| 3337 | projectId, |
| 3338 | title: "MCP parent", |
| 3339 | modelSelection: { instanceId: codexInstanceId, model: "gpt-5.4" }, |
| 3340 | runtimeMode: "approval-required", |
| 3341 | interactionMode: "default", |
| 3342 | branch: null, |
| 3343 | worktreePath: cwd, |
| 3344 | }); |
| 3345 | yield* orchestrator.dispatch({ |
| 3346 | type: "message.dispatch", |
| 3347 | createdBy: "user", |
| 3348 | creationSource: "web", |
| 3349 | commandId: CommandId.make("parent:start"), |
| 3350 | threadId: parentThreadId, |
| 3351 | messageId: MessageId.make("parent:message"), |
| 3352 | text: "Create a thread.", |
| 3353 | attachments: [], |
| 3354 | dispatchMode: { type: "start_immediately" }, |
| 3355 | }); |
| 3356 | const request = { |
| 3357 | threads: [{ target: { driverKind: driver, model } }], |
| 3358 | clientRequestId: "create-retry", |
| 3359 | }; |
| 3360 | const first = yield* service.createThreads(scope, request); |
| 3361 | const child = first.threads[0]!; |
| 3362 | const selection = parentEnabled |
| 3363 | ? { instanceId: codexInstanceId, model: "gpt-5.4" } |
| 3364 | : { instanceId: altInstanceId, model: "gpt-5.5" }; |
| 3365 | assert.equal(first.threads.length, 1); |
| 3366 | assert.equal(child.providerInstanceId, selection.instanceId); |
| 3367 | assert.equal(child.model, selection.model); |
| 3368 | assert.deepEqual(yield* service.createThreads(scope, request), first); |
| 3369 | |
| 3370 | // The creation receipt exists, but this prompt has not been accepted yet. |
| 3371 | const withPrompt = { |
| 3372 | ...request, |
| 3373 | threads: [{ ...request.threads[0]!, prompt: "Start work." }], |
| 3374 | }; |
| 3375 | const started = yield* service.createThreads(scope, withPrompt); |
| 3376 | assert.equal(started.threads[0]?.threadId, child.threadId); |
| 3377 | const before = yield* orchestrator.getThreadProjection(child.threadId); |
| 3378 | assert.deepEqual(before.runs[0]?.modelSelection, selection); |
| 3379 | assert.equal(before.messages.length, 1); |
| 3380 | const empty = yield* service.createThreads(scope, { |
| 3381 | ...request, |
| 3382 | clientRequestId: "empty", |
| 3383 | }); |
| 3384 | const raised = yield* service.createThreads(scope, { |
| 3385 | ...request, |
| 3386 | clientRequestId: "raised", |
| 3387 | }); |
| 3388 | const raisedId = raised.threads[0]!.threadId; |
| 3389 | yield* orchestrator.dispatch({ |
| 3390 | type: "thread.runtime-mode.set", |
| 3391 | commandId: CommandId.make("raise-created-thread"), |
| 3392 | threadId: raisedId, |
| 3393 | runtimeMode: "full-access", |
| 3394 | }); |
| 3395 | const rejected = yield* service |
| 3396 | .createThreads(scope, { ...withPrompt, clientRequestId: "raised" }) |
| 3397 | .pipe(Effect.flip); |
| 3398 | assert.equal(rejected.code, "runtime_mode_escalation_denied"); |
| 3399 | assert.equal((yield* orchestrator.getThreadProjection(raisedId)).runs.length, 0); |
| 3400 | |
| 3401 | const emojiAtLimit = yield* service.createThreads(scope, { |
| 3402 | threads: [{ ...request.threads[0]!, prompt: `${"a".repeat(76)}😀 and more work.` }], |
| 3403 | clientRequestId: "emoji-title", |
| 3404 | }); |
| 3405 | const titled = yield* orchestrator.getThreadProjection(emojiAtLimit.threads[0]!.threadId); |
| 3406 | assert.equal(titled.thread.title, `${"a".repeat(76)}...`); |
| 3407 | // One commit holds a prompted thread and its run, so no client sees it idle between. |
| 3408 | const promptedCommits = yield* orchestrator |
| 3409 | .streamStoredEventsFrom({ threadId: titled.thread.id }) |
| 3410 | .pipe( |
| 3411 | Stream.filter( |
| 3412 | ({ event }) => event.type === "thread.created" || event.type === "run.created", |
| 3413 | ), |
| 3414 | Stream.take(2), |
| 3415 | Stream.runCollect, |
| 3416 | ); |
| 3417 | assert.equal(promptedCommits[0]?.commandId, promptedCommits[1]?.commandId); |
| 3418 | |
| 3419 | yield* settings.updateSettings({ |
| 3420 | projectSettingsOverrides: { |
| 3421 | [projectId]: { |
| 3422 | providerInstances: { |
| 3423 | [codexInstanceId]: { enabled: false }, |
| 3424 | [altInstanceId]: { enabled: false }, |
| 3425 | }, |
| 3426 | }, |
| 3427 | }, |
| 3428 | }); |
| 3429 | assert.deepEqual(yield* service.createThreads(scope, withPrompt), started); |
| 3430 | const after = yield* orchestrator.getThreadProjection(child.threadId); |
| 3431 | assert.deepEqual(after.thread.modelSelection, selection); |
| 3432 | assert.deepEqual(after.runs, before.runs); |
| 3433 | assert.deepEqual(after.messages, before.messages); |
| 3434 | |
| 3435 | const freshError = yield* service |
| 3436 | .createThreads(scope, { |
| 3437 | ...request, |
| 3438 | clientRequestId: "fresh", |
| 3439 | }) |
| 3440 | .pipe(Effect.flip); |
| 3441 | assert.equal(freshError.code, "provider_unavailable"); |
| 3442 | const promptError = yield* service |
| 3443 | .createThreads(scope, { |
| 3444 | ...withPrompt, |
| 3445 | clientRequestId: "empty", |
| 3446 | }) |
| 3447 | .pipe(Effect.flip); |
| 3448 | assert.equal(promptError.code, "invalid_request"); |
| 3449 | assert.include(promptError.message, "disabled"); |
| 3450 | const untouched = yield* orchestrator.getThreadProjection(empty.threads[0]!.threadId); |
| 3451 | assert.equal(untouched.messages.length, 0); |
| 3452 | assert.equal(untouched.runs.length, 0); |
| 3453 | }).pipe(Effect.provide(layerTest)); |
| 3454 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 3455 | ); |
| 3456 | |
| 3457 | it.effect.each(["local", "remote"] as const)( |
| 3458 | "a blocking %s delegation cancelled mid-wait wakes its parent like an async task", |
| 3459 | (placement) => |
| 3460 | Effect.gen(function* () { |
| 3461 | const driver = ProviderDriverKind.make("codex"); |
| 3462 | const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ |
| 3463 | { |
| 3464 | instanceId: codexInstanceId, |
| 3465 | driver, |
| 3466 | getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), |
| 3467 | planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), |
| 3468 | openSession: () => Effect.die("The child never starts: the effect worker is off."), |
| 3469 | }, |
| 3470 | ]); |
| 3471 | const layerDatabase = SqlitePersistence.layerMemory; |
| 3472 | const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( |
| 3473 | { name: "mcp-wait-cancelled" }, |
| 3474 | layerRegistry, |
| 3475 | { databaseLayer: layerDatabase, runEffectWorker: false }, |
| 3476 | ); |
| 3477 | const layerSettings = ServerSettings.layerTest({ |
| 3478 | providerInstances: { [codexInstanceId]: { driver: "codex", enabled: true } }, |
| 3479 | }); |
| 3480 | const layerThreads = ThreadManagementService.layer.pipe( |
| 3481 | Layer.provideMerge(layerOrchestrator), |
| 3482 | Layer.provide( |
| 3483 | LegacyV1ThreadImporter.layer.pipe( |
| 3484 | Layer.provide(layerOrchestrator), |
| 3485 | Layer.provide(layerDatabase), |
| 3486 | ), |
| 3487 | ), |
| 3488 | Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))), |
| 3489 | Layer.provideMerge(layerSettings), |
| 3490 | ); |
| 3491 | const waiting = yield* Deferred.make<void>(); |
| 3492 | const layerWatchedThreads = Layer.effect( |
| 3493 | ThreadManagementService.ThreadManagementService, |
| 3494 | Effect.gen(function* () { |
| 3495 | const threads = yield* ThreadManagementService.ThreadManagementService; |
| 3496 | return { |
| 3497 | ...threads, |
| 3498 | streamStoredEventsFrom: (input) => |
| 3499 | Stream.unwrap( |
| 3500 | Deferred.succeed(waiting, undefined).pipe( |
| 3501 | Effect.as(threads.streamStoredEventsFrom(input)), |
| 3502 | ), |
| 3503 | ), |
| 3504 | } satisfies ThreadManagementService.ThreadManagementService["Service"]; |
| 3505 | }), |
| 3506 | ).pipe(Layer.provideMerge(layerThreads)); |
| 3507 | const remoteChild = { |
| 3508 | environmentId: EnvironmentId.make("environment:mcp-providers-box"), |
| 3509 | threadId: ThreadId.make("thread:mcp-providers-on-the-box"), |
| 3510 | label: "Box", |
| 3511 | }; |
| 3512 | // Records the task as the real delegation does once the linked environment launched it. |
| 3513 | const layerRemoteDelegation = Layer.unwrap( |
| 3514 | Effect.gen(function* () { |
| 3515 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 3516 | return Layer.mock(RemoteDelegation.RemoteDelegation)({ |
| 3517 | delegate: (_scope, input) => |
| 3518 | Effect.gen(function* () { |
| 3519 | const run = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!; |
| 3520 | yield* orchestrator.dispatch({ |
| 3521 | type: "delegated_task.remote.request", |
| 3522 | commandId: CommandId.make("command:remote-delegate:wait-cancelled"), |
| 3523 | parentThreadId, |
| 3524 | parentRunId: run.id, |
| 3525 | parentNodeId: run.rootNodeId!, |
| 3526 | task: input.task, |
| 3527 | driver: ProviderDriverKind.make("remote"), |
| 3528 | modelSelection: run.modelSelection, |
| 3529 | remoteChild, |
| 3530 | completionWake: "settled_only", |
| 3531 | }); |
| 3532 | const parent = yield* orchestrator.getThreadProjection(parentThreadId); |
| 3533 | return { taskId: parent.subagents[0]!.id }; |
| 3534 | }).pipe(Effect.orDie), |
| 3535 | runStatus: () => Effect.succeed(null), |
| 3536 | }); |
| 3537 | }), |
| 3538 | ).pipe(Layer.provide(layerWatchedThreads)); |
| 3539 | const layerTest = layerOrchestratorService.pipe( |
| 3540 | Layer.provideMerge(layerWatchedThreads), |
| 3541 | Layer.provide( |
| 3542 | Layer.mergeAll( |
| 3543 | NodeServices.layer, |
| 3544 | layerRegistry, |
| 3545 | layerSettings, |
| 3546 | providerRegistryLayer([ |
| 3547 | providerSnapshot({ instanceId: codexInstanceId, driver, model: "gpt-5.4" }), |
| 3548 | ]), |
| 3549 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 3550 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 3551 | layerRemoteDelegation, |
| 3552 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 3553 | ), |
| 3554 | ), |
| 3555 | ); |
| 3556 | yield* Effect.gen(function* () { |
| 3557 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 3558 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 3559 | yield* orchestrator.dispatch({ |
| 3560 | type: "thread.create", |
| 3561 | createdBy: "user", |
| 3562 | creationSource: "web", |
| 3563 | commandId: CommandId.make("parent:create"), |
| 3564 | threadId: parentThreadId, |
| 3565 | projectId, |
| 3566 | title: "MCP parent", |
| 3567 | modelSelection: { instanceId: codexInstanceId, model: "gpt-5.4" }, |
| 3568 | runtimeMode: "full-access", |
| 3569 | interactionMode: "default", |
| 3570 | branch: null, |
| 3571 | worktreePath: null, |
| 3572 | }); |
| 3573 | yield* orchestrator.dispatch({ |
| 3574 | type: "message.dispatch", |
| 3575 | createdBy: "user", |
| 3576 | creationSource: "web", |
| 3577 | commandId: CommandId.make("parent:start"), |
| 3578 | threadId: parentThreadId, |
| 3579 | messageId: MessageId.make("parent:message"), |
| 3580 | text: "Delegate a review and wait for it.", |
| 3581 | attachments: [], |
| 3582 | dispatchMode: { type: "start_immediately" }, |
| 3583 | }); |
| 3584 | const call = yield* service |
| 3585 | .delegateTask(scope, { |
| 3586 | task: "Review the change.", |
| 3587 | ...(placement === "remote" |
| 3588 | ? { target: { environmentId: remoteChild.environmentId } } |
| 3589 | : {}), |
| 3590 | mode: "wait", |
| 3591 | clientRequestId: "delegate-wait-cancelled", |
| 3592 | }) |
| 3593 | .pipe(Effect.forkChild); |
| 3594 | yield* Deferred.await(waiting); |
| 3595 | // A steered Claude parent cancels the tools/call, which interrupts this fiber. |
| 3596 | yield* Fiber.interrupt(call); |
| 3597 | const parent = yield* orchestrator.getThreadProjection(parentThreadId); |
| 3598 | const task = parent.subagents.find((subagent) => subagent.origin === "app_owned"); |
| 3599 | assert.equal(task?.status, "running"); |
| 3600 | assert.equal( |
| 3601 | task?.completionWake, |
| 3602 | "always", |
| 3603 | "a cancelled blocking delegation left the task settled_only, so its result never reaches the still-live parent run", |
| 3604 | ); |
| 3605 | }).pipe(Effect.provide(layerTest)); |
| 3606 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 3607 | ); |
| 3608 | |
| 3609 | it.effect( |
| 3610 | "inherits an available parent instance for driver-only targets and otherwise selects a healthy peer", |
| 3611 | () => |
| 3612 | Effect.gen(function* () { |
| 3613 | const codexAltInstanceId = ProviderInstanceId.make("codex-alt"); |
| 3614 | const driver = ProviderDriverKind.make("codex"); |
| 3615 | const claudeDriver = ProviderDriverKind.make("claudeAgent"); |
| 3616 | const parentModelSelection = { |
| 3617 | instanceId: codexInstanceId, |
| 3618 | model: "gpt-5.4", |
| 3619 | options: [{ id: "reasoningEffort", value: "high" }], |
| 3620 | } as const; |
| 3621 | const task = { |
| 3622 | id: taskId, |
| 3623 | threadId: parentThreadId, |
| 3624 | runId: parentRunId, |
| 3625 | parentNodeId, |
| 3626 | origin: "app_owned", |
| 3627 | createdBy: "agent", |
| 3628 | driver, |
| 3629 | providerInstanceId: codexInstanceId, |
| 3630 | providerThreadId: null, |
| 3631 | childThreadId, |
| 3632 | nativeTaskRef: null, |
| 3633 | prompt: "Summarize the diff.", |
| 3634 | title: null, |
| 3635 | model: "gpt-5.4", |
| 3636 | status: "running", |
| 3637 | result: null, |
| 3638 | startedAt: null, |
| 3639 | completedAt: null, |
| 3640 | }; |
| 3641 | const cases = [ |
| 3642 | { |
| 3643 | name: "healthy-inherited", |
| 3644 | inheritedEnabled: true, |
| 3645 | peerEnabled: true, |
| 3646 | explicit: false, |
| 3647 | selectedInstanceId: codexInstanceId, |
| 3648 | candidateDriver: driver, |
| 3649 | }, |
| 3650 | { |
| 3651 | name: "unavailable-inherited-falls-back-to-healthy-peer", |
| 3652 | inheritedEnabled: false, |
| 3653 | peerEnabled: true, |
| 3654 | explicit: false, |
| 3655 | selectedInstanceId: codexAltInstanceId, |
| 3656 | candidateDriver: driver, |
| 3657 | }, |
| 3658 | { |
| 3659 | name: "no-available-peer", |
| 3660 | inheritedEnabled: false, |
| 3661 | peerEnabled: false, |
| 3662 | explicit: false, |
| 3663 | selectedInstanceId: null, |
| 3664 | candidateDriver: driver, |
| 3665 | }, |
| 3666 | { |
| 3667 | name: "cross-driver-no-available-candidate", |
| 3668 | inheritedEnabled: false, |
| 3669 | peerEnabled: false, |
| 3670 | explicit: false, |
| 3671 | selectedInstanceId: null, |
| 3672 | candidateDriver: claudeDriver, |
| 3673 | }, |
| 3674 | { |
| 3675 | name: "explicit-unavailable", |
| 3676 | inheritedEnabled: false, |
| 3677 | peerEnabled: true, |
| 3678 | explicit: true, |
| 3679 | selectedInstanceId: null, |
| 3680 | candidateDriver: driver, |
| 3681 | }, |
| 3682 | { |
| 3683 | name: "inherited-unavailable", |
| 3684 | inheritedEnabled: false, |
| 3685 | peerEnabled: true, |
| 3686 | explicit: false, |
| 3687 | selectedInstanceId: null, |
| 3688 | candidateDriver: driver, |
| 3689 | }, |
| 3690 | { |
| 3691 | name: "explicit-disabled-without-adapter", |
| 3692 | inheritedEnabled: false, |
| 3693 | peerEnabled: true, |
| 3694 | explicit: true, |
| 3695 | selectedInstanceId: null, |
| 3696 | candidateDriver: driver, |
| 3697 | }, |
| 3698 | { |
| 3699 | name: "explicit-healthy", |
| 3700 | inheritedEnabled: true, |
| 3701 | peerEnabled: true, |
| 3702 | explicit: true, |
| 3703 | selectedInstanceId: codexAltInstanceId, |
| 3704 | candidateDriver: driver, |
| 3705 | }, |
| 3706 | ] as const; |
| 3707 | |
| 3708 | for (const testCase of cases) { |
| 3709 | const dispatched = yield* Ref.make<ReadonlyArray<unknown>>([]); |
| 3710 | let delegated = false; |
| 3711 | const layerDependencies = Layer.mergeAll( |
| 3712 | NodeServices.layer, |
| 3713 | NodeCrypto.layer, |
| 3714 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 3715 | hasReceipt: () => Effect.succeed(false), |
| 3716 | assertProviderInstanceEnabled: () => Effect.void, |
| 3717 | isProviderInstanceEnabledForProject: () => Effect.succeed(true), |
| 3718 | getThreadRecords: (threadId) => |
| 3719 | Effect.succeed( |
| 3720 | threadId === parentThreadId |
| 3721 | ? parentProjection(delegated ? [task] : [], parentModelSelection) |
| 3722 | : childProjection, |
| 3723 | ), |
| 3724 | dispatch: (command) => |
| 3725 | Ref.update(dispatched, (commands) => [...commands, command]).pipe( |
| 3726 | Effect.andThen( |
| 3727 | Effect.sync(() => { |
| 3728 | delegated = true; |
| 3729 | }), |
| 3730 | ), |
| 3731 | Effect.as({ |
| 3732 | sequence: 1, |
| 3733 | storedEvents: [ |
| 3734 | { |
| 3735 | sequence: 1, |
| 3736 | commandId: null, |
| 3737 | event: { type: "subagent.updated", payload: task }, |
| 3738 | }, |
| 3739 | ], |
| 3740 | } as never), |
| 3741 | ), |
| 3742 | }), |
| 3743 | ServerSettings.layerTest(), |
| 3744 | providerRegistryLayer([ |
| 3745 | providerSnapshot({ |
| 3746 | instanceId: codexInstanceId, |
| 3747 | driver, |
| 3748 | model: "gpt-5.4", |
| 3749 | enabled: testCase.inheritedEnabled, |
| 3750 | }), |
| 3751 | providerSnapshot({ |
| 3752 | instanceId: codexAltInstanceId, |
| 3753 | driver: testCase.candidateDriver, |
| 3754 | model: "codex-alt-model", |
| 3755 | enabled: testCase.peerEnabled, |
| 3756 | }), |
| 3757 | ]), |
| 3758 | adapterRegistryLayer( |
| 3759 | testCase.name === "explicit-disabled-without-adapter" |
| 3760 | ? [codexAltInstanceId] |
| 3761 | : [codexInstanceId, codexAltInstanceId], |
| 3762 | ), |
| 3763 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 3764 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 3765 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 3766 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 3767 | ); |
| 3768 | |
| 3769 | yield* Effect.gen(function* () { |
| 3770 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 3771 | const target = |
| 3772 | testCase.name === "inherited-unavailable" |
| 3773 | ? undefined |
| 3774 | : testCase.explicit |
| 3775 | ? ({ |
| 3776 | providerInstanceId: |
| 3777 | testCase.selectedInstanceId === null |
| 3778 | ? codexInstanceId |
| 3779 | : testCase.selectedInstanceId, |
| 3780 | } as const) |
| 3781 | : ({ driverKind: testCase.candidateDriver } as const); |
| 3782 | if (testCase.selectedInstanceId === null) { |
| 3783 | const error = yield* service |
| 3784 | .delegateTask(scope, { |
| 3785 | task: "Summarize the diff.", |
| 3786 | target, |
| 3787 | mode: "async", |
| 3788 | clientRequestId: `delegate-select-${testCase.name}`, |
| 3789 | }) |
| 3790 | .pipe(Effect.flip); |
| 3791 | assert.equal(error.code, "provider_unavailable", testCase.name); |
| 3792 | if ( |
| 3793 | testCase.name === "explicit-unavailable" || |
| 3794 | testCase.name === "inherited-unavailable" || |
| 3795 | testCase.name === "explicit-disabled-without-adapter" |
| 3796 | ) { |
| 3797 | const expectedMessage = |
| 3798 | `Provider ${codexInstanceId} cannot run a child task: ` + |
| 3799 | (testCase.name === "explicit-disabled-without-adapter" |
| 3800 | ? "No V2 provider adapter is registered. " |
| 3801 | : "") + |
| 3802 | "Provider instance is disabled."; |
| 3803 | assert.equal(error.message, expectedMessage); |
| 3804 | const threadError = yield* service |
| 3805 | .createThreads(scope, { |
| 3806 | threads: [{ prompt: "Summarize the diff.", target }], |
| 3807 | clientRequestId: `disabled-threads-${testCase.name}`, |
| 3808 | }) |
| 3809 | .pipe(Effect.flip); |
| 3810 | assert.equal(threadError.code, "provider_unavailable"); |
| 3811 | assert.equal(threadError.message, expectedMessage); |
| 3812 | } |
| 3813 | if (testCase.name === "cross-driver-no-available-candidate") { |
| 3814 | assert.isTrue(error.message.includes("driver claudeAgent"), testCase.name); |
| 3815 | const threadError = yield* service |
| 3816 | .createThreads(scope, { |
| 3817 | threads: [{ prompt: "Summarize the diff.", target }], |
| 3818 | clientRequestId: `delegate-threads-${testCase.name}`, |
| 3819 | }) |
| 3820 | .pipe(Effect.flip); |
| 3821 | assert.equal( |
| 3822 | threadError.code, |
| 3823 | "provider_unavailable", |
| 3824 | `${testCase.name}-createThreads`, |
| 3825 | ); |
| 3826 | assert.isTrue( |
| 3827 | threadError.message.includes("driver claudeAgent"), |
| 3828 | `${testCase.name}-createThreads`, |
| 3829 | ); |
| 3830 | } |
| 3831 | assert.deepEqual(yield* Ref.get(dispatched), [], testCase.name); |
| 3832 | return; |
| 3833 | } |
| 3834 | const result = yield* service.delegateTask(scope, { |
| 3835 | task: "Summarize the diff.", |
| 3836 | target, |
| 3837 | mode: "async", |
| 3838 | clientRequestId: `delegate-select-${testCase.name}`, |
| 3839 | }); |
| 3840 | assert.equal(result.status, "running", testCase.name); |
| 3841 | const commands = yield* Ref.get(dispatched); |
| 3842 | assert.equal(commands.length, 1, testCase.name); |
| 3843 | const request = commands[0] as { |
| 3844 | type: string; |
| 3845 | modelSelection: { |
| 3846 | instanceId: string; |
| 3847 | model: string; |
| 3848 | options?: ReadonlyArray<{ id: string; value: unknown }>; |
| 3849 | }; |
| 3850 | }; |
| 3851 | assert.equal(request.type, "delegated_task.request", testCase.name); |
| 3852 | assert.equal( |
| 3853 | request.modelSelection.instanceId, |
| 3854 | testCase.selectedInstanceId, |
| 3855 | testCase.name, |
| 3856 | ); |
| 3857 | if (testCase.name === "healthy-inherited") { |
| 3858 | assert.deepEqual(request.modelSelection, parentModelSelection, testCase.name); |
| 3859 | } else { |
| 3860 | assert.equal(request.modelSelection.model, "codex-alt-model", testCase.name); |
| 3861 | } |
| 3862 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 3863 | } |
| 3864 | }), |
| 3865 | ); |
| 3866 | |
| 3867 | describe("scheduled tasks at modes above the caller's", () => { |
| 3868 | const projectId = ProjectId.make("project:scheduled"); |
| 3869 | const boundThreadId = ThreadId.make("thread:scheduled-bound"); |
| 3870 | const task = (overrides: Partial<ScheduledTask>): ScheduledTask => ({ |
| 3871 | id: ScheduledTaskId.make("scheduled-task:webhook"), |
| 3872 | title: "On push", |
| 3873 | prompt: "Do {{body.instruction}}", |
| 3874 | enabled: true, |
| 3875 | schedule: { type: "webhook", signature: null }, |
| 3876 | projectId, |
| 3877 | threadId: null, |
| 3878 | workspaceStrategy: { type: "root" }, |
| 3879 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, |
| 3880 | runtimeMode: "approval-required", |
| 3881 | interactionMode: "default", |
| 3882 | createdBy: "agent", |
| 3883 | creationSource: "mcp", |
| 3884 | createdAt: "2026-10-05T00:00:00.000Z", |
| 3885 | updatedAt: "2026-10-05T00:00:00.000Z", |
| 3886 | nextRunAt: null, |
| 3887 | lastRunAt: null, |
| 3888 | lastRunStatus: "never", |
| 3889 | lastRunError: null, |
| 3890 | runCount: 0, |
| 3891 | webhook: { |
| 3892 | path: "/hooks/scheduled-task/secret", |
| 3893 | url: "https://t3.example/hooks/secret", |
| 3894 | hasSecret: false, |
| 3895 | }, |
| 3896 | ...overrides, |
| 3897 | }); |
| 3898 | const supervisedClient: McpInvocationScope = { |
| 3899 | environmentId: EnvironmentId.make("environment:scheduled"), |
| 3900 | requestNamespace: "client:scheduled", |
| 3901 | thread: undefined, |
| 3902 | client: { |
| 3903 | sessionId: "scheduled", |
| 3904 | label: "Claude Code", |
| 3905 | access: "approval-required", |
| 3906 | }, |
| 3907 | capabilities: new Set(["orchestration"]), |
| 3908 | issuedAt: 1, |
| 3909 | }; |
| 3910 | const service = ( |
| 3911 | tasks: ReadonlyArray<ScheduledTask>, |
| 3912 | boundThread: OrchestrationV2ThreadShell | null, |
| 3913 | upserted: Ref.Ref<number>, |
| 3914 | saved: ScheduledTask = tasks[0]!, |
| 3915 | ) => |
| 3916 | OrchestratorMcpService.layer.pipe( |
| 3917 | Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), |
| 3918 | Layer.provide( |
| 3919 | Layer.mock(GitVcsDriver.GitVcsDriver)({ |
| 3920 | resolvePrimaryRemoteName: () => Effect.succeed("origin"), |
| 3921 | resolveDefaultBranchName: () => Effect.succeed("main"), |
| 3922 | resolveCommit: () => Effect.succeed({ commitSha: "abc123" }), |
| 3923 | }), |
| 3924 | ), |
| 3925 | Layer.provide( |
| 3926 | Layer.mergeAll( |
| 3927 | NodeServices.layer, |
| 3928 | NodeCrypto.layer, |
| 3929 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 3930 | getThreadShell: (threadId) => |
| 3931 | Effect.succeed(threadId === boundThreadId ? boundThread : null), |
| 3932 | }), |
| 3933 | ServerSettings.layerTest(), |
| 3934 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 3935 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 3936 | list: () => Effect.succeed([]), |
| 3937 | }), |
| 3938 | Layer.mock(ProjectService.ProjectService)({ |
| 3939 | getById: (id) => |
| 3940 | Effect.succeedSome({ |
| 3941 | id, |
| 3942 | workspaceRoot: "/repo/scheduled", |
| 3943 | defaultModelSelection: saved.modelSelection, |
| 3944 | } as Project), |
| 3945 | }), |
| 3946 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 3947 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 3948 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({ |
| 3949 | list: () => Effect.succeed({ tasks }), |
| 3950 | upsert: () => |
| 3951 | Ref.update(upserted, (count) => count + 1).pipe(Effect.as({ task: saved })), |
| 3952 | }), |
| 3953 | ), |
| 3954 | ), |
| 3955 | ); |
| 3956 | |
| 3957 | it.effect("lists a webhook task without its URL to a caller that may run it", () => |
| 3958 | Effect.gen(function* () { |
| 3959 | const upserted = yield* Ref.make(0); |
| 3960 | const listed = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 3961 | Effect.flatMap((mcp) => mcp.listScheduledTasks(supervisedClient, { projectId })), |
| 3962 | Effect.provide(service([task({})], null, upserted)), |
| 3963 | ); |
| 3964 | assert.deepEqual( |
| 3965 | listed.tasks.map((summary) => [summary.webhookUrl, summary.webhookSignature]), |
| 3966 | [[undefined, "none"]], |
| 3967 | ); |
| 3968 | }), |
| 3969 | ); |
| 3970 | |
| 3971 | it.effect("lists only the named task within the requested project", () => |
| 3972 | Effect.gen(function* () { |
| 3973 | const upserted = yield* Ref.make(0); |
| 3974 | const first = task({}); |
| 3975 | const second = task({ id: ScheduledTaskId.make("scheduled-task:second") }); |
| 3976 | const elsewhere = task({ |
| 3977 | id: ScheduledTaskId.make("scheduled-task:elsewhere"), |
| 3978 | projectId: ProjectId.make("project:elsewhere"), |
| 3979 | }); |
| 3980 | const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 3981 | Effect.provide(service([first, second, elsewhere], null, upserted)), |
| 3982 | ); |
| 3983 | const ids = (input: OrchestratorMcpListScheduledTasksInput) => |
| 3984 | mcp |
| 3985 | .listScheduledTasks(supervisedClient, input) |
| 3986 | .pipe(Effect.map(({ tasks }) => tasks.map((summary) => summary.scheduledTaskId))); |
| 3987 | assert.deepEqual(yield* ids({ scheduledTaskId: second.id }), [second.id]); |
| 3988 | assert.deepEqual(yield* ids({ projectId, scheduledTaskId: elsewhere.id }), []); |
| 3989 | }), |
| 3990 | ); |
| 3991 | |
| 3992 | it.effect("returns a webhook URL when creating a task, not when updating it", () => |
| 3993 | Effect.gen(function* () { |
| 3994 | const upserted = yield* Ref.make(0); |
| 3995 | const hook = task({}); |
| 3996 | const timer = task({ |
| 3997 | schedule: { type: "interval", everyMs: 3_600_000 }, |
| 3998 | webhook: undefined, |
| 3999 | }); |
| 4000 | const created = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4001 | Effect.flatMap((mcp) => |
| 4002 | mcp.scheduleTask(supervisedClient, { |
| 4003 | projectId, |
| 4004 | prompt: hook.prompt, |
| 4005 | schedule: { type: "webhook" }, |
| 4006 | }), |
| 4007 | ), |
| 4008 | Effect.provide(service([hook], null, upserted)), |
| 4009 | ); |
| 4010 | assert.equal(created.webhookUrl, "https://t3.example/hooks/secret"); |
| 4011 | const converted = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4012 | Effect.flatMap((mcp) => |
| 4013 | mcp.updateScheduledTask(supervisedClient, { |
| 4014 | scheduledTaskId: timer.id, |
| 4015 | schedule: { type: "webhook" }, |
| 4016 | }), |
| 4017 | ), |
| 4018 | Effect.provide(service([timer], null, upserted, hook)), |
| 4019 | ); |
| 4020 | assert.equal(converted.webhookUrl, undefined); |
| 4021 | }), |
| 4022 | ); |
| 4023 | |
| 4024 | it.effect("checks a bound task against its thread's current modes", () => |
| 4025 | Effect.gen(function* () { |
| 4026 | const upserted = yield* Ref.make(0); |
| 4027 | const bound = task({ threadId: boundThreadId }); |
| 4028 | const layer = service( |
| 4029 | [bound], |
| 4030 | liveThreadShell(boundThreadId, { runtimeMode: "full-access" }), |
| 4031 | upserted, |
| 4032 | ); |
| 4033 | const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4034 | Effect.provide(layer), |
| 4035 | ); |
| 4036 | const listed = yield* mcp.listScheduledTasks(supervisedClient, { projectId }); |
| 4037 | assert.equal(listed.tasks[0]?.webhookUrl, undefined); |
| 4038 | const error = yield* mcp |
| 4039 | .updateScheduledTask(supervisedClient, { |
| 4040 | scheduledTaskId: bound.id, |
| 4041 | prompt: "Something else", |
| 4042 | }) |
| 4043 | .pipe(Effect.flip); |
| 4044 | assert.equal(error.code, "runtime_mode_escalation_denied"); |
| 4045 | assert.equal(yield* Ref.get(upserted), 0); |
| 4046 | }), |
| 4047 | ); |
| 4048 | |
| 4049 | it.effect("reports a saved task even when its bound thread cannot be read", () => |
| 4050 | Effect.gen(function* () { |
| 4051 | const upserted = yield* Ref.make(0); |
| 4052 | const bound = task({ threadId: boundThreadId }); |
| 4053 | const lookups = yield* Ref.make(0); |
| 4054 | const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4055 | Effect.provide( |
| 4056 | layerOrchestratorService.pipe( |
| 4057 | Layer.provide( |
| 4058 | Layer.mergeAll( |
| 4059 | NodeServices.layer, |
| 4060 | NodeCrypto.layer, |
| 4061 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 4062 | getThreadShell: (threadId) => |
| 4063 | Ref.getAndUpdate(lookups, (count) => count + 1).pipe( |
| 4064 | Effect.flatMap((count) => |
| 4065 | count === 0 |
| 4066 | ? Effect.succeed( |
| 4067 | liveThreadShell(threadId, { runtimeMode: "approval-required" }), |
| 4068 | ) |
| 4069 | : Effect.fail(new OrchestratorProjectionError({ threadId })), |
| 4070 | ), |
| 4071 | ), |
| 4072 | }), |
| 4073 | ServerSettings.layerTest(), |
| 4074 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 4075 | getProviders: Effect.succeed([]), |
| 4076 | }), |
| 4077 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 4078 | list: () => Effect.succeed([]), |
| 4079 | }), |
| 4080 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 4081 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 4082 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 4083 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({ |
| 4084 | list: () => Effect.succeed({ tasks: [bound] }), |
| 4085 | upsert: () => |
| 4086 | Ref.update(upserted, (count) => count + 1).pipe(Effect.as({ task: bound })), |
| 4087 | }), |
| 4088 | ), |
| 4089 | ), |
| 4090 | ), |
| 4091 | ), |
| 4092 | ); |
| 4093 | const updated = yield* mcp.updateScheduledTask(supervisedClient, { |
| 4094 | scheduledTaskId: bound.id, |
| 4095 | prompt: "Something else", |
| 4096 | }); |
| 4097 | assert.equal(yield* Ref.get(upserted), 1); |
| 4098 | assert.equal(updated.scheduledTaskId, bound.id); |
| 4099 | assert.equal(updated.webhookUrl, undefined); |
| 4100 | }), |
| 4101 | ); |
| 4102 | }); |
| 4103 | |
| 4104 | describe("the base branch of an unbound scheduled task", () => { |
| 4105 | const projectId = ProjectId.make("project:scheduled-base"); |
| 4106 | const workspaceRoot = "/repo/scheduled-base"; |
| 4107 | const existing: ScheduledTask = { |
| 4108 | id: ScheduledTaskId.make("scheduled-task:base"), |
| 4109 | title: "Nightly", |
| 4110 | prompt: "Check the build", |
| 4111 | enabled: true, |
| 4112 | schedule: { type: "interval", everyMs: 3_600_000 }, |
| 4113 | projectId, |
| 4114 | threadId: null, |
| 4115 | workspaceStrategy: { type: "root" }, |
| 4116 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, |
| 4117 | runtimeMode: "approval-required", |
| 4118 | interactionMode: "default", |
| 4119 | createdBy: "agent", |
| 4120 | creationSource: "mcp", |
| 4121 | createdAt: "2026-10-05T00:00:00.000Z", |
| 4122 | updatedAt: "2026-10-05T00:00:00.000Z", |
| 4123 | nextRunAt: null, |
| 4124 | lastRunAt: null, |
| 4125 | lastRunStatus: "never", |
| 4126 | lastRunError: null, |
| 4127 | runCount: 0, |
| 4128 | }; |
| 4129 | const client: McpInvocationScope = { |
| 4130 | environmentId: EnvironmentId.make("environment:scheduled-base"), |
| 4131 | requestNamespace: "client:scheduled-base", |
| 4132 | thread: undefined, |
| 4133 | client: { |
| 4134 | sessionId: "scheduled-base", |
| 4135 | label: "Claude Code", |
| 4136 | access: "approval-required", |
| 4137 | }, |
| 4138 | capabilities: new Set(["orchestration"]), |
| 4139 | issuedAt: 1, |
| 4140 | }; |
| 4141 | const service = ( |
| 4142 | git: Partial<GitVcsDriver.GitVcsDriver["Service"]>, |
| 4143 | saved: Ref.Ref<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>, |
| 4144 | task: ScheduledTask = existing, |
| 4145 | inputs?: Ref.Ref<ReadonlyArray<ScheduledTaskUpsertInput>>, |
| 4146 | defaults: { |
| 4147 | readonly project: ScheduledTask["modelSelection"] | null; |
| 4148 | readonly environment?: ScheduledTask["modelSelection"]; |
| 4149 | } = { project: existing.modelSelection }, |
| 4150 | ) => |
| 4151 | OrchestratorMcpService.layer.pipe( |
| 4152 | Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), |
| 4153 | Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)(git)), |
| 4154 | Layer.provide( |
| 4155 | Layer.mergeAll( |
| 4156 | NodeServices.layer, |
| 4157 | NodeCrypto.layer, |
| 4158 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 4159 | getThreadShell: () => Effect.succeed(null), |
| 4160 | }), |
| 4161 | ServerSettings.layerTest( |
| 4162 | defaults.environment === undefined |
| 4163 | ? {} |
| 4164 | : { defaultModelSelection: defaults.environment }, |
| 4165 | ), |
| 4166 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 4167 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 4168 | list: () => Effect.succeed([]), |
| 4169 | }), |
| 4170 | Layer.mock(ProjectService.ProjectService)({ |
| 4171 | getById: () => |
| 4172 | Effect.succeedSome({ |
| 4173 | id: projectId, |
| 4174 | workspaceRoot, |
| 4175 | defaultModelSelection: defaults.project, |
| 4176 | } as never), |
| 4177 | }), |
| 4178 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 4179 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 4180 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({ |
| 4181 | list: () => Effect.succeed({ tasks: [task] }), |
| 4182 | upsert: (input) => |
| 4183 | Ref.update(saved, (strategies) => [...strategies, input.workspaceStrategy]).pipe( |
| 4184 | Effect.andThen( |
| 4185 | inputs === undefined |
| 4186 | ? Effect.void |
| 4187 | : Ref.update(inputs, (all) => [...all, input]), |
| 4188 | ), |
| 4189 | Effect.as({ task }), |
| 4190 | ), |
| 4191 | }), |
| 4192 | ), |
| 4193 | ), |
| 4194 | ); |
| 4195 | const masterRepository: Partial<GitVcsDriver.GitVcsDriver["Service"]> = { |
| 4196 | resolvePrimaryRemoteName: () => Effect.succeed("origin"), |
| 4197 | resolveDefaultBranchName: (cwd, remoteName) => |
| 4198 | Effect.succeed(cwd === workspaceRoot && remoteName === "origin" ? "master" : null), |
| 4199 | resolveCommit: () => Effect.succeed({ commitSha: "abc123" }), |
| 4200 | }; |
| 4201 | const schedule = { type: "interval", everyMs: 3_600_000 } as const; |
| 4202 | |
| 4203 | it.effect("starts from the project's default branch", () => |
| 4204 | Effect.gen(function* () { |
| 4205 | const saved = yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]); |
| 4206 | const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4207 | Effect.provide(service(masterRepository, saved)), |
| 4208 | ); |
| 4209 | yield* mcp.scheduleTask(client, { projectId, prompt: "Check the build", schedule }); |
| 4210 | assert.deepEqual(yield* Ref.get(saved), [ |
| 4211 | { type: "worktree", baseRef: "origin/master", startFromOrigin: true }, |
| 4212 | ]); |
| 4213 | }), |
| 4214 | ); |
| 4215 | |
| 4216 | it.effect("uses the environment's default model when the project inherits it", () => |
| 4217 | Effect.gen(function* () { |
| 4218 | const environmentDefault = { |
| 4219 | instanceId: ProviderInstanceId.make("claudeAgent"), |
| 4220 | model: "claude-opus-5-5", |
| 4221 | }; |
| 4222 | const inputs = yield* Ref.make<ReadonlyArray<ScheduledTaskUpsertInput>>([]); |
| 4223 | const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4224 | Effect.provide( |
| 4225 | service( |
| 4226 | masterRepository, |
| 4227 | yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]), |
| 4228 | existing, |
| 4229 | inputs, |
| 4230 | { project: null, environment: environmentDefault }, |
| 4231 | ), |
| 4232 | ), |
| 4233 | ); |
| 4234 | yield* mcp.scheduleTask(client, { projectId, prompt: "Check the build", schedule }); |
| 4235 | assert.deepEqual( |
| 4236 | (yield* Ref.get(inputs)).map((input) => input.modelSelection), |
| 4237 | [environmentDefault], |
| 4238 | ); |
| 4239 | }), |
| 4240 | ); |
| 4241 | |
| 4242 | it.effect.each([ |
| 4243 | { |
| 4244 | name: "drops an emoji the limit splits", |
| 4245 | prompt: `${"a".repeat(79)}😀 rest`, |
| 4246 | title: "a".repeat(79), |
| 4247 | }, |
| 4248 | { |
| 4249 | name: "keeps an emoji that ends at the limit", |
| 4250 | prompt: `${"a".repeat(78)}😀 rest`, |
| 4251 | title: `${"a".repeat(78)}😀`, |
| 4252 | }, |
| 4253 | ])("a prompt-derived title $name", ({ prompt, title }) => |
| 4254 | Effect.gen(function* () { |
| 4255 | const inputs = yield* Ref.make<ReadonlyArray<ScheduledTaskUpsertInput>>([]); |
| 4256 | const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4257 | Effect.provide( |
| 4258 | service( |
| 4259 | masterRepository, |
| 4260 | yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]), |
| 4261 | existing, |
| 4262 | inputs, |
| 4263 | ), |
| 4264 | ), |
| 4265 | ); |
| 4266 | yield* mcp.scheduleTask(client, { projectId, prompt, schedule }); |
| 4267 | assert.deepEqual( |
| 4268 | (yield* Ref.get(inputs)).map((input) => input.title), |
| 4269 | [title], |
| 4270 | ); |
| 4271 | }), |
| 4272 | ); |
| 4273 | |
| 4274 | it.effect("keeps one thread when fresh sessions are turned off before the first run", () => |
| 4275 | Effect.gen(function* () { |
| 4276 | const inputs = yield* Ref.make<ReadonlyArray<ScheduledTaskUpsertInput>>([]); |
| 4277 | const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4278 | Effect.provide( |
| 4279 | service( |
| 4280 | masterRepository, |
| 4281 | yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]), |
| 4282 | { ...existing, threadMode: "fresh_session" }, |
| 4283 | inputs, |
| 4284 | ), |
| 4285 | ), |
| 4286 | ); |
| 4287 | yield* mcp.updateScheduledTask(client, { |
| 4288 | scheduledTaskId: existing.id, |
| 4289 | freshSession: false, |
| 4290 | }); |
| 4291 | yield* mcp.updateScheduledTask(client, { |
| 4292 | scheduledTaskId: existing.id, |
| 4293 | bindToCurrentThread: false, |
| 4294 | }); |
| 4295 | assert.deepEqual( |
| 4296 | (yield* Ref.get(inputs)).map((input) => input.threadMode), |
| 4297 | ["continue", "new_thread"], |
| 4298 | ); |
| 4299 | }), |
| 4300 | ); |
| 4301 | |
| 4302 | it.effect( |
| 4303 | "refuses unbinding into fresh sessions in one call, which would keep the thread", |
| 4304 | () => |
| 4305 | Effect.gen(function* () { |
| 4306 | const inputs = yield* Ref.make<ReadonlyArray<ScheduledTaskUpsertInput>>([]); |
| 4307 | const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4308 | Effect.provide( |
| 4309 | service( |
| 4310 | masterRepository, |
| 4311 | yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]), |
| 4312 | { |
| 4313 | ...existing, |
| 4314 | threadId: ThreadId.make("thread:scheduled-base"), |
| 4315 | threadMode: "continue", |
| 4316 | }, |
| 4317 | inputs, |
| 4318 | ), |
| 4319 | ), |
| 4320 | ); |
| 4321 | const refused = yield* mcp |
| 4322 | .updateScheduledTask(client, { |
| 4323 | scheduledTaskId: existing.id, |
| 4324 | bindToCurrentThread: false, |
| 4325 | freshSession: true, |
| 4326 | }) |
| 4327 | .pipe(Effect.flip); |
| 4328 | assert.include(refused.message, "first unbind it"); |
| 4329 | assert.deepEqual(yield* Ref.get(inputs), []); |
| 4330 | }), |
| 4331 | ); |
| 4332 | |
| 4333 | it.effect("follows the default branch when a task is unbound from its thread", () => |
| 4334 | Effect.gen(function* () { |
| 4335 | const saved = yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]); |
| 4336 | const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4337 | Effect.provide( |
| 4338 | service(masterRepository, saved, { |
| 4339 | ...existing, |
| 4340 | threadId: ThreadId.make("thread:scheduled-base"), |
| 4341 | threadMode: "continue", |
| 4342 | }), |
| 4343 | ), |
| 4344 | ); |
| 4345 | yield* mcp.updateScheduledTask(client, { |
| 4346 | scheduledTaskId: existing.id, |
| 4347 | bindToCurrentThread: false, |
| 4348 | }); |
| 4349 | assert.deepEqual(yield* Ref.get(saved), [ |
| 4350 | { type: "worktree", baseRef: "origin/master", startFromOrigin: true }, |
| 4351 | ]); |
| 4352 | }), |
| 4353 | ); |
| 4354 | |
| 4355 | it.effect("keeps the saved workspace when an unbound task stays unbound", () => |
| 4356 | Effect.gen(function* () { |
| 4357 | const saved = yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]); |
| 4358 | const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4359 | Effect.provide(service(masterRepository, saved)), |
| 4360 | ); |
| 4361 | yield* mcp.updateScheduledTask(client, { |
| 4362 | scheduledTaskId: existing.id, |
| 4363 | bindToCurrentThread: false, |
| 4364 | }); |
| 4365 | assert.deepEqual(yield* Ref.get(saved), [{ type: "root" }]); |
| 4366 | }), |
| 4367 | ); |
| 4368 | |
| 4369 | it.effect.each([ |
| 4370 | { |
| 4371 | name: "no remote, only master", |
| 4372 | remote: null, |
| 4373 | remoteDefault: null, |
| 4374 | refs: ["refs/heads/master"], |
| 4375 | baseRef: "master", |
| 4376 | }, |
| 4377 | { |
| 4378 | name: "no remote, main and master", |
| 4379 | remote: null, |
| 4380 | remoteDefault: null, |
| 4381 | refs: ["refs/heads/master", "refs/heads/main"], |
| 4382 | baseRef: "main", |
| 4383 | }, |
| 4384 | { |
| 4385 | name: "no remote, neither main nor master", |
| 4386 | remote: null, |
| 4387 | remoteDefault: null, |
| 4388 | refs: ["refs/heads/develop"], |
| 4389 | baseRef: "main", |
| 4390 | }, |
| 4391 | { |
| 4392 | name: "no recorded HEAD, remote main and a stale local master", |
| 4393 | remote: "origin", |
| 4394 | remoteDefault: null, |
| 4395 | refs: ["refs/heads/master", "refs/remotes/origin/main"], |
| 4396 | baseRef: "origin/main", |
| 4397 | }, |
| 4398 | { |
| 4399 | name: "no recorded HEAD, master only on the remote", |
| 4400 | remote: "origin", |
| 4401 | remoteDefault: null, |
| 4402 | refs: ["refs/remotes/origin/master"], |
| 4403 | baseRef: "origin/master", |
| 4404 | }, |
| 4405 | { |
| 4406 | name: "no recorded HEAD, local main and master only on the remote", |
| 4407 | remote: "origin", |
| 4408 | remoteDefault: null, |
| 4409 | refs: ["refs/heads/main", "refs/remotes/origin/master"], |
| 4410 | baseRef: "origin/master", |
| 4411 | }, |
| 4412 | { |
| 4413 | name: "no recorded HEAD, nothing conventional on the remote, local main", |
| 4414 | remote: "origin", |
| 4415 | remoteDefault: null, |
| 4416 | refs: ["refs/heads/main", "refs/remotes/origin/develop"], |
| 4417 | baseRef: "main", |
| 4418 | }, |
| 4419 | { |
| 4420 | name: "a recorded HEAD whose branch is gone", |
| 4421 | remote: "origin", |
| 4422 | remoteDefault: "main", |
| 4423 | refs: ["refs/heads/main", "refs/remotes/origin/master"], |
| 4424 | baseRef: "origin/master", |
| 4425 | }, |
| 4426 | { |
| 4427 | name: "a remote not called origin", |
| 4428 | remote: "upstream", |
| 4429 | remoteDefault: "develop", |
| 4430 | refs: ["refs/remotes/upstream/develop"], |
| 4431 | baseRef: "upstream/develop", |
| 4432 | }, |
| 4433 | { |
| 4434 | name: "a remote not called origin, no recorded HEAD", |
| 4435 | remote: "upstream", |
| 4436 | remoteDefault: null, |
| 4437 | refs: ["refs/remotes/upstream/main"], |
| 4438 | baseRef: "upstream/main", |
| 4439 | }, |
| 4440 | ])("$name starts from $baseRef", ({ remote, remoteDefault, refs, baseRef }) => |
| 4441 | Effect.gen(function* () { |
| 4442 | const saved = yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]); |
| 4443 | const gitFailure = (cwd: string, detail: string) => |
| 4444 | new GitCommandError({ operation: "GitVcsDriver.test", command: "git", cwd, detail }); |
| 4445 | const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( |
| 4446 | Effect.provide( |
| 4447 | service( |
| 4448 | { |
| 4449 | resolvePrimaryRemoteName: (cwd) => |
| 4450 | remote === null |
| 4451 | ? Effect.fail(gitFailure(cwd, "No git remote is configured.")) |
| 4452 | : Effect.succeed(remote), |
| 4453 | resolveDefaultBranchName: () => Effect.succeed(remoteDefault), |
| 4454 | resolveCommit: ({ cwd, revision }) => |
| 4455 | refs.includes(revision) |
| 4456 | ? Effect.succeed({ commitSha: "abc123" }) |
| 4457 | : Effect.fail(gitFailure(cwd, "Needed a single revision")), |
| 4458 | }, |
| 4459 | saved, |
| 4460 | ), |
| 4461 | ), |
| 4462 | ); |
| 4463 | yield* mcp.scheduleTask(client, { projectId, prompt: "Check the build", schedule }); |
| 4464 | assert.deepEqual(yield* Ref.get(saved), [ |
| 4465 | { type: "worktree", baseRef, startFromOrigin: true }, |
| 4466 | ]); |
| 4467 | }), |
| 4468 | ); |
| 4469 | }); |
| 4470 | it.effect( |
| 4471 | "reports the child run's selection after a restart and the thread selection before launch", |
| 4472 | () => |
| 4473 | Effect.gen(function* () { |
| 4474 | const runSelection = { |
| 4475 | instanceId: ProviderInstanceId.make("claudeAgent-personal"), |
| 4476 | model: "claude-opus-4-6", |
| 4477 | options: [ |
| 4478 | { id: "effort", value: "max" }, |
| 4479 | { id: "fastMode", value: true }, |
| 4480 | ], |
| 4481 | } as const; |
| 4482 | const threadSelection = { |
| 4483 | instanceId: codexInstanceId, |
| 4484 | model: "gpt-5.4", |
| 4485 | options: [{ id: "reasoningEffort", value: "high" }], |
| 4486 | } as const; |
| 4487 | let hasRun = true; |
| 4488 | const task = { |
| 4489 | id: taskId, |
| 4490 | threadId: parentThreadId, |
| 4491 | origin: "app_owned", |
| 4492 | childThreadId, |
| 4493 | providerInstanceId: ProviderInstanceId.make("claudeAgent-work"), |
| 4494 | model: "claude-sonnet-4-6", |
| 4495 | status: "running", |
| 4496 | result: null, |
| 4497 | }; |
| 4498 | const dependencies = Layer.mergeAll( |
| 4499 | NodeServices.layer, |
| 4500 | NodeCrypto.layer, |
| 4501 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 4502 | getThreadRecords: (threadId) => |
| 4503 | Effect.succeed( |
| 4504 | threadId === parentThreadId |
| 4505 | ? parentProjection([task]) |
| 4506 | : ({ |
| 4507 | ...childProjection, |
| 4508 | thread: { ...childProjection.thread, modelSelection: threadSelection }, |
| 4509 | runs: hasRun |
| 4510 | ? [ |
| 4511 | { |
| 4512 | id: RunId.make("run:mcp-restarted-child"), |
| 4513 | ordinal: 1, |
| 4514 | status: "running", |
| 4515 | modelSelection: runSelection, |
| 4516 | activeAttemptId: "attempt:mcp-restarted-child", |
| 4517 | }, |
| 4518 | ] |
| 4519 | : [], |
| 4520 | // Claude ran the requested Opus on Sonnet. |
| 4521 | providerTurns: [ |
| 4522 | { |
| 4523 | runAttemptId: "attempt:mcp-restarted-child", |
| 4524 | ordinal: 1, |
| 4525 | model: "claude-sonnet-4-6", |
| 4526 | }, |
| 4527 | ], |
| 4528 | } as unknown as OrchestrationV2ThreadProjection), |
| 4529 | ), |
| 4530 | }), |
| 4531 | ServerSettings.layerTest(), |
| 4532 | providerRegistryLayer([]), |
| 4533 | adapterRegistryLayer([]), |
| 4534 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 4535 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 4536 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 4537 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 4538 | ); |
| 4539 | yield* Effect.gen(function* () { |
| 4540 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 4541 | for (const [selection, executedModel] of [ |
| 4542 | [runSelection, "claude-sonnet-4-6"], |
| 4543 | [threadSelection, null], |
| 4544 | ] as const) { |
| 4545 | const result = yield* service.taskStatus(scope, taskId); |
| 4546 | assert.equal(result.providerInstanceId, selection.instanceId); |
| 4547 | assert.equal(result.model, selection.model); |
| 4548 | assert.deepEqual(result.options, selection.options); |
| 4549 | assert.equal(result.executedModel, executedModel); |
| 4550 | hasRun = false; |
| 4551 | } |
| 4552 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); |
| 4553 | }), |
| 4554 | ); |
| 4555 | |
| 4556 | it.effect( |
| 4557 | "inherits delegated options, merges overrides, and resets on explicit clearing or a new target", |
| 4558 | () => |
| 4559 | Effect.gen(function* () { |
| 4560 | const peerId = ProviderInstanceId.make("codex-subscription-2"); |
| 4561 | const antigravityId = ProviderInstanceId.make("antigravity"); |
| 4562 | const driver = ProviderDriverKind.make("codex"); |
| 4563 | const inherited = { |
| 4564 | instanceId: codexInstanceId, |
| 4565 | model: "gpt-5.4", |
| 4566 | options: [ |
| 4567 | { id: "reasoningEffort", value: "high" }, |
| 4568 | { id: "serviceTier", value: "priority" }, |
| 4569 | ], |
| 4570 | } as const; |
| 4571 | const override = [{ id: "reasoningEffort", value: "max" }] as const; |
| 4572 | const cases = [ |
| 4573 | { |
| 4574 | name: "partial override", |
| 4575 | target: { options: override }, |
| 4576 | expected: { ...inherited, options: [...override, inherited.options[1]] }, |
| 4577 | }, |
| 4578 | { |
| 4579 | name: "clear with array", |
| 4580 | target: { options: [] }, |
| 4581 | expected: { ...inherited, options: [] }, |
| 4582 | }, |
| 4583 | { |
| 4584 | name: "clear with object", |
| 4585 | target: { options: {} }, |
| 4586 | expected: { ...inherited, options: [] }, |
| 4587 | }, |
| 4588 | { |
| 4589 | name: "same model by alias", |
| 4590 | target: { model: "GPT" }, |
| 4591 | expected: { ...inherited, model: "GPT" }, |
| 4592 | }, |
| 4593 | { |
| 4594 | name: "parent named the same model by alias", |
| 4595 | parent: { ...inherited, model: "gpt" }, |
| 4596 | target: { model: inherited.model }, |
| 4597 | expected: inherited, |
| 4598 | }, |
| 4599 | { |
| 4600 | name: "change model", |
| 4601 | target: { model: "other-model" }, |
| 4602 | expected: { instanceId: codexInstanceId, model: "other-model" }, |
| 4603 | }, |
| 4604 | { |
| 4605 | name: "change provider with override", |
| 4606 | target: { providerInstanceId: peerId, options: { reasoningEffort: "max" } }, |
| 4607 | expected: { instanceId: peerId, model: inherited.model, options: override }, |
| 4608 | }, |
| 4609 | { |
| 4610 | name: "Antigravity model with a thinking suffix", |
| 4611 | target: { providerInstanceId: antigravityId, model: "gemini-4-neon-high" }, |
| 4612 | expected: { |
| 4613 | instanceId: antigravityId, |
| 4614 | model: "gemini-4-neon", |
| 4615 | options: [{ id: "thought_level", value: "high" }], |
| 4616 | }, |
| 4617 | }, |
| 4618 | { |
| 4619 | name: "explicit Antigravity thinking overrides the suffix", |
| 4620 | target: { |
| 4621 | providerInstanceId: antigravityId, |
| 4622 | model: "gemini-4-neon-high", |
| 4623 | options: { thought_level: "medium" }, |
| 4624 | }, |
| 4625 | expected: { |
| 4626 | instanceId: antigravityId, |
| 4627 | model: "gemini-4-neon", |
| 4628 | options: [{ id: "thought_level", value: "medium" }], |
| 4629 | }, |
| 4630 | }, |
| 4631 | { |
| 4632 | name: "clear Antigravity suffix options", |
| 4633 | target: { providerInstanceId: antigravityId, model: "gemini-4-neon-high", options: {} }, |
| 4634 | expected: { instanceId: antigravityId, model: "gemini-4-neon", options: [] }, |
| 4635 | }, |
| 4636 | { |
| 4637 | name: "old Ultracode effort level", |
| 4638 | target: { model: "ultracode-model", options: { effort: "ultracode" } }, |
| 4639 | expected: { |
| 4640 | instanceId: codexInstanceId, |
| 4641 | model: "ultracode-model", |
| 4642 | options: [ |
| 4643 | { id: "effort", value: "xhigh" }, |
| 4644 | { id: "ultracode", value: true }, |
| 4645 | ], |
| 4646 | }, |
| 4647 | }, |
| 4648 | ] as const; |
| 4649 | for (const testCase of cases) { |
| 4650 | const commands: Array<unknown> = []; |
| 4651 | const task = { |
| 4652 | id: taskId, |
| 4653 | threadId: parentThreadId, |
| 4654 | origin: "app_owned", |
| 4655 | childThreadId, |
| 4656 | providerInstanceId: testCase.expected.instanceId, |
| 4657 | model: testCase.expected.model, |
| 4658 | status: "running", |
| 4659 | result: null, |
| 4660 | }; |
| 4661 | const dependencies = Layer.mergeAll( |
| 4662 | NodeServices.layer, |
| 4663 | NodeCrypto.layer, |
| 4664 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 4665 | hasReceipt: () => Effect.succeed(false), |
| 4666 | assertProviderInstanceEnabled: () => Effect.void, |
| 4667 | getThreadRecords: (threadId) => |
| 4668 | Effect.succeed( |
| 4669 | threadId === parentThreadId |
| 4670 | ? parentProjection( |
| 4671 | commands.length > 0 ? [task] : [], |
| 4672 | "parent" in testCase ? testCase.parent : inherited, |
| 4673 | ) |
| 4674 | : childProjection, |
| 4675 | ), |
| 4676 | dispatch: (command) => |
| 4677 | Effect.sync(() => { |
| 4678 | commands.push(command); |
| 4679 | return { |
| 4680 | sequence: 1, |
| 4681 | storedEvents: [{ event: { type: "subagent.updated", payload: task } }], |
| 4682 | } as never; |
| 4683 | }), |
| 4684 | }), |
| 4685 | ServerSettings.layerTest(), |
| 4686 | providerRegistryLayer([ |
| 4687 | { |
| 4688 | ...providerSnapshot({ |
| 4689 | instanceId: codexInstanceId, |
| 4690 | driver, |
| 4691 | model: inherited.model, |
| 4692 | }), |
| 4693 | models: [ |
| 4694 | ...[inherited.model, "other-model"].map((model) => ({ |
| 4695 | slug: model, |
| 4696 | name: model, |
| 4697 | isCustom: false, |
| 4698 | capabilities: null, |
| 4699 | ...(model === inherited.model ? { aliases: ["gpt"] } : {}), |
| 4700 | })), |
| 4701 | { |
| 4702 | slug: "ultracode-model", |
| 4703 | name: "ultracode-model", |
| 4704 | isCustom: false, |
| 4705 | capabilities: { |
| 4706 | optionDescriptors: [ |
| 4707 | { |
| 4708 | id: "effort", |
| 4709 | label: "Reasoning", |
| 4710 | type: "select", |
| 4711 | options: [ |
| 4712 | { id: "high", label: "High" }, |
| 4713 | { id: "xhigh", label: "Extra High" }, |
| 4714 | ], |
| 4715 | }, |
| 4716 | { id: "ultracode", label: "Ultracode", type: "boolean" }, |
| 4717 | ], |
| 4718 | }, |
| 4719 | }, |
| 4720 | ], |
| 4721 | }, |
| 4722 | providerSnapshot({ instanceId: peerId, driver, model: inherited.model }), |
| 4723 | { |
| 4724 | ...providerSnapshot({ |
| 4725 | instanceId: antigravityId, |
| 4726 | driver: ProviderDriverKind.make("antigravity"), |
| 4727 | }), |
| 4728 | models: [ |
| 4729 | { |
| 4730 | slug: "gemini-4-neon", |
| 4731 | name: "Gemini 4 Neon", |
| 4732 | isCustom: false, |
| 4733 | capabilities: { |
| 4734 | optionDescriptors: [ |
| 4735 | { |
| 4736 | id: "thought_level", |
| 4737 | role: "reasoning", |
| 4738 | label: "Thinking", |
| 4739 | type: "select", |
| 4740 | options: [ |
| 4741 | { id: "medium", label: "Medium" }, |
| 4742 | { id: "high", label: "High" }, |
| 4743 | ], |
| 4744 | }, |
| 4745 | ], |
| 4746 | }, |
| 4747 | }, |
| 4748 | ], |
| 4749 | }, |
| 4750 | ]), |
| 4751 | adapterRegistryLayer([codexInstanceId, peerId, antigravityId]), |
| 4752 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 4753 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 4754 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 4755 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 4756 | ); |
| 4757 | yield* Effect.gen(function* () { |
| 4758 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 4759 | const capabilities = yield* service.capabilities(scope); |
| 4760 | assert.deepEqual(capabilities.inheritedOptions, inherited.options); |
| 4761 | yield* service.delegateTask(scope, { |
| 4762 | task: "Review the change.", |
| 4763 | target: yield* decodeTarget(testCase.target), |
| 4764 | mode: "async", |
| 4765 | clientRequestId: testCase.name, |
| 4766 | }); |
| 4767 | assert.deepEqual( |
| 4768 | (commands[0] as { modelSelection: unknown }).modelSelection, |
| 4769 | testCase.expected, |
| 4770 | testCase.name, |
| 4771 | ); |
| 4772 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); |
| 4773 | } |
| 4774 | }), |
| 4775 | ); |
| 4776 | |
| 4777 | it.effect("accepts the inherited options it reports back as a delegate target", () => |
| 4778 | Effect.gen(function* () { |
| 4779 | // t3_thread_launch keeps a model selection as given, so a thread can hold an option its model lacks. |
| 4780 | const inherited = { |
| 4781 | instanceId: codexInstanceId, |
| 4782 | model: "gpt-5.4", |
| 4783 | options: [ |
| 4784 | { id: "reasoningEffort", value: "low" }, |
| 4785 | { id: "fastMode", value: false }, |
| 4786 | ], |
| 4787 | } as const; |
| 4788 | const commands: Array<{ readonly modelSelection?: unknown }> = []; |
| 4789 | const task = { |
| 4790 | id: taskId, |
| 4791 | threadId: parentThreadId, |
| 4792 | origin: "app_owned", |
| 4793 | childThreadId, |
| 4794 | providerInstanceId: codexInstanceId, |
| 4795 | model: inherited.model, |
| 4796 | status: "running", |
| 4797 | result: null, |
| 4798 | }; |
| 4799 | const dependencies = Layer.mergeAll( |
| 4800 | NodeServices.layer, |
| 4801 | NodeCrypto.layer, |
| 4802 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 4803 | hasReceipt: () => Effect.succeed(false), |
| 4804 | assertProviderInstanceEnabled: () => Effect.void, |
| 4805 | getThreadRecords: (threadId) => |
| 4806 | Effect.succeed( |
| 4807 | threadId === parentThreadId |
| 4808 | ? parentProjection(commands.length > 0 ? [task] : [], inherited) |
| 4809 | : childProjection, |
| 4810 | ), |
| 4811 | dispatch: (command) => |
| 4812 | Effect.sync(() => { |
| 4813 | commands.push(command as { readonly modelSelection?: unknown }); |
| 4814 | return { |
| 4815 | sequence: 1, |
| 4816 | storedEvents: [{ event: { type: "subagent.updated", payload: task } }], |
| 4817 | } as never; |
| 4818 | }), |
| 4819 | }), |
| 4820 | ServerSettings.layerTest(), |
| 4821 | providerRegistryLayer([ |
| 4822 | { |
| 4823 | ...providerSnapshot({ |
| 4824 | instanceId: codexInstanceId, |
| 4825 | driver: ProviderDriverKind.make("codex"), |
| 4826 | }), |
| 4827 | models: [ |
| 4828 | { |
| 4829 | slug: inherited.model, |
| 4830 | name: inherited.model, |
| 4831 | isCustom: false, |
| 4832 | capabilities: { |
| 4833 | optionDescriptors: [ |
| 4834 | { |
| 4835 | id: "reasoningEffort", |
| 4836 | label: "Reasoning", |
| 4837 | type: "select", |
| 4838 | options: [{ id: "low", label: "Low" }], |
| 4839 | }, |
| 4840 | ], |
| 4841 | }, |
| 4842 | }, |
| 4843 | ], |
| 4844 | }, |
| 4845 | ]), |
| 4846 | adapterRegistryLayer([codexInstanceId]), |
| 4847 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 4848 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 4849 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 4850 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 4851 | ); |
| 4852 | yield* Effect.gen(function* () { |
| 4853 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 4854 | const { inheritedOptions } = yield* service.capabilities(scope); |
| 4855 | yield* service.delegateTask(scope, { |
| 4856 | task: "Review the change.", |
| 4857 | target: yield* decodeTarget({ options: inheritedOptions }), |
| 4858 | mode: "async", |
| 4859 | }); |
| 4860 | assert.deepEqual(commands[0]?.modelSelection, { |
| 4861 | ...inherited, |
| 4862 | options: [inherited.options[0]], |
| 4863 | }); |
| 4864 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); |
| 4865 | }), |
| 4866 | ); |
| 4867 | |
| 4868 | it.effect("validates options against the model a target names by alias", () => |
| 4869 | Effect.gen(function* () { |
| 4870 | const dependencies = Layer.mergeAll( |
| 4871 | NodeServices.layer, |
| 4872 | NodeCrypto.layer, |
| 4873 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 4874 | hasReceipt: () => Effect.succeed(false), |
| 4875 | assertProviderInstanceEnabled: () => Effect.void, |
| 4876 | getThreadRecords: (threadId) => |
| 4877 | Effect.succeed(threadId === parentThreadId ? parentProjection([]) : childProjection), |
| 4878 | dispatch: () => Effect.die("an invalid target must not dispatch"), |
| 4879 | }), |
| 4880 | ServerSettings.layerTest(), |
| 4881 | providerRegistryLayer([ |
| 4882 | { |
| 4883 | ...providerSnapshot({ |
| 4884 | instanceId: codexInstanceId, |
| 4885 | driver: ProviderDriverKind.make("codex"), |
| 4886 | }), |
| 4887 | models: [ |
| 4888 | { |
| 4889 | slug: "gpt-5.4", |
| 4890 | name: "gpt-5.4", |
| 4891 | aliases: ["gpt"], |
| 4892 | isCustom: false, |
| 4893 | capabilities: { |
| 4894 | optionDescriptors: [{ id: "fastMode", label: "Fast", type: "boolean" }], |
| 4895 | }, |
| 4896 | }, |
| 4897 | ], |
| 4898 | }, |
| 4899 | ]), |
| 4900 | adapterRegistryLayer([codexInstanceId]), |
| 4901 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 4902 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 4903 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 4904 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 4905 | ); |
| 4906 | const error = yield* Effect.gen(function* () { |
| 4907 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 4908 | return yield* service |
| 4909 | .delegateTask(scope, { |
| 4910 | task: "Review the change.", |
| 4911 | target: yield* decodeTarget({ model: "GPT", options: { bogus: "x" } }), |
| 4912 | mode: "async", |
| 4913 | }) |
| 4914 | .pipe(Effect.flip); |
| 4915 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); |
| 4916 | assert.equal(error.code, "invalid_request"); |
| 4917 | assert.include(error.message, "Unknown option bogus"); |
| 4918 | }), |
| 4919 | ); |
| 4920 | |
| 4921 | it.effect( |
| 4922 | "reports the dispatch cause instead of the generic wrapper when interrupting fails", |
| 4923 | () => |
| 4924 | Effect.gen(function* () { |
| 4925 | const layerDependencies = Layer.mergeAll( |
| 4926 | NodeServices.layer, |
| 4927 | NodeCrypto.layer, |
| 4928 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 4929 | getThreadRecords: () => Effect.succeed(parentProjection([])), |
| 4930 | interruptThread: (input) => |
| 4931 | Effect.fail( |
| 4932 | new OrchestratorDispatchError({ |
| 4933 | commandId: input.commandId, |
| 4934 | commandType: "thread.interrupt", |
| 4935 | cause: new Error("refused by the orchestrator"), |
| 4936 | }) as never, |
| 4937 | ), |
| 4938 | }), |
| 4939 | ServerSettings.layerTest(), |
| 4940 | Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), |
| 4941 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 4942 | list: () => Effect.succeed([]), |
| 4943 | }), |
| 4944 | Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), |
| 4945 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 4946 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 4947 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 4948 | ); |
| 4949 | const error = yield* Effect.gen(function* () { |
| 4950 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 4951 | return yield* service |
| 4952 | .interruptThread(scope, { |
| 4953 | threadId: parentThreadId, |
| 4954 | clientRequestId: "interrupt-dispatch-cause", |
| 4955 | }) |
| 4956 | .pipe(Effect.flip); |
| 4957 | }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); |
| 4958 | assert.equal(error.code, "orchestration_error"); |
| 4959 | assert.equal( |
| 4960 | error.message, |
| 4961 | `Unable to interrupt thread ${parentThreadId}: refused by the orchestrator`, |
| 4962 | ); |
| 4963 | }), |
| 4964 | ); |
| 4965 | |
| 4966 | describe("resolveRuntimeMode", () => { |
| 4967 | const muse = { |
| 4968 | modelSelection: { instanceId: ProviderInstanceId.make("muse"), model: "muse-model" }, |
| 4969 | supportedRuntimeModes: ["approval-required", "full-access"] as const, |
| 4970 | }; |
| 4971 | |
| 4972 | it.effect("refuses an explicit mode the target provider does not offer", () => |
| 4973 | Effect.gen(function* () { |
| 4974 | const error = yield* resolveRuntimeMode("full-access", "auto-accept-edits", muse).pipe( |
| 4975 | Effect.flip, |
| 4976 | ); |
| 4977 | assert.equal(error.code, "invalid_request"); |
| 4978 | assert.include(error.message, "approval-required, full-access"); |
| 4979 | }), |
| 4980 | ); |
| 4981 | |
| 4982 | it.effect("steps an inherited mode down to the broadest one the provider offers", () => |
| 4983 | Effect.gen(function* () { |
| 4984 | assert.equal(yield* resolveRuntimeMode("full-access", "inherit", muse), "full-access"); |
| 4985 | assert.equal(yield* resolveRuntimeMode("auto", undefined, muse), "approval-required"); |
| 4986 | }), |
| 4987 | ); |
| 4988 | }); |
| 4989 | }); |
| 4990 | |
| 4991 | describe("OrchestratorMcpService thread lookup", () => { |
| 4992 | const bareId = ThreadId.make("5d0b4a3e-8c1f-4a52-9d37-2f6c7e1b9a04"); |
| 4993 | const launched = liveThreadShell(ThreadId.make(`mcp:${bareId}`)); |
| 4994 | const deletedLaunched = { ...launched, deletedAt: DateTime.makeUnsafe("2026-10-05T00:00:00Z") }; |
| 4995 | const client: McpInvocationScope = { |
| 4996 | environmentId: EnvironmentId.make("environment:thread-lookup"), |
| 4997 | requestNamespace: "client:thread-lookup", |
| 4998 | thread: undefined, |
| 4999 | client: { sessionId: "thread-lookup", label: "Claude Code", access: "full-access" }, |
| 5000 | capabilities: new Set(["orchestration"]), |
Showing first 5,000 of 5,694 lines.
View raw