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 DocumentText from "../provider/DocumentText.ts"; |
| 2 | import * as Scheduler from "../scheduling/Scheduler.ts"; |
| 3 | import * as WorktreeSetupTracker from "../project/WorktreeSetupTracker.ts"; |
| 4 | import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts"; |
| 5 | import * as TerminalManager from "../terminal/Manager.ts"; |
| 6 | import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; |
| 7 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 8 | import * as FileSystem from "effect/FileSystem"; |
| 9 | import * as ServerConfig from "../config.ts"; |
| 10 | import { createPendingAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts"; |
| 11 | import * as ThreadMessageIntake from "./ThreadMessageIntake.ts"; |
| 12 | import { assert, it, vi } from "@effect/vitest"; |
| 13 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 14 | import { |
| 15 | ChatAttachmentId, |
| 16 | ComposerContextId, |
| 17 | type ChatAttachment, |
| 18 | CommandId, |
| 19 | DEFAULT_SERVER_SETTINGS, |
| 20 | EnvironmentId, |
| 21 | GitCommandError, |
| 22 | MessageId, |
| 23 | RunId, |
| 24 | ProjectId, |
| 25 | ProviderDriverKind, |
| 26 | ProviderInstanceId, |
| 27 | OrchestrationV2ThreadProjectionJson, |
| 28 | ScheduledTaskId, |
| 29 | type ServerProvider, |
| 30 | ThreadId, |
| 31 | TextGenerationError, |
| 32 | ServerSettingsError, |
| 33 | VcsProcessExitError, |
| 34 | } from "@t3tools/contracts"; |
| 35 | import * as Cause from "effect/Cause"; |
| 36 | import * as Deferred from "effect/Deferred"; |
| 37 | import * as DateTime from "effect/DateTime"; |
| 38 | import * as Duration from "effect/Duration"; |
| 39 | import * as Effect from "effect/Effect"; |
| 40 | import * as Exit from "effect/Exit"; |
| 41 | import * as Fiber from "effect/Fiber"; |
| 42 | import * as Layer from "effect/Layer"; |
| 43 | import * as Option from "effect/Option"; |
| 44 | import * as Ref from "effect/Ref"; |
| 45 | import * as Result from "effect/Result"; |
| 46 | import * as Stream from "effect/Stream"; |
| 47 | import * as Schema from "effect/Schema"; |
| 48 | import * as SqlClient from "effect/sql/SqlClient"; |
| 49 | import * as TestClock from "effect/testing/TestClock"; |
| 50 | |
| 51 | import * as GitWorkflow from "../git/GitWorkflowService.ts"; |
| 52 | import * as SqlitePersistence from "../persistence/Sqlite.ts"; |
| 53 | import * as ProjectStore from "./ProjectStore.ts"; |
| 54 | import * as ProjectService from "../project/ProjectService.ts"; |
| 55 | import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; |
| 56 | import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; |
| 57 | import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMock.ts"; |
| 58 | import * as ServerSettings from "../serverSettings.ts"; |
| 59 | import * as ScheduledTasks from "../scheduledTasks/ScheduledTaskService.ts"; |
| 60 | import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; |
| 61 | import * as SecretRequests from "../secrets/SecretRequests.ts"; |
| 62 | import * as TextGeneration from "../textGeneration/TextGeneration.ts"; |
| 63 | import { ClaudeProviderCapabilitiesV2 } from "./Adapters/ClaudeAdapterV2.ts"; |
| 64 | import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; |
| 65 | import * as CommandReceiptStore from "./CommandReceiptStore.ts"; |
| 66 | import * as Orchestrator from "./Orchestrator.ts"; |
| 67 | import * as EffectOutbox from "./EffectOutbox.ts"; |
| 68 | import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 69 | import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; |
| 70 | import * as ThreadLaunch from "./ThreadLaunchService.ts"; |
| 71 | import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; |
| 72 | import * as ThreadManagement from "./ThreadManagementService.ts"; |
| 73 | import * as ThreadTitleRegeneration from "./ThreadTitleRegenerationService.ts"; |
| 74 | import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; |
| 75 | import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; |
| 76 | import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; |
| 77 | |
| 78 | const projectId = ProjectId.make("project:launch-test"); |
| 79 | const otherProjectId = ProjectId.make("project:launch-other"); |
| 80 | const encodeThreadProjection = Schema.encodeEffect(OrchestrationV2ThreadProjectionJson); |
| 81 | const dispatchIntakeCommand = ( |
| 82 | command: Parameters<typeof ThreadMessageIntake.dispatchCommand>[0], |
| 83 | ) => ThreadMessageIntake.dispatchCommand(command, { managesProviders: true }); |
| 84 | const modelSelection = { |
| 85 | instanceId: ProviderInstanceId.make("codex"), |
| 86 | model: "gpt-5.1-codex", |
| 87 | } as const; |
| 88 | const project = { |
| 89 | id: projectId, |
| 90 | title: "Project", |
| 91 | workspaceRoot: "/repo", |
| 92 | repositoryIdentity: null, |
| 93 | faviconPath: null, |
| 94 | defaultModelSelection: modelSelection, |
| 95 | defaultThreadEnvMode: null, |
| 96 | scripts: [], |
| 97 | pinnedAt: null, |
| 98 | archivedAt: null, |
| 99 | createdAt: "2026-06-20T00:00:00.000Z", |
| 100 | updatedAt: "2026-06-20T00:00:00.000Z", |
| 101 | deletedAt: null, |
| 102 | } as const; |
| 103 | |
| 104 | const otherProject = { |
| 105 | ...project, |
| 106 | id: otherProjectId, |
| 107 | title: "Other", |
| 108 | workspaceRoot: "/other-repo", |
| 109 | } as const; |
| 110 | |
| 111 | const adapter = { |
| 112 | instanceId: modelSelection.instanceId, |
| 113 | driver: ProviderDriverKind.make("codex"), |
| 114 | getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), |
| 115 | planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), |
| 116 | openSession: () => Effect.die("provider execution is disabled in launch tests"), |
| 117 | } as ProviderAdapter.ProviderAdapterV2["Service"]; |
| 118 | |
| 119 | const claudeModelSelection = { |
| 120 | instanceId: ProviderInstanceId.make("claudeAgent"), |
| 121 | model: "claude-opus-5-5", |
| 122 | } as const; |
| 123 | const claudeAdapter = { |
| 124 | instanceId: claudeModelSelection.instanceId, |
| 125 | driver: ProviderDriverKind.make("claudeAgent"), |
| 126 | getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2), |
| 127 | planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), |
| 128 | openSession: () => Effect.die("provider execution is disabled in launch tests"), |
| 129 | } as ProviderAdapter.ProviderAdapterV2["Service"]; |
| 130 | |
| 131 | interface HarnessOptions { |
| 132 | readonly closeTerminal?: TerminalManager.TerminalManager["Service"]["close"]; |
| 133 | readonly adapters?: ReadonlyArray<ProviderAdapter.ProviderAdapterV2["Service"]>; |
| 134 | readonly managedFolders?: Layer.Layer<ManagedProjectFolders.ManagedProjectFolders>; |
| 135 | readonly createWorktree?: GitWorkflow.GitWorkflowService["Service"]["createWorktree"]; |
| 136 | readonly fetchWorktreeBaseCommit?: GitWorkflow.GitWorkflowService["Service"]["fetchWorktreeBaseCommit"]; |
| 137 | readonly remoteExists?: GitWorkflow.GitWorkflowService["Service"]["remoteExists"]; |
| 138 | readonly hasCommit?: GitWorkflow.GitWorkflowService["Service"]["hasCommit"]; |
| 139 | readonly renameBranch?: GitWorkflow.GitWorkflowService["Service"]["renameBranch"]; |
| 140 | readonly runSetup?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"]; |
| 141 | readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"]; |
| 142 | readonly generateBranchName?: TextGeneration.TextGeneration["Service"]["generateBranchName"]; |
| 143 | readonly serverSettings?: Parameters<typeof ServerSettings.layerTest>[0]; |
| 144 | readonly getLaunchSettings?: ServerSettings.ServerSettingsService["Service"]["getSettings"]; |
| 145 | readonly providers?: ReadonlyArray<ServerProvider>; |
| 146 | readonly git?: Partial<GitWorkflow.GitWorkflowService["Service"]>; |
| 147 | readonly dispatch?: ( |
| 148 | command: Parameters<ThreadManagement.ThreadManagementService["Service"]["dispatch"]>[0], |
| 149 | dispatch: ThreadManagement.ThreadManagementService["Service"]["dispatch"], |
| 150 | ) => ReturnType<ThreadManagement.ThreadManagementService["Service"]["dispatch"]>; |
| 151 | readonly isGitRepository?: CheckpointStore.CheckpointStore["Service"]["isGitRepository"]; |
| 152 | } |
| 153 | |
| 154 | function makeHarness(options: HarnessOptions = {}) { |
| 155 | const layerDatabase = SqlitePersistence.layerMemory; |
| 156 | const layerRegistry = ProviderAdapterRegistry.layerFromAdapters(options.adapters ?? [adapter]); |
| 157 | const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( |
| 158 | { name: "thread-launch" }, |
| 159 | layerRegistry, |
| 160 | { databaseLayer: layerDatabase, runEffectWorker: false }, |
| 161 | ); |
| 162 | const layerServerSettings = ServerSettings.layerTest(options.serverSettings); |
| 163 | const layerReceipts = CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase)); |
| 164 | const layerThreadManagement = ThreadManagement.layer.pipe( |
| 165 | Layer.provide(layerOrchestrator), |
| 166 | Layer.provide(layerServerSettings), |
| 167 | Layer.provide(layerReceipts), |
| 168 | ); |
| 169 | const layerOutbox = EffectOutbox.layer.pipe(Layer.provide(layerDatabase)); |
| 170 | const createWorktree = vi.fn( |
| 171 | options.createWorktree ?? |
| 172 | ((input) => |
| 173 | Effect.succeed({ |
| 174 | worktree: { path: "/repo-worktrees/feature", refName: input.newRefName, headSha: "abc" }, |
| 175 | } as never)), |
| 176 | ); |
| 177 | const renameBranch = vi.fn( |
| 178 | options.renameBranch ?? ((input) => Effect.succeed({ branch: input.newBranch })), |
| 179 | ); |
| 180 | const removeWorktree = vi.fn( |
| 181 | (_input: Parameters<GitWorkflow.GitWorkflowService["Service"]["removeWorktree"]>[0]) => |
| 182 | Effect.void, |
| 183 | ); |
| 184 | const deleteLocalBranch = vi.fn( |
| 185 | (_input: Parameters<GitWorkflow.GitWorkflowService["Service"]["deleteLocalBranch"]>[0]) => |
| 186 | Effect.void, |
| 187 | ); |
| 188 | const runSetup = vi.fn( |
| 189 | options.runSetup ?? (() => Effect.succeed({ status: "no-script" as const })), |
| 190 | ); |
| 191 | const closeTerminal = vi.fn(options.closeTerminal ?? (() => Effect.void)); |
| 192 | const generateBranchName = vi.fn( |
| 193 | options.generateBranchName ?? (() => Effect.succeed({ branch: "generated-branch" })), |
| 194 | ); |
| 195 | const generateThreadTitle = vi.fn( |
| 196 | options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })), |
| 197 | ); |
| 198 | const layerExternalServices = Layer.mergeAll( |
| 199 | WorktreeSetupTracker.layer, |
| 200 | Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({ get: () => Effect.succeed(null) }), |
| 201 | Layer.mock(TerminalManager.TerminalManager)({ close: closeTerminal }), |
| 202 | Layer.mock(CheckpointStore.CheckpointStore)({ |
| 203 | isGitRepository: options.isGitRepository ?? (() => Effect.succeed(true)), |
| 204 | }), |
| 205 | Layer.succeed(ProjectService.ProjectService, { |
| 206 | create: () => Effect.die("unused"), |
| 207 | bootstrap: () => Effect.die("unused"), |
| 208 | update: () => Effect.die("unused"), |
| 209 | delete: () => Effect.die("unused"), |
| 210 | listPage: () => Effect.die("unused"), |
| 211 | getById: (id) => |
| 212 | Effect.succeed( |
| 213 | id === projectId |
| 214 | ? Option.some(project) |
| 215 | : id === otherProjectId |
| 216 | ? Option.some(otherProject) |
| 217 | : Option.none(), |
| 218 | ), |
| 219 | getByWorkspaceRoot: () => Effect.succeedSome(project), |
| 220 | workspaceScanDirectory: () => Effect.die("unused"), |
| 221 | snapshot: Effect.die("unused"), |
| 222 | getShell: () => Effect.die("unused"), |
| 223 | listShells: () => Effect.die("unused"), |
| 224 | }), |
| 225 | Layer.mock(GitWorkflow.GitWorkflowService)({ |
| 226 | repositoryRoot: () => Effect.succeed(project.workspaceRoot), |
| 227 | createWorktree, |
| 228 | renameBranch, |
| 229 | fetchWorktreeBaseCommit: |
| 230 | options.fetchWorktreeBaseCommit ?? |
| 231 | (() => Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" })), |
| 232 | hasCommit: options.hasCommit ?? (() => Effect.succeed(false)), |
| 233 | currentBranch: () => Effect.succeed(null), |
| 234 | resolveWorktreeBaseRemote: () => Effect.succeed({ remoteName: "origin", branchName: "main" }), |
| 235 | resolvePrimaryRemoteName: () => Effect.succeed("origin"), |
| 236 | resolveDefaultBranchName: () => Effect.succeed("main"), |
| 237 | remoteExists: options.remoteExists ?? (() => Effect.succeed(true)), |
| 238 | remoteBranchExists: () => Effect.succeed(true), |
| 239 | listLocalBranchNames: () => Effect.succeed([]), |
| 240 | removeWorktree, |
| 241 | deleteLocalBranch, |
| 242 | ...options.git, |
| 243 | }), |
| 244 | Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, { |
| 245 | runForThread: runSetup, |
| 246 | }), |
| 247 | Layer.mock(TextGeneration.TextGeneration)({ |
| 248 | generateThreadTitle, |
| 249 | generateBranchName, |
| 250 | }), |
| 251 | layerServerSettings, |
| 252 | ProviderRegistryMock.layer(options.providers), |
| 253 | options.managedFolders ?? |
| 254 | Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ |
| 255 | namedProjectsRoot: "/projects", |
| 256 | isScratchProject: () => Effect.succeed(false), |
| 257 | folderForThread: () => Effect.succeedNone, |
| 258 | }), |
| 259 | ); |
| 260 | const interceptDispatch = options.dispatch; |
| 261 | const layerLaunchThreads = |
| 262 | interceptDispatch === undefined |
| 263 | ? layerThreadManagement |
| 264 | : Layer.effect( |
| 265 | ThreadManagement.ThreadManagementService, |
| 266 | Effect.gen(function* () { |
| 267 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 268 | return ThreadManagement.ThreadManagementService.of({ |
| 269 | ...threads, |
| 270 | dispatch: (command) => interceptDispatch(command, threads.dispatch), |
| 271 | }); |
| 272 | }), |
| 273 | ).pipe(Layer.provide(layerThreadManagement)); |
| 274 | const layerLaunch = ThreadLaunch.layer.pipe( |
| 275 | Layer.provide( |
| 276 | Layer.mergeAll( |
| 277 | layerExternalServices, |
| 278 | layerLaunchThreads, |
| 279 | layerReceipts, |
| 280 | layerOrchestrator, |
| 281 | IdAllocator.layer, |
| 282 | options.getLaunchSettings === undefined |
| 283 | ? Layer.empty |
| 284 | : Layer.mock(ServerSettings.ServerSettingsService)({ |
| 285 | getSettings: options.getLaunchSettings, |
| 286 | }), |
| 287 | ), |
| 288 | ), |
| 289 | ); |
| 290 | const layerProjectedProjects = Layer.mock(ProjectStore.ProjectStoreV2)({ |
| 291 | get: (requestedProjectId) => |
| 292 | Effect.succeed( |
| 293 | requestedProjectId === projectId |
| 294 | ? Option.some({ |
| 295 | projectId, |
| 296 | title: project.title, |
| 297 | workspaceRoot: project.workspaceRoot, |
| 298 | defaultModelSelection: project.defaultModelSelection, |
| 299 | defaultThreadEnvMode: null, |
| 300 | hasCustomTitle: false, |
| 301 | autoPull: false, |
| 302 | faviconPath: null, |
| 303 | projectIcon: null, |
| 304 | scripts: project.scripts, |
| 305 | pinnedAt: null, |
| 306 | archivedAt: null, |
| 307 | createdAt: project.createdAt, |
| 308 | updatedAt: project.updatedAt, |
| 309 | deletedAt: project.deletedAt, |
| 310 | }) |
| 311 | : Option.none(), |
| 312 | ), |
| 313 | }); |
| 314 | const layerTitleRegeneration = ThreadTitleRegeneration.layer.pipe( |
| 315 | Layer.provide( |
| 316 | Layer.mergeAll( |
| 317 | layerThreadManagement, |
| 318 | layerProjectedProjects, |
| 319 | layerExternalServices, |
| 320 | NodeServices.layer, |
| 321 | ), |
| 322 | ), |
| 323 | ); |
| 324 | return { |
| 325 | layer: Layer.mergeAll( |
| 326 | layerLaunch, |
| 327 | layerRegistry, |
| 328 | layerThreadManagement, |
| 329 | layerTitleRegeneration, |
| 330 | layerOutbox, |
| 331 | layerDatabase, |
| 332 | layerExternalServices, |
| 333 | ), |
| 334 | createWorktree, |
| 335 | removeWorktree, |
| 336 | deleteLocalBranch, |
| 337 | renameBranch, |
| 338 | generateBranchName, |
| 339 | generateThreadTitle, |
| 340 | runSetup, |
| 341 | closeTerminal, |
| 342 | }; |
| 343 | } |
| 344 | |
| 345 | function launchInput(input: { |
| 346 | readonly command: string; |
| 347 | readonly thread: string; |
| 348 | readonly message?: string; |
| 349 | readonly workspace?: ThreadLaunch.ThreadLaunchWorkspaceStrategy; |
| 350 | }) { |
| 351 | return { |
| 352 | commandId: CommandId.make(input.command), |
| 353 | threadId: ThreadId.make(input.thread), |
| 354 | projectId, |
| 355 | title: "New thread", |
| 356 | modelSelection, |
| 357 | runtimeMode: "full-access" as const, |
| 358 | interactionMode: "default" as const, |
| 359 | workspaceStrategy: input.workspace ?? { type: "root" as const }, |
| 360 | ...(input.message === undefined |
| 361 | ? {} |
| 362 | : { |
| 363 | initialMessage: { |
| 364 | messageId: MessageId.make(`${input.message}:id`), |
| 365 | text: input.message, |
| 366 | attachments: [], |
| 367 | }, |
| 368 | }), |
| 369 | createdBy: "user" as const, |
| 370 | creationSource: "web" as const, |
| 371 | }; |
| 372 | } |
| 373 | |
| 374 | it.effect.each( |
| 375 | (["new", "existing"] as const).flatMap((target) => |
| 376 | (["user", "agent"] as const).map((createdBy) => ({ target, createdBy })), |
| 377 | ), |
| 378 | )( |
| 379 | "attributes $createdBy-configured automations in $target threads without changing their prompt", |
| 380 | ({ target, createdBy }) => { |
| 381 | const harness = makeHarness(); |
| 382 | const layerScheduledTasks = ScheduledTasks.layer.pipe( |
| 383 | Layer.provide( |
| 384 | Layer.mergeAll( |
| 385 | harness.layer, |
| 386 | NodeCrypto.layer, |
| 387 | Scheduler.layer, |
| 388 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 389 | ManagedPolicy.layerTest(), |
| 390 | Layer.mock(RemoteDelegation.RemoteDelegation)({}), |
| 391 | ), |
| 392 | ), |
| 393 | ); |
| 394 | return Effect.gen(function* () { |
| 395 | const tasks = yield* ScheduledTasks.ScheduledTaskService; |
| 396 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 397 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 398 | const existing = |
| 399 | target === "existing" |
| 400 | ? yield* launches.launch( |
| 401 | launchInput({ command: "command:existing", thread: "thread:existing" }), |
| 402 | ) |
| 403 | : null; |
| 404 | const { task } = yield* tasks.upsert({ |
| 405 | id: ScheduledTaskId.make("scheduled-task:attribution"), |
| 406 | title: "Daily audit", |
| 407 | prompt: "Audit performance and crashes.", |
| 408 | enabled: false, |
| 409 | schedule: { type: "interval", everyMs: 60_000 }, |
| 410 | projectId, |
| 411 | threadId: existing?.threadId ?? null, |
| 412 | workspaceStrategy: { type: "root" }, |
| 413 | modelSelection, |
| 414 | runtimeMode: "full-access", |
| 415 | interactionMode: "default", |
| 416 | createdBy, |
| 417 | creationSource: createdBy === "agent" ? "mcp" : "web", |
| 418 | }); |
| 419 | const result = yield* tasks.runNow({ id: task.id }); |
| 420 | assert.equal(result.task.lastRunStatus, "succeeded"); |
| 421 | const projectThreads = yield* threads.listProjectThreads({ |
| 422 | projectId, |
| 423 | includeSubagents: false, |
| 424 | }); |
| 425 | const thread = |
| 426 | projectThreads.find((candidate) => candidate.id === existing?.threadId) ?? |
| 427 | projectThreads[0]; |
| 428 | assert.isDefined(thread); |
| 429 | assert.equal(result.threadId, thread!.id); |
| 430 | const projection = yield* threads.getThreadProjection(thread!.id); |
| 431 | const wire = yield* encodeThreadProjection(projection); |
| 432 | assert.equal(wire.messages[0]?.text, task.prompt); |
| 433 | assert.equal(wire.messages[0]?.scheduledTaskId, task.id); |
| 434 | assert.equal(wire.messages[0]?.createdBy, createdBy); |
| 435 | const turnItem = wire.turnItems.find( |
| 436 | (item): item is Extract<typeof item, { type: "user_message" }> => |
| 437 | item.type === "user_message", |
| 438 | ); |
| 439 | assert.equal(turnItem?.text, task.prompt); |
| 440 | assert.equal(turnItem?.scheduledTaskId, task.id); |
| 441 | }).pipe(Effect.provide(Layer.mergeAll(harness.layer, layerScheduledTasks))); |
| 442 | }, |
| 443 | ); |
| 444 | |
| 445 | it.effect( |
| 446 | "returns no dispatched thread when sending an automation to a missing thread fails", |
| 447 | () => { |
| 448 | const harness = makeHarness(); |
| 449 | const layerScheduledTasks = ScheduledTasks.layer.pipe( |
| 450 | Layer.provide( |
| 451 | Layer.mergeAll( |
| 452 | harness.layer, |
| 453 | NodeCrypto.layer, |
| 454 | Scheduler.layer, |
| 455 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 456 | ManagedPolicy.layerTest(), |
| 457 | ), |
| 458 | ), |
| 459 | ); |
| 460 | return Effect.gen(function* () { |
| 461 | const tasks = yield* ScheduledTasks.ScheduledTaskService; |
| 462 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 463 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 464 | const { threadId } = yield* launches.launch( |
| 465 | launchInput({ command: "command:missing", thread: "thread:missing" }), |
| 466 | ); |
| 467 | const { task } = yield* tasks.upsert({ |
| 468 | title: "Daily audit", |
| 469 | prompt: "Audit performance and crashes.", |
| 470 | enabled: false, |
| 471 | schedule: { type: "interval", everyMs: 60_000 }, |
| 472 | projectId, |
| 473 | threadId, |
| 474 | workspaceStrategy: { type: "root" }, |
| 475 | modelSelection, |
| 476 | runtimeMode: "full-access", |
| 477 | interactionMode: "default", |
| 478 | createdBy: "user", |
| 479 | creationSource: "web", |
| 480 | }); |
| 481 | yield* threads.dispatch({ |
| 482 | type: "thread.delete", |
| 483 | commandId: CommandId.make("command:missing:delete"), |
| 484 | threadId, |
| 485 | }); |
| 486 | const result = yield* tasks.runNow({ id: task.id }); |
| 487 | assert.equal(result.task.lastRunStatus, "failed"); |
| 488 | assert.isNull(result.threadId); |
| 489 | assert.equal(result.task.threadId, threadId); |
| 490 | }).pipe(Effect.provide(Layer.mergeAll(harness.layer, layerScheduledTasks))); |
| 491 | }, |
| 492 | ); |
| 493 | |
| 494 | it.effect("leaves a task delegated from a linked environment out of the top-level list", () => { |
| 495 | const harness = makeHarness(); |
| 496 | return Effect.gen(function* () { |
| 497 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 498 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 499 | yield* launches.launch( |
| 500 | launchInput({ command: "command:top-level", thread: "thread:top-level" }), |
| 501 | ); |
| 502 | const delegated = yield* launches.launch({ |
| 503 | ...launchInput({ command: "command:delegated", thread: "thread:delegated" }), |
| 504 | createdBy: "agent", |
| 505 | creationSource: "mcp", |
| 506 | linkOrigin: { sessionId: "mcp-session:linked", label: "Linked laptop" }, |
| 507 | delegatedFrom: { |
| 508 | environmentId: EnvironmentId.make("environment:linked"), |
| 509 | threadId: ThreadId.make("thread:remote-parent"), |
| 510 | title: "Remote parent", |
| 511 | }, |
| 512 | }); |
| 513 | const listed = yield* threads.listProjectThreads({ projectId, includeSubagents: false }); |
| 514 | assert.deepEqual( |
| 515 | listed.map((thread) => thread.id), |
| 516 | [ThreadId.make("thread:top-level")], |
| 517 | ); |
| 518 | const all = yield* threads.listProjectThreads({ projectId, includeSubagents: true }); |
| 519 | assert.include( |
| 520 | all.map((thread) => thread.id), |
| 521 | delegated.threadId, |
| 522 | ); |
| 523 | }).pipe(Effect.provide(harness.layer)); |
| 524 | }); |
| 525 | |
| 526 | it.effect("runs a thread-bound automation on the provider the thread uses now", () => { |
| 527 | const harness = makeHarness({ adapters: [adapter, claudeAdapter] }); |
| 528 | const layerScheduledTasks = ScheduledTasks.layer.pipe( |
| 529 | Layer.provide( |
| 530 | Layer.mergeAll( |
| 531 | harness.layer, |
| 532 | NodeCrypto.layer, |
| 533 | Scheduler.layer, |
| 534 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 535 | ManagedPolicy.layerTest(), |
| 536 | ), |
| 537 | ), |
| 538 | ); |
| 539 | return Effect.gen(function* () { |
| 540 | const tasks = yield* ScheduledTasks.ScheduledTaskService; |
| 541 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 542 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 543 | const launched = yield* launches.launch( |
| 544 | launchInput({ command: "command:switched", thread: "thread:switched" }), |
| 545 | ); |
| 546 | const { task } = yield* tasks.upsert({ |
| 547 | id: ScheduledTaskId.make("scheduled-task:switched"), |
| 548 | title: "Hourly check", |
| 549 | prompt: "Check on the delegated workers.", |
| 550 | enabled: false, |
| 551 | schedule: { type: "interval", everyMs: 3_600_000 }, |
| 552 | projectId, |
| 553 | threadId: launched.threadId, |
| 554 | workspaceStrategy: { type: "root" }, |
| 555 | modelSelection, |
| 556 | runtimeMode: "full-access", |
| 557 | interactionMode: "default", |
| 558 | createdBy: "agent", |
| 559 | creationSource: "mcp", |
| 560 | }); |
| 561 | yield* threads.dispatch({ |
| 562 | type: "thread.model-selection.set", |
| 563 | commandId: CommandId.make("command:switch-selection"), |
| 564 | threadId: launched.threadId, |
| 565 | modelSelection: claudeModelSelection, |
| 566 | }); |
| 567 | |
| 568 | const result = yield* tasks.runNow({ id: task.id }); |
| 569 | assert.equal(result.task.lastRunStatus, "succeeded"); |
| 570 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 571 | const message = projection.messages.find((item) => item.scheduledTaskId === task.id); |
| 572 | const run = projection.runs.find((item) => item.id === message?.runId); |
| 573 | assert.deepStrictEqual(run?.modelSelection, claudeModelSelection); |
| 574 | assert.deepStrictEqual(projection.thread.modelSelection, claudeModelSelection); |
| 575 | }).pipe(Effect.provide(Layer.mergeAll(harness.layer, layerScheduledTasks))); |
| 576 | }); |
| 577 | |
| 578 | it.effect("retains automation and sender attribution while a message waits in the queue", () => { |
| 579 | const harness = makeHarness({ runSetup: () => Effect.never }); |
| 580 | return Effect.gen(function* () { |
| 581 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 582 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 583 | const launched = yield* launches.launch( |
| 584 | launchInput({ |
| 585 | command: "command:automation:queue", |
| 586 | thread: "thread:automation:queue", |
| 587 | message: "First message", |
| 588 | workspace: { type: "worktree", baseRef: "main" }, |
| 589 | }), |
| 590 | ); |
| 591 | const scheduledTaskId = ScheduledTaskId.make("scheduled-task:queued"); |
| 592 | const senderThreadId = ThreadId.make("thread:agent-sender"); |
| 593 | const queued = yield* threads.sendToThread({ |
| 594 | projectId, |
| 595 | commandId: CommandId.make("command:automation:queued"), |
| 596 | threadId: launched.threadId, |
| 597 | messageId: MessageId.make("message:automation:queued"), |
| 598 | scheduledTaskId, |
| 599 | senderThreadId, |
| 600 | text: "Run the audit", |
| 601 | attachments: [], |
| 602 | mode: "queue", |
| 603 | createdBy: "agent", |
| 604 | creationSource: "mcp", |
| 605 | }); |
| 606 | assert.equal(queued.delivery, "queued"); |
| 607 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 608 | const message = projection.messages.find((item) => item.id === queued.message.id); |
| 609 | assert.equal(message?.scheduledTaskId, scheduledTaskId); |
| 610 | assert.equal(message?.senderThreadId, senderThreadId); |
| 611 | assert.equal(message?.text, "Run the audit"); |
| 612 | // A fresh send queues instead of steering, so it needs no steerable run. |
| 613 | const fresh = yield* threads.sendToThread({ |
| 614 | projectId, |
| 615 | commandId: CommandId.make("command:automation:queued-fresh"), |
| 616 | threadId: launched.threadId, |
| 617 | messageId: MessageId.make("message:automation:queued-fresh"), |
| 618 | text: "Start over", |
| 619 | attachments: [], |
| 620 | mode: "steer", |
| 621 | freshContext: true, |
| 622 | createdBy: "agent", |
| 623 | creationSource: "mcp", |
| 624 | }); |
| 625 | assert.equal(fresh.delivery, "queued"); |
| 626 | assert.isTrue(fresh.run.freshContext); |
| 627 | }).pipe(Effect.provide(harness.layer)); |
| 628 | }); |
| 629 | |
| 630 | it.effect("a run asked for a result stores what its agent submits once it fits the schema", () => { |
| 631 | const harness = makeHarness({ runSetup: () => Effect.never }); |
| 632 | const outputSchema = { |
| 633 | type: "object", |
| 634 | properties: { verdict: { enum: ["merge", "fix-first"] } }, |
| 635 | required: ["verdict"], |
| 636 | }; |
| 637 | return Effect.gen(function* () { |
| 638 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 639 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 640 | const input = launchInput({ |
| 641 | command: "command:output:launch", |
| 642 | thread: "thread:output", |
| 643 | message: "Review it", |
| 644 | workspace: { type: "worktree", baseRef: "main" }, |
| 645 | }); |
| 646 | const launched = yield* launches.launch({ |
| 647 | ...input, |
| 648 | initialMessage: { ...input.initialMessage!, outputSchema }, |
| 649 | }); |
| 650 | const submit = (command: string, json: string) => |
| 651 | threads.submitRunOutput({ |
| 652 | threadId: launched.threadId, |
| 653 | commandId: CommandId.make(command), |
| 654 | json, |
| 655 | }); |
| 656 | |
| 657 | const rejected = yield* submit("command:output:bad", '{"verdict":"maybe"}').pipe(Effect.flip); |
| 658 | assert.equal(rejected._tag, "ThreadManagementRunOutputRejectedError"); |
| 659 | // What did not fit is kept as the cause, for the agent that wrote it and nobody's logs. |
| 660 | assert.equal(rejected.message, "The result does not match the schema."); |
| 661 | assert.include( |
| 662 | String((rejected as { cause?: { message?: string } }).cause?.message), |
| 663 | "verdict", |
| 664 | ); |
| 665 | const unparsed = yield* submit("command:output:text", "merge").pipe(Effect.flip); |
| 666 | assert.include(unparsed.message, "not valid JSON"); |
| 667 | |
| 668 | const accepted = yield* submit("command:output:good", '{"verdict":"merge","note":"kept"}'); |
| 669 | const stored = (yield* threads.getThreadProjection(launched.threadId)).runs.find( |
| 670 | (run) => run.id === accepted.runId, |
| 671 | ); |
| 672 | assert.deepStrictEqual(stored?.outputSchema, outputSchema); |
| 673 | // Kept as submitted, including what the schema does not name. |
| 674 | assert.deepStrictEqual(stored?.output?.value, { verdict: "merge", note: "kept" }); |
| 675 | |
| 676 | // Asking for a result never joins the running turn, and a plain turn has nothing to submit to. |
| 677 | const next = yield* threads.sendToThread({ |
| 678 | projectId, |
| 679 | commandId: CommandId.make("command:output:next"), |
| 680 | threadId: launched.threadId, |
| 681 | messageId: MessageId.make("message:output:next"), |
| 682 | text: "Review it again", |
| 683 | attachments: [], |
| 684 | mode: "steer", |
| 685 | outputSchema, |
| 686 | createdBy: "agent", |
| 687 | creationSource: "mcp", |
| 688 | }); |
| 689 | assert.equal(next.delivery, "queued"); |
| 690 | assert.deepStrictEqual(next.run.outputSchema, outputSchema); |
| 691 | assert.isUndefined(next.run.output); |
| 692 | const unusable = yield* threads |
| 693 | .sendToThread({ |
| 694 | projectId, |
| 695 | commandId: CommandId.make("command:output:unusable"), |
| 696 | threadId: launched.threadId, |
| 697 | messageId: MessageId.make("message:output:unusable"), |
| 698 | text: "Review it again", |
| 699 | attachments: [], |
| 700 | mode: "queue", |
| 701 | outputSchema: { $ref: "#/$defs/Missing" }, |
| 702 | createdBy: "agent", |
| 703 | creationSource: "mcp", |
| 704 | }) |
| 705 | .pipe(Effect.result); |
| 706 | assert.isTrue(Result.isFailure(unusable)); |
| 707 | }).pipe(Effect.provide(harness.layer)); |
| 708 | }); |
| 709 | |
| 710 | it.effect("a run that was not asked for a result rejects a submission", () => { |
| 711 | const harness = makeHarness({ runSetup: () => Effect.never }); |
| 712 | return Effect.gen(function* () { |
| 713 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 714 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 715 | const launched = yield* launches.launch( |
| 716 | launchInput({ |
| 717 | command: "command:no-output:launch", |
| 718 | thread: "thread:no-output", |
| 719 | message: "Just talk", |
| 720 | workspace: { type: "worktree", baseRef: "main" }, |
| 721 | }), |
| 722 | ); |
| 723 | const rejected = yield* threads |
| 724 | .submitRunOutput({ |
| 725 | threadId: launched.threadId, |
| 726 | commandId: CommandId.make("command:no-output:submit"), |
| 727 | json: "{}", |
| 728 | }) |
| 729 | .pipe(Effect.flip); |
| 730 | assert.include(rejected.message, "not asked for a result"); |
| 731 | }).pipe(Effect.provide(harness.layer)); |
| 732 | }); |
| 733 | |
| 734 | it.effect("provisions independent launches concurrently instead of behind a global semaphore", () => |
| 735 | Effect.gen(function* () { |
| 736 | const setupCount = yield* Ref.make(0); |
| 737 | const bothEntered = yield* Deferred.make<void>(); |
| 738 | const allowSetup = yield* Deferred.make<void>(); |
| 739 | const harness = makeHarness({ |
| 740 | runSetup: () => |
| 741 | Ref.updateAndGet(setupCount, (count) => count + 1).pipe( |
| 742 | Effect.tap((count) => |
| 743 | count === 2 ? Deferred.succeed(bothEntered, undefined) : Effect.void, |
| 744 | ), |
| 745 | Effect.andThen(Deferred.await(allowSetup)), |
| 746 | Effect.as({ status: "no-script" as const }), |
| 747 | ), |
| 748 | }); |
| 749 | yield* Effect.gen(function* () { |
| 750 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 751 | const results = yield* Effect.all( |
| 752 | [ |
| 753 | launches.launch( |
| 754 | launchInput({ |
| 755 | command: "command:launch:concurrent-a", |
| 756 | thread: "thread:launch:concurrent-a", |
| 757 | message: "First", |
| 758 | workspace: { type: "worktree", baseRef: "main" }, |
| 759 | }), |
| 760 | ), |
| 761 | launches.launch( |
| 762 | launchInput({ |
| 763 | command: "command:launch:concurrent-b", |
| 764 | thread: "thread:launch:concurrent-b", |
| 765 | message: "Second", |
| 766 | workspace: { type: "worktree", baseRef: "main" }, |
| 767 | }), |
| 768 | ), |
| 769 | ], |
| 770 | { concurrency: "unbounded" }, |
| 771 | ); |
| 772 | assert.deepEqual( |
| 773 | results.map((result) => result.projection.runs[0]?.status), |
| 774 | ["preparing", "preparing"], |
| 775 | ); |
| 776 | yield* Deferred.await(bothEntered); |
| 777 | assert.equal(yield* Ref.get(setupCount), 2); |
| 778 | yield* Deferred.succeed(allowSetup, undefined); |
| 779 | }).pipe(Effect.provide(harness.layer)); |
| 780 | }), |
| 781 | ); |
| 782 | |
| 783 | it.effect.each([" /COMPACT "])( |
| 784 | "uses the first conversation message for a title after %s", |
| 785 | (nativeCommand) => |
| 786 | Effect.gen(function* () { |
| 787 | const harness = makeHarness(); |
| 788 | yield* Effect.gen(function* () { |
| 789 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 790 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 791 | const outbox = yield* EffectOutbox.EffectOutboxV2; |
| 792 | const launched = yield* launches.launch({ |
| 793 | ...launchInput({ |
| 794 | command: "compact-title", |
| 795 | thread: "compact-title-thread", |
| 796 | message: nativeCommand, |
| 797 | }), |
| 798 | generateTitle: true, |
| 799 | }); |
| 800 | assert.isUndefined( |
| 801 | (yield* threads.getThreadProjection(launched.threadId)).thread.titleRegeneration, |
| 802 | ); |
| 803 | assert.isNull((yield* threads.getThreadProjection(launched.threadId)).thread.lastVisitedAt); |
| 804 | assert.isFalse( |
| 805 | (yield* outbox.listByCommandId(CommandId.make("compact-title"))).some( |
| 806 | (effect) => effect.request.type === "thread-title.generate", |
| 807 | ), |
| 808 | ); |
| 809 | const commandId = CommandId.make("compact-title-conversation"); |
| 810 | const messageId = MessageId.make("compact-title-conversation-message"); |
| 811 | yield* threads.dispatch({ |
| 812 | type: "message.dispatch", |
| 813 | commandId, |
| 814 | threadId: launched.threadId, |
| 815 | messageId, |
| 816 | createdBy: "user", |
| 817 | creationSource: "web", |
| 818 | text: "Fix the failing parser", |
| 819 | attachments: [], |
| 820 | dispatchMode: { type: "defer_start" }, |
| 821 | }); |
| 822 | assert.equal( |
| 823 | (yield* threads.getThreadProjection(launched.threadId)).thread.titleRegeneration |
| 824 | ?.requestId, |
| 825 | commandId, |
| 826 | ); |
| 827 | assert.deepEqual( |
| 828 | (yield* outbox.listByCommandId(commandId)) |
| 829 | .filter((effect) => effect.request.type === "thread-title.generate") |
| 830 | .map((effect) => effect.request), |
| 831 | [{ type: "thread-title.generate", kind: { type: "initial", messageId } }], |
| 832 | ); |
| 833 | }).pipe(Effect.provide(harness.layer)); |
| 834 | }), |
| 835 | ); |
| 836 | |
| 837 | it.effect("keeps native maintenance commands out of steering and restart messages", () => |
| 838 | Effect.gen(function* () { |
| 839 | const harness = makeHarness(); |
| 840 | yield* Effect.gen(function* () { |
| 841 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 842 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 843 | const outbox = yield* EffectOutbox.EffectOutboxV2; |
| 844 | for (const scenario of [ |
| 845 | { |
| 846 | name: "compact-steer", |
| 847 | first: "Fix the parser", |
| 848 | next: " /COMPACT ", |
| 849 | mode: "steer_active", |
| 850 | }, |
| 851 | { |
| 852 | name: "compact-restart", |
| 853 | first: "Fix the parser", |
| 854 | next: "/compact", |
| 855 | mode: "restart_active", |
| 856 | }, |
| 857 | { |
| 858 | name: "logout-steer", |
| 859 | first: "Fix the parser", |
| 860 | next: "/logout", |
| 861 | mode: "steer_active", |
| 862 | }, |
| 863 | { |
| 864 | name: "logout-restart", |
| 865 | first: "Fix the parser", |
| 866 | next: "/logout", |
| 867 | mode: "restart_active", |
| 868 | }, |
| 869 | { |
| 870 | name: "steer-logout", |
| 871 | first: "/logout", |
| 872 | next: "Continue with the parser", |
| 873 | mode: "steer_active", |
| 874 | }, |
| 875 | { |
| 876 | name: "steer-compaction", |
| 877 | first: "/compact", |
| 878 | next: "Continue with the parser", |
| 879 | mode: "steer_active", |
| 880 | }, |
| 881 | ] as const) { |
| 882 | const launched = yield* launches.launch( |
| 883 | launchInput({ |
| 884 | command: `${scenario.name}:launch`, |
| 885 | thread: scenario.name, |
| 886 | message: scenario.first, |
| 887 | }), |
| 888 | ); |
| 889 | const before = yield* threads.getThreadProjection(launched.threadId); |
| 890 | const targetRun = before.runs[0]; |
| 891 | if (targetRun === undefined) return yield* Effect.die("Launch must create a run"); |
| 892 | const commandId = CommandId.make(`${scenario.name}:message`); |
| 893 | const dispatch = threads.dispatch({ |
| 894 | type: "message.dispatch", |
| 895 | commandId, |
| 896 | threadId: launched.threadId, |
| 897 | messageId: MessageId.make(`${scenario.name}:message`), |
| 898 | createdBy: "user", |
| 899 | creationSource: "web", |
| 900 | text: scenario.next, |
| 901 | attachments: [], |
| 902 | dispatchMode: { type: scenario.mode, targetRunId: targetRun.id }, |
| 903 | }); |
| 904 | if (scenario.name.startsWith("steer-")) { |
| 905 | yield* dispatch; |
| 906 | const queued = (yield* threads.getThreadProjection(launched.threadId)).runs[1]; |
| 907 | assert.equal(queued?.status, "queued"); |
| 908 | assert.equal(queued?.userMessageId, MessageId.make(`${scenario.name}:message`)); |
| 909 | continue; |
| 910 | } |
| 911 | const failure = yield* dispatch.pipe(Effect.flip); |
| 912 | assert.include( |
| 913 | String(failure.cause).toLowerCase(), |
| 914 | scenario.name.includes("logout") ? "sign" : "context compaction", |
| 915 | ); |
| 916 | const after = yield* threads.getThreadProjection(launched.threadId); |
| 917 | assert.deepEqual(after.messages, before.messages); |
| 918 | assert.deepEqual(after.thread.titleRegeneration, before.thread.titleRegeneration); |
| 919 | assert.deepEqual(yield* outbox.listByCommandId(commandId), []); |
| 920 | } |
| 921 | }).pipe(Effect.provide(harness.layer)); |
| 922 | }), |
| 923 | ); |
| 924 | |
| 925 | it.effect("arms durable title generation after accepting the first message", () => |
| 926 | Effect.gen(function* () { |
| 927 | const harness = makeHarness({ |
| 928 | generateTitle: (input) => |
| 929 | Effect.succeed({ |
| 930 | title: input.previousTitle === undefined ? "Generated title" : "Regenerated title", |
| 931 | }), |
| 932 | }); |
| 933 | yield* Effect.gen(function* () { |
| 934 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 935 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 936 | const outbox = yield* EffectOutbox.EffectOutboxV2; |
| 937 | const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 938 | const input = { |
| 939 | ...launchInput({ |
| 940 | command: "command:launch:title-generation", |
| 941 | thread: "thread:launch:title-generation", |
| 942 | message: "Generate my title", |
| 943 | }), |
| 944 | title: "Generate my title", |
| 945 | generateTitle: true, |
| 946 | }; |
| 947 | const launched = yield* launches.launch(input); |
| 948 | const generationCommandId = input.commandId; |
| 949 | |
| 950 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 951 | assert.equal(projection.thread.title, "Generate my title"); |
| 952 | assert.equal(projection.thread.titleRegeneration?.requestId, generationCommandId); |
| 953 | assert.deepEqual( |
| 954 | (yield* outbox.listByCommandId(generationCommandId)).map((effect) => effect.request), |
| 955 | [ |
| 956 | { |
| 957 | type: "thread-title.generate", |
| 958 | kind: { type: "initial", messageId: MessageId.make("Generate my title:id") }, |
| 959 | }, |
| 960 | ], |
| 961 | ); |
| 962 | yield* titleRegeneration.execute({ |
| 963 | threadId: launched.threadId, |
| 964 | requestId: generationCommandId, |
| 965 | kind: { type: "initial", messageId: MessageId.make("Generate my title:id") }, |
| 966 | }); |
| 967 | const generated = yield* threads.getThreadProjection(launched.threadId); |
| 968 | assert.equal(generated.thread.title, "Generated title"); |
| 969 | assert.deepEqual( |
| 970 | harness.generateThreadTitle.mock.calls[0]?.[0]?.modelSelection, |
| 971 | DEFAULT_SERVER_SETTINGS.textGenerationModelSelection, |
| 972 | ); |
| 973 | |
| 974 | const manualRequestId = CommandId.make("command:title-generation:manual"); |
| 975 | yield* threads.dispatch({ |
| 976 | type: "thread.metadata.update", |
| 977 | commandId: manualRequestId, |
| 978 | threadId: launched.threadId, |
| 979 | regenerateTitle: true, |
| 980 | }); |
| 981 | assert.deepEqual( |
| 982 | (yield* outbox.listByCommandId(manualRequestId)).map((effect) => effect.request), |
| 983 | [{ type: "thread-title.generate", kind: { type: "regenerate" } }], |
| 984 | ); |
| 985 | yield* titleRegeneration.execute({ |
| 986 | threadId: launched.threadId, |
| 987 | requestId: manualRequestId, |
| 988 | kind: { type: "regenerate" }, |
| 989 | }); |
| 990 | const regenerated = yield* threads.getThreadProjection(launched.threadId); |
| 991 | assert.equal(regenerated.thread.title, "Regenerated title"); |
| 992 | assert.equal( |
| 993 | harness.generateThreadTitle.mock.calls[1]?.[0]?.previousTitle, |
| 994 | "Generated title", |
| 995 | ); |
| 996 | |
| 997 | yield* threads.dispatch({ |
| 998 | type: "thread.metadata.update", |
| 999 | commandId: CommandId.make("command:title-generation:user-rename"), |
| 1000 | threadId: launched.threadId, |
| 1001 | title: "Keep my title", |
| 1002 | }); |
| 1003 | const renamed = yield* threads.getThreadProjection(launched.threadId); |
| 1004 | yield* TestClock.adjust(Duration.seconds(1)); |
| 1005 | yield* threads.dispatch({ |
| 1006 | type: "thread.title.regeneration.complete", |
| 1007 | commandId: CommandId.make("command:title-generation:stale-completion"), |
| 1008 | threadId: launched.threadId, |
| 1009 | requestId: generationCommandId, |
| 1010 | title: "Stale generated title", |
| 1011 | }); |
| 1012 | const afterStaleCompletion = yield* threads.getThreadProjection(launched.threadId); |
| 1013 | assert.equal(afterStaleCompletion.thread.title, "Keep my title"); |
| 1014 | assert.equal( |
| 1015 | DateTime.toEpochMillis(afterStaleCompletion.thread.updatedAt), |
| 1016 | DateTime.toEpochMillis(renamed.thread.updatedAt), |
| 1017 | ); |
| 1018 | }).pipe(Effect.provide(harness.layer)); |
| 1019 | }), |
| 1020 | ); |
| 1021 | |
| 1022 | it.effect("a rejected initial message leaves no title change and no new thread", () => |
| 1023 | Effect.gen(function* () { |
| 1024 | const harness = makeHarness({ adapters: [adapter, claudeAdapter] }); |
| 1025 | yield* Effect.gen(function* () { |
| 1026 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1027 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 1028 | const outbox = yield* EffectOutbox.EffectOutboxV2; |
| 1029 | const threadId = ThreadId.make("thread:launch:reused-title-failure"); |
| 1030 | yield* threads.dispatch({ |
| 1031 | type: "thread.create", |
| 1032 | commandId: CommandId.make("command:launch:reused-title-failure:create"), |
| 1033 | threadId, |
| 1034 | projectId, |
| 1035 | title: "Original title", |
| 1036 | modelSelection, |
| 1037 | runtimeMode: "full-access", |
| 1038 | interactionMode: "default", |
| 1039 | branch: null, |
| 1040 | worktreePath: null, |
| 1041 | createdBy: "user", |
| 1042 | creationSource: "web", |
| 1043 | }); |
| 1044 | |
| 1045 | const commandId = CommandId.make("command:launch:reused-title-failure"); |
| 1046 | const failed = yield* launches |
| 1047 | .launch({ |
| 1048 | ...launchInput({ |
| 1049 | command: commandId, |
| 1050 | thread: threadId, |
| 1051 | message: "Generate a provisional title", |
| 1052 | }), |
| 1053 | reuseExistingThread: true, |
| 1054 | title: "Generate a provisional title", |
| 1055 | generateTitle: true, |
| 1056 | modelSelection: { |
| 1057 | instanceId: ProviderInstanceId.make("missing-provider"), |
| 1058 | model: "missing-model", |
| 1059 | }, |
| 1060 | }) |
| 1061 | .pipe(Effect.exit); |
| 1062 | |
| 1063 | assert.isTrue(Exit.isFailure(failed)); |
| 1064 | const projection = yield* threads.getThreadProjection(threadId); |
| 1065 | assert.equal(projection.thread.title, "Original title"); |
| 1066 | assert.isUndefined(projection.thread.titleRegeneration); |
| 1067 | assert.isEmpty(projection.messages); |
| 1068 | assert.isEmpty(yield* outbox.listByCommandId(CommandId.make(`${commandId}:initial-message`))); |
| 1069 | |
| 1070 | // The orchestrator refuses this goal command, after the launch's own checks pass. |
| 1071 | const newThreadId = ThreadId.make("thread:launch:rejected-new-thread"); |
| 1072 | const rejected = yield* launches |
| 1073 | .launch({ |
| 1074 | ...launchInput({ |
| 1075 | command: "command:launch:rejected-new-thread", |
| 1076 | thread: newThreadId, |
| 1077 | message: "/goal pause", |
| 1078 | }), |
| 1079 | modelSelection: claudeModelSelection, |
| 1080 | }) |
| 1081 | .pipe(Effect.flip); |
| 1082 | if (rejected._tag !== "ThreadLaunchError") { |
| 1083 | assert.fail(`expected ThreadLaunchError, got ${rejected._tag}`); |
| 1084 | } |
| 1085 | assert.equal(rejected.operation, "create-thread"); |
| 1086 | assert.isNull(yield* threads.getThreadShell(newThreadId)); |
| 1087 | }).pipe(Effect.provide(harness.layer)); |
| 1088 | }), |
| 1089 | ); |
| 1090 | |
| 1091 | // Stands `projectId` in for a plain folder, not a Git repository, so Git fails |
| 1092 | // there with the error a real one raises. It is the Scratch project unless |
| 1093 | // `scratch` is false. |
| 1094 | function scratchHarness({ scratch = true }: { readonly scratch?: boolean } = {}) { |
| 1095 | const claimed: Array<ThreadId> = []; |
| 1096 | const scratchRoot = project.workspaceRoot; |
| 1097 | const notARepository = (operation: string, cwd: string) => |
| 1098 | new GitCommandError({ |
| 1099 | operation, |
| 1100 | command: "vcs-route", |
| 1101 | cwd, |
| 1102 | detail: "Failed to resolve the VCS driver for this Git command.", |
| 1103 | }); |
| 1104 | const harness = makeHarness({ |
| 1105 | managedFolders: Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ |
| 1106 | namedProjectsRoot: "/projects", |
| 1107 | isScratchProject: (id) => Effect.succeed(scratch && id === projectId), |
| 1108 | folderForThread: (input) => |
| 1109 | Effect.sync(() => { |
| 1110 | if (!scratch || input.projectId !== projectId) return Option.none(); |
| 1111 | claimed.push(input.threadId); |
| 1112 | return Option.some(`/scratch/folder-${claimed.length}`); |
| 1113 | }), |
| 1114 | }), |
| 1115 | git: { repositoryRoot: (cwd) => Effect.succeed(cwd === scratchRoot ? null : cwd) }, |
| 1116 | // The other project is a repository Git cannot read, which must not count as none. |
| 1117 | isGitRepository: (cwd) => |
| 1118 | cwd === scratchRoot |
| 1119 | ? Effect.succeed(false) |
| 1120 | : Effect.fail( |
| 1121 | new VcsProcessExitError({ |
| 1122 | operation: "GitVcsDriver.probeWorkTree", |
| 1123 | command: "git rev-parse", |
| 1124 | cwd, |
| 1125 | exitCode: 128, |
| 1126 | detail: "fatal: bad config line 1", |
| 1127 | }), |
| 1128 | ), |
| 1129 | remoteExists: (input) => |
| 1130 | input.cwd === scratchRoot |
| 1131 | ? Effect.fail(notARepository("GitWorkflowService.remoteExists", input.cwd)) |
| 1132 | : Effect.succeed(true), |
| 1133 | createWorktree: (input) => |
| 1134 | input.cwd === scratchRoot |
| 1135 | ? Effect.fail(notARepository("GitWorkflowService.createWorktree", input.cwd)) |
| 1136 | : Effect.succeed({ |
| 1137 | worktree: { |
| 1138 | path: "/other-repo-worktrees/feature", |
| 1139 | refName: input.newRefName, |
| 1140 | headSha: "abc", |
| 1141 | }, |
| 1142 | } as never), |
| 1143 | }); |
| 1144 | const layerScheduledTasks = ScheduledTasks.layer.pipe( |
| 1145 | Layer.provide( |
| 1146 | Layer.mergeAll( |
| 1147 | harness.layer, |
| 1148 | NodeCrypto.layer, |
| 1149 | Scheduler.layer, |
| 1150 | Layer.mock(SecretRequests.SecretRequests)({}), |
| 1151 | ManagedPolicy.layerTest(), |
| 1152 | ), |
| 1153 | ), |
| 1154 | ); |
| 1155 | return { |
| 1156 | ...harness, |
| 1157 | claimed, |
| 1158 | layer: Layer.mergeAll(harness.layer, layerScheduledTasks), |
| 1159 | }; |
| 1160 | } |
| 1161 | |
| 1162 | const worktreeStrategy = { type: "worktree", baseRef: "main", startFromOrigin: true } as const; |
| 1163 | |
| 1164 | /** Settles once preparation releases the run, or fails it. */ |
| 1165 | const preparationSettled = (threadId: ThreadId) => |
| 1166 | Effect.gen(function* () { |
| 1167 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 1168 | yield* threads.streamStoredEventsFrom({ threadId }).pipe( |
| 1169 | Stream.filter( |
| 1170 | (stored) => |
| 1171 | stored.event.type === "run.updated" && |
| 1172 | (stored.commandId?.endsWith(":release") === true || |
| 1173 | stored.event.payload.status === "failed"), |
| 1174 | ), |
| 1175 | Stream.runHead, |
| 1176 | ); |
| 1177 | return yield* threads.getThreadProjection(threadId); |
| 1178 | }); |
| 1179 | |
| 1180 | it.effect.each([ |
| 1181 | { prefix: "my-prefix", collision: null, expected: /^my-prefix\/[0-9a-f]{8}$/ }, |
| 1182 | { prefix: "my-prefix", collision: "my-prefix", expected: /^my-prefix-[0-9a-f]{8}$/ }, |
| 1183 | { prefix: "team/topic", collision: "team", expected: /^team-topic-[0-9a-f]{8}$/ }, |
| 1184 | ])("keeps prefix '$prefix' with collision '$collision' when naming fails", (scenario) => |
| 1185 | Effect.gen(function* () { |
| 1186 | const namingAttempted = yield* Deferred.make<void>(); |
| 1187 | const harness = makeHarness({ |
| 1188 | serverSettings: { |
| 1189 | branchNamePrefix: "global-prefix", |
| 1190 | projectSettingsOverrides: { |
| 1191 | [projectId]: { branchNamingMode: "static", branchNamePrefix: scenario.prefix }, |
| 1192 | }, |
| 1193 | }, |
| 1194 | hasCommit: ({ refName }) => Effect.succeed(refName === `refs/heads/${scenario.collision}`), |
| 1195 | generateBranchName: () => |
| 1196 | Deferred.succeed(namingAttempted, undefined).pipe( |
| 1197 | Effect.andThen( |
| 1198 | Effect.fail( |
| 1199 | new TextGenerationError({ operation: "generateBranchName", detail: "Unavailable" }), |
| 1200 | ), |
| 1201 | ), |
| 1202 | ), |
| 1203 | }); |
| 1204 | yield* Effect.gen(function* () { |
| 1205 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1206 | const launched = yield* launches.launch( |
| 1207 | launchInput({ |
| 1208 | command: "prefix-launch", |
| 1209 | thread: "prefix-thread", |
| 1210 | message: "Fix the parser", |
| 1211 | workspace: { type: "worktree", baseRef: "main" }, |
| 1212 | }), |
| 1213 | ); |
| 1214 | const projection = yield* preparationSettled(launched.threadId); |
| 1215 | assert.match(projection.thread.branch!, scenario.expected); |
| 1216 | yield* Deferred.await(namingAttempted); |
| 1217 | assert.equal(projection.runs[0]?.status, "starting"); |
| 1218 | assert.equal(harness.createWorktree.mock.calls[0]?.[0]?.newRefName, projection.thread.branch); |
| 1219 | assert.equal(harness.renameBranch.mock.calls.length, 0); |
| 1220 | assert.isFalse(projection.turnItems.some((item) => item.type === "error")); |
| 1221 | }).pipe(Effect.provide(harness.layer)); |
| 1222 | }), |
| 1223 | ); |
| 1224 | |
| 1225 | it.effect( |
| 1226 | "starts a worktree with the default temporary name when settings secrets cannot be read", |
| 1227 | () => { |
| 1228 | const harness = makeHarness({ |
| 1229 | getLaunchSettings: Effect.fail( |
| 1230 | new ServerSettingsError({ settingsPath: "/settings.json", operation: "read-secret" }), |
| 1231 | ), |
| 1232 | }); |
| 1233 | return Effect.gen(function* () { |
| 1234 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1235 | const launched = yield* launches.launch( |
| 1236 | launchInput({ |
| 1237 | command: "settings-fallback", |
| 1238 | thread: "settings-fallback-thread", |
| 1239 | message: "Fix the parser", |
| 1240 | workspace: { type: "worktree", baseRef: "main" }, |
| 1241 | }), |
| 1242 | ); |
| 1243 | const projection = yield* preparationSettled(launched.threadId); |
| 1244 | assert.equal(projection.runs[0]?.status, "starting"); |
| 1245 | assert.match(projection.thread.branch!, /^t3\/[0-9a-f]{8}$/); |
| 1246 | assert.equal(harness.createWorktree.mock.calls[0]?.[0]?.newRefName, projection.thread.branch); |
| 1247 | assert.equal(harness.runSetup.mock.calls.length, 1); |
| 1248 | assert.equal(harness.renameBranch.mock.calls.length, 0); |
| 1249 | assert.isFalse(projection.turnItems.some((item) => item.type === "error")); |
| 1250 | }).pipe(Effect.provide(harness.layer)); |
| 1251 | }, |
| 1252 | ); |
| 1253 | |
| 1254 | it.effect("renames a temporary branch with a configured prefix when generation succeeds", () => { |
| 1255 | const harness = makeHarness({ |
| 1256 | serverSettings: { branchNamingMode: "static", branchNamePrefix: "my-prefix" }, |
| 1257 | generateBranchName: () => Effect.succeed({ branch: "my-prefix/fix-parser" }), |
| 1258 | }); |
| 1259 | return Effect.gen(function* () { |
| 1260 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1261 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 1262 | const launched = yield* launches.launch( |
| 1263 | launchInput({ |
| 1264 | command: "prefix-rename", |
| 1265 | thread: "prefix-rename-thread", |
| 1266 | message: "Fix the parser", |
| 1267 | workspace: { type: "worktree", baseRef: "main" }, |
| 1268 | }), |
| 1269 | ); |
| 1270 | yield* threads.streamStoredEventsFrom({ threadId: launched.threadId }).pipe( |
| 1271 | Stream.filter((stored) => stored.commandId === "prefix-rename:branch-rename"), |
| 1272 | Stream.runHead, |
| 1273 | ); |
| 1274 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 1275 | assert.equal(projection.thread.branch, "my-prefix/fix-parser"); |
| 1276 | assert.match( |
| 1277 | harness.renameBranch.mock.calls[0]?.[0]?.oldBranch ?? "", |
| 1278 | /^my-prefix\/[0-9a-f]{8}$/, |
| 1279 | ); |
| 1280 | }).pipe(Effect.provide(harness.layer)); |
| 1281 | }); |
| 1282 | |
| 1283 | function scheduledTaskInput(id: string, targetProjectId: ProjectId) { |
| 1284 | return { |
| 1285 | id: ScheduledTaskId.make(id), |
| 1286 | title: "Daily summary", |
| 1287 | prompt: "Summarize the day.", |
| 1288 | enabled: false, |
| 1289 | schedule: { type: "interval" as const, everyMs: 60_000 }, |
| 1290 | projectId: targetProjectId, |
| 1291 | threadId: null, |
| 1292 | workspaceStrategy: worktreeStrategy, |
| 1293 | modelSelection, |
| 1294 | runtimeMode: "full-access" as const, |
| 1295 | interactionMode: "default" as const, |
| 1296 | }; |
| 1297 | } |
| 1298 | |
| 1299 | it.effect("records the checkout's branch on a root launch that names none", () => { |
| 1300 | const harness = makeHarness({ |
| 1301 | git: { currentBranch: () => Effect.succeed("fix/checkout-total") }, |
| 1302 | }); |
| 1303 | return Effect.gen(function* () { |
| 1304 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1305 | const launched = yield* launches.launch( |
| 1306 | launchInput({ command: "command:launch:root-branch", thread: "thread:launch:root-branch" }), |
| 1307 | ); |
| 1308 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 1309 | const { thread } = yield* threads.getThreadProjection(launched.threadId); |
| 1310 | assert.equal(thread.branch, "fix/checkout-total"); |
| 1311 | }).pipe(Effect.provide(harness.layer)); |
| 1312 | }); |
| 1313 | |
| 1314 | it.effect("launches a worktree request for Scratch at the root, in its own folder", () => { |
| 1315 | const harness = scratchHarness(); |
| 1316 | return Effect.gen(function* () { |
| 1317 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1318 | yield* launches.checkWorktreeBase({ projectId, workspaceStrategy: worktreeStrategy }); |
| 1319 | const launched = yield* launches.launch( |
| 1320 | launchInput({ |
| 1321 | command: "command:launch:scratch-worktree", |
| 1322 | thread: "thread:launch:scratch-worktree", |
| 1323 | message: "Tidy my notes", |
| 1324 | workspace: worktreeStrategy, |
| 1325 | }), |
| 1326 | ); |
| 1327 | const scratch = yield* preparationSettled(launched.threadId); |
| 1328 | assert.equal(scratch.thread.worktreePath, "/scratch/folder-1"); |
| 1329 | // Released past preparation; provider execution is disabled here. |
| 1330 | assert.equal(scratch.runs[0]?.status, "starting"); |
| 1331 | assert.deepEqual(scratch.runs[0]?.workspacePreparation, { |
| 1332 | type: "existing_worktree", |
| 1333 | worktreePath: "/scratch/folder-1", |
| 1334 | }); |
| 1335 | assert.equal(harness.runSetup.mock.calls[0]?.[0]?.worktreePath, "/scratch/folder-1"); |
| 1336 | assert.equal(harness.createWorktree.mock.calls.length, 0); |
| 1337 | |
| 1338 | // A Git project still gets the worktree it asked for. |
| 1339 | const other = yield* launches.launch({ |
| 1340 | ...launchInput({ |
| 1341 | command: "command:launch:git-worktree", |
| 1342 | thread: "thread:launch:git-worktree", |
| 1343 | message: "Build the feature", |
| 1344 | workspace: worktreeStrategy, |
| 1345 | }), |
| 1346 | projectId: otherProjectId, |
| 1347 | }); |
| 1348 | const git = yield* preparationSettled(other.threadId); |
| 1349 | assert.equal(git.runs[0]?.status, "starting"); |
| 1350 | assert.equal(git.runs[0]?.workspacePreparation?.type, "worktree"); |
| 1351 | assert.equal(git.thread.worktreePath, "/other-repo-worktrees/feature"); |
| 1352 | assert.equal(harness.createWorktree.mock.calls[0]?.[0]?.cwd, "/other-repo"); |
| 1353 | assert.deepEqual(harness.claimed, [launched.threadId]); |
| 1354 | }).pipe(Effect.provide(harness.layer)); |
| 1355 | }); |
| 1356 | |
| 1357 | it.effect.each([true, false])( |
| 1358 | "stores a non-Git scheduled task at the root and keeps worktrees elsewhere (Scratch: %s)", |
| 1359 | (scratch) => { |
| 1360 | const harness = scratchHarness({ scratch }); |
| 1361 | return Effect.gen(function* () { |
| 1362 | const tasks = yield* ScheduledTasks.ScheduledTaskService; |
| 1363 | const plain = yield* tasks.upsert( |
| 1364 | scheduledTaskInput("scheduled-task:plain-upsert", projectId), |
| 1365 | ); |
| 1366 | assert.deepEqual(plain.task.workspaceStrategy, { type: "root" }); |
| 1367 | const git = yield* tasks.upsert( |
| 1368 | scheduledTaskInput("scheduled-task:git-upsert", otherProjectId), |
| 1369 | ); |
| 1370 | assert.deepEqual(git.task.workspaceStrategy, worktreeStrategy); |
| 1371 | }).pipe(Effect.provide(harness.layer)); |
| 1372 | }, |
| 1373 | ); |
| 1374 | |
| 1375 | it.effect("runs a Scratch scheduled task saved with a worktree in its own folder", () => { |
| 1376 | const harness = scratchHarness(); |
| 1377 | return Effect.gen(function* () { |
| 1378 | const tasks = yield* ScheduledTasks.ScheduledTaskService; |
| 1379 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 1380 | const sql = yield* SqlClient.SqlClient; |
| 1381 | const { task } = yield* tasks.upsert( |
| 1382 | scheduledTaskInput("scheduled-task:scratch-stored", projectId), |
| 1383 | ); |
| 1384 | // Tasks saved before Scratch was coerced still hold a worktree strategy. |
| 1385 | yield* sql` |
| 1386 | UPDATE scheduled_tasks |
| 1387 | SET workspace_strategy_json = ${JSON.stringify(worktreeStrategy)} |
| 1388 | WHERE task_id = ${task.id} |
| 1389 | `; |
| 1390 | const ran = yield* tasks.runNow({ id: task.id }); |
| 1391 | assert.equal(ran.task.lastRunStatus, "succeeded"); |
| 1392 | const [thread] = yield* threads.listProjectThreads({ projectId, includeSubagents: false }); |
| 1393 | assert.isDefined(thread); |
| 1394 | const projection = yield* preparationSettled(thread!.id); |
| 1395 | assert.equal(projection.runs[0]?.status, "starting"); |
| 1396 | assert.equal(projection.thread.worktreePath, "/scratch/folder-1"); |
| 1397 | assert.deepEqual(projection.runs[0]?.workspacePreparation, { |
| 1398 | type: "existing_worktree", |
| 1399 | worktreePath: "/scratch/folder-1", |
| 1400 | }); |
| 1401 | assert.equal(harness.runSetup.mock.calls[0]?.[0]?.worktreePath, "/scratch/folder-1"); |
| 1402 | assert.equal(harness.createWorktree.mock.calls.length, 0); |
| 1403 | }).pipe(Effect.provide(harness.layer)); |
| 1404 | }); |
| 1405 | |
| 1406 | it.effect.each(["stable", "upstream/release"])( |
| 1407 | "launches from %s with the fetched commit and remote PR base", |
| 1408 | (baseRef) => |
| 1409 | Effect.gen(function* () { |
| 1410 | const fs = yield* FileSystem.FileSystem; |
| 1411 | const git = yield* GitVcsDriver.GitVcsDriver; |
| 1412 | const directory = yield* fs.makeTempDirectoryScoped({ prefix: "launch-remote-base-" }); |
| 1413 | const cwd = `${directory}/repo`; |
| 1414 | const remote = `${directory}/remote.git`; |
| 1415 | const worktreePath = `${directory}/worktree`; |
| 1416 | yield* fs.makeDirectory(cwd); |
| 1417 | const command = (at: string, args: string[]) => |
| 1418 | git.execute({ operation: "launch-test", cwd: at, args }); |
| 1419 | yield* command(cwd, ["init", "-b", "stable"]); |
| 1420 | yield* command(cwd, ["config", "user.name", "Test"]); |
| 1421 | yield* command(cwd, ["config", "user.email", "test@example.test"]); |
| 1422 | yield* command(cwd, ["commit", "--allow-empty", "-m", "initial"]); |
| 1423 | const localHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim(); |
| 1424 | yield* command(cwd, ["init", "--bare", remote]); |
| 1425 | yield* command(cwd, ["remote", "add", "upstream", remote]); |
| 1426 | yield* command(cwd, ["push", "-u", "upstream", "stable:release"]); |
| 1427 | yield* command(cwd, ["commit", "--allow-empty", "-m", "remote advance"]); |
| 1428 | yield* command(cwd, ["push", "upstream", "stable:release"]); |
| 1429 | const remoteHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim(); |
| 1430 | yield* command(cwd, ["reset", "--hard", localHead]); |
| 1431 | yield* command(cwd, ["update-ref", "-d", "refs/remotes/upstream/release"]); |
| 1432 | |
| 1433 | const setupStarted = yield* Deferred.make<void>(); |
| 1434 | const harness = makeHarness({ |
| 1435 | hasCommit: ({ refName }) => |
| 1436 | command(cwd, ["rev-parse", "--verify", `${refName}^{commit}`]).pipe( |
| 1437 | Effect.as(true), |
| 1438 | Effect.orElseSucceed(() => false), |
| 1439 | ), |
| 1440 | git: { |
| 1441 | resolveWorktreeBaseRemote: (input) => git.resolveWorktreeBaseRemote({ ...input, cwd }), |
| 1442 | hasRefNamed: () => Effect.succeed(false), |
| 1443 | listLocalBranchNames: () => git.listLocalBranchNames(cwd), |
| 1444 | }, |
| 1445 | fetchWorktreeBaseCommit: (input) => git.fetchWorktreeBaseCommit({ ...input, cwd }), |
| 1446 | createWorktree: (input, options) => |
| 1447 | git.createWorktree({ ...input, cwd, path: worktreePath }, options), |
| 1448 | runSetup: () => |
| 1449 | Deferred.succeed(setupStarted, undefined).pipe( |
| 1450 | Effect.as({ status: "no-script" as const }), |
| 1451 | ), |
| 1452 | }); |
| 1453 | yield* Effect.gen(function* () { |
| 1454 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1455 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 1456 | const workspace = { |
| 1457 | type: "worktree" as const, |
| 1458 | baseRef, |
| 1459 | branch: "feature", |
| 1460 | startFromOrigin: true, |
| 1461 | }; |
| 1462 | yield* launches.checkWorktreeBase({ projectId, workspaceStrategy: workspace }); |
| 1463 | const launched = yield* launches.launch( |
| 1464 | launchInput({ |
| 1465 | command: "command:launch:remote-base", |
| 1466 | thread: "thread:launch:remote-base", |
| 1467 | workspace, |
| 1468 | }), |
| 1469 | ); |
| 1470 | yield* Deferred.await(setupStarted); |
| 1471 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 1472 | assert.equal(projection.thread.worktreePath, worktreePath); |
| 1473 | assert.equal( |
| 1474 | (yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim(), |
| 1475 | remoteHead, |
| 1476 | ); |
| 1477 | const preview = yield* git.getReviewDiffPreview({ cwd: worktreePath }); |
| 1478 | const comparisonBase = preview.sources.find( |
| 1479 | (source) => source.kind === "branch-range", |
| 1480 | )!.baseRef; |
| 1481 | assert.equal( |
| 1482 | (yield* command(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`])).stdout.trim(), |
| 1483 | remoteHead, |
| 1484 | ); |
| 1485 | }).pipe(Effect.provide(harness.layer)); |
| 1486 | }).pipe( |
| 1487 | Effect.provide( |
| 1488 | GitVcsDriver.layer.pipe( |
| 1489 | Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "launch-remote-git-" })), |
| 1490 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1491 | ), |
| 1492 | ), |
| 1493 | ), |
| 1494 | ); |
| 1495 | |
| 1496 | const withRealGitRepo = <A, E, R>( |
| 1497 | run: (repo: { |
| 1498 | readonly directory: string; |
| 1499 | readonly cwd: string; |
| 1500 | readonly worktreePath: string; |
| 1501 | readonly command: ( |
| 1502 | at: string, |
| 1503 | args: string[], |
| 1504 | ) => ReturnType<GitVcsDriver.GitVcsDriver["Service"]["execute"]>; |
| 1505 | readonly harness: (options?: HarnessOptions) => ReturnType<typeof makeHarness>; |
| 1506 | }) => Effect.Effect<A, E, R>, |
| 1507 | ) => |
| 1508 | Effect.gen(function* () { |
| 1509 | const fs = yield* FileSystem.FileSystem; |
| 1510 | const git = yield* GitVcsDriver.GitVcsDriver; |
| 1511 | const directory = yield* fs.makeTempDirectoryScoped({ prefix: "launch-base-fallback-" }); |
| 1512 | const cwd = `${directory}/repo`; |
| 1513 | const worktreePath = `${directory}/worktree`; |
| 1514 | yield* fs.makeDirectory(cwd); |
| 1515 | const command = (at: string, args: string[]) => |
| 1516 | git.execute({ operation: "launch-test", cwd: at, args }); |
| 1517 | yield* command(cwd, ["init", "-b", "beta"]); |
| 1518 | yield* command(cwd, ["config", "user.name", "Test"]); |
| 1519 | yield* command(cwd, ["config", "user.email", "test@example.test"]); |
| 1520 | const harness = (options: HarnessOptions = {}) => |
| 1521 | makeHarness({ |
| 1522 | hasCommit: ({ refName }) => |
| 1523 | command(cwd, ["rev-parse", "--verify", `${refName}^{commit}`]).pipe( |
| 1524 | Effect.as(true), |
| 1525 | Effect.orElseSucceed(() => false), |
| 1526 | ), |
| 1527 | fetchWorktreeBaseCommit: (input) => git.fetchWorktreeBaseCommit({ ...input, cwd }), |
| 1528 | createWorktree: (input, progress) => |
| 1529 | git.createWorktree({ ...input, cwd, path: worktreePath }, progress), |
| 1530 | ...options, |
| 1531 | git: { |
| 1532 | resolveWorktreeBaseRemote: (input) => git.resolveWorktreeBaseRemote({ ...input, cwd }), |
| 1533 | resolvePrimaryRemoteName: () => git.resolvePrimaryRemoteName(cwd), |
| 1534 | resolveDefaultBranchName: (_cwd, remoteName) => |
| 1535 | git.resolveDefaultBranchName(cwd, remoteName), |
| 1536 | currentBranch: () => |
| 1537 | command(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]).pipe( |
| 1538 | Effect.map((result) => result.stdout.trim() || null), |
| 1539 | Effect.orElseSucceed(() => null), |
| 1540 | ), |
| 1541 | hasRefNamed: () => Effect.succeed(false), |
| 1542 | ...options.git, |
| 1543 | }, |
| 1544 | }); |
| 1545 | return yield* run({ directory, cwd, worktreePath, command, harness }); |
| 1546 | }).pipe( |
| 1547 | Effect.provide( |
| 1548 | GitVcsDriver.layer.pipe( |
| 1549 | Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "launch-base-git-" })), |
| 1550 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1551 | ), |
| 1552 | ), |
| 1553 | ); |
| 1554 | |
| 1555 | const launchFromBase = (harness: ReturnType<typeof makeHarness>, baseRef: string) => |
| 1556 | Effect.gen(function* () { |
| 1557 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1558 | const launched = yield* launches.launch( |
| 1559 | launchInput({ |
| 1560 | command: "command:launch:base-fallback", |
| 1561 | thread: "thread:launch:base-fallback", |
| 1562 | message: "Build the feature", |
| 1563 | workspace: { type: "worktree", baseRef, branch: "feature", startFromOrigin: true }, |
| 1564 | }), |
| 1565 | ); |
| 1566 | const projection = yield* preparationSettled(launched.threadId); |
| 1567 | assert.equal(projection.runs[0]?.status, "starting"); |
| 1568 | }).pipe(Effect.provide(harness.layer)); |
| 1569 | |
| 1570 | it.effect("re-bases a stored base that no longer exists on the remote default branch", () => |
| 1571 | withRealGitRepo(({ directory, cwd, worktreePath, command, harness }) => |
| 1572 | Effect.gen(function* () { |
| 1573 | const remote = `${directory}/remote.git`; |
| 1574 | yield* command(cwd, ["commit", "--allow-empty", "-m", "initial"]); |
| 1575 | yield* command(cwd, ["init", "--bare", remote]); |
| 1576 | yield* command(cwd, ["remote", "add", "origin", remote]); |
| 1577 | yield* command(cwd, ["push", "-u", "origin", "beta"]); |
| 1578 | yield* command(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/beta"]); |
| 1579 | const remoteHead = (yield* command(cwd, ["rev-parse", "beta"])).stdout.trim(); |
| 1580 | yield* command(cwd, ["checkout", "--detach"]); |
| 1581 | yield* command(cwd, ["commit", "--allow-empty", "-m", "local only"]); |
| 1582 | |
| 1583 | // Tasks saved before the base followed the default branch still record "main". |
| 1584 | yield* launchFromBase(harness(), "main"); |
| 1585 | assert.equal((yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim(), remoteHead); |
| 1586 | }), |
| 1587 | ), |
| 1588 | ); |
| 1589 | |
| 1590 | it.effect("keeps a `:/` commit-search base instead of re-basing", () => |
| 1591 | withRealGitRepo(({ cwd, worktreePath, command, harness }) => |
| 1592 | Effect.gen(function* () { |
| 1593 | yield* command(cwd, ["commit", "--allow-empty", "-m", "searched base"]); |
| 1594 | const searchedHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim(); |
| 1595 | yield* command(cwd, ["commit", "--allow-empty", "-m", "later work"]); |
| 1596 | |
| 1597 | yield* launchFromBase(harness(), ":/searched"); |
| 1598 | assert.equal( |
| 1599 | (yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim(), |
| 1600 | searchedHead, |
| 1601 | ); |
| 1602 | }), |
| 1603 | ), |
| 1604 | ); |
| 1605 | |
| 1606 | it.effect("skips a stale tracking ref when the remote reports the base branch is gone", () => |
| 1607 | withRealGitRepo(({ cwd, worktreePath, command, harness }) => |
| 1608 | Effect.gen(function* () { |
| 1609 | yield* command(cwd, ["commit", "--allow-empty", "-m", "stale point"]); |
| 1610 | const staleHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim(); |
| 1611 | yield* command(cwd, ["commit", "--allow-empty", "-m", "current work"]); |
| 1612 | const betaHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim(); |
| 1613 | // The deleted remote branch leaves its tracking ref (and origin/HEAD) behind. |
| 1614 | yield* command(cwd, ["update-ref", "refs/remotes/origin/gone", staleHead]); |
| 1615 | yield* command(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/gone"]); |
| 1616 | |
| 1617 | yield* launchFromBase( |
| 1618 | harness({ |
| 1619 | // A completed fetch that found no branch, as when the branch was deleted. |
| 1620 | fetchWorktreeBaseCommit: () => Effect.succeed(null), |
| 1621 | git: { resolvePrimaryRemoteName: () => Effect.succeed("origin") }, |
| 1622 | }), |
| 1623 | "main", |
| 1624 | ); |
| 1625 | assert.equal((yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim(), betaHead); |
| 1626 | }), |
| 1627 | ), |
| 1628 | ); |
| 1629 | |
| 1630 | it.effect("fetches the origin base from the remote it already resolved", () => { |
| 1631 | let fetchInput: Deferred.Deferred<unknown> | null = null; |
| 1632 | const harness = makeHarness({ |
| 1633 | fetchWorktreeBaseCommit: (input) => Deferred.succeed(fetchInput!, input).pipe(Effect.as(null)), |
| 1634 | }); |
| 1635 | return Effect.gen(function* () { |
| 1636 | fetchInput = yield* Deferred.make<unknown>(); |
| 1637 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1638 | yield* launches.launch( |
| 1639 | launchInput({ |
| 1640 | command: "command:launch:resolved-remote", |
| 1641 | thread: "thread:launch:resolved-remote", |
| 1642 | workspace: { type: "worktree", baseRef: "main", startFromOrigin: true }, |
| 1643 | }), |
| 1644 | ); |
| 1645 | assert.deepEqual(yield* Deferred.await(fetchInput), { |
| 1646 | cwd: project.workspaceRoot, |
| 1647 | refName: "main", |
| 1648 | remote: { remoteName: "origin", branchName: "main" }, |
| 1649 | }); |
| 1650 | }).pipe(Effect.provide(harness.layer)); |
| 1651 | }); |
| 1652 | |
| 1653 | it.effect("shows the fetch diagnosis when preparing a worktree from origin fails", () => { |
| 1654 | const detail = |
| 1655 | "Git could not authenticate with the remote. Check Git credentials or SSH access on the server, then retry."; |
| 1656 | const harness = makeHarness({ |
| 1657 | fetchWorktreeBaseCommit: () => |
| 1658 | Effect.fail( |
| 1659 | new GitCommandError({ |
| 1660 | operation: "GitVcsDriver.fetchRemote", |
| 1661 | command: "git", |
| 1662 | cwd: project.workspaceRoot, |
| 1663 | detail, |
| 1664 | exitCode: 128, |
| 1665 | }), |
| 1666 | ), |
| 1667 | }); |
| 1668 | return Effect.gen(function* () { |
| 1669 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1670 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 1671 | const launched = yield* launches.launch( |
| 1672 | launchInput({ |
| 1673 | command: "command:launch:fetch-failure", |
| 1674 | thread: "thread:launch:fetch-failure", |
| 1675 | message: "Start from origin", |
| 1676 | workspace: { type: "worktree", baseRef: "main", startFromOrigin: true }, |
| 1677 | }), |
| 1678 | ); |
| 1679 | yield* threads.streamStoredEventsFrom({ threadId: launched.threadId }).pipe( |
| 1680 | Stream.filter( |
| 1681 | (stored) => stored.event.type === "run.updated" && stored.event.payload.status === "failed", |
| 1682 | ), |
| 1683 | Stream.runHead, |
| 1684 | ); |
| 1685 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 1686 | assert.equal(projection.messages[0]?.text, "Start from origin"); |
| 1687 | assert.equal(projection.runs[0]?.status, "failed"); |
| 1688 | assert.equal(projection.thread.worktreePath, null); |
| 1689 | assert.equal( |
| 1690 | projection.turnItems.find((item) => item.type === "command_execution")?.status, |
| 1691 | "failed", |
| 1692 | ); |
| 1693 | assert.include( |
| 1694 | projection.turnItems.find((item) => item.type === "error")?.failure.message ?? "", |
| 1695 | detail, |
| 1696 | ); |
| 1697 | assert.equal(harness.createWorktree.mock.calls.length, 0); |
| 1698 | assert.equal(harness.runSetup.mock.calls.length, 0); |
| 1699 | }).pipe(Effect.provide(harness.layer)); |
| 1700 | }); |
| 1701 | |
| 1702 | it.effect("names the missing base branch when a worktree cannot be created from it", () => |
| 1703 | Effect.gen(function* () { |
| 1704 | const fs = yield* FileSystem.FileSystem; |
| 1705 | const git = yield* GitVcsDriver.GitVcsDriver; |
| 1706 | const directory = yield* fs.makeTempDirectoryScoped({ prefix: "launch-missing-base-" }); |
| 1707 | const cwd = `${directory}/repo`; |
| 1708 | const remote = `${directory}/remote.git`; |
| 1709 | yield* fs.makeDirectory(cwd); |
| 1710 | const command = (at: string, args: string[]) => |
| 1711 | git.execute({ operation: "launch-test", cwd: at, args }); |
| 1712 | yield* command(cwd, ["init", "-b", "dev"]); |
| 1713 | yield* command(cwd, ["config", "user.name", "Test"]); |
| 1714 | yield* command(cwd, ["config", "user.email", "test@example.test"]); |
| 1715 | yield* command(cwd, ["commit", "--allow-empty", "-m", "initial"]); |
| 1716 | yield* command(cwd, ["init", "--bare", remote]); |
| 1717 | yield* command(cwd, ["remote", "add", "origin", remote]); |
| 1718 | yield* command(cwd, ["push", "-u", "origin", "dev"]); |
| 1719 | |
| 1720 | const harness = makeHarness({ |
| 1721 | git: { |
| 1722 | resolveWorktreeBaseRemote: (input) => git.resolveWorktreeBaseRemote({ ...input, cwd }), |
| 1723 | }, |
| 1724 | fetchWorktreeBaseCommit: (input) => git.fetchWorktreeBaseCommit({ ...input, cwd }), |
| 1725 | createWorktree: (input, options) => |
| 1726 | git.createWorktree({ ...input, cwd, path: `${directory}/worktree` }, options), |
| 1727 | }); |
| 1728 | yield* Effect.gen(function* () { |
| 1729 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1730 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 1731 | const launched = yield* launches.launch( |
| 1732 | launchInput({ |
| 1733 | command: "command:launch:missing-base", |
| 1734 | thread: "thread:launch:missing-base", |
| 1735 | message: "Start from master", |
| 1736 | workspace: { type: "worktree", baseRef: "master", startFromOrigin: true }, |
| 1737 | }), |
| 1738 | ); |
| 1739 | yield* threads.streamStoredEventsFrom({ threadId: launched.threadId }).pipe( |
| 1740 | Stream.filter( |
| 1741 | (stored) => |
| 1742 | stored.event.type === "run.updated" && stored.event.payload.status === "failed", |
| 1743 | ), |
| 1744 | Stream.runHead, |
| 1745 | ); |
| 1746 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 1747 | assert.equal(projection.runs[0]?.status, "failed"); |
| 1748 | assert.include( |
| 1749 | projection.turnItems.find((item) => item.type === "error")?.failure.message ?? "", |
| 1750 | `Base ref "master" does not resolve to a commit in project "Project" (/repo).`, |
| 1751 | ); |
| 1752 | }).pipe(Effect.provide(harness.layer)); |
| 1753 | }).pipe( |
| 1754 | Effect.provide( |
| 1755 | GitVcsDriver.layer.pipe( |
| 1756 | Layer.provide( |
| 1757 | ServerConfig.layerTest(process.cwd(), { prefix: "launch-missing-base-git-" }), |
| 1758 | ), |
| 1759 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1760 | ), |
| 1761 | ), |
| 1762 | ), |
| 1763 | ); |
| 1764 | |
| 1765 | it.effect("rejects a preparation retry after the project disables its provider", () => { |
| 1766 | let fetchAttempts = 0; |
| 1767 | const harness = makeHarness({ |
| 1768 | fetchWorktreeBaseCommit: () => |
| 1769 | fetchAttempts++ === 0 |
| 1770 | ? Effect.fail( |
| 1771 | new GitCommandError({ |
| 1772 | operation: "GitVcsDriver.fetchRemote", |
| 1773 | command: "git", |
| 1774 | cwd: project.workspaceRoot, |
| 1775 | detail: "Git could not reach the remote.", |
| 1776 | exitCode: 128, |
| 1777 | }), |
| 1778 | ) |
| 1779 | : Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }), |
| 1780 | }); |
| 1781 | return Effect.gen(function* () { |
| 1782 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1783 | const settings = yield* ServerSettings.ServerSettingsService; |
| 1784 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 1785 | const launched = yield* launches.launch( |
| 1786 | launchInput({ |
| 1787 | command: "command:launch:disabled-preparation-retry", |
| 1788 | thread: "thread:launch:disabled-preparation-retry", |
| 1789 | message: "Start from origin", |
| 1790 | workspace: { type: "worktree", baseRef: "main", startFromOrigin: true }, |
| 1791 | }), |
| 1792 | ); |
| 1793 | yield* preparationSettled(launched.threadId); |
| 1794 | yield* settings.updateSettings({ |
| 1795 | projectSettingsOverrides: { |
| 1796 | [projectId]: { providerInstances: { [modelSelection.instanceId]: { enabled: false } } }, |
| 1797 | }, |
| 1798 | }); |
| 1799 | |
| 1800 | const error = yield* launches |
| 1801 | .retryPreparation({ |
| 1802 | commandId: CommandId.make("command:launch:disabled-preparation-retry:retry"), |
| 1803 | threadId: launched.threadId, |
| 1804 | runId: launched.projection.runs[0]!.id, |
| 1805 | }) |
| 1806 | .pipe(Effect.flip); |
| 1807 | |
| 1808 | assert.equal(error._tag, "ThreadManagementProviderInstanceDisabledError"); |
| 1809 | assert.equal((yield* threads.getThreadProjection(launched.threadId)).runs[0]?.status, "failed"); |
| 1810 | assert.equal(fetchAttempts, 1); |
| 1811 | }).pipe(Effect.provide(harness.layer)); |
| 1812 | }); |
| 1813 | |
| 1814 | it.effect("does not release a prepared run after the project disables its provider", () => { |
| 1815 | return Effect.gen(function* () { |
| 1816 | const setupEntered = yield* Deferred.make<void>(); |
| 1817 | const allowSetup = yield* Deferred.make<void>(); |
| 1818 | const harness = makeHarness({ |
| 1819 | runSetup: () => |
| 1820 | Deferred.succeed(setupEntered, undefined).pipe( |
| 1821 | Effect.andThen(Deferred.await(allowSetup)), |
| 1822 | Effect.as({ status: "no-script" as const }), |
| 1823 | ), |
| 1824 | }); |
| 1825 | yield* Effect.gen(function* () { |
| 1826 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1827 | const settings = yield* ServerSettings.ServerSettingsService; |
| 1828 | const launched = yield* launches.launch( |
| 1829 | launchInput({ |
| 1830 | command: "command:launch:disable-during-preparation", |
| 1831 | thread: "thread:launch:disable-during-preparation", |
| 1832 | message: "Prepare a worktree", |
| 1833 | workspace: { type: "worktree", baseRef: "main" }, |
| 1834 | }), |
| 1835 | ); |
| 1836 | yield* Deferred.await(setupEntered); |
| 1837 | yield* settings.updateSettings({ |
| 1838 | projectSettingsOverrides: { |
| 1839 | [projectId]: { providerInstances: { [modelSelection.instanceId]: { enabled: false } } }, |
| 1840 | }, |
| 1841 | }); |
| 1842 | yield* Deferred.succeed(allowSetup, undefined); |
| 1843 | const projection = yield* preparationSettled(launched.threadId); |
| 1844 | assert.equal(projection.runs[0]?.status, "failed"); |
| 1845 | const effects = yield* (yield* EffectOutbox.EffectOutboxV2).listByCommandId( |
| 1846 | CommandId.make("command:launch:disable-during-preparation:release"), |
| 1847 | ); |
| 1848 | assert.isFalse( |
| 1849 | effects.some( |
| 1850 | (effect) => |
| 1851 | effect.request.type === "provider-turn.start" && |
| 1852 | effect.request.runId === launched.projection.runs[0]?.id, |
| 1853 | ), |
| 1854 | ); |
| 1855 | }).pipe(Effect.provide(harness.layer)); |
| 1856 | }); |
| 1857 | }); |
| 1858 | |
| 1859 | it.effect.each(["fails", "is interrupted"] as const)( |
| 1860 | "holds a message queued during setup when the workspace preparation %s", |
| 1861 | (ending) => |
| 1862 | Effect.gen(function* () { |
| 1863 | const fetchEntered = yield* Deferred.make<void>(); |
| 1864 | const allowFetch = yield* Deferred.make<void>(); |
| 1865 | let fetchFailures = 1; |
| 1866 | const harness = makeHarness({ |
| 1867 | fetchWorktreeBaseCommit: () => |
| 1868 | fetchFailures-- <= 0 |
| 1869 | ? Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }) |
| 1870 | : Deferred.succeed(fetchEntered, undefined).pipe( |
| 1871 | Effect.andThen(Deferred.await(allowFetch)), |
| 1872 | Effect.andThen( |
| 1873 | Effect.fail( |
| 1874 | new GitCommandError({ |
| 1875 | operation: "GitVcsDriver.fetchRemote", |
| 1876 | command: "git", |
| 1877 | cwd: project.workspaceRoot, |
| 1878 | detail: "Git could not reach the remote.", |
| 1879 | exitCode: 128, |
| 1880 | }), |
| 1881 | ), |
| 1882 | ), |
| 1883 | ), |
| 1884 | }); |
| 1885 | yield* Effect.gen(function* () { |
| 1886 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1887 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 1888 | const launched = yield* launches.launch( |
| 1889 | launchInput({ |
| 1890 | command: `command:launch:queued-setup-${ending}`, |
| 1891 | thread: `thread:launch:queued-setup-${ending}`, |
| 1892 | message: "First message", |
| 1893 | workspace: { type: "worktree", baseRef: "main", startFromOrigin: true }, |
| 1894 | }), |
| 1895 | ); |
| 1896 | yield* Deferred.await(fetchEntered); |
| 1897 | const queued = yield* threads.sendToThread({ |
| 1898 | projectId, |
| 1899 | commandId: CommandId.make(`command:launch:queued-setup-${ending}:follow-up`), |
| 1900 | threadId: launched.threadId, |
| 1901 | messageId: MessageId.make(`message:launch:queued-setup-${ending}:follow-up`), |
| 1902 | text: "Sent during setup", |
| 1903 | attachments: [], |
| 1904 | mode: "queue", |
| 1905 | createdBy: "user", |
| 1906 | creationSource: "web", |
| 1907 | }); |
| 1908 | assert.equal(queued.delivery, "queued"); |
| 1909 | if (ending === "fails") { |
| 1910 | yield* Deferred.succeed(allowFetch, undefined); |
| 1911 | } else { |
| 1912 | yield* threads.dispatch({ |
| 1913 | type: "run.interrupt", |
| 1914 | commandId: CommandId.make("command:launch:queued-setup-interrupt"), |
| 1915 | threadId: launched.threadId, |
| 1916 | runId: launched.projection.runs[0]!.id, |
| 1917 | }); |
| 1918 | } |
| 1919 | |
| 1920 | yield* threads.streamStoredEventsFrom({ threadId: launched.threadId }).pipe( |
| 1921 | Stream.filter( |
| 1922 | (stored) => |
| 1923 | stored.event.type === "run.updated" && stored.event.payload.queueHeld === true, |
| 1924 | ), |
| 1925 | Stream.runHead, |
| 1926 | ); |
| 1927 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 1928 | assert.equal(projection.runs.at(-1)?.status, "queued"); |
| 1929 | assert.equal(projection.thread.worktreePath, null); |
| 1930 | |
| 1931 | if (ending === "fails") { |
| 1932 | yield* launches.retryPreparation({ |
| 1933 | commandId: CommandId.make("command:launch:queued-setup-retry"), |
| 1934 | threadId: launched.threadId, |
| 1935 | runId: launched.projection.runs[0]!.id, |
| 1936 | }); |
| 1937 | const retried = yield* threads.getThreadProjection(launched.threadId); |
| 1938 | assert.equal(retried.runs.at(-1)?.queueHeld, false); |
| 1939 | } |
| 1940 | }).pipe(Effect.provide(harness.layer)); |
| 1941 | }), |
| 1942 | ); |
| 1943 | |
| 1944 | it.effect("returns from prepareRun without retrying a scheduling failure", () => |
| 1945 | Effect.gen(function* () { |
| 1946 | const rejected = yield* Deferred.make<void>(); |
| 1947 | let rejectedWrites = 0; |
| 1948 | const harness = makeHarness({ |
| 1949 | dispatch: (command, dispatch) => |
| 1950 | command.type !== "prepared-run.fail" |
| 1951 | ? dispatch(command) |
| 1952 | : Effect.suspend(() => { |
| 1953 | rejectedWrites += 1; |
| 1954 | return Deferred.succeed(rejected, undefined).pipe( |
| 1955 | Effect.andThen(Effect.die("SQLITE_FULL: database or disk is full")), |
| 1956 | ); |
| 1957 | }), |
| 1958 | }); |
| 1959 | yield* Effect.gen(function* () { |
| 1960 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 1961 | yield* launches.prepareRun({ |
| 1962 | commandId: CommandId.make("command:prepare:missing-thread"), |
| 1963 | threadId: ThreadId.make("thread:prepare:missing-thread"), |
| 1964 | runId: RunId.make("run:prepare:missing-thread"), |
| 1965 | }); |
| 1966 | yield* Deferred.await(rejected); |
| 1967 | yield* TestClock.adjust("1 second"); |
| 1968 | assert.equal(rejectedWrites, 1); |
| 1969 | }).pipe(Effect.provide(harness.layer)); |
| 1970 | }), |
| 1971 | ); |
| 1972 | |
| 1973 | it.effect("fails a run whose preparation failure could not be stored until storage recovers", () => |
| 1974 | Effect.gen(function* () { |
| 1975 | const storageFull = yield* Deferred.make<void>(); |
| 1976 | let rejectedWrites = 0; |
| 1977 | let preparations = 0; |
| 1978 | const harness = makeHarness({ |
| 1979 | fetchWorktreeBaseCommit: () => |
| 1980 | Effect.sync(() => preparations++).pipe( |
| 1981 | Effect.andThen( |
| 1982 | Effect.fail( |
| 1983 | new GitCommandError({ |
| 1984 | operation: "GitVcsDriver.fetchRemote", |
| 1985 | command: "git", |
| 1986 | cwd: project.workspaceRoot, |
| 1987 | detail: "Git could not reach the remote.", |
| 1988 | exitCode: 128, |
| 1989 | }), |
| 1990 | ), |
| 1991 | ), |
| 1992 | ), |
| 1993 | dispatch: (command, dispatch) => |
| 1994 | command.type !== "prepared-run.fail" |
| 1995 | ? dispatch(command) |
| 1996 | : Effect.suspend(() => { |
| 1997 | if (rejectedWrites >= 2) return dispatch(command); |
| 1998 | rejectedWrites += 1; |
| 1999 | return Deferred.succeed(storageFull, undefined).pipe( |
| 2000 | Effect.andThen( |
| 2001 | Effect.fail( |
| 2002 | new Orchestrator.OrchestratorDispatchError({ |
| 2003 | commandId: command.commandId, |
| 2004 | commandType: command.type, |
| 2005 | cause: new Error("SQLITE_FULL: database or disk is full"), |
| 2006 | }), |
| 2007 | ), |
| 2008 | ), |
| 2009 | ); |
| 2010 | }), |
| 2011 | }); |
| 2012 | yield* Effect.gen(function* () { |
| 2013 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2014 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 2015 | const input = launchInput({ |
| 2016 | command: "command:launch:storage-full", |
| 2017 | thread: "thread:launch:storage-full", |
| 2018 | message: "First message", |
| 2019 | workspace: { type: "worktree", baseRef: "main", startFromOrigin: true }, |
| 2020 | }); |
| 2021 | const launched = yield* launches.launch(input); |
| 2022 | yield* Deferred.await(storageFull); |
| 2023 | yield* TestClock.adjust("0 seconds"); |
| 2024 | yield* launches.launch(input); |
| 2025 | yield* TestClock.adjust("0 seconds"); |
| 2026 | assert.equal(preparations, 1); |
| 2027 | yield* TestClock.adjust("1 second"); |
| 2028 | yield* threads.streamStoredEventsFrom({ threadId: launched.threadId }).pipe( |
| 2029 | Stream.filter( |
| 2030 | (stored) => |
| 2031 | stored.event.type === "run.updated" && stored.event.payload.status === "failed", |
| 2032 | ), |
| 2033 | Stream.runHead, |
| 2034 | ); |
| 2035 | assert.equal(rejectedWrites, 2); |
| 2036 | }).pipe(Effect.provide(harness.layer)); |
| 2037 | }), |
| 2038 | ); |
| 2039 | |
| 2040 | it.effect.each(["failed", "interrupted"] as const)( |
| 2041 | "holds every message that arrives after the setup %s without a worktree", |
| 2042 | (ending) => { |
| 2043 | let fetchEntered: Deferred.Deferred<void> | null = null; |
| 2044 | const harness = makeHarness({ |
| 2045 | fetchWorktreeBaseCommit: () => |
| 2046 | ending === "interrupted" |
| 2047 | ? Deferred.succeed(fetchEntered!, undefined).pipe(Effect.andThen(Effect.never)) |
| 2048 | : Effect.fail( |
| 2049 | new GitCommandError({ |
| 2050 | operation: "GitVcsDriver.fetchRemote", |
| 2051 | command: "git", |
| 2052 | cwd: project.workspaceRoot, |
| 2053 | detail: "Git could not reach the remote.", |
| 2054 | exitCode: 128, |
| 2055 | }), |
| 2056 | ), |
| 2057 | }); |
| 2058 | return Effect.gen(function* () { |
| 2059 | fetchEntered = yield* Deferred.make<void>(); |
| 2060 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2061 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 2062 | const launched = yield* launches.launch( |
| 2063 | launchInput({ |
| 2064 | command: `command:launch:late-queued-follow-up-${ending}`, |
| 2065 | thread: `thread:launch:late-queued-follow-up-${ending}`, |
| 2066 | message: "First message", |
| 2067 | workspace: { type: "worktree", baseRef: "main", startFromOrigin: true }, |
| 2068 | }), |
| 2069 | ); |
| 2070 | if (ending === "interrupted") { |
| 2071 | yield* Deferred.await(fetchEntered); |
| 2072 | yield* threads.dispatch({ |
| 2073 | type: "run.interrupt", |
| 2074 | commandId: CommandId.make("command:launch:late-queued-follow-up:interrupt"), |
| 2075 | threadId: launched.threadId, |
| 2076 | runId: launched.projection.runs[0]!.id, |
| 2077 | }); |
| 2078 | } |
| 2079 | yield* threads.streamStoredEventsFrom({ threadId: launched.threadId }).pipe( |
| 2080 | Stream.filter( |
| 2081 | (stored) => stored.event.type === "run.updated" && stored.event.payload.status === ending, |
| 2082 | ), |
| 2083 | Stream.runHead, |
| 2084 | ); |
| 2085 | |
| 2086 | const queued = yield* threads.sendToThread({ |
| 2087 | projectId, |
| 2088 | commandId: CommandId.make(`command:launch:late-queued-follow-up-${ending}:send`), |
| 2089 | threadId: launched.threadId, |
| 2090 | messageId: MessageId.make(`message:launch:late-queued-follow-up-${ending}:send`), |
| 2091 | text: "Sent during setup", |
| 2092 | attachments: [], |
| 2093 | mode: "queue", |
| 2094 | createdBy: "user", |
| 2095 | creationSource: "web", |
| 2096 | }); |
| 2097 | assert.equal(queued.delivery, "queued"); |
| 2098 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 2099 | const held = projection.runs.at(-1)!; |
| 2100 | assert.equal(held.status, "queued"); |
| 2101 | assert.equal(held.queueHeld, true); |
| 2102 | |
| 2103 | // A message sent fresh after the setup ended waits behind it too, rather |
| 2104 | // than starting in the project checkout with no worktree. |
| 2105 | const sentAfter = yield* threads.sendToThread({ |
| 2106 | projectId, |
| 2107 | commandId: CommandId.make(`command:launch:late-queued-follow-up-${ending}:start`), |
| 2108 | threadId: launched.threadId, |
| 2109 | messageId: MessageId.make(`message:launch:late-queued-follow-up-${ending}:start`), |
| 2110 | text: "Sent after setup", |
| 2111 | attachments: [], |
| 2112 | mode: "auto", |
| 2113 | createdBy: "user", |
| 2114 | creationSource: "web", |
| 2115 | }); |
| 2116 | assert.equal(sentAfter.delivery, "queued"); |
| 2117 | yield* threads.dispatch({ |
| 2118 | type: "message.dispatch", |
| 2119 | commandId: CommandId.make(`command:launch:late-queued-follow-up-${ending}:wake`), |
| 2120 | threadId: launched.threadId, |
| 2121 | messageId: MessageId.make(`message:launch:late-queued-follow-up-${ending}:wake`), |
| 2122 | text: "Background task completed.", |
| 2123 | attachments: [], |
| 2124 | dispatchMode: { type: "queue_after_active" }, |
| 2125 | createdBy: "agent", |
| 2126 | creationSource: "provider", |
| 2127 | }); |
| 2128 | const wake = (yield* threads.getThreadProjection(launched.threadId)).runs.at(-1)!; |
| 2129 | assert.equal(wake.status, "queued"); |
| 2130 | assert.isTrue(wake.queueHeld); |
| 2131 | |
| 2132 | const sentAgain = yield* threads.sendToThread({ |
| 2133 | projectId, |
| 2134 | commandId: CommandId.make(`command:launch:late-queued-follow-up-${ending}:again`), |
| 2135 | threadId: launched.threadId, |
| 2136 | messageId: MessageId.make(`message:launch:late-queued-follow-up-${ending}:again`), |
| 2137 | text: "Sent after that", |
| 2138 | attachments: [], |
| 2139 | mode: "auto", |
| 2140 | createdBy: "user", |
| 2141 | creationSource: "web", |
| 2142 | }); |
| 2143 | assert.equal(sentAgain.delivery, "queued"); |
| 2144 | const after = yield* threads.getThreadProjection(launched.threadId); |
| 2145 | assert.isTrue(after.runs.find((run) => run.id === held.id)?.queueHeld); |
| 2146 | assert.deepStrictEqual( |
| 2147 | after.runs.slice(1).map((run) => [run.status, run.queueHeld === true]), |
| 2148 | [ |
| 2149 | ["queued", true], |
| 2150 | ["queued", true], |
| 2151 | ["queued", true], |
| 2152 | ["queued", true], |
| 2153 | ], |
| 2154 | ); |
| 2155 | assert.equal(after.thread.worktreePath, null); |
| 2156 | }).pipe(Effect.provide(harness.layer)); |
| 2157 | }, |
| 2158 | ); |
| 2159 | |
| 2160 | it.effect("replays a server-allocated launch", () => |
| 2161 | Effect.gen(function* () { |
| 2162 | const setupEntered = yield* Deferred.make<void>(); |
| 2163 | const allowSetup = yield* Deferred.make<void>(); |
| 2164 | const harness = makeHarness({ |
| 2165 | runSetup: () => |
| 2166 | Deferred.succeed(setupEntered, undefined).pipe( |
| 2167 | Effect.andThen(Deferred.await(allowSetup)), |
| 2168 | Effect.as({ status: "no-script" as const }), |
| 2169 | ), |
| 2170 | }); |
| 2171 | yield* Effect.gen(function* () { |
| 2172 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2173 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 2174 | const { threadId: _unusedThreadId, ...rest } = launchInput({ |
| 2175 | command: "command:launch:allocated-retry", |
| 2176 | thread: "unused", |
| 2177 | message: "Only once", |
| 2178 | workspace: { type: "worktree", baseRef: "main" }, |
| 2179 | }); |
| 2180 | const first = yield* launches.launch(rest); |
| 2181 | // One commit holds the thread and its first run, so no client sees the thread idle between. |
| 2182 | const launchCommits = yield* threads |
| 2183 | .streamStoredEventsFrom({ threadId: first.threadId }) |
| 2184 | .pipe( |
| 2185 | Stream.filter( |
| 2186 | (stored) => |
| 2187 | stored.event.type === "thread.created" || stored.event.type === "run.created", |
| 2188 | ), |
| 2189 | Stream.take(2), |
| 2190 | Stream.runCollect, |
| 2191 | ); |
| 2192 | assert.deepEqual( |
| 2193 | Array.from(launchCommits, (stored) => stored.commandId), |
| 2194 | [rest.commandId, rest.commandId], |
| 2195 | ); |
| 2196 | yield* Deferred.await(setupEntered); |
| 2197 | const retry = yield* launches.launch(rest); |
| 2198 | assert.equal(first.threadId, retry.threadId); |
| 2199 | assert.isFalse(first.resumed); |
| 2200 | assert.isTrue(retry.resumed); |
| 2201 | // Clients drop their pending copy once the thread reaches the message's commit. |
| 2202 | assert.isNumber(first.sequence); |
| 2203 | assert.equal(retry.sequence, first.sequence); |
| 2204 | assert.equal(harness.runSetup.mock.calls.length, 1); |
| 2205 | assert.equal(retry.projection.messages.length, 1); |
| 2206 | assert.equal(retry.projection.runs.length, 1); |
| 2207 | assert.equal(retry.projection.messages[0]?.id, first.projection.messages[0]?.id); |
| 2208 | assert.equal(retry.projection.runs[0]?.id, first.projection.runs[0]?.id); |
| 2209 | yield* Deferred.succeed(allowSetup, undefined); |
| 2210 | yield* threads.streamStoredEventsFrom({ threadId: first.threadId }).pipe( |
| 2211 | Stream.filter( |
| 2212 | (stored) => |
| 2213 | stored.commandId === CommandId.make(`${rest.commandId}:release`) && |
| 2214 | stored.event.type === "run.updated", |
| 2215 | ), |
| 2216 | Stream.runHead, |
| 2217 | ); |
| 2218 | const settled = yield* launches.launch(rest); |
| 2219 | assert.equal(settled.threadId, first.threadId); |
| 2220 | assert.isTrue(settled.resumed); |
| 2221 | assert.equal(settled.projection.messages[0]?.id, first.projection.messages[0]?.id); |
| 2222 | assert.equal(settled.projection.runs[0]?.id, first.projection.runs[0]?.id); |
| 2223 | assert.equal(harness.runSetup.mock.calls.length, 1); |
| 2224 | }).pipe(Effect.provide(harness.layer)); |
| 2225 | }), |
| 2226 | ); |
| 2227 | |
| 2228 | it.effect("replays an accepted launch after the project disables the instance", () => { |
| 2229 | const harness = makeHarness(); |
| 2230 | return Effect.gen(function* () { |
| 2231 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2232 | const settings = yield* ServerSettings.ServerSettingsService; |
| 2233 | const input = launchInput({ |
| 2234 | command: "command:launch:retry-after-disable", |
| 2235 | thread: "thread:launch:retry-after-disable", |
| 2236 | message: "Hello", |
| 2237 | }); |
| 2238 | const first = yield* launches.launch(input); |
| 2239 | |
| 2240 | yield* settings.updateSettings({ |
| 2241 | projectSettingsOverrides: { |
| 2242 | [projectId]: { providerInstances: { [modelSelection.instanceId]: { enabled: false } } }, |
| 2243 | }, |
| 2244 | }); |
| 2245 | |
| 2246 | const retry = yield* launches.launch(input); |
| 2247 | assert.equal(retry.threadId, first.threadId); |
| 2248 | assert.isTrue(retry.resumed); |
| 2249 | |
| 2250 | const fresh = yield* launches |
| 2251 | .launch( |
| 2252 | launchInput({ |
| 2253 | command: "command:launch:fresh-after-disable", |
| 2254 | thread: "thread:launch:fresh-after-disable", |
| 2255 | message: "Hello", |
| 2256 | }), |
| 2257 | ) |
| 2258 | .pipe(Effect.flip); |
| 2259 | if (fresh._tag !== "ThreadManagementProviderInstanceDisabledError") { |
| 2260 | assert.fail(`expected ThreadManagementProviderInstanceDisabledError, got ${fresh._tag}`); |
| 2261 | } |
| 2262 | }).pipe(Effect.provide(harness.layer)); |
| 2263 | }); |
| 2264 | |
| 2265 | it.effect("an agent's launch never starts work above the modes it asks for", () => { |
| 2266 | const harness = makeHarness(); |
| 2267 | return Effect.gen(function* () { |
| 2268 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2269 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 2270 | // The first launch, at full access, creates the thread without a message. |
| 2271 | const created = yield* launches.launch( |
| 2272 | launchInput({ command: "command:launch:narrowed-retry", thread: "thread:narrowed" }), |
| 2273 | ); |
| 2274 | // The same key comes back from a narrower agent, now carrying a message, |
| 2275 | // as a retry or a concurrent launch that lost the create would. |
| 2276 | const failed = yield* launches |
| 2277 | .launch({ |
| 2278 | ...launchInput({ |
| 2279 | command: "command:launch:narrowed-retry", |
| 2280 | thread: "thread:narrowed", |
| 2281 | message: "Run this", |
| 2282 | }), |
| 2283 | runtimeMode: "approval-required", |
| 2284 | interactionMode: "plan", |
| 2285 | createdBy: "agent", |
| 2286 | creationSource: "mcp", |
| 2287 | }) |
| 2288 | .pipe(Effect.flip); |
| 2289 | if (failed._tag !== "ThreadLaunchError") { |
| 2290 | assert.fail(`expected ThreadLaunchError, got ${failed._tag}`); |
| 2291 | } |
| 2292 | assert.equal(failed.operation, "dispatch-message"); |
| 2293 | const projection = yield* threads.getThreadProjection(created.threadId); |
| 2294 | assert.equal(projection.runs.length, 0); |
| 2295 | assert.equal(projection.messages.length, 0); |
| 2296 | }).pipe(Effect.provide(harness.layer)); |
| 2297 | }); |
| 2298 | |
| 2299 | it.effect("rejects a server-allocated launch replay with a mismatching thread id", () => { |
| 2300 | const harness = makeHarness(); |
| 2301 | return Effect.gen(function* () { |
| 2302 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2303 | const { threadId: _unusedThreadId, ...rest } = launchInput({ |
| 2304 | command: "command:launch:allocated-mismatch", |
| 2305 | thread: "unused", |
| 2306 | message: "Mismatch", |
| 2307 | }); |
| 2308 | const first = yield* launches.launch(rest); |
| 2309 | const failed = yield* launches |
| 2310 | .launch({ |
| 2311 | ...rest, |
| 2312 | threadId: ThreadId.make("thread:launch:allocated-mismatch"), |
| 2313 | }) |
| 2314 | .pipe(Effect.flip); |
| 2315 | assert.notEqual(first.threadId, ThreadId.make("thread:launch:allocated-mismatch")); |
| 2316 | if (failed._tag !== "ThreadLaunchError") { |
| 2317 | assert.fail(`expected ThreadLaunchError, got ${failed._tag}`); |
| 2318 | } |
| 2319 | assert.equal(failed.operation, "create-thread"); |
| 2320 | assert.include(String(failed.cause), "cannot be replayed"); |
| 2321 | }).pipe(Effect.provide(harness.layer)); |
| 2322 | }); |
| 2323 | |
| 2324 | it.effect("does not treat an unrelated accepted command receipt as a launch", () => { |
| 2325 | const harness = makeHarness(); |
| 2326 | return Effect.gen(function* () { |
| 2327 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2328 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 2329 | const threadId = ThreadId.make("thread:launch:unrelated-receipt"); |
| 2330 | yield* threads.dispatch({ |
| 2331 | type: "thread.create", |
| 2332 | commandId: CommandId.make("command:launch:unrelated-receipt:create"), |
| 2333 | threadId, |
| 2334 | projectId, |
| 2335 | title: "Existing", |
| 2336 | modelSelection, |
| 2337 | runtimeMode: "full-access", |
| 2338 | interactionMode: "default", |
| 2339 | branch: null, |
| 2340 | worktreePath: null, |
| 2341 | createdBy: "user", |
| 2342 | creationSource: "web", |
| 2343 | }); |
| 2344 | yield* threads.dispatch({ |
| 2345 | type: "thread.metadata.update", |
| 2346 | commandId: CommandId.make("command:launch:unrelated-receipt"), |
| 2347 | threadId, |
| 2348 | expectedEmpty: true, |
| 2349 | }); |
| 2350 | const { threadId: _unusedThreadId, ...rest } = launchInput({ |
| 2351 | command: "command:launch:unrelated-receipt", |
| 2352 | thread: "unused", |
| 2353 | message: "Should not become a launch", |
| 2354 | }); |
| 2355 | const failed = yield* launches.launch(rest).pipe(Effect.flip); |
| 2356 | if (failed._tag !== "ThreadLaunchError") { |
| 2357 | assert.fail(`expected ThreadLaunchError, got ${failed._tag}`); |
| 2358 | } |
| 2359 | assert.equal(failed.operation, "create-thread"); |
| 2360 | assert.include(String(failed.cause), "cannot be replayed"); |
| 2361 | const projection = yield* threads.getThreadProjection(threadId); |
| 2362 | assert.equal(projection.messages.length, 0); |
| 2363 | assert.equal(projection.runs.length, 0); |
| 2364 | }).pipe(Effect.provide(harness.layer)); |
| 2365 | }); |
| 2366 | |
| 2367 | it.effect("bounds concurrent first launches to one thread per command", () => |
| 2368 | Effect.gen(function* () { |
| 2369 | const setupEntered = yield* Deferred.make<void>(); |
| 2370 | const allowSetup = yield* Deferred.make<void>(); |
| 2371 | const harness = makeHarness({ |
| 2372 | runSetup: () => |
| 2373 | Deferred.succeed(setupEntered, undefined).pipe( |
| 2374 | Effect.andThen(Deferred.await(allowSetup)), |
| 2375 | Effect.as({ status: "no-script" as const }), |
| 2376 | ), |
| 2377 | }); |
| 2378 | yield* Effect.gen(function* () { |
| 2379 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2380 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 2381 | const { threadId: _unusedThreadId, ...rest } = launchInput({ |
| 2382 | command: "command:launch:concurrent-allocated", |
| 2383 | thread: "unused", |
| 2384 | message: "Race me", |
| 2385 | workspace: { type: "worktree", baseRef: "main" }, |
| 2386 | }); |
| 2387 | const results = yield* Effect.all( |
| 2388 | [launches.launch(rest).pipe(Effect.exit), launches.launch(rest).pipe(Effect.exit)], |
| 2389 | { concurrency: "unbounded" }, |
| 2390 | ); |
| 2391 | const winner = results.find(Exit.isSuccess); |
| 2392 | assert.isDefined(winner); |
| 2393 | const threadId = winner!.value.threadId; |
| 2394 | for (const result of results) { |
| 2395 | if (Exit.isSuccess(result)) { |
| 2396 | assert.equal(result.value.threadId, threadId); |
| 2397 | continue; |
| 2398 | } |
| 2399 | const error = Cause.findErrorOption(result.cause).pipe(Option.getOrThrow); |
| 2400 | if (error._tag !== "ThreadLaunchError") { |
| 2401 | assert.fail(`expected ThreadLaunchError, got ${error._tag}`); |
| 2402 | } |
| 2403 | assert.equal(error.operation, "create-thread"); |
| 2404 | assert.include(String(error.cause), "cannot be replayed"); |
| 2405 | const retried = yield* launches.launch(rest); |
| 2406 | assert.equal(retried.threadId, threadId); |
| 2407 | } |
| 2408 | const projectThreads = yield* threads.listProjectThreads({ |
| 2409 | projectId, |
| 2410 | includeSubagents: false, |
| 2411 | }); |
| 2412 | assert.equal(projectThreads.length, 1); |
| 2413 | const projection = yield* threads.getThreadProjection(threadId); |
| 2414 | assert.equal(projection.messages.length, 1); |
| 2415 | assert.equal(projection.runs.length, 1); |
| 2416 | yield* Deferred.await(setupEntered); |
| 2417 | assert.equal(harness.runSetup.mock.calls.length, 1); |
| 2418 | yield* Deferred.succeed(allowSetup, undefined); |
| 2419 | }).pipe(Effect.provide(harness.layer)); |
| 2420 | }), |
| 2421 | ); |
| 2422 | |
| 2423 | it.effect("does not let a failing same-command caller strand a concurrent durable launch", () => |
| 2424 | Effect.gen(function* () { |
| 2425 | const setupEntered = yield* Deferred.make<void>(); |
| 2426 | const allowSetup = yield* Deferred.make<void>(); |
| 2427 | const harness = makeHarness({ |
| 2428 | runSetup: () => |
| 2429 | Deferred.succeed(setupEntered, undefined).pipe( |
| 2430 | Effect.andThen(Deferred.await(allowSetup)), |
| 2431 | Effect.as({ status: "no-script" as const }), |
| 2432 | ), |
| 2433 | }); |
| 2434 | yield* Effect.gen(function* () { |
| 2435 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2436 | const command = "command:launch:failed-owner-race"; |
| 2437 | const [failed, launched] = yield* Effect.all( |
| 2438 | [ |
| 2439 | launches |
| 2440 | .launch({ |
| 2441 | ...launchInput({ |
| 2442 | command, |
| 2443 | thread: "thread:launch:failed-owner-race", |
| 2444 | message: "This invalid reuse fails", |
| 2445 | workspace: { type: "worktree", baseRef: "main" }, |
| 2446 | }), |
| 2447 | reuseExistingThread: true, |
| 2448 | }) |
| 2449 | .pipe(Effect.exit), |
| 2450 | launches.launch( |
| 2451 | launchInput({ |
| 2452 | command, |
| 2453 | thread: "thread:launch:successful-peer", |
| 2454 | message: "This peer persists", |
| 2455 | workspace: { type: "worktree", baseRef: "main" }, |
| 2456 | }), |
| 2457 | ), |
| 2458 | ], |
| 2459 | { concurrency: "unbounded" }, |
| 2460 | ); |
| 2461 | assert.isTrue(Exit.isFailure(failed)); |
| 2462 | assert.equal(launched.projection.runs[0]?.status, "preparing"); |
| 2463 | const entered = yield* Deferred.await(setupEntered).pipe( |
| 2464 | Effect.timeoutOption(Duration.seconds(2)), |
| 2465 | ); |
| 2466 | assert.isTrue(Option.isSome(entered)); |
| 2467 | assert.equal(harness.runSetup.mock.calls.length, 1); |
| 2468 | yield* Deferred.succeed(allowSetup, undefined); |
| 2469 | }).pipe(Effect.provide(harness.layer)); |
| 2470 | }), |
| 2471 | ); |
| 2472 | |
| 2473 | it.effect("reports one concurrent same-command launch as new and the rest as resumed", () => |
| 2474 | Effect.gen(function* () { |
| 2475 | // Both launches read no receipt before either one claims the thread. |
| 2476 | const arrived = yield* Ref.make(0); |
| 2477 | const bothRead = yield* Deferred.make<void>(); |
| 2478 | const harness = makeHarness({ |
| 2479 | managedFolders: Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ |
| 2480 | namedProjectsRoot: "/projects", |
| 2481 | isScratchProject: () => Effect.succeed(false), |
| 2482 | folderForThread: () => |
| 2483 | Ref.updateAndGet(arrived, (count) => count + 1).pipe( |
| 2484 | Effect.tap((count) => |
| 2485 | count === 2 ? Deferred.succeed(bothRead, undefined) : Effect.void, |
| 2486 | ), |
| 2487 | Effect.andThen(Deferred.await(bothRead)), |
| 2488 | Effect.as(Option.none()), |
| 2489 | ), |
| 2490 | }), |
| 2491 | }); |
| 2492 | yield* Effect.gen(function* () { |
| 2493 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2494 | const input = launchInput({ |
| 2495 | command: "command:launch:concurrent-resumed", |
| 2496 | thread: "thread:launch:concurrent-resumed", |
| 2497 | }); |
| 2498 | const results = yield* Effect.all([launches.launch(input), launches.launch(input)], { |
| 2499 | concurrency: "unbounded", |
| 2500 | }); |
| 2501 | assert.deepEqual(results.map((result) => result.resumed).sort(), [false, true]); |
| 2502 | }).pipe(Effect.provide(harness.layer)); |
| 2503 | }), |
| 2504 | ); |
| 2505 | |
| 2506 | it.effect( |
| 2507 | "does not report a retry as resumed when the earlier attempt only claimed the thread", |
| 2508 | () => |
| 2509 | Effect.gen(function* () { |
| 2510 | const harness = makeHarness(); |
| 2511 | yield* Effect.gen(function* () { |
| 2512 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2513 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 2514 | const input = launchInput({ |
| 2515 | command: "command:launch:claimed-only", |
| 2516 | thread: "thread:launch:claimed-only", |
| 2517 | message: "Counted once", |
| 2518 | }); |
| 2519 | yield* threads.dispatch({ |
| 2520 | type: "thread.create", |
| 2521 | commandId: input.commandId, |
| 2522 | threadId: input.threadId, |
| 2523 | projectId: input.projectId, |
| 2524 | title: input.title, |
| 2525 | modelSelection: input.modelSelection, |
| 2526 | runtimeMode: input.runtimeMode, |
| 2527 | interactionMode: input.interactionMode, |
| 2528 | branch: null, |
| 2529 | worktreePath: null, |
| 2530 | createdBy: input.createdBy, |
| 2531 | creationSource: input.creationSource, |
| 2532 | }); |
| 2533 | const retried = yield* launches.launch(input); |
| 2534 | assert.isFalse(retried.resumed); |
| 2535 | assert.isTrue((yield* launches.launch(input)).resumed); |
| 2536 | }).pipe(Effect.provide(harness.layer)); |
| 2537 | }), |
| 2538 | ); |
| 2539 | |
| 2540 | it.effect( |
| 2541 | "schedules an accepted preparing message exactly once, from its accepted worktree base", |
| 2542 | () => |
| 2543 | Effect.gen(function* () { |
| 2544 | const setupEntered = yield* Deferred.make<void>(); |
| 2545 | const allowSetup = yield* Deferred.make<void>(); |
| 2546 | const fetched: Array<string> = []; |
| 2547 | const harness = makeHarness({ |
| 2548 | fetchWorktreeBaseCommit: ({ refName }) => |
| 2549 | Effect.sync(() => { |
| 2550 | fetched.push(refName); |
| 2551 | return null; |
| 2552 | }), |
| 2553 | hasCommit: ({ refName }) => Effect.succeed(refName === "main"), |
| 2554 | runSetup: () => |
| 2555 | Deferred.succeed(setupEntered, undefined).pipe( |
| 2556 | Effect.andThen(Deferred.await(allowSetup)), |
| 2557 | Effect.as({ status: "no-script" as const }), |
| 2558 | ), |
| 2559 | }); |
| 2560 | yield* Effect.gen(function* () { |
| 2561 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2562 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 2563 | const input = launchInput({ |
| 2564 | command: "command:launch:accepted-before-fork", |
| 2565 | thread: "thread:launch:accepted-before-fork", |
| 2566 | message: "Resume preparation", |
| 2567 | workspace: { type: "worktree", baseRef: "main" }, |
| 2568 | }); |
| 2569 | const messageId = MessageId.make("message:launch:accepted-before-fork"); |
| 2570 | |
| 2571 | yield* threads.dispatch({ |
| 2572 | type: "thread.create", |
| 2573 | commandId: input.commandId, |
| 2574 | threadId: input.threadId, |
| 2575 | projectId: input.projectId, |
| 2576 | title: input.title, |
| 2577 | modelSelection: input.modelSelection, |
| 2578 | runtimeMode: input.runtimeMode, |
| 2579 | interactionMode: input.interactionMode, |
| 2580 | branch: null, |
| 2581 | worktreePath: null, |
| 2582 | createdBy: input.createdBy, |
| 2583 | creationSource: input.creationSource, |
| 2584 | }); |
| 2585 | yield* threads.dispatch({ |
| 2586 | type: "message.dispatch", |
| 2587 | commandId: CommandId.make(`${input.commandId}:initial-message`), |
| 2588 | threadId: input.threadId, |
| 2589 | messageId, |
| 2590 | text: "Resume preparation", |
| 2591 | attachments: [], |
| 2592 | modelSelection: input.modelSelection, |
| 2593 | dispatchMode: { |
| 2594 | type: "defer_start", |
| 2595 | workspaceStrategy: { type: "worktree", baseRef: "main", startFromOrigin: true }, |
| 2596 | }, |
| 2597 | createdBy: input.createdBy, |
| 2598 | creationSource: input.creationSource, |
| 2599 | }); |
| 2600 | const preparing = yield* threads.getThreadProjection(input.threadId); |
| 2601 | assert.equal(preparing.runs[0]?.status, "preparing"); |
| 2602 | |
| 2603 | const [first, second] = yield* Effect.all( |
| 2604 | [launches.launch(input), launches.launch(input)], |
| 2605 | { |
| 2606 | concurrency: "unbounded", |
| 2607 | }, |
| 2608 | ); |
| 2609 | yield* Deferred.await(setupEntered); |
| 2610 | assert.isTrue(first.resumed); |
| 2611 | assert.isTrue(second.resumed); |
| 2612 | assert.equal(harness.runSetup.mock.calls.length, 1); |
| 2613 | assert.deepEqual(fetched, ["main"]); |
| 2614 | yield* Deferred.succeed(allowSetup, undefined); |
| 2615 | }).pipe(Effect.provide(harness.layer)); |
| 2616 | }), |
| 2617 | ); |
| 2618 | |
| 2619 | it.effect("prepares a launch whose caller goes away after its first message commits", () => |
| 2620 | Effect.gen(function* () { |
| 2621 | const messageCommitted = yield* Deferred.make<void>(); |
| 2622 | const finishDispatch = yield* Deferred.make<void>(); |
| 2623 | const setupEntered = yield* Deferred.make<void>(); |
| 2624 | const harness = makeHarness({ |
| 2625 | runSetup: () => |
| 2626 | Deferred.succeed(setupEntered, undefined).pipe(Effect.as({ status: "no-script" as const })), |
| 2627 | dispatch: (command, dispatch) => |
| 2628 | dispatch(command).pipe( |
| 2629 | Effect.tap((result) => |
| 2630 | result.storedEvents.some((stored) => stored.event.type === "run.created") |
| 2631 | ? Deferred.succeed(messageCommitted, undefined).pipe( |
| 2632 | Effect.andThen(Deferred.await(finishDispatch)), |
| 2633 | ) |
| 2634 | : Effect.void, |
| 2635 | ), |
| 2636 | ), |
| 2637 | }); |
| 2638 | yield* Effect.gen(function* () { |
| 2639 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2640 | const launch = yield* Effect.forkChild( |
| 2641 | launches.launch( |
| 2642 | launchInput({ |
| 2643 | command: "command:launch:caller-gone", |
| 2644 | thread: "thread:launch:caller-gone", |
| 2645 | message: "Prepare without the caller", |
| 2646 | workspace: { type: "worktree", baseRef: "main" }, |
| 2647 | }), |
| 2648 | ), |
| 2649 | ); |
| 2650 | yield* Deferred.await(messageCommitted); |
| 2651 | yield* Effect.sync(() => launch.interruptUnsafe()); |
| 2652 | yield* Deferred.succeed(finishDispatch, undefined); |
| 2653 | yield* Fiber.await(launch); |
| 2654 | yield* Deferred.await(setupEntered); |
| 2655 | }).pipe(Effect.provide(harness.layer)); |
| 2656 | }), |
| 2657 | ); |
| 2658 | |
| 2659 | it.effect("creates a strong provider-thread mapping for an imported native session", () => { |
| 2660 | const harness = makeHarness(); |
| 2661 | return Effect.gen(function* () { |
| 2662 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2663 | const input = { |
| 2664 | ...launchInput({ |
| 2665 | command: "command:launch:imported-native-session", |
| 2666 | thread: "thread:launch:imported-native-session", |
| 2667 | }), |
| 2668 | importedNativeThread: { |
| 2669 | ref: { |
| 2670 | driver: ProviderDriverKind.make("codex"), |
| 2671 | nativeId: "native-session-42", |
| 2672 | strength: "strong" as const, |
| 2673 | }, |
| 2674 | metadata: { |
| 2675 | title: "Native session", |
| 2676 | updatedAt: "2026-08-23T00:00:00Z", |
| 2677 | }, |
| 2678 | }, |
| 2679 | }; |
| 2680 | |
| 2681 | const launched = yield* launches.launch(input); |
| 2682 | |
| 2683 | assert.deepInclude(launched.projection.providerThreads[0], { |
| 2684 | id: IdAllocator.deriveProviderThread({ |
| 2685 | driver: input.importedNativeThread.ref.driver, |
| 2686 | providerInstanceId: modelSelection.instanceId, |
| 2687 | nativeThreadId: input.importedNativeThread.ref.nativeId, |
| 2688 | }), |
| 2689 | driver: input.importedNativeThread.ref.driver, |
| 2690 | providerInstanceId: modelSelection.instanceId, |
| 2691 | appThreadId: input.threadId, |
| 2692 | nativeThreadRef: input.importedNativeThread.ref, |
| 2693 | status: "not_loaded", |
| 2694 | nativeMetadata: input.importedNativeThread.metadata, |
| 2695 | }); |
| 2696 | assert.equal( |
| 2697 | launched.projection.thread.activeProviderThreadId, |
| 2698 | launched.projection.providerThreads[0]?.id, |
| 2699 | ); |
| 2700 | }).pipe(Effect.provide(harness.layer)); |
| 2701 | }); |
| 2702 | |
| 2703 | it.effect("shared intake preserves durable attachment bytes after a lost launch result", () => { |
| 2704 | const harness = makeHarness(); |
| 2705 | const layerFiles = ServerConfig.layerTest(process.cwd(), { prefix: "t3-message-intake-" }).pipe( |
| 2706 | Layer.provideMerge(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))), |
| 2707 | ); |
| 2708 | return Effect.gen(function* () { |
| 2709 | const config = yield* ServerConfig.ServerConfig; |
| 2710 | const fs = yield* FileSystem.FileSystem; |
| 2711 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2712 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 2713 | const pendingId = createPendingAttachmentId(); |
| 2714 | assert.isNotNull(pendingId); |
| 2715 | const attachment: ChatAttachment = { |
| 2716 | type: "image", |
| 2717 | id: ChatAttachmentId.make(pendingId), |
| 2718 | name: "image.png", |
| 2719 | mimeType: "image/png", |
| 2720 | sizeBytes: 4, |
| 2721 | }; |
| 2722 | const pendingPath = resolveAttachmentPath({ |
| 2723 | attachmentsDir: config.attachmentsDir, |
| 2724 | attachment, |
| 2725 | }); |
| 2726 | assert.isNotNull(pendingPath); |
| 2727 | yield* fs.makeDirectory(config.attachmentsDir, { recursive: true }); |
| 2728 | yield* fs.writeFile(pendingPath, new Uint8Array([1, 2, 3, 4])); |
| 2729 | const input = { |
| 2730 | ...launchInput({ command: "intake-launch", thread: "intake-thread" }), |
| 2731 | initialMessage: { |
| 2732 | messageId: MessageId.make("intake-first"), |
| 2733 | text: "First [file](t3-context://v1/file/intake-file)", |
| 2734 | context: { |
| 2735 | version: 1 as const, |
| 2736 | records: [ |
| 2737 | { |
| 2738 | version: 1 as const, |
| 2739 | contextId: ComposerContextId.make("intake-file"), |
| 2740 | kind: "file" as const, |
| 2741 | label: attachment.name, |
| 2742 | attachmentId: attachment.id, |
| 2743 | name: attachment.name, |
| 2744 | mimeType: attachment.mimeType, |
| 2745 | sizeBytes: attachment.sizeBytes, |
| 2746 | }, |
| 2747 | ], |
| 2748 | }, |
| 2749 | attachments: [attachment], |
| 2750 | }, |
| 2751 | }; |
| 2752 | const failed = yield* ThreadMessageIntake.launchThread(input).pipe( |
| 2753 | Effect.provideService(ThreadLaunch.ThreadLaunchService, { |
| 2754 | launch: (request) => |
| 2755 | launches.launch(request).pipe( |
| 2756 | Effect.andThen( |
| 2757 | new ThreadLaunch.ThreadLaunchError({ |
| 2758 | operation: "create-thread", |
| 2759 | commandId: request.commandId, |
| 2760 | projectId, |
| 2761 | cause: "lost result after acceptance", |
| 2762 | }), |
| 2763 | ), |
| 2764 | ), |
| 2765 | checkWorktreeBase: launches.checkWorktreeBase, |
| 2766 | isNonGitProject: launches.isNonGitProject, |
| 2767 | retryPreparation: launches.retryPreparation, |
| 2768 | prepareRun: launches.prepareRun, |
| 2769 | }), |
| 2770 | Effect.flip, |
| 2771 | ); |
| 2772 | assert.equal(failed._tag, "ThreadLaunchError"); |
| 2773 | const accepted = yield* threads.getThreadProjection(input.threadId); |
| 2774 | const stored = accepted.messages.find( |
| 2775 | (message) => message.id === input.initialMessage.messageId, |
| 2776 | ); |
| 2777 | assert.isDefined(stored); |
| 2778 | assert.notEqual(stored.attachments[0]?.id, attachment.id); |
| 2779 | const record = stored.context?.records[0]; |
| 2780 | assert.isDefined(record); |
| 2781 | assert.equal((record as { attachmentId: string }).attachmentId, stored.attachments[0]?.id); |
| 2782 | const userItem = accepted.turnItems.find( |
| 2783 | (item) => item.type === "user_message" && item.messageId === stored.id, |
| 2784 | ); |
| 2785 | assert.ok(userItem?.type === "user_message"); |
| 2786 | assert.deepEqual(userItem.context, stored.context); |
| 2787 | const storedPath = resolveAttachmentPath({ |
| 2788 | attachmentsDir: config.attachmentsDir, |
| 2789 | attachment: stored.attachments[0]!, |
| 2790 | }); |
| 2791 | assert.isNotNull(storedPath); |
| 2792 | assert.deepEqual(yield* fs.readFile(storedPath), new Uint8Array([1, 2, 3, 4])); |
| 2793 | assert.deepEqual(yield* fs.readFile(pendingPath), new Uint8Array([1, 2, 3, 4])); |
| 2794 | |
| 2795 | const replayed = yield* ThreadMessageIntake.launchThread(input); |
| 2796 | assert.equal(replayed.projection.messages[0]?.id, stored.id); |
| 2797 | assert.deepEqual(replayed.projection.messages[0]?.attachments, stored.attachments); |
| 2798 | const claimedFiles = Effect.map(fs.readDirectory(config.attachmentsDir), (files) => |
| 2799 | files.filter((name) => !name.startsWith("pending-")), |
| 2800 | ); |
| 2801 | assert.equal((yield* claimedFiles).length, 1); |
| 2802 | |
| 2803 | const duplicate = yield* ThreadMessageIntake.launchThread({ |
| 2804 | ...input, |
| 2805 | commandId: CommandId.make("intake-duplicate-create"), |
| 2806 | initialMessage: { ...input.initialMessage, messageId: MessageId.make("intake-duplicate") }, |
| 2807 | }).pipe(Effect.result); |
| 2808 | assert.ok(Result.isFailure(duplicate)); |
| 2809 | assert.ok(duplicate.failure._tag === "ThreadLaunchError"); |
| 2810 | assert.equal(duplicate.failure.operation, "create-thread"); |
| 2811 | assert.propertyVal(duplicate.failure.cause, "_tag", "OrchestratorThreadAlreadyExistsError"); |
| 2812 | assert.equal((yield* claimedFiles).length, 1); |
| 2813 | assert.deepEqual(yield* fs.readFile(storedPath), new Uint8Array([1, 2, 3, 4])); |
| 2814 | assert.deepEqual(yield* fs.readFile(pendingPath), new Uint8Array([1, 2, 3, 4])); |
| 2815 | |
| 2816 | const missingProject = yield* ThreadMessageIntake.launchThread({ |
| 2817 | ...input, |
| 2818 | commandId: CommandId.make("intake-no-project"), |
| 2819 | projectId: ProjectId.make("missing-project"), |
| 2820 | }).pipe(Effect.flip); |
| 2821 | assert.equal(missingProject._tag, "ThreadLaunchError"); |
| 2822 | assert.equal((yield* claimedFiles).length, 1); |
| 2823 | const missingThread = yield* dispatchIntakeCommand({ |
| 2824 | type: "message.dispatch", |
| 2825 | commandId: CommandId.make("intake-no-thread"), |
| 2826 | threadId: ThreadId.make("missing-thread"), |
| 2827 | messageId: MessageId.make("intake-missing"), |
| 2828 | text: "Missing", |
| 2829 | attachments: [attachment], |
| 2830 | dispatchMode: { type: "start_immediately" }, |
| 2831 | createdBy: "user", |
| 2832 | creationSource: "web", |
| 2833 | }).pipe(Effect.flip); |
| 2834 | assert.equal(missingThread._tag, "OrchestratorProjectionError"); |
| 2835 | assert.equal((yield* claimedFiles).length, 1); |
| 2836 | |
| 2837 | const dispatch = dispatchIntakeCommand({ |
| 2838 | type: "message.dispatch", |
| 2839 | commandId: CommandId.make("intake-dispatch"), |
| 2840 | threadId: input.threadId, |
| 2841 | messageId: MessageId.make("intake-second"), |
| 2842 | text: "Second", |
| 2843 | attachments: [attachment], |
| 2844 | dispatchMode: { type: "queue_after_active" }, |
| 2845 | createdBy: "user", |
| 2846 | creationSource: "web", |
| 2847 | }); |
| 2848 | yield* dispatch; |
| 2849 | yield* dispatch; |
| 2850 | const queuedProjection = yield* threads.getThreadProjection(input.threadId); |
| 2851 | const queuedRun = queuedProjection.runs.find( |
| 2852 | (run) => run.userMessageId === MessageId.make("intake-second"), |
| 2853 | ); |
| 2854 | assert.isDefined(queuedRun); |
| 2855 | assert.equal(queuedRun.status, "queued"); |
| 2856 | const queuedMessage = queuedProjection.messages.find( |
| 2857 | (message) => message.id === queuedRun.userMessageId, |
| 2858 | ); |
| 2859 | assert.isDefined(queuedMessage); |
| 2860 | const file: ChatAttachment = { |
| 2861 | type: "file", |
| 2862 | id: ChatAttachmentId.make(createPendingAttachmentId("pdf")), |
| 2863 | name: "queued.pdf", |
| 2864 | mimeType: "application/pdf", |
| 2865 | sizeBytes: 4, |
| 2866 | }; |
| 2867 | const filePath = resolveAttachmentPath({ |
| 2868 | attachmentsDir: config.attachmentsDir, |
| 2869 | attachment: file, |
| 2870 | }); |
| 2871 | assert.isNotNull(filePath); |
| 2872 | yield* fs.writeFile(filePath, new Uint8Array([5, 6, 7, 8])); |
| 2873 | const edit = dispatchIntakeCommand({ |
| 2874 | type: "queued-run.edit", |
| 2875 | commandId: CommandId.make("intake-edit"), |
| 2876 | threadId: input.threadId, |
| 2877 | runId: queuedRun.id, |
| 2878 | text: "Edited with a file", |
| 2879 | attachments: [...queuedMessage.attachments, file], |
| 2880 | }); |
| 2881 | yield* edit; |
| 2882 | yield* edit; |
| 2883 | const editedProjection = yield* threads.getThreadProjection(input.threadId); |
| 2884 | const editedMessage = editedProjection.messages.find( |
| 2885 | (message) => message.id === queuedRun.userMessageId, |
| 2886 | ); |
| 2887 | assert.isDefined(editedMessage); |
| 2888 | assert.equal(editedMessage.attachments.length, 2); |
| 2889 | assert.deepEqual(editedMessage.attachments[0], queuedMessage.attachments[0]); |
| 2890 | assert.notEqual(editedMessage.attachments[1]?.id, file.id); |
| 2891 | const durableFilePath = resolveAttachmentPath({ |
| 2892 | attachmentsDir: config.attachmentsDir, |
| 2893 | attachment: editedMessage.attachments[1]!, |
| 2894 | }); |
| 2895 | assert.isNotNull(durableFilePath); |
| 2896 | assert.deepEqual(yield* fs.readFile(durableFilePath), new Uint8Array([5, 6, 7, 8])); |
| 2897 | assert.deepEqual(yield* fs.readFile(filePath), new Uint8Array([5, 6, 7, 8])); |
| 2898 | const beforeRejectedEdit = (yield* claimedFiles).length; |
| 2899 | const rejectedEdit = yield* dispatchIntakeCommand({ |
| 2900 | type: "queued-run.edit", |
| 2901 | commandId: CommandId.make("intake-edit-rejected"), |
| 2902 | threadId: input.threadId, |
| 2903 | runId: queuedRun.id, |
| 2904 | text: "", |
| 2905 | attachments: [file], |
| 2906 | }).pipe(Effect.flip); |
| 2907 | assert.equal(rejectedEdit._tag, "OrchestratorCommandRejectedError"); |
| 2908 | assert.equal((yield* claimedFiles).length, beforeRejectedEdit); |
| 2909 | assert.deepEqual(yield* fs.readFile(filePath), new Uint8Array([5, 6, 7, 8])); |
| 2910 | const send = ThreadMessageIntake.sendToThread({ |
| 2911 | commandId: CommandId.make("intake-send"), |
| 2912 | projectId, |
| 2913 | threadId: input.threadId, |
| 2914 | messageId: MessageId.make("intake-third"), |
| 2915 | text: "Third", |
| 2916 | attachments: [attachment], |
| 2917 | mode: "queue", |
| 2918 | createdBy: "agent", |
| 2919 | creationSource: "mcp", |
| 2920 | }); |
| 2921 | yield* send; |
| 2922 | yield* send; |
| 2923 | assert.equal((yield* claimedFiles).length, 4); |
| 2924 | const final = yield* threads.getThreadProjection(input.threadId); |
| 2925 | assert.equal(final.messages.length, 3); |
| 2926 | for (const message of final.messages) { |
| 2927 | const path = resolveAttachmentPath({ |
| 2928 | attachmentsDir: config.attachmentsDir, |
| 2929 | attachment: message.attachments[0]!, |
| 2930 | }); |
| 2931 | assert.isNotNull(path); |
| 2932 | assert.deepEqual(yield* fs.readFile(path), new Uint8Array([1, 2, 3, 4])); |
| 2933 | } |
| 2934 | }).pipe(Effect.provide(Layer.mergeAll(harness.layer, layerFiles))); |
| 2935 | }); |
| 2936 | |
| 2937 | it.effect("cancels tracked setup before provider work is released", () => |
| 2938 | Effect.gen(function* () { |
| 2939 | const entered = yield* Deferred.make<void>(); |
| 2940 | const renamed = yield* Deferred.make<void>(); |
| 2941 | const harness = makeHarness({ |
| 2942 | renameBranch: (input) => |
| 2943 | Deferred.succeed(renamed, undefined).pipe(Effect.as({ branch: input.newBranch })), |
| 2944 | runSetup: () => |
| 2945 | Deferred.await(renamed).pipe( |
| 2946 | Effect.andThen(Deferred.succeed(entered, undefined)), |
| 2947 | Effect.andThen(Effect.never), |
| 2948 | ), |
| 2949 | }); |
| 2950 | yield* Effect.gen(function* () { |
| 2951 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2952 | const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; |
| 2953 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 2954 | const outbox = yield* EffectOutbox.EffectOutboxV2; |
| 2955 | const input = launchInput({ |
| 2956 | command: "launch:cancel-tracked", |
| 2957 | thread: "thread:cancel-tracked", |
| 2958 | message: "Start", |
| 2959 | workspace: { type: "worktree", baseRef: "main" }, |
| 2960 | }); |
| 2961 | const launched = yield* launches.launch(input); |
| 2962 | yield* Deferred.await(entered); |
| 2963 | assert.equal((yield* tracker.get(launched.threadId))?.phase, "running"); |
| 2964 | assert.isTrue(yield* tracker.cancel(launched.threadId)); |
| 2965 | assert.equal((yield* tracker.get(launched.threadId))?.phase, "cancelled"); |
| 2966 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 2967 | assert.equal(projection.runs[0]?.status, "failed"); |
| 2968 | assert.isNull(projection.thread.worktreePath); |
| 2969 | assert.deepEqual(harness.deleteLocalBranch.mock.calls[0]?.[0], { |
| 2970 | cwd: "/repo", |
| 2971 | refName: "generated-branch", |
| 2972 | force: true, |
| 2973 | }); |
| 2974 | assert.isEmpty(yield* outbox.listByCommandId(CommandId.make(`${input.commandId}:release`))); |
| 2975 | }).pipe(Effect.provide(harness.layer)); |
| 2976 | }), |
| 2977 | ); |
| 2978 | |
| 2979 | it.effect( |
| 2980 | "deletes a claimed worktree's branch when setup is cancelled before checkout returns", |
| 2981 | () => |
| 2982 | Effect.gen(function* () { |
| 2983 | const claimed = yield* Deferred.make<void>(); |
| 2984 | const harness = makeHarness({ |
| 2985 | createWorktree: (_input, options) => |
| 2986 | (options?.progress?.onWorktreeClaimed?.("/repo-worktrees/feature") ?? Effect.void).pipe( |
| 2987 | Effect.andThen(Deferred.succeed(claimed, undefined)), |
| 2988 | Effect.andThen(Effect.never), |
| 2989 | ), |
| 2990 | }); |
| 2991 | yield* Effect.gen(function* () { |
| 2992 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 2993 | const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; |
| 2994 | const launched = yield* launches.launch( |
| 2995 | launchInput({ |
| 2996 | command: "launch:cancel-claimed", |
| 2997 | thread: "thread:cancel-claimed", |
| 2998 | message: "Start", |
| 2999 | workspace: { type: "worktree", baseRef: "main" }, |
| 3000 | }), |
| 3001 | ); |
| 3002 | yield* Deferred.await(claimed); |
| 3003 | assert.isTrue(yield* tracker.cancel(launched.threadId)); |
| 3004 | assert.equal(harness.removeWorktree.mock.calls[0]?.[0].path, "/repo-worktrees/feature"); |
| 3005 | assert.equal( |
| 3006 | harness.deleteLocalBranch.mock.calls[0]?.[0].refName, |
| 3007 | harness.createWorktree.mock.calls[0]?.[0].newRefName, |
| 3008 | ); |
| 3009 | }).pipe(Effect.provide(harness.layer)); |
| 3010 | }), |
| 3011 | ); |
| 3012 | |
| 3013 | it.effect("stops an in-flight branch rename when tracked setup is cancelled", () => |
| 3014 | Effect.gen(function* () { |
| 3015 | const setupEntered = yield* Deferred.make<void>(); |
| 3016 | const branchNameStarted = yield* Deferred.make<void>(); |
| 3017 | const allowBranchName = yield* Deferred.make<void>(); |
| 3018 | const branchNameInterrupted = yield* Deferred.make<void>(); |
| 3019 | const renameAttempted = yield* Deferred.make<void>(); |
| 3020 | const harness = makeHarness({ |
| 3021 | renameBranch: (input) => |
| 3022 | Deferred.succeed(renameAttempted, undefined).pipe(Effect.as({ branch: input.newBranch })), |
| 3023 | runSetup: () => Deferred.succeed(setupEntered, undefined).pipe(Effect.andThen(Effect.never)), |
| 3024 | generateBranchName: () => |
| 3025 | Deferred.succeed(branchNameStarted, undefined).pipe( |
| 3026 | Effect.andThen(Deferred.await(allowBranchName)), |
| 3027 | Effect.as({ branch: "generated-branch" }), |
| 3028 | Effect.onInterrupt(() => Deferred.succeed(branchNameInterrupted, undefined)), |
| 3029 | ), |
| 3030 | }); |
| 3031 | yield* Effect.gen(function* () { |
| 3032 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3033 | const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; |
| 3034 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 3035 | const launched = yield* launches.launch( |
| 3036 | launchInput({ |
| 3037 | command: "launch:cancel-renaming", |
| 3038 | thread: "thread:cancel-renaming", |
| 3039 | message: "Start", |
| 3040 | workspace: { type: "worktree", baseRef: "main" }, |
| 3041 | }), |
| 3042 | ); |
| 3043 | yield* Deferred.await(setupEntered); |
| 3044 | yield* Deferred.await(branchNameStarted); |
| 3045 | assert.isTrue(yield* tracker.cancel(launched.threadId)); |
| 3046 | yield* Deferred.succeed(allowBranchName, undefined); |
| 3047 | yield* Effect.raceFirst( |
| 3048 | Deferred.await(branchNameInterrupted), |
| 3049 | Deferred.await(renameAttempted), |
| 3050 | ); |
| 3051 | assert.isTrue( |
| 3052 | yield* Deferred.isDone(branchNameInterrupted), |
| 3053 | "the cancelled setup's branch rename kept running", |
| 3054 | ); |
| 3055 | assert.equal(harness.renameBranch.mock.calls.length, 0); |
| 3056 | assert.isNull((yield* threads.getThreadProjection(launched.threadId)).thread.worktreePath); |
| 3057 | assert.equal( |
| 3058 | harness.deleteLocalBranch.mock.calls[0]?.[0].refName, |
| 3059 | harness.createWorktree.mock.calls[0]?.[0].newRefName, |
| 3060 | ); |
| 3061 | }).pipe(Effect.provide(harness.layer)); |
| 3062 | }), |
| 3063 | ); |
| 3064 | |
| 3065 | it.effect("starts the agent of a new worktree thread only after its branch is renamed", () => |
| 3066 | Effect.gen(function* () { |
| 3067 | const branchNameStarted = yield* Deferred.make<void>(); |
| 3068 | const allowBranchName = yield* Deferred.make<void>(); |
| 3069 | const releasedAtRename = yield* Deferred.make<boolean>(); |
| 3070 | let releaseEffects: Effect.Effect<ReadonlyArray<unknown>> = Effect.succeed([]); |
| 3071 | const harness = makeHarness({ |
| 3072 | generateBranchName: () => |
| 3073 | Deferred.succeed(branchNameStarted, undefined).pipe( |
| 3074 | Effect.andThen(Deferred.await(allowBranchName)), |
| 3075 | Effect.as({ branch: "generated-branch" }), |
| 3076 | ), |
| 3077 | renameBranch: (input) => |
| 3078 | Effect.suspend(() => releaseEffects).pipe( |
| 3079 | Effect.flatMap((effects) => Deferred.succeed(releasedAtRename, effects.length > 0)), |
| 3080 | Effect.as({ branch: input.newBranch }), |
| 3081 | ), |
| 3082 | }); |
| 3083 | yield* Effect.gen(function* () { |
| 3084 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3085 | const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; |
| 3086 | const outbox = yield* EffectOutbox.EffectOutboxV2; |
| 3087 | const input = launchInput({ |
| 3088 | command: "launch:release-after-rename", |
| 3089 | thread: "thread:release-after-rename", |
| 3090 | message: "Start", |
| 3091 | workspace: { type: "worktree", baseRef: "main" }, |
| 3092 | }); |
| 3093 | releaseEffects = outbox |
| 3094 | .listByCommandId(CommandId.make(`${input.commandId}:release`)) |
| 3095 | .pipe(Effect.orDie); |
| 3096 | const launched = yield* launches.launch(input); |
| 3097 | yield* Deferred.await(branchNameStarted); |
| 3098 | yield* tracker.stream(launched.threadId).pipe( |
| 3099 | Stream.filter( |
| 3100 | (snapshot) => |
| 3101 | snapshot?.stages.some( |
| 3102 | (stage) => stage.id === "setup-script" && stage.status === "skipped", |
| 3103 | ) === true, |
| 3104 | ), |
| 3105 | Stream.runHead, |
| 3106 | ); |
| 3107 | yield* Deferred.succeed(allowBranchName, undefined); |
| 3108 | assert.isFalse( |
| 3109 | yield* Deferred.await(releasedAtRename), |
| 3110 | "the agent's run was released while its branch still had the temporary name", |
| 3111 | ); |
| 3112 | }).pipe(Effect.provide(harness.layer)); |
| 3113 | }), |
| 3114 | ); |
| 3115 | |
| 3116 | it.effect("tells the thread when its worktree branch could not be renamed", () => |
| 3117 | Effect.gen(function* () { |
| 3118 | const harness = makeHarness({ |
| 3119 | generateBranchName: () => |
| 3120 | Effect.fail( |
| 3121 | new TextGenerationError({ |
| 3122 | operation: "generateBranchName", |
| 3123 | detail: "Failed to spawn Codex CLI process", |
| 3124 | }), |
| 3125 | ), |
| 3126 | }); |
| 3127 | yield* Effect.gen(function* () { |
| 3128 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3129 | const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; |
| 3130 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 3131 | const launched = yield* launches.launch( |
| 3132 | launchInput({ |
| 3133 | command: "launch:rename-fails", |
| 3134 | thread: "thread:rename-fails", |
| 3135 | message: "Start", |
| 3136 | workspace: { type: "worktree", baseRef: "main" }, |
| 3137 | }), |
| 3138 | ); |
| 3139 | yield* tracker.stream(launched.threadId).pipe( |
| 3140 | Stream.filter((snapshot) => snapshot?.phase === "done"), |
| 3141 | Stream.runHead, |
| 3142 | ); |
| 3143 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 3144 | const notice = projection.turnItems.find((item) => item.type === "system_notice"); |
| 3145 | assert.equal(notice?.type === "system_notice" ? notice.runId : null, projection.runs[0]?.id); |
| 3146 | assert.include( |
| 3147 | notice?.type === "system_notice" ? notice.message : "", |
| 3148 | `stays ${projection.thread.branch}. Text generation failed in generateBranchName: Failed to spawn Codex CLI process`, |
| 3149 | ); |
| 3150 | }).pipe(Effect.provide(harness.layer)); |
| 3151 | }), |
| 3152 | ); |
| 3153 | |
| 3154 | it.effect("starts the agent on the temporary branch when branch naming hangs", () => |
| 3155 | Effect.gen(function* () { |
| 3156 | const branchNameStarted = yield* Deferred.make<void>(); |
| 3157 | const harness = makeHarness({ |
| 3158 | // A rate-limited provider retries until the CLI's own timeout, minutes later. |
| 3159 | generateBranchName: () => |
| 3160 | Deferred.succeed(branchNameStarted, undefined).pipe(Effect.andThen(Effect.never)), |
| 3161 | }); |
| 3162 | yield* Effect.gen(function* () { |
| 3163 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3164 | const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; |
| 3165 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 3166 | const launched = yield* launches.launch( |
| 3167 | launchInput({ |
| 3168 | command: "launch:rename-hangs", |
| 3169 | thread: "thread:rename-hangs", |
| 3170 | message: "Start", |
| 3171 | workspace: { type: "worktree", baseRef: "main" }, |
| 3172 | }), |
| 3173 | ); |
| 3174 | yield* Deferred.await(branchNameStarted); |
| 3175 | yield* TestClock.adjust("20 seconds"); |
| 3176 | yield* tracker.stream(launched.threadId).pipe( |
| 3177 | Stream.filter((snapshot) => snapshot?.phase === "done"), |
| 3178 | Stream.runHead, |
| 3179 | ); |
| 3180 | assert.equal(harness.renameBranch.mock.calls.length, 0); |
| 3181 | const projection = yield* threads.getThreadProjection(launched.threadId); |
| 3182 | const notice = projection.turnItems.find((item) => item.type === "system_notice"); |
| 3183 | assert.include( |
| 3184 | notice?.type === "system_notice" ? notice.message : "", |
| 3185 | `stays ${projection.thread.branch}. Text generation failed in generateBranchName: Timed out after 20 seconds.`, |
| 3186 | ); |
| 3187 | }).pipe(Effect.provide(harness.layer)); |
| 3188 | }), |
| 3189 | ); |
| 3190 | |
| 3191 | it.effect("reports submodule downloads as their own setup step", () => |
| 3192 | Effect.gen(function* () { |
| 3193 | const progressReady = |
| 3194 | yield* Deferred.make< |
| 3195 | NonNullable< |
| 3196 | NonNullable< |
| 3197 | Parameters<GitWorkflow.GitWorkflowService["Service"]["createWorktree"]>[1] |
| 3198 | >["progress"] |
| 3199 | > |
| 3200 | >(); |
| 3201 | const release = yield* Deferred.make<void>(); |
| 3202 | const harness = makeHarness({ |
| 3203 | createWorktree: (input, options) => |
| 3204 | Deferred.succeed(progressReady, options?.progress ?? {}).pipe( |
| 3205 | Effect.andThen(Deferred.await(release)), |
| 3206 | Effect.as({ |
| 3207 | worktree: { |
| 3208 | path: "/repo-worktrees/feature", |
| 3209 | refName: input.newRefName, |
| 3210 | headSha: "abc", |
| 3211 | }, |
| 3212 | } as never), |
| 3213 | ), |
| 3214 | }); |
| 3215 | yield* Effect.gen(function* () { |
| 3216 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3217 | const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; |
| 3218 | const launched = yield* launches.launch( |
| 3219 | launchInput({ |
| 3220 | command: "launch:submodule-progress", |
| 3221 | thread: "thread:submodule-progress", |
| 3222 | message: "Start", |
| 3223 | workspace: { type: "worktree", baseRef: "main" }, |
| 3224 | }), |
| 3225 | ); |
| 3226 | const stage = (id: string) => |
| 3227 | tracker |
| 3228 | .get(launched.threadId) |
| 3229 | .pipe(Effect.map((snapshot) => snapshot?.stages.find((entry) => entry.id === id))); |
| 3230 | const progress = yield* Deferred.await(progressReady); |
| 3231 | const line = (text: string) => progress.onSubmoduleLine?.(text) ?? Effect.void; |
| 3232 | |
| 3233 | yield* progress.onSubmodulesStarted?.() ?? Effect.void; |
| 3234 | yield* line("Receiving objects: 20% (2/10), 4.00 MiB | 1.50 MiB/s"); |
| 3235 | yield* line("Receiving objects: 30% (3/10), 6.00 MiB | 1.50 MiB/s"); |
| 3236 | assert.equal((yield* stage("checkout"))?.status, "done"); |
| 3237 | assert.deepInclude(yield* stage("submodules"), { |
| 3238 | status: "running", |
| 3239 | detail: "Receiving objects: 20% (2/10), 4.00 MiB | 1.50 MiB/s", |
| 3240 | }); |
| 3241 | |
| 3242 | yield* TestClock.adjust("1 second"); |
| 3243 | yield* line("Receiving objects: 60% (6/10), 12.00 MiB | 1.50 MiB/s"); |
| 3244 | assert.equal( |
| 3245 | (yield* stage("submodules"))?.detail, |
| 3246 | "Receiving objects: 60% (6/10), 12.00 MiB | 1.50 MiB/s", |
| 3247 | ); |
| 3248 | |
| 3249 | yield* line("Submodule path 'vendor/o'hare': checked out 'abc'"); |
| 3250 | yield* progress.onSubmodulesFinished?.({ ok: true, detail: null }) ?? Effect.void; |
| 3251 | yield* Deferred.succeed(release, undefined); |
| 3252 | yield* tracker.stream(launched.threadId).pipe( |
| 3253 | Stream.filter((snapshot) => snapshot?.phase !== "running"), |
| 3254 | Stream.runHead, |
| 3255 | ); |
| 3256 | assert.deepInclude(yield* stage("submodules"), { |
| 3257 | status: "done", |
| 3258 | detail: "vendor/o'hare", |
| 3259 | }); |
| 3260 | }).pipe(Effect.provide(harness.layer)); |
| 3261 | }), |
| 3262 | ); |
| 3263 | |
| 3264 | it.effect.each([0, 1])("releases an async setup before its completion with exit %s", (exitCode) => |
| 3265 | Effect.gen(function* () { |
| 3266 | const completion = yield* Deferred.make<{ exitCode: number | null; durationMs: number }>(); |
| 3267 | const harness = makeHarness({ |
| 3268 | runSetup: () => |
| 3269 | Effect.succeed({ |
| 3270 | status: "started" as const, |
| 3271 | async: true, |
| 3272 | scriptId: "setup", |
| 3273 | scriptName: "Setup", |
| 3274 | scriptCommand: "vp install", |
| 3275 | terminalId: "setup", |
| 3276 | cwd: "/repo-worktrees/feature", |
| 3277 | completion: Deferred.await(completion), |
| 3278 | }), |
| 3279 | }); |
| 3280 | yield* Effect.gen(function* () { |
| 3281 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3282 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 3283 | const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; |
| 3284 | const launched = yield* launches.launch( |
| 3285 | launchInput({ |
| 3286 | command: `command:launch:async-${exitCode}`, |
| 3287 | thread: `thread:launch:async-${exitCode}`, |
| 3288 | message: "Start during setup", |
| 3289 | workspace: { type: "worktree", baseRef: "main" }, |
| 3290 | }), |
| 3291 | ); |
| 3292 | yield* tracker.stream(launched.threadId).pipe( |
| 3293 | Stream.filter( |
| 3294 | (snapshot) => |
| 3295 | snapshot?.stages.some((stage) => stage.id === "agent" && stage.status === "done") === |
| 3296 | true, |
| 3297 | ), |
| 3298 | Stream.runHead, |
| 3299 | ); |
| 3300 | const running = yield* threads.getThreadProjection(launched.threadId); |
| 3301 | assert.equal(running.runs[0]?.status, "starting"); |
| 3302 | assert.equal((yield* tracker.get(launched.threadId))?.phase, "running"); |
| 3303 | yield* Deferred.succeed(completion, { exitCode, durationMs: 1 }); |
| 3304 | yield* tracker.stream(launched.threadId).pipe( |
| 3305 | Stream.filter((snapshot) => snapshot?.phase === "done"), |
| 3306 | Stream.runHead, |
| 3307 | ); |
| 3308 | const settled = yield* tracker.get(launched.threadId); |
| 3309 | assert.equal( |
| 3310 | settled?.stages.find((stage) => stage.id === "setup-script")?.status, |
| 3311 | exitCode === 0 ? "done" : "failed", |
| 3312 | ); |
| 3313 | assert.deepInclude( |
| 3314 | settled?.stages.find((stage) => stage.id === "submodules"), |
| 3315 | { status: "skipped", detail: "none" }, |
| 3316 | ); |
| 3317 | assert.equal( |
| 3318 | (yield* threads.getThreadProjection(launched.threadId)).runs[0]?.status, |
| 3319 | "starting", |
| 3320 | ); |
| 3321 | }).pipe(Effect.provide(harness.layer)); |
| 3322 | }), |
| 3323 | ); |
| 3324 | |
| 3325 | it.effect("shows an async setup as done while the agent still waits for its branch name", () => |
| 3326 | Effect.gen(function* () { |
| 3327 | const branchNameStarted = yield* Deferred.make<void>(); |
| 3328 | const allowBranchName = yield* Deferred.make<void>(); |
| 3329 | const harness = makeHarness({ |
| 3330 | runSetup: () => |
| 3331 | Effect.succeed({ |
| 3332 | status: "started" as const, |
| 3333 | async: true, |
| 3334 | scriptId: "setup", |
| 3335 | scriptName: "Setup", |
| 3336 | scriptCommand: "vp install", |
| 3337 | terminalId: "setup", |
| 3338 | cwd: "/repo-worktrees/feature", |
| 3339 | completion: Effect.succeed({ exitCode: 0, durationMs: 1 }), |
| 3340 | }), |
| 3341 | generateBranchName: () => |
| 3342 | Deferred.succeed(branchNameStarted, undefined).pipe( |
| 3343 | Effect.andThen(Deferred.await(allowBranchName)), |
| 3344 | Effect.as({ branch: "generated-branch" }), |
| 3345 | ), |
| 3346 | }); |
| 3347 | yield* Effect.gen(function* () { |
| 3348 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3349 | const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; |
| 3350 | const launched = yield* launches.launch( |
| 3351 | launchInput({ |
| 3352 | command: "launch:async-setup-before-name", |
| 3353 | thread: "thread:async-setup-before-name", |
| 3354 | message: "Start", |
| 3355 | workspace: { type: "worktree", baseRef: "main" }, |
| 3356 | }), |
| 3357 | ); |
| 3358 | yield* Deferred.await(branchNameStarted); |
| 3359 | const snapshot = yield* tracker.stream(launched.threadId).pipe( |
| 3360 | Stream.filter( |
| 3361 | (current) => |
| 3362 | current?.stages.some( |
| 3363 | (stage) => |
| 3364 | (stage.id === "setup-script" && |
| 3365 | (stage.status === "done" || stage.status === "failed")) || |
| 3366 | (stage.id === "agent" && stage.status === "done"), |
| 3367 | ) === true, |
| 3368 | ), |
| 3369 | Stream.runHead, |
| 3370 | ); |
| 3371 | const stages = Option.getOrUndefined(snapshot)?.stages ?? []; |
| 3372 | const setupStage = stages.find((stage) => stage.id === "setup-script"); |
| 3373 | assert.equal(setupStage?.status, "done"); |
| 3374 | assert.isNotNull(setupStage?.endedAt ?? null); |
| 3375 | assert.notEqual(stages.find((stage) => stage.id === "agent")?.status, "done"); |
| 3376 | yield* Deferred.succeed(allowBranchName, undefined); |
| 3377 | }).pipe(Effect.provide(harness.layer)); |
| 3378 | }), |
| 3379 | ); |
| 3380 | |
| 3381 | it.effect.each(["origin/master", ":/initial"])( |
| 3382 | "refuses a worktree in a non-Git project before checking base %s", |
| 3383 | (baseRef) => |
| 3384 | Effect.gen(function* () { |
| 3385 | const harness = makeHarness({ |
| 3386 | git: { repositoryRoot: () => Effect.succeed(null) }, |
| 3387 | }); |
| 3388 | yield* Effect.gen(function* () { |
| 3389 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3390 | const result = yield* launches |
| 3391 | .checkWorktreeBase({ |
| 3392 | projectId, |
| 3393 | workspaceStrategy: { type: "worktree", baseRef, startFromOrigin: true }, |
| 3394 | }) |
| 3395 | .pipe(Effect.result); |
| 3396 | assert.isTrue(Result.isFailure(result)); |
| 3397 | if (Result.isFailure(result)) { |
| 3398 | assert.instanceOf(result.failure, ThreadLaunch.ThreadLaunchNotRepositoryError); |
| 3399 | assert.deepInclude(result.failure, { |
| 3400 | projectId, |
| 3401 | projectTitle: project.title, |
| 3402 | workspaceRoot: project.workspaceRoot, |
| 3403 | }); |
| 3404 | } |
| 3405 | yield* launches.checkWorktreeBase({ projectId, workspaceStrategy: { type: "root" } }); |
| 3406 | yield* launches.checkWorktreeBase({ |
| 3407 | projectId, |
| 3408 | workspaceStrategy: { type: "existing_worktree", worktreePath: "/existing-worktree" }, |
| 3409 | }); |
| 3410 | }).pipe(Effect.provide(harness.layer)); |
| 3411 | }), |
| 3412 | ); |
| 3413 | |
| 3414 | it.effect("leaves uncertain Git detection failures to workspace preparation", () => |
| 3415 | Effect.gen(function* () { |
| 3416 | const harness = makeHarness({ |
| 3417 | git: { |
| 3418 | repositoryRoot: () => |
| 3419 | Effect.fail( |
| 3420 | new GitCommandError({ |
| 3421 | operation: "detect-repository", |
| 3422 | command: "git", |
| 3423 | cwd: project.workspaceRoot, |
| 3424 | detail: "Detection failed.", |
| 3425 | }), |
| 3426 | ), |
| 3427 | }, |
| 3428 | hasCommit: () => Effect.succeed(true), |
| 3429 | }); |
| 3430 | yield* ThreadLaunch.ThreadLaunchService.pipe( |
| 3431 | Effect.flatMap((launches) => |
| 3432 | launches.checkWorktreeBase({ projectId, workspaceStrategy: worktreeStrategy }), |
| 3433 | ), |
| 3434 | Effect.provide(harness.layer), |
| 3435 | ); |
| 3436 | }), |
| 3437 | ); |
| 3438 | |
| 3439 | it.effect.each([ |
| 3440 | { name: "is missing", baseRef: "t3/renamed", startFromOrigin: false, origin: true }, |
| 3441 | { |
| 3442 | name: "has no origin to come from", |
| 3443 | baseRef: "t3/renamed", |
| 3444 | startFromOrigin: true, |
| 3445 | origin: false, |
| 3446 | }, |
| 3447 | { |
| 3448 | name: "was deleted on its remote", |
| 3449 | baseRef: "origin/development", |
| 3450 | startFromOrigin: true, |
| 3451 | origin: true, |
| 3452 | }, |
| 3453 | { |
| 3454 | name: "is a previous checkout there never was", |
| 3455 | baseRef: "-", |
| 3456 | startFromOrigin: false, |
| 3457 | origin: true, |
| 3458 | }, |
| 3459 | ])("refuses a new worktree whose base ref $name", (testCase) => |
| 3460 | Effect.gen(function* () { |
| 3461 | const harness = makeHarness({ |
| 3462 | hasCommit: ({ refName }) => Effect.succeed(refName === "HEAD"), |
| 3463 | fetchWorktreeBaseCommit: () => Effect.succeed(null), |
| 3464 | git: { |
| 3465 | resolveWorktreeBaseRemote: () => |
| 3466 | Effect.succeed(testCase.origin ? { remoteName: "origin", branchName: "main" } : null), |
| 3467 | hasRefNamed: () => Effect.succeed(false), |
| 3468 | }, |
| 3469 | }); |
| 3470 | yield* Effect.gen(function* () { |
| 3471 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3472 | const error = yield* launches |
| 3473 | .checkWorktreeBase({ |
| 3474 | projectId, |
| 3475 | workspaceStrategy: { |
| 3476 | type: "worktree", |
| 3477 | baseRef: testCase.baseRef, |
| 3478 | startFromOrigin: testCase.startFromOrigin, |
| 3479 | }, |
| 3480 | }) |
| 3481 | .pipe(Effect.flip); |
| 3482 | assert.deepInclude(error, { |
| 3483 | _tag: "ThreadLaunchBaseRefError", |
| 3484 | projectId, |
| 3485 | baseRef: testCase.baseRef, |
| 3486 | }); |
| 3487 | assert.equal( |
| 3488 | error.message, |
| 3489 | `Base ref "${testCase.baseRef}" does not resolve to a commit in project "Project" (/repo).`, |
| 3490 | ); |
| 3491 | }).pipe(Effect.provide(harness.layer)); |
| 3492 | }), |
| 3493 | ); |
| 3494 | |
| 3495 | it.effect("refuses a new worktree whose explicit branch already exists", () => |
| 3496 | Effect.gen(function* () { |
| 3497 | const fs = yield* FileSystem.FileSystem; |
| 3498 | const git = yield* GitVcsDriver.GitVcsDriver; |
| 3499 | const directory = yield* fs.makeTempDirectoryScoped({ prefix: "launch-branch-exists-" }); |
| 3500 | const cwd = `${directory}/repo`; |
| 3501 | const temporaryBranch = "t3code/0b5e7a1c-3f2d-4e8a-9b6c-1d2e3f4a5b6c"; |
| 3502 | yield* fs.makeDirectory(cwd); |
| 3503 | const command = (args: string[]) => git.execute({ operation: "launch-test", cwd, args }); |
| 3504 | yield* command(["init", "-b", "main"]); |
| 3505 | yield* command(["config", "user.name", "Test"]); |
| 3506 | yield* command(["config", "user.email", "test@example.test"]); |
| 3507 | yield* command(["commit", "--allow-empty", "-m", "initial"]); |
| 3508 | yield* command(["branch", "feature/idle"]); |
| 3509 | yield* command(["branch", temporaryBranch]); |
| 3510 | // Resolves as `refs/heads/feature/tagged` although no such branch exists. |
| 3511 | yield* command(["tag", "refs/heads/feature/tagged"]); |
| 3512 | yield* command(["worktree", "add", "-b", "feature/taken", `${directory}/taken`]); |
| 3513 | const harness = makeHarness({ |
| 3514 | hasCommit: ({ refName }) => |
| 3515 | command(["rev-parse", "--verify", `${refName}^{commit}`]).pipe( |
| 3516 | Effect.as(true), |
| 3517 | Effect.orElseSucceed(() => false), |
| 3518 | ), |
| 3519 | git: { listLocalBranchNames: () => git.listLocalBranchNames(cwd) }, |
| 3520 | }); |
| 3521 | yield* Effect.gen(function* () { |
| 3522 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3523 | const check = (branch: string, baseRef = "main") => |
| 3524 | launches |
| 3525 | .checkWorktreeBase({ |
| 3526 | projectId, |
| 3527 | workspaceStrategy: { type: "worktree", baseRef, branch }, |
| 3528 | }) |
| 3529 | .pipe( |
| 3530 | Effect.match({ |
| 3531 | onSuccess: () => [branch, "accepted"], |
| 3532 | onFailure: (error) => [branch, error._tag], |
| 3533 | }), |
| 3534 | ); |
| 3535 | assert.deepEqual( |
| 3536 | yield* Effect.forEach( |
| 3537 | ["feature/idle", "feature/taken", temporaryBranch, "feature/fresh", "feature/tagged"], |
| 3538 | (branch) => check(branch), |
| 3539 | ), |
| 3540 | [ |
| 3541 | ["feature/idle", "ThreadLaunchBranchExistsError"], |
| 3542 | ["feature/taken", "ThreadLaunchBranchExistsError"], |
| 3543 | [temporaryBranch, "ThreadLaunchBranchExistsError"], |
| 3544 | ["feature/fresh", "accepted"], |
| 3545 | ["feature/tagged", "accepted"], |
| 3546 | ], |
| 3547 | ); |
| 3548 | // A `:/text` base skips the base check but not the branch check. |
| 3549 | assert.deepEqual(yield* check("feature/taken", ":/initial"), [ |
| 3550 | "feature/taken", |
| 3551 | "ThreadLaunchBranchExistsError", |
| 3552 | ]); |
| 3553 | }).pipe(Effect.provide(harness.layer)); |
| 3554 | }).pipe( |
| 3555 | Effect.provide( |
| 3556 | GitVcsDriver.layer.pipe( |
| 3557 | Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "launch-branch-exists-" })), |
| 3558 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 3559 | ), |
| 3560 | ), |
| 3561 | ), |
| 3562 | ); |
| 3563 | |
| 3564 | it.effect.each([ |
| 3565 | { requested: "werkstatt/baseline", blocking: "werkstatt" }, |
| 3566 | { requested: "foo", blocking: "foo/bar" }, |
| 3567 | ])("refuses a new worktree branch $requested that collides with branch $blocking", (testCase) => |
| 3568 | Effect.gen(function* () { |
| 3569 | const harness = makeHarness({ |
| 3570 | hasCommit: () => Effect.succeed(true), |
| 3571 | git: { listLocalBranchNames: () => Effect.succeed(["main", "werkstatt", "foo/bar"]) }, |
| 3572 | }); |
| 3573 | yield* Effect.gen(function* () { |
| 3574 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3575 | const workspace = { type: "worktree" as const, baseRef: "main", branch: testCase.requested }; |
| 3576 | const commandId = CommandId.make("launch:branch-conflict"); |
| 3577 | const check = (branch: string) => |
| 3578 | launches.checkWorktreeBase({ |
| 3579 | commandId, |
| 3580 | projectId, |
| 3581 | workspaceStrategy: { ...workspace, branch }, |
| 3582 | }); |
| 3583 | yield* check("werkstatt-baseline"); |
| 3584 | const error = yield* check(testCase.requested).pipe(Effect.flip); |
| 3585 | assert.deepInclude(error, { |
| 3586 | _tag: "ThreadLaunchBranchConflictError", |
| 3587 | branch: testCase.requested, |
| 3588 | conflictingBranch: testCase.blocking, |
| 3589 | }); |
| 3590 | yield* launches.launch( |
| 3591 | launchInput({ command: commandId, thread: "thread:branch-conflict", workspace }), |
| 3592 | ); |
| 3593 | yield* check(testCase.requested); |
| 3594 | }).pipe(Effect.provide(harness.layer)); |
| 3595 | }), |
| 3596 | ); |
| 3597 | |
| 3598 | it.effect("replays an accepted send after the project disables the instance", () => { |
| 3599 | const harness = makeHarness(); |
| 3600 | const layerFiles = ServerConfig.layerTest(process.cwd(), { prefix: "t3-send-retry-" }).pipe( |
| 3601 | Layer.provideMerge(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))), |
| 3602 | ); |
| 3603 | return Effect.gen(function* () { |
| 3604 | const launches = yield* ThreadLaunch.ThreadLaunchService; |
| 3605 | const settings = yield* ServerSettings.ServerSettingsService; |
| 3606 | const created = yield* launches.launch( |
| 3607 | launchInput({ |
| 3608 | command: "command:send:retry-setup", |
| 3609 | thread: "thread:send:retry-after-disable", |
| 3610 | }), |
| 3611 | ); |
| 3612 | |
| 3613 | const sendInput = { |
| 3614 | commandId: CommandId.make("command:send:retry-after-disable"), |
| 3615 | projectId, |
| 3616 | threadId: created.threadId, |
| 3617 | messageId: MessageId.make("message:send:retry-after-disable"), |
| 3618 | text: "Hello again", |
| 3619 | attachments: [], |
| 3620 | mode: "auto" as const, |
| 3621 | createdBy: "user" as const, |
| 3622 | creationSource: "web" as const, |
| 3623 | }; |
| 3624 | const first = yield* ThreadMessageIntake.sendToThread(sendInput); |
| 3625 | |
| 3626 | yield* settings.updateSettings({ |
| 3627 | projectSettingsOverrides: { |
| 3628 | [projectId]: { providerInstances: { [modelSelection.instanceId]: { enabled: false } } }, |
| 3629 | }, |
| 3630 | }); |
| 3631 | |
| 3632 | const retry = yield* ThreadMessageIntake.sendToThread(sendInput); |
| 3633 | assert.equal(retry.message.id, first.message.id); |
| 3634 | |
| 3635 | const fresh = yield* ThreadMessageIntake.sendToThread({ |
| 3636 | ...sendInput, |
| 3637 | commandId: CommandId.make("command:send:fresh-after-disable"), |
| 3638 | messageId: MessageId.make("message:send:fresh-after-disable"), |
| 3639 | }).pipe(Effect.flip); |
| 3640 | if (fresh._tag !== "ThreadManagementProviderInstanceDisabledError") { |
| 3641 | assert.fail(`expected ThreadManagementProviderInstanceDisabledError, got ${fresh._tag}`); |
| 3642 | } |
| 3643 | }).pipe(Effect.provide(Layer.mergeAll(harness.layer, layerFiles))); |
| 3644 | }); |