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 { assert, it } from "@effect/vitest"; |
| 2 | import { |
| 3 | CommandId, |
| 4 | EnvironmentId, |
| 5 | EventId, |
| 6 | MessageId, |
| 7 | NodeId, |
| 8 | ProjectId, |
| 9 | ProviderDriverKind, |
| 10 | ProviderInstanceId, |
| 11 | ProviderThreadId, |
| 12 | RunId, |
| 13 | ThreadId, |
| 14 | } from "@t3tools/contracts"; |
| 15 | import * as Context from "effect/Context"; |
| 16 | import * as DateTime from "effect/DateTime"; |
| 17 | import * as Effect from "effect/Effect"; |
| 18 | import * as Layer from "effect/Layer"; |
| 19 | import * as Ref from "effect/Ref"; |
| 20 | |
| 21 | import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; |
| 22 | import * as EventSink from "./EventSink.ts"; |
| 23 | import * as Orchestrator from "./Orchestrator.ts"; |
| 24 | import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; |
| 25 | import * as ProjectionStore from "./ProjectionStore.ts"; |
| 26 | import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; |
| 27 | import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; |
| 28 | import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; |
| 29 | import * as SqlitePersistence from "../persistence/Sqlite.ts"; |
| 30 | |
| 31 | // A delegated task whose child runs in a linked environment is recorded on |
| 32 | // its parent without a child thread here, and completing it wakes the parent |
| 33 | // the way a local child's result does. |
| 34 | |
| 35 | const instanceId = ProviderInstanceId.make("codex"); |
| 36 | const driver = ProviderDriverKind.make("codex"); |
| 37 | const modelSelection = { instanceId, model: "gpt-5.4" }; |
| 38 | const adapter = { |
| 39 | instanceId, |
| 40 | driver, |
| 41 | getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), |
| 42 | planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), |
| 43 | openSession: () => Effect.die("No provider process needed for delegated task records"), |
| 44 | } as ProviderAdapter.ProviderAdapterV2["Service"]; |
| 45 | |
| 46 | /** Every parent wake the orchestrator offers, for the tests to read. */ |
| 47 | class Offers extends Context.Service< |
| 48 | Offers, |
| 49 | Ref.Ref<ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>> |
| 50 | >()("t3/orchestration-v2/RemoteDelegatedTask.test/Offers") {} |
| 51 | const layerOffers = Layer.effect( |
| 52 | Offers, |
| 53 | Ref.make<ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>>([]), |
| 54 | ); |
| 55 | const layerDatabase = SqlitePersistence.layerMemory; |
| 56 | const layerTest = Layer.mergeAll( |
| 57 | layerDatabase, |
| 58 | ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), |
| 59 | ProviderReplayHarness.layerWithRegistry( |
| 60 | { name: "remote-delegated-task" }, |
| 61 | ProviderAdapterRegistry.layerFromAdapters([adapter]), |
| 62 | { databaseLayer: layerDatabase, runEffectWorker: false }, |
| 63 | ), |
| 64 | ).pipe( |
| 65 | Layer.provide( |
| 66 | Layer.effect( |
| 67 | ProviderContinuationRequests.ProviderContinuationRequests, |
| 68 | Offers.pipe( |
| 69 | Effect.map((offers) => ({ |
| 70 | offer: (request: ProviderContinuationRequests.ProviderContinuationRequest) => |
| 71 | Ref.update(offers, (seen) => [...seen, request]), |
| 72 | take: Effect.never, |
| 73 | })), |
| 74 | ), |
| 75 | ), |
| 76 | ), |
| 77 | Layer.provideMerge(layerOffers), |
| 78 | ); |
| 79 | |
| 80 | /** A parent thread whose run is live, as when its agent calls delegate_task. */ |
| 81 | const seedLiveParent = (name: string) => |
| 82 | Effect.gen(function* () { |
| 83 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 84 | const sink = yield* EventSink.EventSinkV2; |
| 85 | const now = yield* DateTime.now; |
| 86 | const threadId = ThreadId.make(`thread:${name}`); |
| 87 | const runId = RunId.make(`run:${name}`); |
| 88 | const rootNodeId = NodeId.make(`node:${name}:root`); |
| 89 | const providerThreadId = ProviderThreadId.make(`provider-thread:${name}`); |
| 90 | yield* orchestrator.dispatch({ |
| 91 | type: "thread.create", |
| 92 | createdBy: "user", |
| 93 | creationSource: "web", |
| 94 | commandId: CommandId.make(`command:create:${name}`), |
| 95 | threadId, |
| 96 | projectId: ProjectId.make("project:remote-delegated-task"), |
| 97 | title: "Parent", |
| 98 | modelSelection, |
| 99 | runtimeMode: "full-access", |
| 100 | interactionMode: "default", |
| 101 | branch: null, |
| 102 | worktreePath: null, |
| 103 | }); |
| 104 | yield* sink.write({ |
| 105 | commandId: CommandId.make(`command:seed:${name}`), |
| 106 | events: [ |
| 107 | { |
| 108 | id: EventId.make(`event:seed-provider-thread:${name}`), |
| 109 | type: "provider-thread.updated", |
| 110 | threadId, |
| 111 | driver, |
| 112 | providerInstanceId: instanceId, |
| 113 | occurredAt: now, |
| 114 | payload: { |
| 115 | id: providerThreadId, |
| 116 | driver, |
| 117 | providerInstanceId: instanceId, |
| 118 | providerSessionId: null, |
| 119 | appThreadId: threadId, |
| 120 | ownerNodeId: rootNodeId, |
| 121 | nativeThreadRef: { driver, nativeId: `native:${name}`, strength: "strong" }, |
| 122 | nativeConversationHeadRef: null, |
| 123 | status: "active", |
| 124 | firstRunOrdinal: 1, |
| 125 | lastRunOrdinal: 1, |
| 126 | handoffIds: [], |
| 127 | forkedFrom: null, |
| 128 | createdAt: now, |
| 129 | updatedAt: now, |
| 130 | }, |
| 131 | }, |
| 132 | { |
| 133 | id: EventId.make(`event:seed-node:${name}`), |
| 134 | type: "node.updated", |
| 135 | threadId, |
| 136 | runId, |
| 137 | nodeId: rootNodeId, |
| 138 | driver, |
| 139 | providerInstanceId: instanceId, |
| 140 | occurredAt: now, |
| 141 | payload: { |
| 142 | id: rootNodeId, |
| 143 | threadId, |
| 144 | runId, |
| 145 | parentNodeId: null, |
| 146 | rootNodeId, |
| 147 | kind: "root_turn", |
| 148 | status: "running", |
| 149 | countsForRun: true, |
| 150 | providerThreadId, |
| 151 | providerTurnId: null, |
| 152 | nativeItemRef: null, |
| 153 | runtimeRequestId: null, |
| 154 | checkpointScopeId: null, |
| 155 | startedAt: now, |
| 156 | completedAt: null, |
| 157 | }, |
| 158 | }, |
| 159 | { |
| 160 | id: EventId.make(`event:seed-run:${name}`), |
| 161 | type: "run.updated", |
| 162 | threadId, |
| 163 | runId, |
| 164 | nodeId: rootNodeId, |
| 165 | providerInstanceId: instanceId, |
| 166 | occurredAt: now, |
| 167 | payload: { |
| 168 | id: runId, |
| 169 | threadId, |
| 170 | ordinal: 1, |
| 171 | providerInstanceId: instanceId, |
| 172 | modelSelection, |
| 173 | providerThreadId, |
| 174 | userMessageId: MessageId.make(`message:seed-user:${name}`), |
| 175 | rootNodeId, |
| 176 | activeAttemptId: null, |
| 177 | status: "running", |
| 178 | requestedAt: now, |
| 179 | startedAt: now, |
| 180 | completedAt: null, |
| 181 | checkpointId: null, |
| 182 | contextHandoffId: null, |
| 183 | }, |
| 184 | }, |
| 185 | ], |
| 186 | }); |
| 187 | return { threadId, runId, rootNodeId }; |
| 188 | }); |
| 189 | |
| 190 | const remoteChild = { |
| 191 | environmentId: EnvironmentId.make("environment:box"), |
| 192 | threadId: ThreadId.make("thread:on-the-box"), |
| 193 | label: "Box", |
| 194 | }; |
| 195 | |
| 196 | it.layer(layerTest)("a delegated task in a linked environment", (it) => { |
| 197 | it.effect("is recorded on its parent without a child thread here, once", () => |
| 198 | Effect.gen(function* () { |
| 199 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 200 | const parent = yield* seedLiveParent("records"); |
| 201 | const request = { |
| 202 | type: "delegated_task.remote.request" as const, |
| 203 | commandId: CommandId.make("command:remote-delegate:records"), |
| 204 | parentThreadId: parent.threadId, |
| 205 | parentRunId: parent.runId, |
| 206 | parentNodeId: parent.rootNodeId, |
| 207 | task: "Run the suite there.", |
| 208 | driver: ProviderDriverKind.make("remote"), |
| 209 | modelSelection, |
| 210 | remoteChild, |
| 211 | completionWake: "always" as const, |
| 212 | }; |
| 213 | yield* orchestrator.dispatch(request); |
| 214 | yield* orchestrator.dispatch(request); |
| 215 | const projection = yield* orchestrator.getThreadProjection(parent.threadId); |
| 216 | assert.equal(projection.subagents.length, 1); |
| 217 | const [task] = projection.subagents; |
| 218 | assert.equal(task?.childThreadId, null); |
| 219 | assert.deepEqual(task?.remoteChild, remoteChild); |
| 220 | assert.deepEqual(task?.modelSelection, modelSelection); |
| 221 | assert.equal(task?.status, "running"); |
| 222 | const item = projection.turnItems.find((candidate) => candidate.type === "subagent"); |
| 223 | assert.deepEqual(item?.type === "subagent" ? item.remoteChild : undefined, remoteChild); |
| 224 | // No thread was created here for the child. |
| 225 | assert.equal(yield* orchestrator.getThreadShell(remoteChild.threadId), null); |
| 226 | const other = yield* seedLiveParent("records-no-task"); |
| 227 | const index = yield* (yield* ProjectionStore.ProjectionStoreV2).listActiveShellIndex(); |
| 228 | assert.isTrue(index.find((entry) => entry.id === parent.threadId)?.hasRemoteTasks); |
| 229 | assert.isFalse(index.find((entry) => entry.id === other.threadId)?.hasRemoteTasks); |
| 230 | // Nothing here can cancel the task there, so it must not block archiving. |
| 231 | yield* orchestrator.dispatch({ |
| 232 | type: "thread.archive", |
| 233 | commandId: CommandId.make("command:archive:records"), |
| 234 | threadId: parent.threadId, |
| 235 | }); |
| 236 | assert.isNotNull((yield* orchestrator.getThreadShell(parent.threadId))?.archivedAt); |
| 237 | }), |
| 238 | ); |
| 239 | |
| 240 | it.effect("keeps a newer stop recoverable after an older acknowledgement", () => |
| 241 | Effect.gen(function* () { |
| 242 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 243 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 244 | const parent = yield* seedLiveParent("stop-generation"); |
| 245 | yield* orchestrator.dispatch({ |
| 246 | type: "delegated_task.remote.request", |
| 247 | commandId: CommandId.make("command:remote-delegate:stop-generation"), |
| 248 | parentThreadId: parent.threadId, |
| 249 | parentRunId: parent.runId, |
| 250 | parentNodeId: parent.rootNodeId, |
| 251 | task: "Run a check.", |
| 252 | driver: ProviderDriverKind.make("remote"), |
| 253 | modelSelection, |
| 254 | remoteChild, |
| 255 | }); |
| 256 | const task = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!; |
| 257 | const openFor = projections.getOpenRemoteDelegatedTasks.pipe( |
| 258 | Effect.map((open) => open.filter((entry) => entry.parentThreadId === parent.threadId)), |
| 259 | ); |
| 260 | const complete = { |
| 261 | type: "delegated_task.remote.complete" as const, |
| 262 | parentThreadId: parent.threadId, |
| 263 | taskId: task.id, |
| 264 | status: "completed" as const, |
| 265 | result: "Original result.", |
| 266 | }; |
| 267 | yield* orchestrator.dispatch({ |
| 268 | ...complete, |
| 269 | commandId: CommandId.make("command:result:stop-generation"), |
| 270 | stoppedThere: "ran-out", |
| 271 | }); |
| 272 | for (const count of [1, 2]) { |
| 273 | yield* orchestrator.dispatch({ |
| 274 | type: "delegated_task.remote.stop", |
| 275 | parentThreadId: parent.threadId, |
| 276 | taskId: task.id, |
| 277 | commandId: CommandId.make(`command:stop-generation:${count}`), |
| 278 | }); |
| 279 | } |
| 280 | // Reports from before generation tracking cannot clear a later numbered Stop either. |
| 281 | for (const stopCount of [undefined, 1]) { |
| 282 | const rejected = yield* orchestrator |
| 283 | .dispatch({ |
| 284 | ...complete, |
| 285 | commandId: CommandId.make(`command:stale-stop:${stopCount}`), |
| 286 | stoppedThere: "stopped", |
| 287 | ...(stopCount === undefined ? {} : { stopCount }), |
| 288 | }) |
| 289 | .pipe(Effect.flip); |
| 290 | assert.equal(rejected._tag, "OrchestratorDispatchError"); |
| 291 | assert.deepEqual(yield* openFor, [{ parentThreadId: parent.threadId, taskId: task.id }]); |
| 292 | } |
| 293 | yield* orchestrator.dispatch({ |
| 294 | ...complete, |
| 295 | commandId: CommandId.make("command:current-stop:2"), |
| 296 | stoppedThere: "stopped", |
| 297 | stopCount: 2, |
| 298 | }); |
| 299 | const settled = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!; |
| 300 | assert.equal(settled.result, "Original result."); |
| 301 | assert.equal(settled.status, "completed"); |
| 302 | assert.equal(settled.remoteChild?.stoppedThere, true); |
| 303 | assert.deepEqual(yield* openFor, []); |
| 304 | }), |
| 305 | ); |
| 306 | |
| 307 | it.effect("owes a stop there for a Stop here that loses the race to its result", () => |
| 308 | Effect.gen(function* () { |
| 309 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 310 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 311 | const parent = yield* seedLiveParent("stop-after-result"); |
| 312 | yield* orchestrator.dispatch({ |
| 313 | type: "delegated_task.remote.request", |
| 314 | commandId: CommandId.make("command:remote-delegate:stop-after-result"), |
| 315 | parentThreadId: parent.threadId, |
| 316 | parentRunId: parent.runId, |
| 317 | parentNodeId: parent.rootNodeId, |
| 318 | task: "Run a check.", |
| 319 | driver: ProviderDriverKind.make("remote"), |
| 320 | modelSelection, |
| 321 | remoteChild, |
| 322 | }); |
| 323 | const task = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!; |
| 324 | const complete = { |
| 325 | type: "delegated_task.remote.complete" as const, |
| 326 | parentThreadId: parent.threadId, |
| 327 | taskId: task.id, |
| 328 | }; |
| 329 | yield* orchestrator.dispatch({ |
| 330 | ...complete, |
| 331 | commandId: CommandId.make("command:result:stop-after-result"), |
| 332 | status: "completed", |
| 333 | result: "Done there.", |
| 334 | stoppedThere: "ran-out", |
| 335 | }); |
| 336 | // The parent's Stop read the task before its result landed. |
| 337 | yield* orchestrator.dispatch({ |
| 338 | ...complete, |
| 339 | commandId: CommandId.make("command:parent-stop:stop-after-result"), |
| 340 | status: "interrupted", |
| 341 | result: "Stopped with its parent.", |
| 342 | }); |
| 343 | |
| 344 | const stopped = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!; |
| 345 | assert.equal(stopped.status, "completed"); |
| 346 | assert.equal(stopped.result, "Done there."); |
| 347 | assert.equal(stopped.remoteChild?.stoppedThere, false); |
| 348 | assert.equal(stopped.remoteChild?.stopCount, 1); |
| 349 | const open = yield* projections.getOpenRemoteDelegatedTasks; |
| 350 | assert.deepEqual( |
| 351 | open.filter((entry) => entry.parentThreadId === parent.threadId), |
| 352 | [{ parentThreadId: parent.threadId, taskId: task.id }], |
| 353 | ); |
| 354 | }), |
| 355 | ); |
| 356 | |
| 357 | it.effect("wakes its parent with the result when it completes there", () => |
| 358 | Effect.gen(function* () { |
| 359 | const orchestrator = yield* Orchestrator.OrchestratorV2; |
| 360 | const parent = yield* seedLiveParent("completes"); |
| 361 | const recorded = yield* orchestrator.dispatch({ |
| 362 | type: "delegated_task.remote.request", |
| 363 | commandId: CommandId.make("command:remote-delegate:completes"), |
| 364 | parentThreadId: parent.threadId, |
| 365 | parentRunId: parent.runId, |
| 366 | parentNodeId: parent.rootNodeId, |
| 367 | task: "Run the suite there.", |
| 368 | driver: ProviderDriverKind.make("remote"), |
| 369 | modelSelection, |
| 370 | remoteChild, |
| 371 | completionWake: "always", |
| 372 | }); |
| 373 | const taskEvent = recorded.storedEvents.find( |
| 374 | (stored) => stored.event.type === "subagent.updated", |
| 375 | ); |
| 376 | const taskId = |
| 377 | taskEvent?.event.type === "subagent.updated" ? taskEvent.event.payload.id : undefined; |
| 378 | assert.isDefined(taskId); |
| 379 | // Until it completes, it is open, and a restarted follower picks it up. |
| 380 | const projections = yield* ProjectionStore.ProjectionStoreV2; |
| 381 | const openFor = projections.getOpenRemoteDelegatedTasks.pipe( |
| 382 | Effect.map((open) => open.filter((task) => task.parentThreadId === parent.threadId)), |
| 383 | ); |
| 384 | assert.deepEqual(yield* openFor, [{ parentThreadId: parent.threadId, taskId: taskId! }]); |
| 385 | const offers = yield* Offers; |
| 386 | yield* Ref.set(offers, []); |
| 387 | const complete = (result: string) => |
| 388 | orchestrator.dispatch({ |
| 389 | type: "delegated_task.remote.complete", |
| 390 | commandId: CommandId.make(`command:remote-complete:${result}`), |
| 391 | parentThreadId: parent.threadId, |
| 392 | taskId: taskId!, |
| 393 | status: "completed", |
| 394 | result, |
| 395 | stoppedThere: "ran-out", |
| 396 | }); |
| 397 | yield* complete("All 412 tests pass on the box."); |
| 398 | // A second report is refused, so the first result stands. |
| 399 | const late = yield* complete("A late, different answer.").pipe(Effect.flip); |
| 400 | assert.equal(late._tag, "OrchestratorDispatchError"); |
| 401 | |
| 402 | const projection = yield* orchestrator.getThreadProjection(parent.threadId); |
| 403 | const task = projection.subagents.find((candidate) => candidate.id === taskId); |
| 404 | assert.equal(task?.status, "completed"); |
| 405 | assert.equal(task?.result, "All 412 tests pass on the box."); |
| 406 | // The live parent run claimed it, so task_status acknowledges it as for a local child. |
| 407 | assert.equal(task?.completionDelivery?.state, "claimed"); |
| 408 | // Nothing is left for the follower to pick up after a restart. |
| 409 | assert.deepEqual(yield* openFor, []); |
| 410 | const item = projection.turnItems.find( |
| 411 | (candidate) => candidate.type === "subagent" && candidate.subagentId === taskId, |
| 412 | ); |
| 413 | assert.equal(item?.status, "completed"); |
| 414 | // The parent's live run is offered the delivery, as for a local child. |
| 415 | const delivery = projection.runs.find((run) => run.id === parent.runId)?.delegatedCompletion |
| 416 | ?.delivery; |
| 417 | assert.deepEqual(delivery?.taskIds, [taskId]); |
| 418 | const offered = yield* Ref.get(offers); |
| 419 | assert.equal(offered.length, 1); |
| 420 | assert.equal(offered[0]?.threadId, parent.threadId); |
| 421 | }), |
| 422 | ); |
| 423 | }); |