diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 3213027e059df..f26253f715413 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -86,6 +86,11 @@ import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMoc const decodeTarget = Schema.decodeUnknownEffect(OrchestratorMcpTarget); +const localRemoteDelegationLayer = Layer.mock(RemoteDelegation.RemoteDelegation)({ + place: (scope) => Effect.succeed(scope.environmentId), + placed: () => Effect.succeedNone, +}); + const layerOrchestratorService = OrchestratorMcpService.layer.pipe( Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), @@ -217,7 +222,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -341,7 +346,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -487,7 +492,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -586,7 +591,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -706,7 +711,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -817,7 +822,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -919,7 +924,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1028,7 +1033,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1125,7 +1130,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1219,7 +1224,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1311,7 +1316,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1501,7 +1506,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1781,7 +1786,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -1911,7 +1916,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2003,7 +2008,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2052,7 +2057,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2118,7 +2123,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2256,7 +2261,7 @@ describe("OrchestratorMcpService provider resolution", () => { ]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), Layer.mock(HostResources.HostResources)({ read: Effect.succeed(hostSnapshot) }), ); @@ -2443,7 +2448,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId, opencodeInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), @@ -2601,7 +2606,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([museInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2702,7 +2707,7 @@ describe("OrchestratorMcpService provider resolution", () => { getById: () => Effect.succeedSome({ id: projectId, workspaceRoot } as never), }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2784,7 +2789,7 @@ describe("OrchestratorMcpService provider resolution", () => { Effect.succeedSome({ id: projectId, title: "parent", workspaceRoot } as never), }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const notARepository = (cwd: string) => @@ -2886,20 +2891,31 @@ describe("OrchestratorMcpService provider resolution", () => { }), }), ServerSettings.layerTest(), - providerRegistryLayer([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + refreshWorkspaceSnapshot: () => + Effect.succeed([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + }), adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedSome({ id: projectId, title: "parent", workspaceRoot } as never), + workspaceScanDirectory: Effect.succeed, }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), Layer.mock(ThreadLaunchService.ThreadLaunchService)({ isNonGitProject: () => Effect.succeed(false), @@ -2939,6 +2955,230 @@ describe("OrchestratorMcpService provider resolution", () => { ), ); + it.live( + "places isolation: worktree on a headless host from the pushed ref and refuses unpushed commits while a human is active", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const git = yield* GitVcsDriver.GitVcsDriver; + const remoteRoot = yield* fileSystem.realPath( + yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-pushed-origin-" }), + ); + const workspaceRoot = yield* fileSystem.realPath( + yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-pushed-clone-" }), + ); + yield* git.execute({ operation: "pushed-test", cwd: remoteRoot, args: ["init", "--bare"] }); + for (const args of [ + ["init", "-b", "main"], + ["config", "user.email", "delegate@example.test"], + ["config", "user.name", "Delegate"], + ["commit", "--allow-empty", "-m", "initial"], + ["remote", "add", "origin", remoteRoot], + ["push", "-u", "origin", "main"], + ]) { + yield* git.execute({ operation: "pushed-test", cwd: workspaceRoot, args }); + } + + const remoteEnvId = EnvironmentId.make("environment:r720-headless"); + const delegatedCalls: Array<{ + readonly environmentId: EnvironmentId; + readonly workspaceStrategy: unknown; + }> = []; + const remoteTask = { + id: taskId, + threadId: parentThreadId, + origin: "app_owned", + childThreadId: null, + remoteChild: { + environmentId: remoteEnvId, + threadId: childThreadId, + label: "R720", + title: "Review PR", + }, + providerInstanceId: codexInstanceId, + model: "gpt-5.4", + status: "running", + result: null, + }; + const dependencies = Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), + getThreadRecords: () => + Effect.succeed({ + ...parentProjection([remoteTask]), + thread: { + ...parentProjection([]).thread, + worktreePath: null, + branch: "main", + }, + } as OrchestrationV2ThreadProjection), + }), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + refreshWorkspaceSnapshot: () => + Effect.succeed([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + }), + adapterRegistryLayer([codexInstanceId]), + Layer.mock(ProjectService.ProjectService)({ + getById: () => + Effect.succeedSome({ id: projectId, title: "parent", workspaceRoot } as never), + workspaceScanDirectory: Effect.succeed, + }), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(HostResources.HostResources)({ + read: Effect.succeed({ + sampledAt: 0, + cpuUtilization: 0.1, + cpuCount: 8, + availableMemoryBytes: 8 * 1024 ** 3, + totalMemoryBytes: 16 * 1024 ** 3, + loadPerCpu: 0.1, + runningAgents: 0, + placementRole: "interactive", + humanActive: true, + }), + }), + Layer.mock(RemoteDelegation.RemoteDelegation)({ + place: () => Effect.succeed(remoteEnvId), + placed: () => Effect.succeedNone, + delegate: (_scope, delegateInput) => { + delegatedCalls.push({ + environmentId: delegateInput.target.environmentId, + workspaceStrategy: delegateInput.workspaceStrategy, + }); + return Effect.succeed({ taskId }); + }, + runStatus: () => + Effect.succeed({ + runStatus: "running", + peerStatus: "reachable", + lastSeenAt: undefined, + }), + }), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({ + isNonGitProject: () => Effect.succeed(false), + }), + Layer.succeed(GitVcsDriver.GitVcsDriver, git), + ); + + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const placed = yield* service.delegateTask(scope, { + task: "Review PR from pushed ref.", + isolation: "worktree", + mode: "async", + clientRequestId: "pushed-worktree-1", + }); + assert.equal(placed.remoteChild?.environmentId, remoteEnvId); + assert.deepEqual(delegatedCalls, [ + { + environmentId: remoteEnvId, + workspaceStrategy: { + type: "worktree", + baseRef: "origin/main", + startFromOrigin: true, + }, + }, + ]); + + // Once local HEAD has an unpushed commit, remote placement cannot fetch it and the + // active-human interactive host refuses running locally without needsLocalCheckout. + yield* git.execute({ + operation: "pushed-test", + cwd: workspaceRoot, + args: ["commit", "--allow-empty", "-m", "unpushed local commit"], + }); + const refused = yield* service + .delegateTask(scope, { + task: "Review with unpushed local commit.", + isolation: "worktree", + mode: "async", + clientRequestId: "unpushed-worktree-1", + }) + .pipe(Effect.flip); + assert.equal(refused.code, "invalid_request"); + assert.include(refused.message, "active"); + assert.include(refused.message, "needsLocalCheckout"); + assert.equal(delegatedCalls.length, 1); + + // Push the second commit to origin/main, then check out an unpushed branch at the + // older commit (HEAD~1). Even though HEAD is an ancestor of origin/main, it must NOT + // fall back to the newer origin/main tip. + yield* git.execute({ + operation: "pushed-test", + cwd: workspaceRoot, + args: ["push", "origin", "main"], + }); + yield* git.execute({ + operation: "pushed-test", + cwd: workspaceRoot, + args: ["checkout", "-b", "feat/older-base", "HEAD~1"], + }); + const olderBaseRefused = yield* service + .delegateTask(scope, { + task: "Review branch cut from older origin/main commit.", + isolation: "worktree", + mode: "async", + clientRequestId: "older-base-worktree-1", + }) + .pipe(Effect.flip); + assert.equal(olderBaseRefused.code, "invalid_request"); + assert.include(olderBaseRefused.message, "no pushed ref covers HEAD"); + assert.equal(delegatedCalls.length, 1); + + // Once that older-base branch is pushed itself, remote placement targets origin/feat/older-base. + yield* git.execute({ + operation: "pushed-test", + cwd: workspaceRoot, + args: ["push", "-u", "origin", "feat/older-base"], + }); + const pushedFeature = yield* service.delegateTask(scope, { + task: "Review pushed older-base branch.", + isolation: "worktree", + mode: "async", + clientRequestId: "pushed-older-base-worktree-1", + }); + assert.equal(pushedFeature.remoteChild?.environmentId, remoteEnvId); + assert.deepEqual(delegatedCalls[1], { + environmentId: remoteEnvId, + workspaceStrategy: { + type: "worktree", + baseRef: "origin/feat/older-base", + startFromOrigin: true, + }, + }); + }).pipe(Effect.provide(OrchestratorMcpService.layer.pipe(Layer.provide(dependencies)))); + }).pipe( + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + GitVcsDriver.layer.pipe( + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-pushed-ref-" }), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), + Effect.scoped, + ), + ); + it.effect("rejects delegation to a provider without a registered adapter", () => Effect.gen(function* () { const forkOnlyInstanceId = ProviderInstanceId.make("forkOnly"); @@ -2967,7 +3207,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); @@ -3028,7 +3268,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const error = yield* Effect.gen(function* () { @@ -3086,17 +3326,27 @@ describe("OrchestratorMcpService provider resolution", () => { : Effect.succeed({ storedEvents: [] } as never), }), ServerSettings.layerTest(), - providerRegistryLayer([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + refreshWorkspaceSnapshot: () => + Effect.succeed([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + }), adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const error = yield* Effect.gen(function* () { @@ -3143,7 +3393,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); @@ -3269,7 +3519,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId, claudeInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); @@ -3385,7 +3635,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId, altInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ServerSettings.layerTest(), ); @@ -3476,17 +3726,27 @@ describe("OrchestratorMcpService provider resolution", () => { } as never), ), }), - providerRegistryLayer([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + refreshWorkspaceSnapshot: () => + Effect.succeed([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + }), adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ServerSettings.layerTest(), ); @@ -3606,7 +3866,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId, altInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ServerSettings.layerTest(), ); @@ -3702,7 +3962,7 @@ describe("OrchestratorMcpService provider resolution", () => { ]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), @@ -3914,6 +4174,8 @@ describe("OrchestratorMcpService provider resolution", () => { Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; return Layer.mock(RemoteDelegation.RemoteDelegation)({ + place: (scope) => Effect.succeed(scope.environmentId), + placed: () => Effect.succeedNone, delegate: (_scope, input) => Effect.gen(function* () { const run = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!; @@ -4167,7 +4429,7 @@ describe("OrchestratorMcpService provider resolution", () => { ), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); @@ -4351,7 +4613,7 @@ describe("OrchestratorMcpService provider resolution", () => { } as Project), }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({ list: () => created === undefined @@ -4534,7 +4796,7 @@ describe("OrchestratorMcpService provider resolution", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({ list: () => Effect.succeed({ tasks: [bound] }), upsert: () => @@ -4631,7 +4893,7 @@ describe("OrchestratorMcpService provider resolution", () => { } as never), }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({ list: () => Effect.succeed({ tasks: [task] }), upsert: (input) => @@ -4988,7 +5250,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -5206,7 +5468,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId, peerId, antigravityId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -5301,7 +5563,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -5355,7 +5617,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const error = yield* Effect.gen(function* () { @@ -5398,7 +5660,7 @@ describe("OrchestratorMcpService provider resolution", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const error = yield* Effect.gen(function* () { @@ -5482,7 +5744,7 @@ describe("OrchestratorMcpService thread lookup", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), @@ -5980,7 +6242,7 @@ describe("OrchestratorMcpService thread list", () => { : Effect.succeedNone, }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), @@ -6221,7 +6483,7 @@ describe("OrchestratorMcpService thread stop", () => { Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), @@ -6440,7 +6702,7 @@ describe("OrchestratorMcpService thread stop", () => { Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), Layer.mock(ProjectService.ProjectService)({}), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + localRemoteDelegationLayer, Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 69abe7d9c68de..b96a1a68adbe4 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -109,6 +109,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; @@ -1404,6 +1405,7 @@ const make = Effect.gen(function* () { const gitDriver = yield* GitVcsDriver.GitVcsDriver; const serverSettings = yield* ServerSettings.ServerSettingsService; const remoteDelegation = yield* RemoteDelegation.RemoteDelegation; + const localCheckoutLock = yield* Semaphore.make(1); const requireProject = (projectId: ProjectId) => projects.getById(projectId).pipe( @@ -2505,23 +2507,147 @@ const make = Effect.gen(function* () { ), ); + // Closura: fail closed when telemetry is present on an interactive host — unknown activity counts + // as active so agent-origin children do not disrupt an interactive machine in use. + const isInteractiveHostWithActiveHuman = Effect.fn( + "OrchestratorMcpService.isInteractiveHostWithActiveHuman", + )(function* () { + if (Option.isNone(hostResources)) return false; + const resources = yield* hostResources.value.read; + const tier = resources.placementRole === "headless" ? "headless" : "interactive"; + return tier === "interactive" && resources.humanActive !== false; + }); + + /** True when at least one local agent-origin child thread currently has an active run here. */ + const hasActiveLocalAgentChild = Effect.fn("OrchestratorMcpService.hasActiveLocalAgentChild")( + function* () { + const entries = yield* threadManagement + .listActiveShellIndex() + .pipe(Effect.mapError(threadManagementFailure)); + for (const entry of entries) { + if (entry.lineage.relationshipToParent !== "subagent" || !entry.mayBeLive) continue; + const records = yield* threadManagement + .getThreadRecords(entry.id, ["runs"], { + runStatuses: ThreadManagementService.ACTIVE_RUN_STATUSES, + }) + .pipe(Effect.orElseSucceed(() => ({ runs: [] }))); + if (records.runs.some(ThreadManagementService.isActiveRun)) return true; + } + return false; + }, + ); + + /** + * Closura: resolve a pushed remote ref whose tip matches the parent checkout's `HEAD` so + * `isolation: "worktree"` can be placed on a headless host via `startFromOrigin: true`. + */ + const resolvePushedWorktreeStrategy = Effect.fn( + "OrchestratorMcpService.resolvePushedWorktreeStrategy", + )(function* (parent: Pick) { + const project = yield* projects.getById(parent.thread.projectId).pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); + if (project === undefined) return undefined; + const nonGit = yield* threadLaunch + .isNonGitProject(parent.thread.projectId) + .pipe(Effect.orElseSucceed(() => true)); + if (nonGit) return undefined; + const cwd = parent.thread.worktreePath ?? project.workspaceRoot; + const headCommit = yield* gitDriver.resolveCommit({ cwd, revision: "HEAD" }).pipe( + Effect.map((resolved) => resolved.commitSha), + Effect.orElseSucceed(() => null), + ); + if (headCommit === null) return undefined; + const symbolicBranch = yield* gitDriver + .execute({ + operation: "delegateTask.resolveBranch", + cwd, + args: ["symbolic-ref", "--quiet", "--short", "HEAD"], + allowNonZeroExit: true, + timeoutMs: 5_000, + }) + .pipe( + Effect.map((result) => { + const name = result.exitCode === 0 ? result.stdout.trim() : ""; + return name.length > 0 ? name : null; + }), + Effect.orElseSucceed(() => undefined), + ); + const branch = symbolicBranch === undefined ? parent.thread.branch : symbolicBranch; + const matchesHead = (remoteName: string, branchName: string) => + gitDriver.resolveCommit({ cwd, revision: `refs/remotes/${remoteName}/${branchName}` }).pipe( + Effect.map((resolved) => resolved.commitSha === headCommit), + Effect.orElseSucceed(() => false), + ); + if (branch !== null) { + const remote = yield* gitDriver + .resolveWorktreeBaseRemote({ cwd, refName: branch }) + .pipe(Effect.orElseSucceed(() => null)); + if (remote !== null && (yield* matchesHead(remote.remoteName, remote.branchName))) { + return { + type: "worktree" as const, + baseRef: `${remote.remoteName}/${remote.branchName}`, + startFromOrigin: true, + }; + } + } + const defaultRemote = yield* gitDriver.resolvePrimaryRemoteName(cwd).pipe( + Effect.flatMap((remoteName) => + gitDriver + .resolveDefaultBranchName(cwd, remoteName) + .pipe( + Effect.map((branchName) => (branchName === null ? null : { remoteName, branchName })), + ), + ), + Effect.orElseSucceed(() => null), + ); + if ( + defaultRemote !== null && + (yield* matchesHead(defaultRemote.remoteName, defaultRemote.branchName)) + ) { + return { + type: "worktree" as const, + baseRef: `${defaultRemote.remoteName}/${defaultRemote.branchName}`, + startFromOrigin: true, + }; + } + return undefined; + }); + /** The environment bound to an auto-placed task, for the parent's model or the exact one named. */ const placeTask = Effect.fn("OrchestratorMcpService.placeTask")(function* ( callerScope: McpInvocationScope, input: OrchestratorMcpDelegateTaskInput, key: string, + explicitAuto: boolean, ) { yield* requireCapability(callerScope); const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task"); + const parentRun = + ThreadManagementService.latestActiveRun(parent) ?? + (yield* backgroundSubagentRun(scope, parent.thread.id)); + if ( + parentRun === undefined || + parentRun.rootNodeId === null || + parentRun.providerInstanceId !== scope.thread.providerInstanceId + ) { + return yield* failure( + "parent_not_active", + "Delegated tasks require an active run owned by this MCP provider session.", + ); + } const target = input.target; // Placement qualifies the project with this repository wherever it runs, and no other. if (target?.projectId !== undefined) { + if (!explicitAuto) return undefined; return yield* failure( "invalid_request", 'With placement "auto", omit target.projectId: the task runs in the project with this repository wherever it is placed. To use another project, pass target.environmentId with it.', ); } if (target?.driverKind !== undefined && target.providerInstanceId === undefined) { + if (!explicitAuto) return undefined; return yield* failure( "invalid_request", 'With placement "auto", name target.providerInstanceId instead of driverKind; every environment matches it exactly.', @@ -2532,6 +2658,7 @@ const make = Effect.gen(function* () { const model = target?.model ?? (instanceId === inherited.instanceId ? inherited.model : undefined); if (model === undefined) { + if (!explicitAuto) return undefined; return yield* failure( "target_required", 'With placement "auto" and another providerInstanceId, pass target.model.', @@ -3038,36 +3165,128 @@ const make = Effect.gen(function* () { // One key for the placement, the launch and the record, so a retry finds all three. const clientRequestId = yield* requestKey(input.clientRequestId); const named = input.target?.environmentId; - // A named target or the parent's checkout decides; only work needing neither is placed. + const needsLocalCheckout = input.needsLocalCheckout === true; + if (needsLocalCheckout && input.placement === "auto") { + return yield* failure( + "invalid_request", + 'needsLocalCheckout cannot be combined with placement "auto": a task needing this checkout must stay on this environment.', + ); + } + const existingLocalReceipt = + callerScope.thread !== undefined && input.clientRequestId !== undefined + ? yield* threadManagement.hasReceipt( + stableCommandId({ + scope: callerScope, + requestKey: clientRequestId, + operation: "delegate-task", + }), + ) + : false; + // Reconcile an already-placed clientRequestId before re-evaluating defaults or local HEAD, + // so a retry after toggling automaticPlacementByDefault or committing locally never duplicates locally. + const boundEnvironmentId = + callerScope.thread !== undefined && + input.clientRequestId !== undefined && + named === undefined && + !existingLocalReceipt + ? Option.getOrUndefined( + yield* remoteDelegation.placed(callerScope, { + operation: "delegate-task", + key: clientRequestId, + }), + ) + : undefined; + const boundRemote = + boundEnvironmentId !== undefined && + PeerForwarding.remoteTarget(callerScope, boundEnvironmentId) !== undefined; + // Closura: default `delegate_task` placement to `"auto"` (governed by `automaticPlacementByDefault`) + // so agent-origin children move off interactive hosts onto headless compute unless bound here. + const automaticByDefault = + boundEnvironmentId === undefined && + input.placement === undefined && + named === undefined && + !needsLocalCheckout && + !existingLocalReceipt && + (yield* serverSettings.getSettings.pipe( + Effect.map((settings) => settings.automaticPlacementByDefault), + Effect.orElseSucceed(() => false), + )); + const explicitAuto = + boundEnvironmentId === undefined && input.placement === "auto" && named === undefined; + const wantsAutoPlacement = explicitAuto || automaticByDefault; + // Closura: allow `isolation: "worktree"` to place on a headless host from the pushed ref + // instead of forcing the origin interactive host. + const namedRemote = + named !== undefined && PeerForwarding.remoteTarget(callerScope, named) !== undefined; + const needsPushedWorktree = + input.isolation === "worktree" && + !needsLocalCheckout && + !existingLocalReceipt && + (boundRemote || wantsAutoPlacement || namedRemote); + const preloadedCaller = + boundRemote || needsPushedWorktree + ? yield* loadThreadCaller(callerScope, "delegate_task") + : undefined; + const remoteWorktreeStrategy = + needsPushedWorktree && preloadedCaller !== undefined + ? yield* resolvePushedWorktreeStrategy(preloadedCaller.parent) + : undefined; + const boundRemoteModes = + boundRemote && preloadedCaller !== undefined + ? { + runtimeMode: yield* resolveRuntimeMode( + preloadedCaller.parent.thread.runtimeMode, + input.runtimeMode, + ), + interactionMode: yield* resolveInteractionMode( + preloadedCaller.parent.thread.interactionMode, + input.interactionMode, + ), + } + : undefined; + const canPlaceRemotely = + boundRemote || + (!needsLocalCheckout && + (input.isolation !== "worktree" || remoteWorktreeStrategy !== undefined || namedRemote)); const automatic = - input.placement === "auto" && named === undefined && input.isolation === undefined - ? yield* placeTask(callerScope, input, clientRequestId) + wantsAutoPlacement && canPlaceRemotely + ? yield* placeTask(callerScope, input, clientRequestId, explicitAuto) : undefined; const placed = - automatic !== undefined + boundEnvironmentId ?? + (automatic !== undefined ? automatic.environmentId : yield* admitPlacement( chooseThreadPlacement( { originEnvironmentId: callerScope.environmentId, pinnedEnvironmentId: named ?? callerScope.environmentId, - requiresOrigin: input.isolation === "worktree", + requiresOrigin: !canPlaceRemotely, }, [], 0, ), - 'A task in a linked environment runs in that project\'s checkout; isolation "worktree" is not supported there. Omit isolation, or use t3_thread_launch with environmentId and a worktree workspaceStrategy.', - ); + needsLocalCheckout + ? "needsLocalCheckout requires this environment and cannot run in a linked environment." + : 'A task in a linked environment with isolation "worktree" requires a pushed ref (startFromOrigin: true). Push the branch first, omit isolation, or set needsLocalCheckout: true.', + )); const environmentId = PeerForwarding.remoteTarget(callerScope, placed); if (environmentId !== undefined) { yield* requireCapability(callerScope); const scope = yield* requireThreadScope(callerScope, "delegate_task"); + const resolvedModes = automatic ?? boundRemoteModes; // The task's child runs as an ordinary thread there; this thread keeps the task. const { taskId } = yield* remoteDelegation.delegate(scope, { ...input, - ...(automatic === undefined + ...(resolvedModes === undefined ? {} - : { runtimeMode: automatic.runtimeMode, interactionMode: automatic.interactionMode }), + : { + runtimeMode: resolvedModes.runtimeMode, + interactionMode: resolvedModes.interactionMode, + }), + ...(remoteWorktreeStrategy === undefined + ? {} + : { workspaceStrategy: remoteWorktreeStrategy }), clientRequestId, target: { ...input.target, environmentId }, }); @@ -3106,6 +3325,18 @@ const make = Effect.gen(function* () { operation: "delegate-task", }); const isRetryOfAcceptedDelegation = yield* threadManagement.hasReceipt(commandId); + // Closura: refuse agent-origin children on an interactive host while its human is active, + // unless `needsLocalCheckout` is explicitly set (at most one active child at a time). + const activeHumanGuard = + !isRetryOfAcceptedDelegation && (yield* isInteractiveHostWithActiveHuman()); + if (activeHumanGuard && !needsLocalCheckout) { + return yield* failure( + "invalid_request", + needsPushedWorktree && remoteWorktreeStrategy === undefined + ? "Refusing agent-origin child on this interactive host while its human is active: no pushed ref covers HEAD for remote worktree placement. Push the branch so it can run on a headless host, or set needsLocalCheckout: true (at most one active child at a time)." + : "Refusing agent-origin child on this interactive host while its human is active. Place work on a headless host, or set needsLocalCheckout: true (at most one active child at a time).", + ); + } const target = yield* resolveTargetRechecking({ parent, target: input.target, @@ -3176,6 +3407,45 @@ const make = Effect.gen(function* () { } const safeTask = yield* resolveSafeTaskPrompt(input); const parentNodeId = parentRun.rootNodeId; + const dispatchLocalTask = () => + threadManagement + .dispatch({ + type: "delegated_task.request", + createdBy: "agent", + creationSource: "mcp", + commandId, + parentThreadId: scope.thread.threadId, + parentRunId: parentRun.id, + parentNodeId, + task: safeTask, + ...(input.title === undefined ? {} : { title: input.title }), + modelSelection: target.modelSelection, + runtimeMode, + interactionMode, + ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }), + // Async delegations wake the parent on every child terminal; wait + // delegations deliver through the blocking tool call until `awaitTask` + // gives up the wait (timeout, cancelled call) and upgrades the wake. + completionWake: input.mode === "wait" ? "settled_only" : "always", + ...(input.mode === "wait" + ? { + staleTimeoutMs: staleTimeoutMs( + input.staleTimeoutMinutes, + BACKGROUND_WAIT_STALE_MINUTES, + ), + } + : {}), + }) + .pipe( + Effect.mapError((error) => + error._tag === "ThreadManagementProviderInstanceDisabledError" + ? threadManagementFailure(error) + : failure( + "orchestration_error", + `Unable to create delegated task: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, + ), + ), + ); // The command commits the child's preparing run, which only this call // prepares, so a caller that goes away must not stop it in between. return yield* Effect.uninterruptibleMask((restore) => @@ -3183,44 +3453,22 @@ const make = Effect.gen(function* () { // ThreadManagementService.dispatch is the chokepoint for this command // type's own enablement check, using the same command id and its // receipt-replay exemption, so no separate assert runs here. - const result = yield* threadManagement - .dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId, - parentThreadId: scope.thread.threadId, - parentRunId: parentRun.id, - parentNodeId, - task: safeTask, - ...(input.title === undefined ? {} : { title: input.title }), - modelSelection: target.modelSelection, - runtimeMode, - interactionMode, - ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }), - // Async delegations wake the parent on every child terminal; wait - // delegations deliver through the blocking tool call until `awaitTask` - // gives up the wait (timeout, cancelled call) and upgrades the wake. - completionWake: input.mode === "wait" ? "settled_only" : "always", - ...(input.mode === "wait" - ? { - staleTimeoutMs: staleTimeoutMs( - input.staleTimeoutMinutes, - BACKGROUND_WAIT_STALE_MINUTES, - ), + const result = activeHumanGuard + ? yield* localCheckoutLock.withPermits(1)( + Effect.gen(function* () { + if ( + !(yield* threadManagement.hasReceipt(commandId)) && + (yield* hasActiveLocalAgentChild()) + ) { + return yield* failure( + "invalid_request", + "This interactive host already has an active agent-origin child while its human is active; needsLocalCheckout allows at most one at a time.", + ); } - : {}), - }) - .pipe( - Effect.mapError((error) => - error._tag === "ThreadManagementProviderInstanceDisabledError" - ? threadManagementFailure(error) - : failure( - "orchestration_error", - `Unable to create delegated task: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, - ), - ), - ); + return yield* dispatchLocalTask(); + }), + ) + : yield* dispatchLocalTask(); const taskEvent = result.storedEvents.find( (stored) => stored.event.type === "subagent.updated" && diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 151d90e766440..e14584ec9d4e9 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -289,7 +289,12 @@ describe("orchestrator MCP toolkit", () => { Layer.provide(layerOrchestration), ), ), - Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})), + Layer.provide( + Layer.mock(RemoteDelegation.RemoteDelegation)({ + place: (scope) => Effect.succeed(scope.environmentId), + placed: () => Effect.succeedNone, + }), + ), Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); diff --git a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts index b2e9a90bb7d3c..cdfcbfd85c482 100644 --- a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts +++ b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts @@ -233,10 +233,17 @@ const cancelBackgroundOnlyTask = ( layerAdapters, Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([provider]), + refreshWorkspaceSnapshot: () => Effect.succeed([provider]), + }), + Layer.mock(ProjectService.ProjectService)({ + getById: () => Effect.succeedNone, + workspaceScanDirectory: Effect.succeed, }), - Layer.mock(ProjectService.ProjectService)({}), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({ + place: (scope) => Effect.succeed(scope.environmentId), + placed: () => Effect.succeedNone, + }), ServerSettings.layerTest(), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), NodeServices.layer, diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 830e29d40c6ff..7929278f990f5 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -107,6 +107,13 @@ interface BoxThread { readonly holdRefill: Ref.Ref; readonly beforeTail: Ref.Ref>; readonly launched: Ref.Ref; + /** Every thread launched on this peer with its workspaceStrategy, in order. */ + readonly launches: Ref.Ref< + ReadonlyArray<{ + readonly threadId: ThreadId; + readonly workspaceStrategy?: ThreadLaunch.ThreadLaunchInput["workspaceStrategy"]; + }> + >; /** The link session that launched it, as the box stamps it. */ readonly linkOrigin: Ref.Ref<{ readonly sessionId: string; readonly label: string } | null>; /** The parent the launch names, so the thread there can link back to it. */ @@ -183,6 +190,12 @@ const makeBoxThread = Effect.gen(function* () { holdRefill: yield* Ref.make(false), beforeTail: yield* Ref.make>(Effect.void), launched: yield* Ref.make(null), + launches: yield* Ref.make< + ReadonlyArray<{ + readonly threadId: ThreadId; + readonly workspaceStrategy?: ThreadLaunch.ThreadLaunchInput["workspaceStrategy"]; + }> + >([]), linkOrigin: yield* Ref.make<{ readonly sessionId: string; readonly label: string } | null>( null, ), @@ -571,6 +584,17 @@ const boxToolkitLayer = (thread: BoxThread) => { Ref.get(thread.runless).pipe( Effect.flatMap((runless) => Ref.set(thread.launched, input.threadId!).pipe( + Effect.andThen( + Ref.update(thread.launches, (seen) => [ + ...seen, + { + threadId: input.threadId!, + ...(input.workspaceStrategy === undefined + ? {} + : { workspaceStrategy: input.workspaceStrategy }), + }, + ]), + ), Effect.andThen(Ref.set(thread.linkOrigin, input.linkOrigin ?? null)), Effect.andThen(Ref.set(thread.delegatedFrom, input.delegatedFrom ?? null)), Effect.andThen(Ref.set(thread.message, input.initialMessage?.text ?? null)), @@ -726,6 +750,21 @@ const makeLaptop = ( readonly afterSession?: (session: Option.Option) => Effect.Effect; /** Runs whenever something here reaches for a local launch, which this harness cannot make. */ readonly localLaunch?: Effect.Effect; + /** Host telemetry reported for the laptop itself when provided. */ + readonly hostResources?: Ref.Ref; + /** Pushed remote ref covering HEAD on the laptop checkout for remote worktree tests. */ + readonly pushedWorktreeRef?: + | { + readonly remoteName: string; + readonly branchName: string; + } + | Ref.Ref<{ + readonly remoteName: string; + readonly branchName: string; + } | null> + | null; + /** Local providers available on the laptop when testing local delegation. */ + readonly localProviders?: ReadonlyArray; } = {}, ) => Effect.gen(function* () { @@ -820,32 +859,104 @@ const makeLaptop = ( Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), Layer.provide(NodeCrypto.layer), Layer.provideMerge(layerThreads), - // The laptop lists no provider of its own, so it never runs the box's model. + // The laptop lists no provider of its own unless configured for a local-delegation test. Layer.provide( - Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed(hooks.localProviders ?? []), + refreshWorkspaceSnapshot: () => Effect.succeed(hooks.localProviders ?? []), + }), ), Layer.provide( Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ - list: () => Effect.succeed([]), + list: () => Effect.succeed((hooks.localProviders ?? []).map((p) => p.instanceId)), }), ), + Layer.provide( + hooks.hostResources === undefined + ? Layer.empty + : Layer.succeed(HostResources.HostResources, { + read: Ref.get(hooks.hostResources), + }), + ), Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), Layer.provide( Layer.mock(ProjectService.ProjectService)({ getById: (id) => Effect.succeedSome({ ...laptopProject, id }), + workspaceScanDirectory: Effect.succeed, }), ), Layer.provide(Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({})), Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})), Layer.provide( Layer.mock(ThreadLaunch.ThreadLaunchService)({ + isNonGitProject: () => Effect.succeed(false), + prepareRun: () => Effect.void, launch: () => (hooks.localLaunch ?? Effect.void).pipe(Effect.andThen(Effect.die("no local launch"))), checkWorktreeBase: () => (hooks.localLaunch ?? Effect.void).pipe(Effect.andThen(Effect.die("no local launch"))), }), ), - Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), + Layer.provide( + (() => { + const readPushedWorktreeRef = + hooks.pushedWorktreeRef !== null && + hooks.pushedWorktreeRef !== undefined && + !("remoteName" in hooks.pushedWorktreeRef) + ? Ref.get(hooks.pushedWorktreeRef) + : Effect.succeed(hooks.pushedWorktreeRef ?? null); + return Layer.mock(GitVcsDriver.GitVcsDriver)({ + resolveCommit: ({ revision }) => + readPushedWorktreeRef.pipe( + Effect.flatMap((ref) => { + if (revision === "HEAD") { + return Effect.succeed({ + commitSha: "1111111111111111111111111111111111111111", + }); + } + if (ref && revision === `refs/remotes/${ref.remoteName}/${ref.branchName}`) { + return Effect.succeed({ + commitSha: "1111111111111111111111111111111111111111", + }); + } + return Effect.fail(new Error("unknown revision") as never); + }), + ), + resolveWorktreeBaseRemote: () => readPushedWorktreeRef, + resolvePrimaryRemoteName: () => + readPushedWorktreeRef.pipe( + Effect.flatMap((ref) => + ref + ? Effect.succeed(ref.remoteName) + : Effect.fail(new Error("no remote") as never), + ), + ), + resolveDefaultBranchName: () => + readPushedWorktreeRef.pipe(Effect.map((ref) => ref?.branchName ?? null)), + execute: ({ args }) => + readPushedWorktreeRef.pipe( + Effect.map((ref) => { + if (args[0] === "symbolic-ref") { + return { + exitCode: ref ? 0 : 1, + stdout: ref ? `${ref.branchName}\n` : "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + } as never; + } + return { + exitCode: 1, + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + } as never; + }), + ), + }); + })(), + ), Layer.provide( Layer.merge( Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/p" }), @@ -4202,3 +4313,488 @@ it.effect( }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + +const localCodexProvider: ServerProvider = { + instanceId, + driver, + enabled: true, + installed: true, + version: "test", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-09-13T00:00:00.000Z", + models: [{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: null }], + slashCommands: [], + skills: [], +}; + +const interactiveHostResources = (humanActive: boolean | undefined): HostResourcesSnapshot => ({ + sampledAt: 0, + cpuUtilization: 0.1, + cpuCount: 8, + availableMemoryBytes: 8 * GiB, + totalMemoryBytes: 16 * GiB, + loadPerCpu: 0.1, + runningAgents: 0, + activeRuns: 0, + placementRole: "interactive", + ...(humanActive === undefined ? {} : { humanActive }), +}); + +it.effect( + "replays the 12-request review burst: defaults placement to auto, places worktrees from the pushed ref on R720 and ASUS, queues overflow, and puts 0 on the active-human laptop", + () => + Effect.scoped( + Effect.gen(function* () { + const r720 = descriptorOf("environment-r720", "R720"); + const asus = descriptorOf("environment-asus", "ASUS"); + const r720Thread = yield* makeBoxThread; + const asusThread = yield* makeBoxThread; + yield* Ref.set(r720Thread.resources, { ...loadOf(0.1), runningAgents: 0, activeRuns: 0 }); + yield* Ref.set(asusThread.resources, { ...loadOf(0.1), runningAgents: 0, activeRuns: 0 }); + const r720Server = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest)); + const asusServer = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest)); + const r720Peer = yield* servePeer(r720, boxToolkitLayer(r720Thread)).pipe( + Effect.provideContext(r720Server), + ); + const asusPeer = yield* servePeer(asus, boxToolkitLayer(asusThread)).pipe( + Effect.provideContext(asusServer), + ); + + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const laptopResources = yield* Ref.make(interactiveHostResources(true)); + const a = yield* makeLaptop(database, offers, undefined, Effect.void, { + hostResources: laptopResources, + pushedWorktreeRef: { remoteName: "origin", branchName: "master" }, + localProviders: [localCodexProvider, boxClaude], + }); + yield* linkTo(a.links, r720Peer, "full-access"); + yield* linkTo(a.links, asusPeer, "full-access"); + yield* a.settings.updateSettings({ + automaticPlacementHosts: [ + { environmentId: r720.environmentId, maxLanes: 4, minAvailableMemoryGiB: 4 }, + { environmentId: asus.environmentId, maxLanes: 1, minAvailableMemoryGiB: 4 }, + { environmentId: laptop.environmentId, maxLanes: 0, minAvailableMemoryGiB: 4 }, + ], + }); + yield* seedParent(a); + + // Replay all 12 CTO review launches (PRs 2261-2272) omitting `placement` with `isolation: "worktree"`. + const results = yield* Effect.forEach( + Array.from({ length: 12 }, (_, index) => 2261 + index), + (prNumber) => + a.call("delegate_task", { + task: `Review product PR #${prNumber}.`, + title: `Review PR #${prNumber}`, + role: "review", + isolation: "worktree", + target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, + clientRequestId: `burst-pr-${prNumber}`, + }), + ); + + const placedOnR720 = results.filter( + (result) => + !result.isError && + (result.structuredContent as { remoteChild?: { environmentId?: string } }).remoteChild + ?.environmentId === r720.environmentId, + ); + const placedOnAsus = results.filter( + (result) => + !result.isError && + (result.structuredContent as { remoteChild?: { environmentId?: string } }).remoteChild + ?.environmentId === asus.environmentId, + ); + const queuedOverflow = results.filter( + (result) => + result.isError && JSON.stringify(result.content).includes("no-eligible-environment"), + ); + + expect(placedOnR720).toHaveLength(4); + expect(placedOnAsus).toHaveLength(1); + expect(queuedOverflow).toHaveLength(7); + + const r720Launches = yield* Ref.get(r720Thread.launches); + const asusLaunches = yield* Ref.get(asusThread.launches); + expect(r720Launches).toHaveLength(4); + expect(asusLaunches).toHaveLength(1); + for (const launched of [...r720Launches, ...asusLaunches]) { + expect(launched.workspaceStrategy).toEqual({ + type: "worktree", + baseRef: "origin/master", + startFromOrigin: true, + }); + } + // Zero local child threads were created on the active-human laptop. + expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect( + "replays the 12-request review burst when neither headless executor is eligible: queues all 12 with 0 laptop placements", + () => + Effect.scoped( + Effect.gen(function* () { + const r720 = descriptorOf("environment-r720", "R720"); + const asus = descriptorOf("environment-asus", "ASUS"); + const r720Thread = yield* makeBoxThread; + const asusThread = yield* makeBoxThread; + yield* Ref.set(r720Thread.resources, { ...loadOf(0.1), runningAgents: 4, activeRuns: 4 }); + yield* Ref.set(asusThread.resources, { ...loadOf(0.1), runningAgents: 1, activeRuns: 1 }); + const r720Server = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest)); + const asusServer = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest)); + const r720Peer = yield* servePeer(r720, boxToolkitLayer(r720Thread)).pipe( + Effect.provideContext(r720Server), + ); + const asusPeer = yield* servePeer(asus, boxToolkitLayer(asusThread)).pipe( + Effect.provideContext(asusServer), + ); + + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const laptopResources = yield* Ref.make(interactiveHostResources(true)); + const a = yield* makeLaptop(database, offers, undefined, Effect.void, { + hostResources: laptopResources, + pushedWorktreeRef: { remoteName: "origin", branchName: "master" }, + localProviders: [localCodexProvider, boxClaude], + }); + yield* linkTo(a.links, r720Peer, "full-access"); + yield* linkTo(a.links, asusPeer, "full-access"); + // Omit laptop from automaticPlacementHosts to prove active-human refusal holds even without maxLanes: 0. + yield* a.settings.updateSettings({ + automaticPlacementHosts: [ + { environmentId: r720.environmentId, maxLanes: 4, minAvailableMemoryGiB: 4 }, + { environmentId: asus.environmentId, maxLanes: 1, minAvailableMemoryGiB: 4 }, + ], + }); + yield* seedParent(a); + + const results = yield* Effect.forEach( + Array.from({ length: 12 }, (_, index) => 2261 + index), + (prNumber) => + a.call("delegate_task", { + task: `Review product PR #${prNumber}.`, + title: `Review PR #${prNumber}`, + role: "review", + isolation: "worktree", + target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, + clientRequestId: `burst-full-pr-${prNumber}`, + }), + ); + + expect(results).toHaveLength(12); + for (const result of results) { + expect(result.isError).toBe(true); + expect(JSON.stringify(result.content)).toContain("no-eligible-environment"); + } + expect(yield* Ref.get(r720Thread.launches)).toHaveLength(0); + expect(yield* Ref.get(asusThread.launches)).toHaveLength(0); + expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect( + "refuses agent-origin children on an interactive host while its human is active or activity is unknown, unless needsLocalCheckout is set", + () => + Effect.scoped( + Effect.gen(function* () { + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const laptopResources = yield* Ref.make(interactiveHostResources(true)); + const a = yield* makeLaptop(database, offers, undefined, Effect.void, { + hostResources: laptopResources, + pushedWorktreeRef: null, + localProviders: [localCodexProvider], + }); + yield* seedParent(a); + + // Explicit placement: "here" is refused while human is active without needsLocalCheckout. + const explicitHere = yield* a.call("delegate_task", { + task: "Run locally.", + placement: "here", + clientRequestId: "refuse-here", + }); + expect(explicitHere.isError).toBe(true); + expect(JSON.stringify(explicitHere.content)).toContain("needsLocalCheckout"); + + // Explicit placement: "here" with isolation: "worktree" refuses accurately without + // falsely claiming no pushed ref covers HEAD. + const explicitHereWorktree = yield* a.call("delegate_task", { + task: "Run worktree locally.", + placement: "here", + isolation: "worktree", + clientRequestId: "refuse-here-worktree", + }); + expect(explicitHereWorktree.isError).toBe(true); + expect(JSON.stringify(explicitHereWorktree.content)).toContain("needsLocalCheckout"); + expect(JSON.stringify(explicitHereWorktree.content)).not.toContain( + "no pushed ref covers HEAD", + ); + + // Explicit target.environmentId naming the interactive host with isolation: "worktree" + // also refuses without claiming no pushed ref covers HEAD. + const namedLaptop = yield* a.call("delegate_task", { + task: "Run on laptop.", + isolation: "worktree", + target: { environmentId: laptop.environmentId }, + clientRequestId: "refuse-named-laptop", + }); + expect(namedLaptop.isError).toBe(true); + expect(JSON.stringify(namedLaptop.content)).toContain("needsLocalCheckout"); + expect(JSON.stringify(namedLaptop.content)).not.toContain("no pushed ref covers HEAD"); + + // Unpushed worktree (no pushed ref) cannot place remotely and is refused locally while active. + const unpushedWorktree = yield* a.call("delegate_task", { + task: "Worktree without pushed ref.", + isolation: "worktree", + clientRequestId: "refuse-unpushed-worktree", + }); + expect(unpushedWorktree.isError).toBe(true); + expect(JSON.stringify(unpushedWorktree.content)).toContain("needsLocalCheckout"); + expect(JSON.stringify(unpushedWorktree.content)).toContain("no pushed ref covers HEAD"); + + // Unknown human activity fails closed as active. + yield* Ref.set(laptopResources, interactiveHostResources(undefined)); + const unknownActivity = yield* a.call("delegate_task", { + task: "Run while activity is unknown.", + placement: "here", + clientRequestId: "refuse-unknown-activity", + }); + expect(unknownActivity.isError).toBe(true); + expect(JSON.stringify(unknownActivity.content)).toContain("needsLocalCheckout"); + + // Conflicting locality: needsLocalCheckout cannot be combined with placement: "auto". + yield* Ref.set(laptopResources, interactiveHostResources(true)); + const conflicting = yield* a.call("delegate_task", { + task: "Conflicting request.", + placement: "auto", + needsLocalCheckout: true, + clientRequestId: "refuse-conflicting", + }); + expect(conflicting.isError).toBe(true); + expect(JSON.stringify(conflicting.content)).toContain("needsLocalCheckout"); + + // Zero local children started across all refusals. + expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); + + // Once the human is away (humanActive: false), explicit local execution is allowed. + yield* Ref.set(laptopResources, interactiveHostResources(false)); + const whileAway = yield* a.call("delegate_task", { + task: "Run while human is away.", + placement: "here", + clientRequestId: "allow-away", + }); + expect(whileAway.isError, JSON.stringify(whileAway.content)).toBe(false); + expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(1); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect( + "enforces the one-at-a-time needsLocalCheckout exception while an interactive host's human is active", + () => + Effect.scoped( + Effect.gen(function* () { + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const laptopResources = yield* Ref.make(interactiveHostResources(true)); + const a = yield* makeLaptop(database, offers, undefined, Effect.void, { + hostResources: laptopResources, + pushedWorktreeRef: null, + localProviders: [localCodexProvider], + }); + yield* seedParent(a); + + // First needsLocalCheckout child is admitted while human is active. + const first = yield* a.call("delegate_task", { + task: "Inspect uncommitted diff.", + needsLocalCheckout: true, + clientRequestId: "local-checkout-1", + }); + expect(first.isError, JSON.stringify(first.content)).toBe(false); + const firstTask = first.structuredContent as { + taskId: NodeId; + childThreadId: ThreadId; + childRunId: RunId; + }; + expect(firstTask.childThreadId).not.toBeNull(); + + // Retrying the same clientRequestId replays the accepted child instead of refusing itself. + const retryFirst = yield* a.call("delegate_task", { + task: "Inspect uncommitted diff.", + needsLocalCheckout: true, + clientRequestId: "local-checkout-1", + }); + expect(retryFirst.isError, JSON.stringify(retryFirst.content)).toBe(false); + expect((retryFirst.structuredContent as { taskId: NodeId }).taskId).toBe(firstTask.taskId); + + // A second distinct needsLocalCheckout child while the first is still active is refused. + const second = yield* a.call("delegate_task", { + task: "Second uncommitted task.", + needsLocalCheckout: true, + clientRequestId: "local-checkout-2", + }); + expect(second.isError).toBe(true); + expect(JSON.stringify(second.content)).toContain("at most one at a time"); + expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(1); + + // Complete the first child's run so the single local-checkout slot frees up. + const firstProjection = yield* a.orchestrator.getThreadProjection(firstTask.childThreadId); + const firstRun = firstProjection.runs[0]!; + const now = yield* DateTime.now; + yield* a.sink.write({ + commandId: CommandId.make("command:complete-local-child-1"), + events: [ + { + id: EventId.make("event:complete-local-child-1"), + type: "run.updated", + threadId: firstTask.childThreadId, + runId: firstRun.id, + ...(firstRun.rootNodeId === null ? {} : { nodeId: firstRun.rootNodeId }), + providerInstanceId: firstRun.providerInstanceId, + occurredAt: now, + payload: { ...firstRun, status: "completed", completedAt: now }, + }, + ], + }); + + // Two concurrent needsLocalCheckout launches after completion: at most one succeeds. + const [concurrentA, concurrentB] = yield* Effect.all( + [ + a.call("delegate_task", { + task: "Concurrent local task A.", + needsLocalCheckout: true, + clientRequestId: "local-checkout-3a", + }), + a.call("delegate_task", { + task: "Concurrent local task B.", + needsLocalCheckout: true, + clientRequestId: "local-checkout-3b", + }), + ], + { concurrency: "unbounded" }, + ); + const succeeded = [concurrentA, concurrentB].filter((result) => !result.isError); + const refused = [concurrentA, concurrentB].filter((result) => result.isError); + expect(succeeded).toHaveLength(1); + expect(refused).toHaveLength(1); + expect(JSON.stringify(refused[0]!.content)).toContain("at most one at a time"); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect( + "reconciles an already-placed remote worktree task on retry after local HEAD becomes unpushed or automaticPlacementByDefault is turned off", + () => + Effect.scoped( + Effect.gen(function* () { + const boxThread = yield* makeBoxThread; + yield* Ref.set(boxThread.resources, { ...loadOf(0.1), runningAgents: 0, activeRuns: 0 }); + const b = yield* serveBox(boxThread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const laptopResources = yield* Ref.make(interactiveHostResources(true)); + const pushedRef = yield* Ref.make<{ + readonly remoteName: string; + readonly branchName: string; + } | null>({ remoteName: "origin", branchName: "master" }); + const a = yield* makeLaptop(database, offers, undefined, Effect.void, { + hostResources: laptopResources, + pushedWorktreeRef: pushedRef, + localProviders: [localCodexProvider, boxClaude], + }); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + + // 1. Place and record a remote worktree task while HEAD is pushed and default auto placement is on. + const initial = yield* a.call("delegate_task", { + task: "Review PR in remote worktree.", + isolation: "worktree", + target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, + clientRequestId: "wt-retry-recorded", + }); + expect(initial.isError, JSON.stringify(initial.content)).toBe(false); + const initialTaskId = (initial.structuredContent as { taskId: NodeId }).taskId; + expect(yield* Ref.get(boxThread.launches)).toHaveLength(1); + expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); + + // Local HEAD advances to an unpushed commit and automaticPlacementByDefault is turned off. + yield* Ref.set(pushedRef, null); + yield* a.settings.updateSettings({ automaticPlacementByDefault: false }); + + // Even while human is active, retrying the same clientRequestId reconciles the remote task. + const retryActive = yield* a.call("delegate_task", { + task: "Review PR in remote worktree.", + isolation: "worktree", + target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, + clientRequestId: "wt-retry-recorded", + }); + expect(retryActive.isError, JSON.stringify(retryActive.content)).toBe(false); + expect((retryActive.structuredContent as { taskId: NodeId }).taskId).toBe(initialTaskId); + + // Even on an idle laptop that could run locally, retrying never spawns a duplicate local child. + yield* Ref.set(laptopResources, interactiveHostResources(false)); + const retryIdle = yield* a.call("delegate_task", { + task: "Review PR in remote worktree.", + isolation: "worktree", + target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, + clientRequestId: "wt-retry-recorded", + }); + expect(retryIdle.isError, JSON.stringify(retryIdle.content)).toBe(false); + expect((retryIdle.structuredContent as { taskId: NodeId }).taskId).toBe(initialTaskId); + expect(yield* Ref.get(boxThread.launches)).toHaveLength(1); + expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); + + // 2. Lost-answer case: remote launch runs on the box, response is lost before local recording, + // then local HEAD becomes unpushed and automaticPlacementByDefault is turned off before retry. + yield* Ref.set(laptopResources, interactiveHostResources(true)); + yield* Ref.set(pushedRef, { remoteName: "origin", branchName: "master" }); + yield* a.settings.updateSettings({ automaticPlacementByDefault: true }); + yield* Ref.set(boxThread.afterLaunch, Effect.die("connection lost")); + const lost = yield* a.call("delegate_task", { + task: "Review PR with lost answer.", + isolation: "worktree", + target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, + clientRequestId: "wt-retry-lost", + }); + expect(lost.isError).toBe(true); + const lostRemoteThreadId = yield* Ref.get(boxThread.launched); + expect(lostRemoteThreadId).not.toBeNull(); + yield* Ref.set(boxThread.afterLaunch, Effect.void); + + yield* Ref.set(pushedRef, null); + yield* a.settings.updateSettings({ automaticPlacementByDefault: false }); + yield* Ref.set(laptopResources, interactiveHostResources(false)); + + const recovered = yield* a.call("delegate_task", { + task: "Review PR with lost answer.", + isolation: "worktree", + target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, + clientRequestId: "wt-retry-lost", + }); + expect(recovered.isError, JSON.stringify(recovered.content)).toBe(false); + expect(yield* Ref.get(boxThread.launched)).toBe(lostRemoteThreadId); + expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); + const recorded = yield* a.orchestrator + .getThreadProjection(parentThreadId) + .pipe(Effect.map((projection) => projection.subagents)); + expect(recorded).toHaveLength(2); + expect(recorded.some((task) => task.remoteChild?.threadId === lostRemoteThreadId)).toBe( + true, + ); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index dc40be891f2f1..a47d24d648de7 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -18,6 +18,7 @@ import { type OrchestratorMcpThreadTimelineItem, type OrchestrationV2RemoteTaskChild, type OrchestrationV2Subagent, + type OrchestrationV2ThreadLaunchWorkspaceStrategy, type OrchestrationV2WorkerAlert, type PeerLink, OrchestrationV2ThreadPlacementAdmitError, @@ -167,6 +168,8 @@ export class RemoteDelegation extends Context.Service< readonly target: NonNullable & { readonly environmentId: EnvironmentId; }; + /** Closura: pushed-ref worktree strategy so `isolation: "worktree"` can run on a headless host. */ + readonly workspaceStrategy?: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined; }, ) => Effect.Effect<{ readonly taskId: NodeId }, OrchestratorMcpFailure>; /** @@ -984,15 +987,17 @@ const make = Effect.gen(function* () { const delegate: RemoteDelegation["Service"]["delegate"] = Effect.fn("RemoteDelegation.delegate")( function* (scope, input) { - const parent = yield* threads.getThreadRecords(scope.thread.threadId, ["runs"]).pipe( - Effect.mapError( - () => - new OrchestratorMcpFailure({ - code: "thread_not_found", - message: "The calling thread was not found.", - }), - ), - ); + const parent = yield* threads + .getThreadRecords(scope.thread.threadId, ["runs", "subagents"]) + .pipe( + Effect.mapError( + () => + new OrchestratorMcpFailure({ + code: "thread_not_found", + message: "The calling thread was not found.", + }), + ), + ); const parentRun = parent.runs .filter(ThreadManagement.isActiveRun) .toSorted((left, right) => right.ordinal - left.ordinal)[0]; @@ -1008,13 +1013,53 @@ const make = Effect.gen(function* () { } const parentNodeId = parentRun.rootNodeId; const { target } = input; - // A worktree there would branch from a commit this checkout has and the - // other may not, so a remote task runs in that project's checkout. - if (input.isolation === "worktree") { + // One key for the launch there and the record here, so a retry finds both. + // Both are scoped to the provider session, as every key a caller passes is: + // the forwarder scopes the launch's, and the record's names it. + const key = input.clientRequestId ?? (yield* random.uuidV4()); + const keyed = (operation: string) => + CommandId.make( + `command:mcp:${encodeURIComponent(scope.requestNamespace)}:${operation}:${encodeURIComponent(key)}`, + ); + const commandId = keyed("remote-delegate"); + const launchId = keyed("remote-launch"); + const childId = keyed("remote-child"); + // Reconcile an already-launched/recorded remote task even when local HEAD has since + // moved to an unpushed commit and no pushed worktree ref is provided. + const priorLaunch = + input.clientRequestId === undefined + ? Option.none() + : yield* threads + .intentOf(launchId) + .pipe(Effect.orElseSucceed(() => Option.none())); + const priorChild = + input.clientRequestId === undefined + ? Option.none() + : yield* threads + .intentOf(childId) + .pipe(Effect.orElseSucceed(() => Option.none())); + if (Option.isSome(priorChild)) { + const recordedTask = parent.subagents.find( + (task) => + task.remoteChild?.environmentId === target.environmentId && + task.remoteChild.threadId === priorChild.value, + ); + if (recordedTask !== undefined) return { taskId: recordedTask.id }; + } + // Closura: allow `isolation: "worktree"` on a headless peer when given a pushed-ref + // strategy (`startFromOrigin: true`); refuse local-only worktrees the peer cannot fetch. + const remoteWorktreeStrategy = + input.isolation === "worktree" ? input.workspaceStrategy : undefined; + if ( + input.isolation === "worktree" && + Option.isNone(priorLaunch) && + (remoteWorktreeStrategy?.type !== "worktree" || + remoteWorktreeStrategy.startFromOrigin !== true) + ) { return yield* new OrchestratorMcpFailure({ code: "invalid_request", message: - 'A task in a linked environment runs in that project\'s checkout; isolation "worktree" is not supported there. Omit isolation, or use t3_thread_launch with environmentId and a worktree workspaceStrategy.', + 'A task in a linked environment with isolation "worktree" requires a pushed ref (startFromOrigin: true). Push the branch first, omit isolation, or set needsLocalCheckout: true.', }); } // The provider and model inherit as they do for a task here. Another @@ -1058,15 +1103,6 @@ const make = Effect.gen(function* () { parent.thread.projectId, target.projectId, ); - // One key for the launch there and the record here, so a retry finds both. - // Both are scoped to the provider session, as every key a caller passes is: - // the forwarder scopes the launch's, and the record's names it. - const key = input.clientRequestId ?? (yield* random.uuidV4()); - const keyed = (operation: string) => - CommandId.make( - `command:mcp:${encodeURIComponent(scope.requestNamespace)}:${operation}:${encodeURIComponent(key)}`, - ); - const commandId = keyed("remote-delegate"); const link = yield* links.get(target.environmentId).pipe( Effect.map(Option.getOrUndefined), Effect.orElseSucceed(() => undefined), @@ -1077,8 +1113,8 @@ const make = Effect.gen(function* () { const sent = yield* launchThere(scope, { environmentId: target.environmentId, label, - launchId: keyed("remote-launch"), - childId: keyed("remote-child"), + launchId, + childId, threadId: parent.thread.id, params: { projectId, @@ -1086,6 +1122,9 @@ const make = Effect.gen(function* () { modelSelection: { instanceId, model, ...(options === undefined ? {} : { options }) }, ...(runtimeMode === undefined ? {} : { runtimeMode }), ...(interactionMode === undefined ? {} : { interactionMode }), + ...(remoteWorktreeStrategy === undefined + ? {} + : { workspaceStrategy: remoteWorktreeStrategy }), message: task, clientRequestId: `delegate:${scope.thread.threadId}:${key}`, // The thread there shows it is this thread's subagent, with a way back. diff --git a/packages/contracts/src/orchestratorMcp.test.ts b/packages/contracts/src/orchestratorMcp.test.ts index d2908fa42db8c..8b776a4ad988f 100644 --- a/packages/contracts/src/orchestratorMcp.test.ts +++ b/packages/contracts/src/orchestratorMcp.test.ts @@ -81,4 +81,21 @@ describe("orchestrator MCP contracts", () => { }).next, ).toBe(next); }); + + it("decodes placement and needsLocalCheckout options on delegated task requests", () => { + expect( + decodeDelegateTaskInput({ + task: "Inspect uncommitted files.", + placement: "here", + needsLocalCheckout: true, + }), + ).toMatchObject({ placement: "here", needsLocalCheckout: true }); + expect( + decodeDelegateTaskInput({ + task: "Review PR 2261.", + isolation: "worktree", + placement: "auto", + }), + ).toMatchObject({ isolation: "worktree", placement: "auto" }); + }); }); diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 75a1a45550027..4bf4c1d28db8f 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -190,13 +190,21 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({ isolation: Schema.optional( Schema.Literals(["shared", "worktree"]).annotate({ description: - "'shared' (default): parent checkout. 'worktree': new prepared checkout from the parent commit, for a separate checkout or PR per child. Uncommitted edits stay out.", + "'shared' (default): parent checkout. 'worktree': new prepared checkout from the pushed ref on a headless host when placed, or from the parent commit locally. Uncommitted edits stay out.", }), ), + // Closura: omitted placement defaults to 'auto' when automaticPlacementByDefault is on. placement: Schema.optional( - Schema.Literals(["auto"]).annotate({ + Schema.Literals(["auto", "here"]).annotate({ description: - "'auto': use for any work that needs none of your checkout's changes. Runs on the least-loaded headless machine, here or linked, with spare capacity, this repository's project and your exact provider and model; there, in that project's checkout. Ignored with target.environmentId or isolation. Reuse clientRequestId on retry to keep the environment chosen.", + "'auto' (default): runs on the least-loaded headless machine, here or linked, with spare capacity, this repository's project and your exact provider and model; when isolation is set to worktree, creates the checkout there from the pushed ref. 'here': keeps the task on this environment (refused on an interactive host while its human is active without needsLocalCheckout). Ignored with target.environmentId. Reuse clientRequestId on retry to keep the environment chosen.", + }), + ), + // Closura: explicit exception for agent-origin children that must use this checkout while a human is active. + needsLocalCheckout: Schema.optional( + Schema.Boolean.annotate({ + description: + "Set true only when the child must read or edit uncommitted state in this checkout. On an interactive host while its human is active, agent-origin children are refused unless this is true (at most one active child at a time).", }), ), mode: Schema.optional(