diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 54c1137870e73..c7489bf0d1034 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -6872,6 +6872,127 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + // The agent answers session/cancel with "cancelled" and never sends terminal/kill or terminal/release. + it.live("Stop kills the command a turn runs in a client terminal", () => + Effect.gen(function* () { + type Runtime = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let handler: Parameters[0] | undefined; + let createTerminal: Parameters[0] | undefined; + let readTerminalOutput: Parameters[0] | undefined; + let terminalId: string | undefined; + const cancelled = yield* Deferred.make(); + const instanceId = ProviderInstanceId.make("devin-stop-terminal"); + const adapter = yield* makeAcpRegistryAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + settings: DEVIN_SETTINGS, + environment: {}, + makeRuntime: makeMockRuntime({ + childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, + mockAgentPath: yield* bundledMockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (next) => + Effect.sync(() => { + handler = next; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(next))), + handleCreateTerminal: (next) => + Effect.sync(() => { + createTerminal = next; + }).pipe(Effect.andThen(runtime.handleCreateTerminal(next))), + handleTerminalOutput: (next) => + Effect.sync(() => { + readTerminalOutput = next; + }).pipe(Effect.andThen(runtime.handleTerminalOutput(next))), + prompt: () => + Effect.gen(function* () { + ({ terminalId } = yield* createTerminal!( + { sessionId: "mock-session-1", command: "sleep 30" }, + { requestId: "exec-1-terminal", method: "terminal/create" }, + )); + yield* handler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call", + toolCallId: "exec-1", + title: "exec", + kind: "execute", + status: "in_progress", + content: [{ type: "terminal", terminalId }], + }, + }); + yield* Deferred.await(cancelled); + return { stopReason: "cancelled" as const }; + }), + cancel: Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid), + }), + }), + }).pipe( + Effect.provide( + Layer.mock(AcpRegistryCatalog)({ resolve: () => Effect.die("runtime is injected") }), + ), + ); + const threadId = ThreadId.make("devin-stop-terminal"); + const modelSelection = { instanceId, model: "default" } as const; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("devin-stop-terminal-session"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ); + const running = Option.getOrThrow( + yield* runtime.events.pipe( + Stream.filter( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "exec-1", + ), + Stream.runHead, + ), + ); + if (running.type !== "turn_item.updated" || running.turnItem.providerTurnId === null) { + return yield* Effect.die("Expected the running command item of the turn"); + } + + yield* runtime.interruptTurn({ + providerThread, + providerTurnId: running.turnItem.providerTurnId, + requestRuntimeRestart: true, + }); + const { exitStatus } = yield* readTerminalOutput!( + { sessionId: "mock-session-1", terminalId: terminalId! }, + { requestId: "exec-1-output", method: "terminal/output" }, + ); + // Killed: a signal on POSIX, a non-zero exit code from taskkill on Windows. + assert.notEqual(exitStatus, undefined); + assert.notEqual(exitStatus?.exitCode, 0); + const lateCreate = yield* createTerminal!( + { sessionId: "mock-session-1", command: "sleep 30" }, + { requestId: "exec-2-terminal", method: "terminal/create" }, + ).pipe(Effect.exit); + assert.isTrue(Exit.isFailure(lateCreate)); + }).pipe(Effect.provide(layerTest)), + ); + it.effect.each([ { label: "grants an ID-only execute approval its tracked command", diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 065f95a3e247a..481d6b3e27ab4 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -7224,7 +7224,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ); - const guardClientTerminalCreate = clientPolicyContext.pipe( + const guardClientTerminalCreate = Effect.gen(function* () { + // Stop already swept this session's terminals; a command started now would outlive it. + if (yield* Ref.get(stoppedRunQuarantine)) { + return yield* EffectAcpErrors.AcpRequestError.internalError( + "The T3 turn was stopped; terminal/create is refused until the next turn.", + ); + } + }).pipe( + Effect.andThen(clientPolicyContext), Effect.flatMap(({ policy, turnKey }) => { const disposition = acpClientExecuteDisposition(policy); if ( @@ -7242,7 +7250,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ) { if (clientTerminals === undefined) return; yield* targetRuntime.handleCreateTerminal((request) => - guardClientTerminalCreate.pipe(Effect.andThen(clientTerminals.create(request))), + clientTerminals.create(request, guardClientTerminalCreate), ); yield* targetRuntime.handleTerminalOutput(clientTerminals.output); yield* targetRuntime.handleTerminalWaitForExit(clientTerminals.waitForExit); @@ -10775,6 +10783,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(runtimeRestartRequired, true); } } + // T3 owns client terminals; an agent may answer session/cancel without killing them. + if ( + turnInput.requestRuntimeRestart === true && + clientTerminals !== undefined + ) { + const sessionId = yield* Ref.get(activeSessionId); + if (sessionId !== null) yield* clientTerminals.killSession(sessionId); + } const stopped = yield* Deferred.await(context.completed).pipe( Effect.timeoutOption(ACP_STOP_CONFIRM_TIMEOUT_MS), ); diff --git a/packages/provider-acp/src/server/clientTerminals.test.ts b/packages/provider-acp/src/server/clientTerminals.test.ts index 87a96999cd1bf..92e129a702357 100644 --- a/packages/provider-acp/src/server/clientTerminals.test.ts +++ b/packages/provider-acp/src/server/clientTerminals.test.ts @@ -97,6 +97,40 @@ describe("AcpClientTerminals", () => { }), ); + it.effect("killSession returns when a killed command never exits", () => + Effect.gen(function* () { + // Models a kill the OS refused (EPERM after the command elevated): the process stays up. + const processExited = yield* Deferred.make(); + const child = ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Deferred.await(processExited).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), + isRunning: Effect.succeed(true), + kill: () => Effect.void, + stdin: Sink.drain, + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); + const terminals = yield* makeAcpClientTerminals({ defaultCwd: process.cwd() }).pipe( + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => Effect.succeed(child)), + ), + ); + yield* Effect.addFinalizer(() => + Deferred.succeed(processExited, undefined).pipe(Effect.andThen(terminals.disposeAll)), + ); + yield* terminals.create({ sessionId: "session", command: "fixture" }); + + const kill = yield* terminals.killSession("session").pipe(Effect.forkChild); + yield* TestClock.adjust("2 seconds"); + yield* Fiber.join(kill); + }), + ); + it.live("resolves terminal environment from the requesting ACP session", () => Effect.gen(function* () { const inheritedEnvironment = yield* HostProcess.Environment; diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index 592bf47553494..591f994ddbbc2 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -4,6 +4,7 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; @@ -22,6 +23,8 @@ const MAX_RETAINED_OUTPUT_BYTES = 16 * 1024 * 1024; const DEFAULT_OUTPUT_BYTE_LIMIT = 4 * 1024 * 1024; const MAX_OUTPUT_BYTE_LIMIT = 8 * 1024 * 1024; const OUTPUT_DRAIN_GRACE = "1 second"; +// After a kill, the exit fiber may still drain output for up to OUTPUT_DRAIN_GRACE. +const KILL_EXIT_CONFIRM_GRACE = "2 seconds"; const terminalRequestError = (message: string, cause?: unknown) => EffectAcpErrors.AcpRequestError.internalError( @@ -100,8 +103,10 @@ interface ManagedAcpTerminal { } export interface AcpClientTerminals { + /** `admit` runs under the creation permit, so a check it makes holds against `killSession`. */ readonly create: ( request: EffectAcpSchema.CreateTerminalRequest, + admit?: Effect.Effect, ) => Effect.Effect; readonly output: ( request: EffectAcpSchema.TerminalOutputRequest, @@ -121,6 +126,8 @@ export interface AcpClientTerminals { terminalId: string, ) => AcpTerminalOutputSnapshot | undefined; readonly readCommandLine: (terminalId: string) => string | undefined; + /** Kills a session's running commands and waits for their exit; the agent can still read them. */ + readonly killSession: (sessionId: string) => Effect.Effect; readonly disposeAll: Effect.Effect; } @@ -226,10 +233,11 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi return Effect.succeed(terminal); }; - const create: AcpClientTerminals["create"] = (request) => + const create: AcpClientTerminals["create"] = (request, admit = Effect.void) => creationPermit.withPermit( Effect.uninterruptibleMask((restore) => Effect.gen(function* () { + yield* admit; const liveCount = Array.from(terminals.values()).filter( (terminal) => !terminal.released && terminal.exitStatus === undefined, ).length; @@ -411,6 +419,42 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi const readCommandLine: AcpClientTerminals["readCommandLine"] = (terminalId) => terminals.get(terminalId)?.commandLine; + // Taking the creation permit lets an in-flight terminal/create register before the sweep. + // A kill can fail (EPERM after a command elevates), so the exit wait is bounded. + const killSession: AcpClientTerminals["killSession"] = (sessionId) => + creationPermit + .withPermit( + Effect.sync(() => + Array.from(terminals.values()).filter( + (terminal) => + terminal.sessionId === sessionId && + !terminal.released && + terminal.exitStatus === undefined, + ), + ), + ) + .pipe( + Effect.flatMap((live) => + Effect.forEach( + live, + (terminal) => + Effect.uninterruptible(terminal.kill).pipe( + Effect.andThen( + Deferred.await(terminal.exit).pipe(Effect.timeoutOption(KILL_EXIT_CONFIRM_GRACE)), + ), + Effect.flatMap((exit) => + Option.isNone(exit) + ? Effect.logWarning("ACP client terminal did not exit after kill", { + terminalId: terminal.terminalId, + }) + : Effect.void, + ), + ), + { concurrency: "unbounded", discard: true }, + ), + ), + ); + const disposeAll: AcpClientTerminals["disposeAll"] = Effect.uninterruptible( Effect.suspend(() => Effect.forEach( @@ -425,12 +469,12 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi ); const logged = - ( + , Response>( operation: string, - handler: (request: Request) => Effect.Effect, + handler: (...args: Args) => Effect.Effect, ) => - (request: Request) => - handler(request).pipe( + (...args: Args) => + handler(...args).pipe( Effect.tapError((error) => Effect.logWarning("ACP client terminal operation failed", { operation, @@ -447,6 +491,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi release: logged("terminal/release", release), readOutputSnapshot, readCommandLine, + killSession, disposeAll, }; });