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 { |
| 2 | EnvironmentId, |
| 3 | NodeId, |
| 4 | type OrchestratorMcpThreadReadResult, |
| 5 | type OrchestrationV2ThreadProjection, |
| 6 | type OrchestrationV2ThreadShell, |
| 7 | ProjectId, |
| 8 | ProviderDriverKind, |
| 9 | ProviderInstanceId, |
| 10 | RunAttemptId, |
| 11 | RunId, |
| 12 | ScheduledTaskId, |
| 13 | SECRET_REQUEST_UNSAVED_NOTE, |
| 14 | ThreadId, |
| 15 | TurnItemId, |
| 16 | } from "@t3tools/contracts"; |
| 17 | import * as DateTime from "effect/DateTime"; |
| 18 | import * as Effect from "effect/Effect"; |
| 19 | import * as Fiber from "effect/Fiber"; |
| 20 | import * as Layer from "effect/Layer"; |
| 21 | import * as Metric from "effect/Metric"; |
| 22 | import * as TestClock from "effect/testing/TestClock"; |
| 23 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 24 | import { expect, it } from "vite-plus/test"; |
| 25 | |
| 26 | import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; |
| 27 | import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; |
| 28 | import * as ProjectService from "../project/ProjectService.ts"; |
| 29 | import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; |
| 30 | import * as ServerSettings from "../serverSettings.ts"; |
| 31 | import * as SecretRequests from "../secrets/SecretRequests.ts"; |
| 32 | import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; |
| 33 | import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; |
| 34 | import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; |
| 35 | import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; |
| 36 | import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; |
| 37 | import type * as McpInvocationContext from "./McpInvocationContext.ts"; |
| 38 | import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; |
| 39 | import { liveThreadShell } from "./McpToolAccess.testkit.ts"; |
| 40 | |
| 41 | const layerOrchestratorService = OrchestratorMcpService.layer.pipe( |
| 42 | Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), |
| 43 | Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), |
| 44 | ); |
| 45 | |
| 46 | const environmentId = EnvironmentId.make("environment-mcp-orchestrator-detail"); |
| 47 | const projectId = ProjectId.make("project-mcp-orchestrator-detail"); |
| 48 | const parentThreadId = ThreadId.make("thread-mcp-orchestrator-parent"); |
| 49 | const childThreadId = ThreadId.make("thread-mcp-orchestrator-child"); |
| 50 | const activeRunId = RunId.make("run-mcp-active"); |
| 51 | const cancelledRunId = RunId.make("run-mcp-cancelled"); |
| 52 | const childRunId = RunId.make("run-mcp-child"); |
| 53 | const taskId = NodeId.make("node-mcp-task-1"); |
| 54 | const now = DateTime.makeUnsafe("2026-08-04T12:00:00.000Z"); |
| 55 | const codexDriver = ProviderDriverKind.make("codex"); |
| 56 | |
| 57 | const customCodexInstanceId = ProviderInstanceId.make("codex-custom-workspace"); |
| 58 | const parentInstanceId = ProviderInstanceId.make("codex"); |
| 59 | |
| 60 | const makeScope = (): McpInvocationContext.McpInvocationScope => ({ |
| 61 | environmentId, |
| 62 | requestNamespace: "provider-session-mcp-orchestrator-detail", |
| 63 | thread: { |
| 64 | threadId: parentThreadId, |
| 65 | providerSessionId: "provider-session-mcp-orchestrator-detail", |
| 66 | providerInstanceId: parentInstanceId, |
| 67 | }, |
| 68 | client: undefined, |
| 69 | capabilities: new Set(["orchestration"]), |
| 70 | issuedAt: 1, |
| 71 | }); |
| 72 | |
| 73 | function baseThread(input: { |
| 74 | readonly threadId: ThreadId; |
| 75 | readonly title: string; |
| 76 | readonly instanceId: ProviderInstanceId; |
| 77 | readonly model: string; |
| 78 | }) { |
| 79 | return { |
| 80 | id: input.threadId, |
| 81 | projectId, |
| 82 | title: input.title, |
| 83 | createdBy: "user" as const, |
| 84 | creationSource: "mcp" as const, |
| 85 | modelSelection: { |
| 86 | instanceId: input.instanceId, |
| 87 | model: input.model, |
| 88 | }, |
| 89 | runtimeMode: "full-access" as const, |
| 90 | interactionMode: "default" as const, |
| 91 | branch: null, |
| 92 | worktreePath: null, |
| 93 | lineage: { |
| 94 | parentThreadId: null, |
| 95 | relationshipToParent: null, |
| 96 | rootThreadId: input.threadId, |
| 97 | }, |
| 98 | archivedAt: null, |
| 99 | deletedAt: null, |
| 100 | providerInstanceId: input.instanceId, |
| 101 | createdAt: now, |
| 102 | updatedAt: now, |
| 103 | }; |
| 104 | } |
| 105 | |
| 106 | function makeRun(input: { |
| 107 | readonly id: RunId; |
| 108 | readonly ordinal: number; |
| 109 | readonly status: "running" | "waiting" | "cancelled" | "queued" | "completed" | "failed"; |
| 110 | readonly instanceId?: ProviderInstanceId; |
| 111 | }) { |
| 112 | return { |
| 113 | id: input.id, |
| 114 | ordinal: input.ordinal, |
| 115 | status: input.status, |
| 116 | modelSelection: { |
| 117 | instanceId: input.instanceId ?? parentInstanceId, |
| 118 | model: "gpt-5.4", |
| 119 | }, |
| 120 | providerInstanceId: input.instanceId ?? parentInstanceId, |
| 121 | requestedAt: now, |
| 122 | startedAt: input.status === "cancelled" || input.status === "queued" ? null : now, |
| 123 | completedAt: input.status === "cancelled" || input.status === "completed" ? now : null, |
| 124 | }; |
| 125 | } |
| 126 | |
| 127 | it("readThread preserves caller access errors and prefers activity-run status over a newer cancelled queued run", async () => { |
| 128 | let callerUnavailable = false; |
| 129 | let pendingBackgroundTasks: OrchestrationV2ThreadShell["pendingBackgroundTasks"] = [ |
| 130 | { |
| 131 | taskId: "task-subagent", |
| 132 | kind: "subagent", |
| 133 | parentTaskId: "task-parent", |
| 134 | providerInstanceId: parentInstanceId, |
| 135 | childThreadId, |
| 136 | }, |
| 137 | ]; |
| 138 | const pullRequestLink = (number: number, state: "open" | "merged", watched: boolean) => ({ |
| 139 | host: "github.com", |
| 140 | repository: "acme/web", |
| 141 | number, |
| 142 | url: `https://github.com/acme/web/pull/${number}`, |
| 143 | source: "agent", |
| 144 | linkedAt: `2026-08-04T11:0${number}:00.000Z`, |
| 145 | snapshot: { state }, |
| 146 | stack: null, |
| 147 | ...(watched |
| 148 | ? { |
| 149 | watch: { |
| 150 | startedAt: "2026-08-04T11:30:00.000Z", |
| 151 | headSha: null, |
| 152 | failedChecks: [], |
| 153 | passed: false, |
| 154 | passedChecks: [], |
| 155 | remarksThrough: "2026-08-04T11:30:00.000Z", |
| 156 | remarkIds: [], |
| 157 | conflicting: false, |
| 158 | wakes: 0, |
| 159 | }, |
| 160 | } |
| 161 | : {}), |
| 162 | }); |
| 163 | const projection = { |
| 164 | thread: { |
| 165 | ...baseThread({ |
| 166 | threadId: parentThreadId, |
| 167 | title: "Parent", |
| 168 | instanceId: parentInstanceId, |
| 169 | model: "gpt-5.4", |
| 170 | }), |
| 171 | pullRequests: [ |
| 172 | pullRequestLink(1, "merged", false), |
| 173 | pullRequestLink(2, "open", true), |
| 174 | ...[3, 4, 5, 6, 7, 8].map((number) => pullRequestLink(number, "open", false)), |
| 175 | ], |
| 176 | }, |
| 177 | runs: [ |
| 178 | makeRun({ id: activeRunId, ordinal: 1, status: "running" }), |
| 179 | makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }), |
| 180 | ], |
| 181 | visibleTurnItems: [], |
| 182 | providerTurns: [], |
| 183 | runtimeRequests: [], |
| 184 | messages: [], |
| 185 | contextTransfers: [], |
| 186 | subagents: [], |
| 187 | updatedAt: now, |
| 188 | } as unknown as OrchestrationV2ThreadProjection; |
| 189 | |
| 190 | const layer = layerOrchestratorService.pipe( |
| 191 | Layer.provide( |
| 192 | Layer.mergeAll( |
| 193 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 194 | getTimelinePage: () => |
| 195 | Effect.succeed({ items: [], totalItems: 0, hasMore: false, hasEarlier: false }), |
| 196 | getThreadRecords: (threadId) => |
| 197 | callerUnavailable |
| 198 | ? Effect.fail( |
| 199 | new Orchestrator.OrchestratorProjectionError({ |
| 200 | threadId, |
| 201 | cause: "Caller unavailable", |
| 202 | }), |
| 203 | ) |
| 204 | : threadId === parentThreadId |
| 205 | ? Effect.succeed(projection) |
| 206 | : Effect.die(`unexpected thread ${threadId}`), |
| 207 | getThreadShell: (threadId) => |
| 208 | callerUnavailable |
| 209 | ? Effect.die("A failed caller read must not reach the target") |
| 210 | : Effect.succeed( |
| 211 | threadId === parentThreadId |
| 212 | ? ({ |
| 213 | ...projection.thread, |
| 214 | pinnedAt: now, |
| 215 | blockedOnThreadWait: true, |
| 216 | pendingBackgroundTasks, |
| 217 | } as unknown as OrchestrationV2ThreadShell) |
| 218 | : null, |
| 219 | ), |
| 220 | getProjectThreadRecords: (input) => |
| 221 | input.threadId === parentThreadId |
| 222 | ? Effect.succeed(projection) |
| 223 | : Effect.die(`unexpected thread ${input.threadId}`), |
| 224 | getRunCount: () => Effect.succeed(projection.runs.length), |
| 225 | } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>), |
| 226 | ServerSettings.layerTest(), |
| 227 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 228 | getProviders: Effect.succeed([]), |
| 229 | } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>), |
| 230 | Layer.mock(ProjectService.ProjectService)({}), |
| 231 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 232 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 233 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({ |
| 234 | list: () => Effect.succeed({ tasks: [] }), |
| 235 | } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>), |
| 236 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 237 | list: () => Effect.succeed([]), |
| 238 | } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>), |
| 239 | NodeCrypto.layer, |
| 240 | ), |
| 241 | ), |
| 242 | ); |
| 243 | |
| 244 | await Effect.gen(function* () { |
| 245 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 246 | const result = yield* service.readThread(makeScope(), { threadId: parentThreadId }); |
| 247 | expect(result.thread.status).toBe("running"); |
| 248 | expect(result.thread.latestRunId).toBe(cancelledRunId); |
| 249 | expect(result.thread.activeRunId).toBe(activeRunId); |
| 250 | expect(result.thread.pinned).toBe(true); |
| 251 | expect(result.thread.blockedOnThreadWait).toBe(true); |
| 252 | expect(result.thread.pendingBackgroundTasks).toEqual([ |
| 253 | { taskId: "task-subagent", kind: "subagent", childThreadId }, |
| 254 | ]); |
| 255 | // Every page read must not repeat each linked PR, and an open PR shows whether it is watched. |
| 256 | // A thread with many open PRs previews a few, watched first, then newest. |
| 257 | const listed = result.thread.pullRequests ?? []; |
| 258 | expect(listed.map((link) => link.number)).toEqual([2, 8, 7, 6, 5]); |
| 259 | expect(result.thread.openPullRequestCount).toBe(7); |
| 260 | expect(listed.find((link) => link.number === 2)).toMatchObject({ |
| 261 | watching: true, |
| 262 | watchStartedAt: "2026-08-04T11:30:00.000Z", |
| 263 | }); |
| 264 | const laterPage = yield* service.readThread(makeScope(), { |
| 265 | threadId: parentThreadId, |
| 266 | afterPosition: 0, |
| 267 | }); |
| 268 | expect(laterPage.thread.pullRequests).toBeUndefined(); |
| 269 | expect(laterPage.thread.pullRequestCount).toBe(8); |
| 270 | |
| 271 | Object.assign(projection, { |
| 272 | runs: [makeRun({ id: activeRunId, ordinal: 1, status: "completed" })], |
| 273 | }); |
| 274 | const awaiting = yield* service.readThread(makeScope(), { threadId: parentThreadId }); |
| 275 | expect(awaiting.thread.status).toBe("waiting"); |
| 276 | |
| 277 | Object.assign(projection, { |
| 278 | runs: [makeRun({ id: activeRunId, ordinal: 1, status: "failed" })], |
| 279 | }); |
| 280 | const failed = yield* service.readThread(makeScope(), { threadId: parentThreadId }); |
| 281 | expect(failed.thread.status).toBe("failed"); |
| 282 | |
| 283 | Object.assign(projection, { |
| 284 | runs: [makeRun({ id: activeRunId, ordinal: 1, status: "completed" })], |
| 285 | }); |
| 286 | // An unawaited command (a dev server) does not hold the thread once its turn ends. |
| 287 | pendingBackgroundTasks = [{ taskId: "dev-server", kind: "command" }]; |
| 288 | const released = yield* service.readThread(makeScope(), { threadId: parentThreadId }); |
| 289 | expect(released.thread.status).toBe("completed"); |
| 290 | |
| 291 | callerUnavailable = true; |
| 292 | const denied = yield* service |
| 293 | .readThread({ ...makeScope(), capabilities: new Set() }, { threadId: parentThreadId }) |
| 294 | .pipe(Effect.flip); |
| 295 | expect(denied.code).toBe("capability_denied"); |
| 296 | const missingCaller = yield* service |
| 297 | .readThread(makeScope(), { threadId: parentThreadId }) |
| 298 | .pipe(Effect.flip); |
| 299 | expect(missingCaller.code).toBe("orchestration_error"); |
| 300 | expect(missingCaller.message).toContain(`Unable to read thread ${parentThreadId}:`); |
| 301 | }).pipe(Effect.provide(layer), Effect.runPromise); |
| 302 | }); |
| 303 | |
| 304 | it("readThread pages cut-off text without splitting an emoji across pages", async () => { |
| 305 | const text = "a😀bc"; |
| 306 | const itemId = TurnItemId.make("turn-item-mcp-reasoning"); |
| 307 | const projection = { |
| 308 | thread: baseThread({ |
| 309 | threadId: parentThreadId, |
| 310 | title: "Parent", |
| 311 | instanceId: parentInstanceId, |
| 312 | model: "gpt-5.4", |
| 313 | }), |
| 314 | runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })], |
| 315 | visibleTurnItems: [], |
| 316 | providerTurns: [], |
| 317 | runtimeRequests: [], |
| 318 | messages: [], |
| 319 | contextTransfers: [], |
| 320 | subagents: [], |
| 321 | updatedAt: now, |
| 322 | } as unknown as OrchestrationV2ThreadProjection; |
| 323 | const row = { |
| 324 | position: 0, |
| 325 | visibility: "visible", |
| 326 | sourceThreadId: parentThreadId, |
| 327 | sourceItemId: itemId, |
| 328 | item: { |
| 329 | type: "reasoning", |
| 330 | runId: activeRunId, |
| 331 | status: "completed", |
| 332 | title: null, |
| 333 | text, |
| 334 | updatedAt: now, |
| 335 | }, |
| 336 | }; |
| 337 | const rows = [ |
| 338 | row, |
| 339 | ...Array.from({ length: 11 }, (_, index) => ({ |
| 340 | ...row, |
| 341 | position: index + 1, |
| 342 | sourceItemId: TurnItemId.make(`turn-item-mcp-${index}`), |
| 343 | item: { ...row.item, text: "x".repeat(600) }, |
| 344 | })), |
| 345 | ]; |
| 346 | |
| 347 | const layer = layerOrchestratorService.pipe( |
| 348 | Layer.provide( |
| 349 | Layer.mergeAll( |
| 350 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 351 | getTimelinePage: (_threadId, options) => { |
| 352 | const remaining = rows.filter( |
| 353 | (candidate) => |
| 354 | candidate.position > (options.afterPosition ?? -1) && |
| 355 | (options.itemId === undefined || candidate.sourceItemId === options.itemId), |
| 356 | ); |
| 357 | return Effect.succeed({ |
| 358 | items: remaining.slice( |
| 359 | 0, |
| 360 | options.limit, |
| 361 | ) as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"], |
| 362 | totalItems: rows.length, |
| 363 | hasMore: remaining.length > options.limit, |
| 364 | hasEarlier: false, |
| 365 | }); |
| 366 | }, |
| 367 | getThreadRecords: () => Effect.succeed(projection), |
| 368 | getProjectThreadRecords: () => Effect.succeed(projection), |
| 369 | getRunCount: () => Effect.succeed(projection.runs.length), |
| 370 | getThreadShell: () => |
| 371 | Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell), |
| 372 | } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>), |
| 373 | ServerSettings.layerTest(), |
| 374 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 375 | getProviders: Effect.succeed([]), |
| 376 | } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>), |
| 377 | Layer.mock(ProjectService.ProjectService)({}), |
| 378 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 379 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 380 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({ |
| 381 | list: () => Effect.succeed({ tasks: [] }), |
| 382 | } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>), |
| 383 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 384 | list: () => Effect.succeed([]), |
| 385 | } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>), |
| 386 | NodeCrypto.layer, |
| 387 | ), |
| 388 | ), |
| 389 | ); |
| 390 | |
| 391 | await Effect.gen(function* () { |
| 392 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 393 | for (const [maxCharsPerItem, expected] of [ |
| 394 | [2, ["a", "😀", "bc"]], |
| 395 | [1, ["a", "😀", "b", "c"]], |
| 396 | ] as const) { |
| 397 | let textOffset = 0; |
| 398 | for (const [index, text] of expected.entries()) { |
| 399 | const result = yield* service.readThread(makeScope(), { |
| 400 | threadId: parentThreadId, |
| 401 | view: "activity", |
| 402 | itemId, |
| 403 | textOffset, |
| 404 | maxCharsPerItem, |
| 405 | }); |
| 406 | textOffset += text.length; |
| 407 | expect(result.items[0]).toMatchObject({ |
| 408 | text, |
| 409 | textTruncated: index < expected.length - 1, |
| 410 | nextTextOffset: index < expected.length - 1 ? textOffset : null, |
| 411 | }); |
| 412 | } |
| 413 | } |
| 414 | const first = yield* service.readThread(makeScope(), { |
| 415 | threadId: parentThreadId, |
| 416 | view: "activity", |
| 417 | }); |
| 418 | expect(first.items[1]).toMatchObject({ |
| 419 | text: "x".repeat(500), |
| 420 | textTruncated: true, |
| 421 | nextTextOffset: 500, |
| 422 | }); |
| 423 | expect(first.items).toHaveLength(10); |
| 424 | expect(first).toMatchObject({ nextPosition: 9, hasMore: true }); |
| 425 | }).pipe(Effect.provide(layer), Effect.runPromise); |
| 426 | }); |
| 427 | |
| 428 | it("readThread returns the newest items that fit the response budget", async () => { |
| 429 | const projection = { |
| 430 | thread: baseThread({ |
| 431 | threadId: parentThreadId, |
| 432 | title: "Parent", |
| 433 | instanceId: parentInstanceId, |
| 434 | model: "gpt-5.4", |
| 435 | }), |
| 436 | runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })], |
| 437 | visibleTurnItems: [], |
| 438 | providerTurns: [], |
| 439 | runtimeRequests: [], |
| 440 | messages: [], |
| 441 | contextTransfers: [], |
| 442 | subagents: [], |
| 443 | updatedAt: now, |
| 444 | } as unknown as OrchestrationV2ThreadProjection; |
| 445 | // A long thread's newest 100 activity items, the read agents make most. |
| 446 | const rows = Array.from({ length: 100 }, (_, position) => ({ |
| 447 | position, |
| 448 | visibility: "local", |
| 449 | sourceThreadId: parentThreadId, |
| 450 | sourceItemId: TurnItemId.make(`turn-item-mcp-long-${position}`), |
| 451 | item: { |
| 452 | type: "reasoning", |
| 453 | runId: activeRunId, |
| 454 | status: "completed", |
| 455 | title: null, |
| 456 | text: "x".repeat(1_500), |
| 457 | updatedAt: now, |
| 458 | }, |
| 459 | })); |
| 460 | const pageOptions: Array<unknown> = []; |
| 461 | |
| 462 | const layer = layerOrchestratorService.pipe( |
| 463 | Layer.provide( |
| 464 | Layer.mergeAll( |
| 465 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 466 | getTimelinePage: (_threadId, options) => { |
| 467 | pageOptions.push(options); |
| 468 | return Effect.succeed({ |
| 469 | items: rows as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"], |
| 470 | totalItems: 3_000, |
| 471 | hasMore: false, |
| 472 | hasEarlier: true, |
| 473 | }); |
| 474 | }, |
| 475 | getThreadRecords: () => Effect.succeed(projection), |
| 476 | getProjectThreadRecords: () => Effect.succeed(projection), |
| 477 | getRunCount: () => Effect.succeed(projection.runs.length), |
| 478 | getThreadShell: () => |
| 479 | Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell), |
| 480 | } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>), |
| 481 | ServerSettings.layerTest(), |
| 482 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 483 | getProviders: Effect.succeed([]), |
| 484 | } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>), |
| 485 | Layer.mock(ProjectService.ProjectService)({}), |
| 486 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 487 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 488 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({ |
| 489 | list: () => Effect.succeed({ tasks: [] }), |
| 490 | } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>), |
| 491 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 492 | list: () => Effect.succeed([]), |
| 493 | } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>), |
| 494 | NodeCrypto.layer, |
| 495 | ), |
| 496 | ), |
| 497 | ); |
| 498 | |
| 499 | await Effect.gen(function* () { |
| 500 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 501 | const read = { |
| 502 | threadId: parentThreadId, |
| 503 | view: "activity" as const, |
| 504 | limit: 100, |
| 505 | maxCharsPerItem: 1_500, |
| 506 | }; |
| 507 | const result = yield* service.readThread(makeScope(), read); |
| 508 | // Linked environments and the CLI read as clients without a cursor and follow only hasMore. |
| 509 | const first = yield* service.readThread({ ...makeScope(), thread: undefined }, read); |
| 510 | const fromStart = yield* service.readThread(makeScope(), { ...read, afterPosition: -1 }); |
| 511 | |
| 512 | expect(pageOptions).toEqual([ |
| 513 | { beforePosition: Number.POSITIVE_INFINITY, limit: 100, view: "activity" }, |
| 514 | { limit: 100, view: "activity" }, |
| 515 | { afterPosition: -1, limit: 100, view: "activity" }, |
| 516 | ]); |
| 517 | // Claude Code saves results over ~50k chars of this JSON to a file instead of showing them. |
| 518 | expect(JSON.stringify(result).length).toBeLessThan(31_000); |
| 519 | expect(result.items.length).toBeLessThan(100); |
| 520 | expect(result.items.at(-1)?.position).toBe(99); |
| 521 | expect(result.earlierPosition).toBe(result.items[0]?.position); |
| 522 | expect(result.hasMore).toBe(false); |
| 523 | expect(first.items[0]?.position).toBe(0); |
| 524 | expect(first.hasMore).toBe(true); |
| 525 | expect(first.nextPosition).toBe(first.items.at(-1)?.position); |
| 526 | expect(fromStart.items[0]?.position).toBe(0); |
| 527 | }).pipe(Effect.provide(layer), Effect.runPromise); |
| 528 | }); |
| 529 | |
| 530 | it("readThread keeps an activity page within an MCP client's output limit and pages the rest", async () => { |
| 531 | const projection = { |
| 532 | thread: baseThread({ |
| 533 | threadId: parentThreadId, |
| 534 | title: "Parent", |
| 535 | instanceId: parentInstanceId, |
| 536 | model: "gpt-5.4", |
| 537 | }), |
| 538 | runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })], |
| 539 | visibleTurnItems: [], |
| 540 | providerTurns: [], |
| 541 | runtimeRequests: [], |
| 542 | messages: [], |
| 543 | contextTransfers: [], |
| 544 | subagents: [], |
| 545 | updatedAt: now, |
| 546 | } as unknown as OrchestrationV2ThreadProjection; |
| 547 | const rows = Array.from({ length: 60 }, (_, position) => ({ |
| 548 | position, |
| 549 | visibility: "visible", |
| 550 | sourceThreadId: parentThreadId, |
| 551 | sourceItemId: TurnItemId.make(`turn-item-mcp-reasoning-${position}`), |
| 552 | item: { |
| 553 | type: "reasoning", |
| 554 | runId: activeRunId, |
| 555 | status: "completed", |
| 556 | // Command titles can carry a whole command. |
| 557 | title: position === 1 ? "標".repeat(60_000) : null, |
| 558 | text: position === 0 ? "😀a".repeat(30_000) : `${position} `.padEnd(3_000, "x"), |
| 559 | updatedAt: now, |
| 560 | }, |
| 561 | })); |
| 562 | |
| 563 | const layer = layerOrchestratorService.pipe( |
| 564 | Layer.provide( |
| 565 | Layer.mergeAll( |
| 566 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 567 | getTimelinePage: (_threadId, options) => { |
| 568 | const after = |
| 569 | options.itemId === undefined |
| 570 | ? rows.filter((row) => row.position > (options.afterPosition ?? -1)) |
| 571 | : rows.filter((row) => row.sourceItemId === options.itemId); |
| 572 | return Effect.succeed({ |
| 573 | items: after.slice( |
| 574 | 0, |
| 575 | options.limit, |
| 576 | ) as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"], |
| 577 | totalItems: rows.length, |
| 578 | hasMore: after.length > options.limit, |
| 579 | hasEarlier: false, |
| 580 | }); |
| 581 | }, |
| 582 | getThreadRecords: () => Effect.succeed(projection), |
| 583 | getProjectThreadRecords: () => Effect.succeed(projection), |
| 584 | getRunCount: () => Effect.succeed(projection.runs.length), |
| 585 | getThreadShell: () => |
| 586 | Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell), |
| 587 | } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>), |
| 588 | ServerSettings.layerTest(), |
| 589 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 590 | getProviders: Effect.succeed([]), |
| 591 | } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>), |
| 592 | Layer.mock(ProjectService.ProjectService)({}), |
| 593 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 594 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 595 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({ |
| 596 | list: () => Effect.succeed({ tasks: [] }), |
| 597 | } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>), |
| 598 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 599 | list: () => Effect.succeed([]), |
| 600 | } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>), |
| 601 | NodeCrypto.layer, |
| 602 | ), |
| 603 | ), |
| 604 | ); |
| 605 | |
| 606 | await Effect.gen(function* () { |
| 607 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 608 | const positions: Array<number> = []; |
| 609 | let afterPosition: number | undefined; |
| 610 | for (let page = 0; page < rows.length; page++) { |
| 611 | const result = yield* service.readThread(makeScope(), { |
| 612 | threadId: parentThreadId, |
| 613 | view: "activity", |
| 614 | limit: 100, |
| 615 | maxCharsPerItem: 1_500, |
| 616 | afterPosition: afterPosition ?? -1, |
| 617 | }); |
| 618 | // Claude Code rejects MCP results over 25k tokens; CJK text is about a token per char. |
| 619 | expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(50_000); |
| 620 | if (page === 0) expect(result.hasMore).toBe(true); |
| 621 | positions.push(...result.items.map((item) => item.position)); |
| 622 | if (!result.hasMore) break; |
| 623 | afterPosition = result.nextPosition ?? undefined; |
| 624 | } |
| 625 | expect(positions).toEqual(rows.map((row) => row.position)); |
| 626 | |
| 627 | const longText = rows[0]!.item.text; |
| 628 | const pages: Array<string> = []; |
| 629 | let textOffset: number | null = 0; |
| 630 | while (textOffset !== null) { |
| 631 | const result: OrchestratorMcpThreadReadResult = yield* service.readThread(makeScope(), { |
| 632 | threadId: parentThreadId, |
| 633 | view: "activity", |
| 634 | itemId: rows[0]!.sourceItemId, |
| 635 | textOffset, |
| 636 | maxCharsPerItem: 50_000, |
| 637 | }); |
| 638 | expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(50_000); |
| 639 | const [item] = result.items; |
| 640 | expect(item?.text?.isWellFormed()).toBe(true); |
| 641 | pages.push(item!.text!); |
| 642 | textOffset = item!.nextTextOffset ?? null; |
| 643 | } |
| 644 | expect(pages.length).toBeGreaterThan(1); |
| 645 | expect(pages.join("")).toBe(longText); |
| 646 | |
| 647 | (projection.thread as { title: string }).title = "標".repeat(30_000); |
| 648 | const underHugeTitle = yield* service.readThread(makeScope(), { |
| 649 | threadId: parentThreadId, |
| 650 | view: "activity", |
| 651 | itemId: rows[0]!.sourceItemId, |
| 652 | maxCharsPerItem: 50_000, |
| 653 | }); |
| 654 | expect(underHugeTitle.items[0]?.text?.length).toBeGreaterThan(1_000); |
| 655 | }).pipe(Effect.provide(layer), Effect.runPromise); |
| 656 | }); |
| 657 | |
| 658 | it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => { |
| 659 | const parentProjection = { |
| 660 | thread: baseThread({ |
| 661 | threadId: parentThreadId, |
| 662 | title: "Parent", |
| 663 | instanceId: parentInstanceId, |
| 664 | model: "gpt-5.4", |
| 665 | }), |
| 666 | runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })], |
| 667 | visibleTurnItems: [], |
| 668 | providerTurns: [], |
| 669 | runtimeRequests: [], |
| 670 | messages: [], |
| 671 | contextTransfers: [], |
| 672 | subagents: [ |
| 673 | { |
| 674 | id: taskId, |
| 675 | threadId: parentThreadId, |
| 676 | runId: activeRunId, |
| 677 | parentNodeId: NodeId.make("node-parent"), |
| 678 | origin: "app_owned", |
| 679 | createdBy: "agent", |
| 680 | driver: codexDriver, |
| 681 | providerInstanceId: customCodexInstanceId, |
| 682 | providerThreadId: null, |
| 683 | childThreadId, |
| 684 | nativeTaskRef: null, |
| 685 | prompt: "Inspect the custom instance.", |
| 686 | title: null, |
| 687 | model: "gpt-5.4", |
| 688 | status: "running", |
| 689 | result: null, |
| 690 | startedAt: now, |
| 691 | completedAt: null, |
| 692 | updatedAt: now, |
| 693 | }, |
| 694 | ], |
| 695 | updatedAt: now, |
| 696 | } as unknown as OrchestrationV2ThreadProjection; |
| 697 | |
| 698 | const childProjection = { |
| 699 | thread: { |
| 700 | ...baseThread({ |
| 701 | threadId: childThreadId, |
| 702 | title: "Child", |
| 703 | instanceId: customCodexInstanceId, |
| 704 | model: "gpt-5.4", |
| 705 | }), |
| 706 | lineage: { |
| 707 | parentThreadId, |
| 708 | relationshipToParent: "subagent", |
| 709 | rootThreadId: parentThreadId, |
| 710 | }, |
| 711 | createdBy: "agent", |
| 712 | }, |
| 713 | runs: [ |
| 714 | makeRun({ |
| 715 | id: childRunId, |
| 716 | ordinal: 1, |
| 717 | status: "running", |
| 718 | instanceId: customCodexInstanceId, |
| 719 | }), |
| 720 | ], |
| 721 | visibleTurnItems: [], |
| 722 | providerTurns: [], |
| 723 | runtimeRequests: [], |
| 724 | messages: [], |
| 725 | contextTransfers: [ |
| 726 | { |
| 727 | type: "subagent_spawn", |
| 728 | sourceThreadId: parentThreadId, |
| 729 | targetThreadId: childThreadId, |
| 730 | targetRunId: childRunId, |
| 731 | }, |
| 732 | ], |
| 733 | subagents: [], |
| 734 | providerThreads: [], |
| 735 | updatedAt: now, |
| 736 | } as unknown as OrchestrationV2ThreadProjection; |
| 737 | |
| 738 | const layer = layerOrchestratorService.pipe( |
| 739 | Layer.provide( |
| 740 | Layer.mergeAll( |
| 741 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 742 | getTimelinePage: () => |
| 743 | Effect.succeed({ items: [], totalItems: 0, hasMore: false, hasEarlier: false }), |
| 744 | getThreadRecords: (threadId) => { |
| 745 | if (threadId === parentThreadId) return Effect.succeed(parentProjection); |
| 746 | if (threadId === childThreadId) return Effect.succeed(childProjection); |
| 747 | return Effect.die(`unexpected thread ${threadId}`); |
| 748 | }, |
| 749 | } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>), |
| 750 | ServerSettings.layerTest(), |
| 751 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 752 | getProviders: Effect.succeed([]), |
| 753 | } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>), |
| 754 | Layer.mock(ProjectService.ProjectService)({}), |
| 755 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 756 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 757 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({ |
| 758 | list: () => Effect.succeed({ tasks: [] }), |
| 759 | } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>), |
| 760 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 761 | list: () => Effect.succeed([]), |
| 762 | } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>), |
| 763 | NodeCrypto.layer, |
| 764 | ), |
| 765 | ), |
| 766 | ); |
| 767 | |
| 768 | await Effect.gen(function* () { |
| 769 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 770 | const result = yield* service.taskStatus(makeScope(), taskId); |
| 771 | expect(result.providerInstanceId).toBe(customCodexInstanceId); |
| 772 | expect(result.providerInstanceId).not.toBe(ProviderInstanceId.make(String(codexDriver))); |
| 773 | expect(result.status).toBe("running"); |
| 774 | expect(result.taskId).toBe(taskId); |
| 775 | expect(result.childThreadId).toBe(childThreadId); |
| 776 | }).pipe(Effect.provide(layer), Effect.runPromise); |
| 777 | }); |
| 778 | |
| 779 | it("readThread and sendToThread reach threads in other projects", async () => { |
| 780 | let parentShell: OrchestrationV2ThreadShell | null = null; |
| 781 | let parentRuns: ReadonlyArray<unknown> = [ |
| 782 | makeRun({ id: RunId.make("run-parent-live"), ordinal: 1, status: "running" }), |
| 783 | ]; |
| 784 | const foreignProjectId = ProjectId.make("project-mcp-orchestrator-foreign"); |
| 785 | const foreignThreadId = ThreadId.make("thread-mcp-orchestrator-foreign"); |
| 786 | const parentProjection = { |
| 787 | thread: baseThread({ |
| 788 | threadId: parentThreadId, |
| 789 | title: "Parent", |
| 790 | instanceId: parentInstanceId, |
| 791 | model: "gpt-5.4", |
| 792 | }), |
| 793 | get runs() { |
| 794 | return parentRuns; |
| 795 | }, |
| 796 | visibleTurnItems: [], |
| 797 | providerTurns: [], |
| 798 | runtimeRequests: [], |
| 799 | messages: [], |
| 800 | contextTransfers: [], |
| 801 | subagents: [], |
| 802 | updatedAt: now, |
| 803 | } as unknown as OrchestrationV2ThreadProjection; |
| 804 | const foreignProjection = (threadId: ThreadId) => |
| 805 | ({ |
| 806 | thread: { |
| 807 | ...baseThread({ |
| 808 | threadId, |
| 809 | title: "Foreign", |
| 810 | instanceId: parentInstanceId, |
| 811 | model: "gpt-5.4", |
| 812 | }), |
| 813 | projectId: foreignProjectId, |
| 814 | }, |
| 815 | runs: [], |
| 816 | visibleTurnItems: [ |
| 817 | { |
| 818 | position: 0, |
| 819 | visibility: "inherited", |
| 820 | sourceThreadId: threadId, |
| 821 | sourceItemId: "item-1", |
| 822 | item: { |
| 823 | id: "item-1", |
| 824 | type: "assistant_message", |
| 825 | messageId: "assistant-1", |
| 826 | status: "completed", |
| 827 | title: null, |
| 828 | text: "Foreign thread said hello", |
| 829 | createdAt: now, |
| 830 | updatedAt: now, |
| 831 | }, |
| 832 | }, |
| 833 | ], |
| 834 | providerTurns: [], |
| 835 | runtimeRequests: [], |
| 836 | messages: [], |
| 837 | contextTransfers: [], |
| 838 | subagents: [], |
| 839 | updatedAt: now, |
| 840 | }) as unknown as OrchestrationV2ThreadProjection; |
| 841 | |
| 842 | const layer = layerOrchestratorService.pipe( |
| 843 | Layer.provide( |
| 844 | Layer.mergeAll( |
| 845 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 846 | getThreadRecords: (threadId) => { |
| 847 | if (threadId === parentThreadId) return Effect.succeed(parentProjection); |
| 848 | if (threadId === foreignThreadId) return Effect.succeed(foreignProjection(threadId)); |
| 849 | return Effect.die(`unexpected thread ${threadId}`); |
| 850 | }, |
| 851 | getThreadShell: (threadId) => |
| 852 | Effect.succeed( |
| 853 | threadId === foreignThreadId |
| 854 | ? (foreignProjection(threadId).thread as unknown as OrchestrationV2ThreadShell) |
| 855 | : threadId === parentThreadId |
| 856 | ? parentShell |
| 857 | : null, |
| 858 | ), |
| 859 | getTimelinePage: (threadId) => |
| 860 | Effect.succeed({ |
| 861 | items: foreignProjection(threadId).visibleTurnItems, |
| 862 | totalItems: 1, |
| 863 | hasMore: false, |
| 864 | hasEarlier: false, |
| 865 | }), |
| 866 | getRunCount: (threadId) => Effect.succeed(foreignProjection(threadId).runs.length), |
| 867 | getProjectThreadRecords: (input) => |
| 868 | input.threadId === foreignThreadId && input.projectId === foreignProjectId |
| 869 | ? Effect.succeed(foreignProjection(input.threadId)) |
| 870 | : Effect.fail( |
| 871 | new ThreadManagementService.ThreadManagementThreadNotFoundError({ |
| 872 | projectId: input.projectId, |
| 873 | threadId: input.threadId, |
| 874 | }), |
| 875 | ), |
| 876 | sendToThread: () => |
| 877 | Effect.succeed({ |
| 878 | run: { id: "run-foreign", status: "queued" }, |
| 879 | delivery: "started", |
| 880 | } as unknown as ThreadManagementService.ThreadManagementSendResult), |
| 881 | } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>), |
| 882 | ServerSettings.layerTest(), |
| 883 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 884 | getProviders: Effect.succeed([]), |
| 885 | } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>), |
| 886 | Layer.mock(ProjectService.ProjectService)({}), |
| 887 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 888 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 889 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({ |
| 890 | list: () => |
| 891 | Effect.succeed({ |
| 892 | tasks: [ |
| 893 | { |
| 894 | id: "task-foreign", |
| 895 | projectId: foreignProjectId, |
| 896 | runtimeMode: "approval-required", |
| 897 | interactionMode: "default", |
| 898 | } as never, |
| 899 | ], |
| 900 | }), |
| 901 | } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>), |
| 902 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ |
| 903 | list: () => Effect.succeed([]), |
| 904 | } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>), |
| 905 | NodeCrypto.layer, |
| 906 | ), |
| 907 | ), |
| 908 | ); |
| 909 | |
| 910 | await Effect.gen(function* () { |
| 911 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 912 | const foreign = yield* service.readThread(makeScope(), { threadId: foreignThreadId }); |
| 913 | expect(foreign.thread.threadId).toBe(foreignThreadId); |
| 914 | expect(foreign.thread.projectId).toBe(foreignProjectId); |
| 915 | expect(foreign.items.map((item) => item.text)).toEqual(["Foreign thread said hello"]); |
| 916 | |
| 917 | const sent = yield* service.sendToThread(makeScope(), { |
| 918 | threadId: foreignThreadId, |
| 919 | message: "hi", |
| 920 | }); |
| 921 | expect(sent.threadId).toBe(foreignThreadId); |
| 922 | |
| 923 | parentRuns = []; |
| 924 | yield* service.readThread(makeScope(), { threadId: foreignThreadId }); |
| 925 | const stale = yield* service |
| 926 | .sendToThread(makeScope(), { threadId: foreignThreadId, message: "hi again" }) |
| 927 | .pipe(Effect.flip); |
| 928 | expect(stale.code).toBe("parent_not_active"); |
| 929 | const staleInterrupt = yield* service |
| 930 | .interruptThread(makeScope(), { threadId: foreignThreadId }) |
| 931 | .pipe(Effect.flip); |
| 932 | expect(staleInterrupt.code).toBe("parent_not_active"); |
| 933 | |
| 934 | const staleSchedule = yield* service |
| 935 | .scheduleTask(makeScope(), { |
| 936 | projectId: foreignProjectId, |
| 937 | prompt: "check in later", |
| 938 | schedule: { type: "interval", everyMs: 3_600_000 }, |
| 939 | }) |
| 940 | .pipe(Effect.flip); |
| 941 | expect(staleSchedule.code).toBe("parent_not_active"); |
| 942 | const staleUpdate = yield* service |
| 943 | .updateScheduledTask(makeScope(), { |
| 944 | scheduledTaskId: ScheduledTaskId.make("task-foreign"), |
| 945 | enabled: false, |
| 946 | }) |
| 947 | .pipe(Effect.flip); |
| 948 | expect(staleUpdate.code).toBe("parent_not_active"); |
| 949 | const staleDelete = yield* service |
| 950 | .deleteScheduledTask(makeScope(), { scheduledTaskId: ScheduledTaskId.make("task-foreign") }) |
| 951 | .pipe(Effect.flip); |
| 952 | expect(staleDelete.code).toBe("parent_not_active"); |
| 953 | |
| 954 | const backgroundTasks = [ |
| 955 | { |
| 956 | taskId: "background-subagent", |
| 957 | kind: "subagent" as const, |
| 958 | providerInstanceId: parentInstanceId, |
| 959 | }, |
| 960 | ]; |
| 961 | parentShell = { |
| 962 | ...liveThreadShell(parentThreadId, { activeRunId: null }), |
| 963 | pendingBackgroundTasks: backgroundTasks, |
| 964 | }; |
| 965 | const backgroundSent = yield* service.sendToThread(makeScope(), { |
| 966 | threadId: foreignThreadId, |
| 967 | message: "background", |
| 968 | }); |
| 969 | expect(backgroundSent.threadId).toBe(foreignThreadId); |
| 970 | const delegate = yield* service |
| 971 | .delegateTask(makeScope(), { task: "requires a run" }) |
| 972 | .pipe(Effect.flip); |
| 973 | expect(delegate.code).toBe("parent_not_active"); |
| 974 | const create = yield* service |
| 975 | .createThreads(makeScope(), { threads: [{ prompt: "requires a run" }] }) |
| 976 | .pipe(Effect.flip); |
| 977 | expect(create.code).toBe("parent_not_active"); |
| 978 | const secret = yield* service |
| 979 | .requestSecret(makeScope(), { label: "Secret", reason: "requires a run" }) |
| 980 | .pipe(Effect.flip); |
| 981 | expect(secret.code).toBe("parent_not_active"); |
| 982 | |
| 983 | parentShell = { ...parentShell, providerInstanceId: customCodexInstanceId }; |
| 984 | const switchedScope = { |
| 985 | ...makeScope(), |
| 986 | thread: { ...makeScope().thread!, providerInstanceId: customCodexInstanceId }, |
| 987 | }; |
| 988 | const switched = yield* service |
| 989 | .sendToThread(switchedScope, { threadId: foreignThreadId, message: "wrong owner" }) |
| 990 | .pipe(Effect.flip); |
| 991 | expect(switched.code).toBe("parent_not_active"); |
| 992 | const mismatched = yield* service |
| 993 | .sendToThread(makeScope(), { threadId: foreignThreadId, message: "stale provider" }) |
| 994 | .pipe(Effect.flip); |
| 995 | expect(mismatched.code).toBe("parent_not_active"); |
| 996 | |
| 997 | parentShell = liveThreadShell(parentThreadId); |
| 998 | const restarted = yield* service.sendToThread(makeScope(), { |
| 999 | threadId: foreignThreadId, |
| 1000 | message: "new run", |
| 1001 | }); |
| 1002 | expect(restarted.threadId).toBe(foreignThreadId); |
| 1003 | |
| 1004 | parentShell = { |
| 1005 | ...parentShell, |
| 1006 | activeRunId: null, |
| 1007 | pendingBackgroundTasks: backgroundTasks, |
| 1008 | archivedAt: now, |
| 1009 | }; |
| 1010 | const archived = yield* service |
| 1011 | .sendToThread(makeScope(), { threadId: foreignThreadId, message: "archived" }) |
| 1012 | .pipe(Effect.flip); |
| 1013 | expect(archived.code).toBe("parent_not_active"); |
| 1014 | |
| 1015 | parentShell = { ...parentShell, archivedAt: null, pendingBackgroundTasks: [] }; |
| 1016 | const stopped = yield* service |
| 1017 | .sendToThread(makeScope(), { threadId: foreignThreadId, message: "after stop" }) |
| 1018 | .pipe(Effect.flip); |
| 1019 | expect(stopped.code).toBe("parent_not_active"); |
| 1020 | }).pipe(Effect.provide(layer), Effect.runPromise); |
| 1021 | }); |
| 1022 | |
| 1023 | it("requestSecret saves a pasted value to a file without opening a card", async () => { |
| 1024 | const projection = { |
| 1025 | thread: baseThread({ |
| 1026 | threadId: parentThreadId, |
| 1027 | title: "Parent", |
| 1028 | instanceId: parentInstanceId, |
| 1029 | model: "gpt-5.4", |
| 1030 | }), |
| 1031 | runs: [{ ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId }], |
| 1032 | visibleTurnItems: [], |
| 1033 | providerTurns: [], |
| 1034 | runtimeRequests: [], |
| 1035 | messages: [], |
| 1036 | contextTransfers: [], |
| 1037 | subagents: [], |
| 1038 | updatedAt: now, |
| 1039 | } as unknown as OrchestrationV2ThreadProjection; |
| 1040 | const dispatched: Array<unknown> = []; |
| 1041 | const saved: Array<{ |
| 1042 | readonly requestNamespace: string; |
| 1043 | readonly requestKey: string; |
| 1044 | readonly value: string; |
| 1045 | }> = []; |
| 1046 | const file = "/home/user/.t3/userdata/secrets/files/0123456789abcdef0123456789abcdef"; |
| 1047 | |
| 1048 | const layer = layerOrchestratorService.pipe( |
| 1049 | Layer.provide( |
| 1050 | Layer.mergeAll( |
| 1051 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1052 | getThreadRecords: (threadId) => |
| 1053 | threadId === parentThreadId |
| 1054 | ? Effect.succeed(projection) |
| 1055 | : Effect.die(`unexpected thread ${threadId}`), |
| 1056 | getThreadShell: (threadId) => |
| 1057 | Effect.succeed( |
| 1058 | threadId === parentThreadId |
| 1059 | ? (projection.thread as unknown as OrchestrationV2ThreadShell) |
| 1060 | : null, |
| 1061 | ), |
| 1062 | dispatch: (command) => Effect.sync(() => void dispatched.push(command) as never), |
| 1063 | } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>), |
| 1064 | ServerSettings.layerTest(), |
| 1065 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 1066 | getProviders: Effect.succeed([]), |
| 1067 | } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>), |
| 1068 | Layer.mock(ProjectService.ProjectService)({}), |
| 1069 | Layer.mock(SecretRequests.SecretRequests)({ |
| 1070 | savePasted: (input) => |
| 1071 | Effect.sync(() => { |
| 1072 | saved.push({ |
| 1073 | requestNamespace: input.requestNamespace, |
| 1074 | requestKey: input.requestKey, |
| 1075 | value: input.value, |
| 1076 | }); |
| 1077 | return file; |
| 1078 | }), |
| 1079 | }), |
| 1080 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 1081 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 1082 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), |
| 1083 | NodeCrypto.layer, |
| 1084 | ), |
| 1085 | ), |
| 1086 | ); |
| 1087 | const counted = Metric.snapshot.pipe( |
| 1088 | Effect.map((snapshots) => { |
| 1089 | const found = snapshots.find( |
| 1090 | (snapshot) => |
| 1091 | snapshot.id === "t3_secret_requests_total" && |
| 1092 | snapshot.attributes?.status === "saved_pasted", |
| 1093 | ); |
| 1094 | return found?.type === "Counter" ? Number(found.state.count) : 0; |
| 1095 | }), |
| 1096 | ); |
| 1097 | |
| 1098 | await Effect.gen(function* () { |
| 1099 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1100 | const before = yield* counted; |
| 1101 | const result = yield* service.requestSecret(makeScope(), { |
| 1102 | label: "Pixel PIN", |
| 1103 | reason: "Unlocks the test phone.", |
| 1104 | value: "482916", |
| 1105 | clientRequestId: "pin-1", |
| 1106 | }); |
| 1107 | expect(result).toEqual({ status: "saved", file }); |
| 1108 | expect(JSON.stringify(result)).not.toContain("482916"); |
| 1109 | expect(saved).toEqual([ |
| 1110 | { |
| 1111 | requestNamespace: "provider-session-mcp-orchestrator-detail", |
| 1112 | requestKey: "pin-1", |
| 1113 | value: "482916", |
| 1114 | }, |
| 1115 | ]); |
| 1116 | expect(dispatched).toEqual([]); |
| 1117 | expect((yield* counted) - before).toBe(1); |
| 1118 | |
| 1119 | const asRef = yield* service |
| 1120 | .requestSecret(makeScope(), { |
| 1121 | label: "Pixel PIN", |
| 1122 | reason: "Unlocks the test phone.", |
| 1123 | value: "482916", |
| 1124 | delivery: "secretRef", |
| 1125 | }) |
| 1126 | .pipe(Effect.flip); |
| 1127 | expect(asRef.code).toBe("invalid_request"); |
| 1128 | expect(asRef.message).not.toContain("482916"); |
| 1129 | expect(saved).toHaveLength(1); |
| 1130 | expect(dispatched).toEqual([]); |
| 1131 | }).pipe(Effect.provide(layer), Effect.runPromise); |
| 1132 | }); |
| 1133 | |
| 1134 | it("requestSecret returns the unsaved note for a declined, cancelled or timed-out card", async () => { |
| 1135 | const outcomes = ["declined", "cancelled", "pending"] as const; |
| 1136 | const results = await Effect.forEach(outcomes, (outcome) => { |
| 1137 | const dispatched: Array<{ readonly type: string; readonly turnItemId?: string }> = []; |
| 1138 | const projection = () => { |
| 1139 | const card = dispatched.find((command) => command.type === "secret_request.record"); |
| 1140 | return { |
| 1141 | thread: baseThread({ |
| 1142 | threadId: parentThreadId, |
| 1143 | title: "Parent", |
| 1144 | instanceId: parentInstanceId, |
| 1145 | model: "gpt-5.4", |
| 1146 | }), |
| 1147 | runs: [ |
| 1148 | { ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId }, |
| 1149 | ], |
| 1150 | visibleTurnItems: [], |
| 1151 | turnItems: |
| 1152 | card === undefined |
| 1153 | ? [] |
| 1154 | : [{ type: "secret_request", id: card.turnItemId, secretStatus: outcome }], |
| 1155 | providerTurns: [], |
| 1156 | runtimeRequests: [], |
| 1157 | messages: [], |
| 1158 | contextTransfers: [], |
| 1159 | subagents: [], |
| 1160 | updatedAt: now, |
| 1161 | } as unknown as OrchestrationV2ThreadProjection; |
| 1162 | }; |
| 1163 | const layer = layerOrchestratorService.pipe( |
| 1164 | Layer.provide( |
| 1165 | Layer.mergeAll( |
| 1166 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1167 | getThreadRecords: () => Effect.sync(projection), |
| 1168 | getThreadShell: () => |
| 1169 | Effect.sync(() => projection().thread as unknown as OrchestrationV2ThreadShell), |
| 1170 | dispatch: (command) => Effect.sync(() => void dispatched.push(command) as never), |
| 1171 | } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>), |
| 1172 | ServerSettings.layerTest(), |
| 1173 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 1174 | getProviders: Effect.succeed([]), |
| 1175 | } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>), |
| 1176 | Layer.mock(ProjectService.ProjectService)({}), |
| 1177 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 1178 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 1179 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 1180 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), |
| 1181 | NodeCrypto.layer, |
| 1182 | ), |
| 1183 | ), |
| 1184 | ); |
| 1185 | return Effect.gen(function* () { |
| 1186 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1187 | const request = yield* service |
| 1188 | .requestSecret(makeScope(), { |
| 1189 | label: "Staging password", |
| 1190 | reason: "Signs in the QA account.", |
| 1191 | delivery: "file", |
| 1192 | timeoutMs: 1_000, |
| 1193 | }) |
| 1194 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1195 | yield* TestClock.adjust("2 seconds"); |
| 1196 | return yield* Fiber.join(request); |
| 1197 | }).pipe(Effect.provide(Layer.merge(layer, TestClock.layer()))); |
| 1198 | }).pipe(Effect.runPromise); |
| 1199 | |
| 1200 | expect(results).toEqual([ |
| 1201 | { status: "declined", note: SECRET_REQUEST_UNSAVED_NOTE.declined }, |
| 1202 | { status: "cancelled", note: SECRET_REQUEST_UNSAVED_NOTE.cancelled }, |
| 1203 | { status: "timed_out", note: SECRET_REQUEST_UNSAVED_NOTE.timed_out }, |
| 1204 | ]); |
| 1205 | }); |
| 1206 | |
| 1207 | it("requestSecret cancels its card when a steering restart supersedes the request", async () => { |
| 1208 | const originalRoot = NodeId.make("node-mcp-secret-root-original"); |
| 1209 | const steeredRoot = NodeId.make("node-mcp-secret-root-steered"); |
| 1210 | const dispatched: Array<{ |
| 1211 | readonly type: string; |
| 1212 | readonly turnItemId?: TurnItemId; |
| 1213 | readonly nodeId?: NodeId; |
| 1214 | readonly secretStatus?: string; |
| 1215 | }> = []; |
| 1216 | let steered = false; |
| 1217 | const projection = () => { |
| 1218 | const card = dispatched.find( |
| 1219 | (command) => command.type === "secret_request.record" && command.secretStatus === "pending", |
| 1220 | ); |
| 1221 | return { |
| 1222 | thread: baseThread({ |
| 1223 | threadId: parentThreadId, |
| 1224 | title: "Parent", |
| 1225 | instanceId: parentInstanceId, |
| 1226 | model: "gpt-5.4", |
| 1227 | }), |
| 1228 | runs: [ |
| 1229 | { |
| 1230 | ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), |
| 1231 | rootNodeId: steered ? steeredRoot : originalRoot, |
| 1232 | activeAttemptId: RunAttemptId.make("attempt-mcp-secret-original"), |
| 1233 | }, |
| 1234 | ], |
| 1235 | visibleTurnItems: [], |
| 1236 | turnItems: |
| 1237 | card === undefined |
| 1238 | ? [] |
| 1239 | : [{ type: "secret_request", id: card.turnItemId, secretStatus: "pending" }], |
| 1240 | providerTurns: [], |
| 1241 | runtimeRequests: [], |
| 1242 | messages: [], |
| 1243 | contextTransfers: [], |
| 1244 | subagents: [], |
| 1245 | updatedAt: now, |
| 1246 | } as unknown as OrchestrationV2ThreadProjection; |
| 1247 | }; |
| 1248 | const layer = layerOrchestratorService.pipe( |
| 1249 | Layer.provide( |
| 1250 | Layer.mergeAll( |
| 1251 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1252 | getThreadRecords: () => Effect.sync(projection), |
| 1253 | getThreadShell: () => |
| 1254 | Effect.sync(() => projection().thread as unknown as OrchestrationV2ThreadShell), |
| 1255 | dispatch: (command) => |
| 1256 | Effect.sync(() => { |
| 1257 | dispatched.push(command as (typeof dispatched)[number]); |
| 1258 | // The user steers right after the card opens, replacing the run's root. |
| 1259 | if (command.type === "secret_request.record" && command.secretStatus === "pending") { |
| 1260 | steered = true; |
| 1261 | } |
| 1262 | return undefined as never; |
| 1263 | }), |
| 1264 | } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>), |
| 1265 | ServerSettings.layerTest(), |
| 1266 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 1267 | getProviders: Effect.succeed([]), |
| 1268 | } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>), |
| 1269 | Layer.mock(ProjectService.ProjectService)({}), |
| 1270 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 1271 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 1272 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 1273 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), |
| 1274 | NodeCrypto.layer, |
| 1275 | ), |
| 1276 | ), |
| 1277 | ); |
| 1278 | |
| 1279 | await Effect.gen(function* () { |
| 1280 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1281 | const result = yield* service.requestSecret(makeScope(), { |
| 1282 | label: "Booking details", |
| 1283 | reason: "To check the passenger in.", |
| 1284 | timeoutMs: 60_000, |
| 1285 | }); |
| 1286 | // The wait ended the moment its attempt was superseded instead of blocking |
| 1287 | // the agent's turn until the timeout, and the card closed with it. |
| 1288 | expect(result).toEqual({ status: "cancelled", note: SECRET_REQUEST_UNSAVED_NOTE.cancelled }); |
| 1289 | const records = dispatched.filter((command) => command.type === "secret_request.record"); |
| 1290 | expect(records.map((command) => command.secretStatus)).toEqual(["pending", "cancelled"]); |
| 1291 | expect(records.every((command) => command.nodeId === originalRoot)).toBe(true); |
| 1292 | }).pipe(Effect.provide(layer), Effect.runPromise); |
| 1293 | }); |
| 1294 | |
| 1295 | it("requestSecret delivers a fields card as one file per field", async () => { |
| 1296 | const dispatched: Array<{ |
| 1297 | readonly type: string; |
| 1298 | readonly turnItemId?: string; |
| 1299 | readonly secretStatus?: string; |
| 1300 | }> = []; |
| 1301 | const files = { |
| 1302 | email: "/home/user/.t3/userdata/secrets/files/0123456789abcdef0123456789abcdef", |
| 1303 | password: "/home/user/.t3/userdata/secrets/files/fedcba9876543210fedcba9876543210", |
| 1304 | }; |
| 1305 | const projection = () => { |
| 1306 | const card = dispatched.find((command) => command.type === "secret_request.record"); |
| 1307 | return { |
| 1308 | thread: baseThread({ |
| 1309 | threadId: parentThreadId, |
| 1310 | title: "Parent", |
| 1311 | instanceId: parentInstanceId, |
| 1312 | model: "gpt-5.4", |
| 1313 | }), |
| 1314 | runs: [ |
| 1315 | { ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId }, |
| 1316 | ], |
| 1317 | visibleTurnItems: [], |
| 1318 | turnItems: |
| 1319 | card === undefined |
| 1320 | ? [] |
| 1321 | : [{ type: "secret_request", id: card.turnItemId, secretStatus: "saved" }], |
| 1322 | runtimeRequests: [], |
| 1323 | messages: [], |
| 1324 | contextTransfers: [], |
| 1325 | subagents: [], |
| 1326 | updatedAt: now, |
| 1327 | } as unknown as OrchestrationV2ThreadProjection; |
| 1328 | }; |
| 1329 | const layer = layerOrchestratorService.pipe( |
| 1330 | Layer.provide( |
| 1331 | Layer.mergeAll( |
| 1332 | Layer.mock(ThreadManagementService.ThreadManagementService)({ |
| 1333 | getThreadRecords: () => Effect.sync(projection), |
| 1334 | getThreadShell: () => |
| 1335 | Effect.sync(() => projection().thread as unknown as OrchestrationV2ThreadShell), |
| 1336 | dispatch: (command) => Effect.sync(() => void dispatched.push(command) as never), |
| 1337 | } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>), |
| 1338 | ServerSettings.layerTest(), |
| 1339 | Layer.mock(ProviderRegistry.ProviderRegistry)({ |
| 1340 | getProviders: Effect.succeed([]), |
| 1341 | } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>), |
| 1342 | Layer.mock(ProjectService.ProjectService)({}), |
| 1343 | Layer.mock(SecretRequests.SecretRequests)({ |
| 1344 | saveToFile: () => Effect.succeed({ files }), |
| 1345 | }), |
| 1346 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 1347 | Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), |
| 1348 | Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), |
| 1349 | NodeCrypto.layer, |
| 1350 | ), |
| 1351 | ), |
| 1352 | ); |
| 1353 | const fields = [ |
| 1354 | { name: "email", label: "Email", secret: false }, |
| 1355 | { name: "password", label: "Password" }, |
| 1356 | ]; |
| 1357 | |
| 1358 | await Effect.gen(function* () { |
| 1359 | const service = yield* OrchestratorMcpService.OrchestratorMcpService; |
| 1360 | for (const conflicting of [{ delivery: "secretRef" as const }, { value: "pw" }]) { |
| 1361 | const refused = yield* service |
| 1362 | .requestSecret(makeScope(), { |
| 1363 | label: "Staging login", |
| 1364 | reason: "Signs in the QA account.", |
| 1365 | fields, |
| 1366 | ...conflicting, |
| 1367 | }) |
| 1368 | .pipe(Effect.flip); |
| 1369 | expect(refused.code).toBe("invalid_request"); |
| 1370 | } |
| 1371 | expect(dispatched).toEqual([]); |
| 1372 | |
| 1373 | const result = yield* service.requestSecret(makeScope(), { |
| 1374 | label: "Staging login", |
| 1375 | reason: "Signs in the QA account.", |
| 1376 | fields, |
| 1377 | }); |
| 1378 | expect(result).toEqual({ status: "saved", files }); |
| 1379 | expect(dispatched[0]).toMatchObject({ |
| 1380 | type: "secret_request.record", |
| 1381 | secretStatus: "pending", |
| 1382 | delivery: "file", |
| 1383 | fields, |
| 1384 | }); |
| 1385 | }).pipe(Effect.provide(layer), Effect.runPromise); |
| 1386 | }); |