From dd3c04b72c991a4f236f0e6f4a80c9227096ef4a Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 10 Nov 2026 17:04:53 +0000 Subject: [PATCH 1/5] fix(core): keep a shell command's output when the user stops its call Stopping a foreground shell call used to remove the command and delete its output file, and the call failed with a bare "Tool execution interrupted". Now the user's stop reaches tools through a new `cancel` effect on Tool.Context: the shell tool stops the command gracefully (SIGTERM, then SIGKILL after 3 s) without forgetting it, waits at most 500 ms for it to exit, and fails the call with the output so far, where the full output is, and the shell ID. The step gives each tool call a cancel gate. On a user stop it completes the gates, lets every tool that was awaiting its gate settle its own call (failing normally, through execute.after hooks and failTool), interrupts every other tool at once, and interrupts stragglers after 5 s. A server shutdown or a closed Location interrupts every tool as before. The step still ends interrupted and starts no new request. The interruption reason travels explicitly from the session execution through the runner to the step, like isLocationClosed. CodeMode never hands `cancel` to nested calls. User decisions: - An interrupted shell call is a failed call carrying its output, not a success - Wait at most 500 ms for the stopped command before settling the call - Use cooperative cancel instead of a side-channel slot - execute.after hooks must still run and be able to replace the error --- packages/core/src/codemode/tool.ts | 2 + packages/core/src/session/execution.ts | 12 +- packages/core/src/session/run-coordinator.ts | 14 +- packages/core/src/session/runner/index.ts | 2 + packages/core/src/session/runner/llm.ts | 9 +- packages/core/src/session/runner/step.ts | 58 +++++- packages/core/src/shell.ts | 67 ++++-- packages/core/src/shell/result.ts | 15 ++ packages/core/src/tool.ts | 3 + packages/core/src/tool/plugin/shell.ts | 192 ++++++++++-------- packages/core/test/codemode.test.ts | 37 ++++ packages/core/test/session-execution.test.ts | 22 ++ .../core/test/session-run-coordinator.test.ts | 25 +++ packages/core/test/session-runner.test.ts | 1 + packages/core/test/session-step.test.ts | 143 ++++++++++++- packages/core/test/shell-result.test.ts | 37 ++++ packages/core/test/tool-shell.test.ts | 146 +++++++++++++ packages/plugin/src/promise/tool.ts | 2 +- packages/schema/src/tool.ts | 5 + 19 files changed, 680 insertions(+), 112 deletions(-) create mode 100644 packages/core/test/shell-result.test.ts diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index 3ff8ae80843f..067ec60abd22 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -132,6 +132,8 @@ export const create = ( ...context, // Progress replaces the execute call's own, so an inner tool's updates would hide the call rows. progress: () => Effect.void, + // A stop is the execute call's to handle: a nested call never fails it with its own error. + cancel: undefined, }).pipe( Effect.mapError((error) => new ToolFailure({ message: toSessionError(error).message, error })), ) diff --git a/packages/core/src/session/execution.ts b/packages/core/src/session/execution.ts index ce11a7a0f97d..f2867c4f7e3d 100644 --- a/packages/core/src/session/execution.ts +++ b/packages/core/src/session/execution.ts @@ -81,6 +81,8 @@ export const layer = Layer.effect( const releaseOnCommit = (sessionID: SessionSchema.ID) => ({ commit: () => store.release(sessionID), }) + // Why a Session's execution is being interrupted, read from the coordinator once it exists. + let interruption: (sessionID: SessionSchema.ID) => InterruptReason | undefined = () => undefined const drain = Effect.fnUntraced(function* ( sessionID: SessionSchema.ID, force: boolean, @@ -91,7 +93,14 @@ export const layer = Layer.effect( const session = yield* store.get(sessionID) if (!session) return yield* Effect.die(new Error(`Session not found: ${sessionID}`)) const result = yield* SessionRunner.Service.use((runner) => - runner.drain({ sessionID, force, continuation, promotable, stepped }), + runner.drain({ + sessionID, + force, + continuation, + promotable, + stepped, + interruption: () => interruption(sessionID), + }), ).pipe( instances.provide(session), Effect.tapCause((cause) => @@ -145,6 +154,7 @@ export const layer = Layer.effect( ), }) + interruption = coordinator.interruption return Service.of({ active: coordinator.active, isActive: coordinator.isActive, diff --git a/packages/core/src/session/run-coordinator.ts b/packages/core/src/session/run-coordinator.ts index a8e75319f1f1..649ad41b2e5f 100644 --- a/packages/core/src/session/run-coordinator.ts +++ b/packages/core/src/session/run-coordinator.ts @@ -20,6 +20,8 @@ export interface Coordinator { * interrupted. */ readonly interrupt: (key: Key, reason?: Reason) => Effect.Effect + /** Why the key's execution is being stopped, once `interrupt` stopped it; undefined for teardown or when running. */ + readonly interruption: (key: Key) => Reason | undefined /** Resolves once no execution is active for the key. Returns immediately when already idle and never starts work. */ readonly awaitIdle: (key: Key) => Effect.Effect } @@ -170,5 +172,15 @@ export const make = (options: { return Deferred.await(execution.done).pipe(Effect.ignoreCause, Effect.andThen(awaitIdle(key))) }) - return { active: Effect.sync(() => new Set(executions.keys())), isActive, run, wake, interrupt, awaitIdle } + const interruption = (key: Key) => executions.get(key)?.interruptionReason + + return { + active: Effect.sync(() => new Set(executions.keys())), + isActive, + run, + wake, + interrupt, + interruption, + awaitIdle, + } }) diff --git a/packages/core/src/session/runner/index.ts b/packages/core/src/session/runner/index.ts index 9f32886248b3..dc1b9d5f1b3c 100644 --- a/packages/core/src/session/runner/index.ts +++ b/packages/core/src/session/runner/index.ts @@ -38,6 +38,8 @@ export interface Interface { readonly promotable?: Promotable /** The previous drain ran a step before handing off, so reaching idle still runs the idle hook. */ readonly stepped?: boolean + /** Why the execution is being interrupted, once it is: `"user"` when someone stopped it. */ + readonly interruption?: () => "user" | "shutdown" | undefined }) => Effect.Effect } diff --git a/packages/core/src/session/runner/llm.ts b/packages/core/src/session/runner/llm.ts index 763b4215724b..637b30b76e6c 100644 --- a/packages/core/src/session/runner/llm.ts +++ b/packages/core/src/session/runner/llm.ts @@ -214,7 +214,7 @@ const layer = Layer.effect( while (true) { const next = yield* advanceToStep() if (next._tag !== "Ready") return next - continuing = yield* runStep(next.context, step) + continuing = yield* runStep(next.context, step, input.interruption) stepped = true step++ force = false @@ -232,7 +232,11 @@ const layer = Layer.effect( }) /** Owns logical Step policy; each attempt owns its streaming, tools, and durable settlement. */ - const runStep = Effect.fn("SessionRunner.runStep")(function* (first: SessionContext.Loaded, step: number) { + const runStep = Effect.fn("SessionRunner.runStep")(function* ( + first: SessionContext.Loaded, + step: number, + interruption: DrainInput["interruption"], + ) { const sessionID = first.session.id let assistantMessageID = SessionMessage.ID.create() const retry = yield* SessionRunnerRetry.make(bus, sessionID) @@ -288,6 +292,7 @@ const layer = Layer.effect( ) const outcome = yield* steps.attempt({ isLocationClosed: lifecycle.isClosed, + interruption, sessionID, assistantMessageID, agent: loaded.agent.id, diff --git a/packages/core/src/session/runner/step.ts b/packages/core/src/session/runner/step.ts index 53f6d7e0bda0..00136eb4d257 100644 --- a/packages/core/src/session/runner/step.ts +++ b/packages/core/src/session/runner/step.ts @@ -8,7 +8,7 @@ import { type ToolCall, } from "@opencode/ai/effect" import type { Agent } from "@opencode/schema/agent" -import { Cause, Clock, Data, Effect, Exit, Fiber, Option, Stream } from "effect" +import { Cause, Clock, Data, Deferred, Effect, Exit, Fiber, Option, Stream } from "effect" import { SessionError } from "@opencode/schema/session-error" import { Bus } from "../../bus.js" import { Permission } from "../../permission.js" @@ -42,6 +42,8 @@ export const Outcome = Data.taggedEnum() interface Input { readonly isLocationClosed: () => boolean + /** Why the execution is being interrupted, once it is: `"user"` when someone stopped it. */ + readonly interruption?: () => "user" | "shutdown" | undefined readonly sessionID: SessionSchema.ID readonly assistantMessageID: SessionMessage.ID readonly agent: Agent.ID @@ -97,9 +99,20 @@ export const make = Effect.gen(function* () { const toolRuns: Array<{ readonly call: ToolCall readonly fiber: Fiber.Fiber + readonly cancel: Cancel }> = [] const interruptTools = Effect.suspend(() => Fiber.interruptAll(toolRuns.map((run) => run.fiber))) - const executeTool = (call: ToolCall) => { + // A user's stop asks each tool awaiting `cancel` to stop and settle its own call, and interrupts every other + // tool. A tool that does not settle in time is interrupted too. Teardown interrupts every tool. + const stopTools = Effect.suspend(() => { + const user = input.interruption?.() === "user" && !input.isLocationClosed() + const immediate = toolRuns.flatMap((run) => (user && run.cancel.trigger() ? [] : [run.fiber])) + return Fiber.interruptAll(immediate).pipe( + Effect.andThen(Fiber.awaitAll(toolRuns.map((run) => run.fiber)).pipe(Effect.timeoutOption(COOPERATIVE_STOP))), + Effect.flatMap((settled) => (Option.isSome(settled) ? Effect.void : interruptTools)), + ) + }) + const executeTool = (call: ToolCall, cancel: Cancel) => { if (input.prepared.request.toolChoice?.type === "none") return new Tool.Error({ message: "Tools are disabled after the maximum agent steps" }) return input.prepared.executeTool({ @@ -108,6 +121,7 @@ export const make = Effect.gen(function* () { messageID: input.assistantMessageID, call, progress: (update) => publisher.progress(call.id, update), + cancel: cancel.effect, }) } @@ -126,10 +140,12 @@ export const make = Effect.gen(function* () { if (firstOutputAt === undefined && publisher.record().outputStarted) firstOutputAt = yield* Clock.currentTimeMillis if (event.type !== "tool-call" || event.providerExecuted) return + const cancel = makeCancel() toolRuns.push({ call: event, + cancel, fiber: yield* Effect.uninterruptibleMask((restore) => - restore(executeTool(event)).pipe( + restore(executeTool(event, cancel)).pipe( Effect.flatMap(toolOutput.truncate), Effect.flatMap((outcome) => publisher.toolExecution(event.id, event.name, outcome)), Effect.catchTag("Tool.Error", (error) => @@ -158,9 +174,9 @@ export const make = Effect.gen(function* () { ) return yield* Effect.failCause(stream.cause) if (publisher.hasStarted()) yield* publisher.streamed() - if (streamInterrupted) yield* interruptTools + if (streamInterrupted) yield* stopTools const joined = yield* restore(Fiber.awaitAll(toolRuns.map((run) => run.fiber))).pipe(Effect.exit) - if (Exit.isFailure(joined)) yield* interruptTools + if (!streamInterrupted && Exit.isFailure(joined)) yield* stopTools const tools = classifyToolExits(joined, toolRuns) if ( @@ -334,3 +350,35 @@ const classifyToolExits = ( .at(0) return { interrupted: causes.some(Cause.hasInterrupts), declines, failure } } + +// How long a user's stop waits for the tools it asked to stop before interrupting them. +const COOPERATIVE_STOP = "5 seconds" + +type Cancel = ReturnType + +// A tool call's `cancel`. `trigger` completes it, and reports whether the tool was awaiting it, so would stop on its +// own; a tool that was not is interrupted instead. +const makeCancel = () => { + let listeners = 0 + let cancelled = false + const gate = Deferred.makeUnsafe() + return { + effect: Effect.suspend(() => { + if (cancelled) return Effect.void + listeners++ + return Deferred.await(gate).pipe( + Effect.ensuring( + Effect.sync(() => { + listeners-- + }), + ), + ) + }), + trigger: () => { + cancelled = true + if (listeners === 0) return false + Deferred.doneUnsafe(gate, Exit.void) + return true + }, + } +} diff --git a/packages/core/src/shell.ts b/packages/core/src/shell.ts index 62ef511b5d73..054237074457 100644 --- a/packages/core/src/shell.ts +++ b/packages/core/src/shell.ts @@ -1,7 +1,7 @@ export * as Shell from "./shell.js" import path from "path" -import { Context, Deferred, Duration, Effect, Fiber, Latch, Layer, Schema, Schedule, Stream } from "effect" +import { Context, Deferred, Duration, Effect, Fiber, Latch, Layer, Option, Schema, Schedule, Stream } from "effect" import { ChildProcess } from "effect/process" import { produce } from "immer" import { Shell } from "@opencode/schema/shell" @@ -35,6 +35,7 @@ export const DIRECTORY = "shell" const SPAN_COMMAND_LIMIT = 200 type Info = Shell.Info +export type StopReason = "timeout" | "killed" type CreateInput = Shell.CreateInput & { shell?: string } @@ -52,10 +53,11 @@ type Active = { done: Deferred.Deferred timeoutFiber?: Fiber.Fiber timeout?: (duration: number) => Effect.Effect + stop?: (reason: StopReason) => Effect.Effect } type Ended = { - status: "exited" | "timeout" + status: "exited" | StopReason exit?: number signal?: string completed: number @@ -81,10 +83,18 @@ export interface Interface { // NotFoundError if the command is unknown or is removed before it terminates. readonly wait: (id: Shell.ID) => Effect.Effect // A known shell's terminal state and bounded tail. Missing capture remains distinct from its exit status. - readonly result: (started: Shell.Info) => Effect.Effect + // With `wait`, stops waiting for the exit after that long and returns the output so far, still running. + readonly result: ( + started: Shell.Info, + options?: { readonly wait?: Duration.Input }, + ) => Effect.Effect // Replaces the running command's timeout from now; zero clears it. Ignored once the command has // ended or timed out, even while its process is still being killed or its output captured. readonly timeout: (id: Shell.ID, duration: number) => Effect.Effect + // Stops a running command gracefully (SIGTERM, then SIGKILL after 3 s) without forgetting it: it ends + // with the given status and stays observable, file included, until retention evicts it. Returns at + // once; `wait` observes the exit. Ignored once the command has ended or is already stopping. + readonly stop: (id: Shell.ID, reason: StopReason) => Effect.Effect readonly output: (id: Shell.ID, input?: Shell.OutputInput) => Effect.Effect readonly remove: (id: Shell.ID) => Effect.Effect } @@ -215,6 +225,14 @@ const layer = () => return command.info }) + const stop = Effect.fn("Shell.stop")(function* (id: Shell.ID, reason: StopReason) { + const command = yield* require(id) + yield* annotate(command.info) + if (command.info.status !== "running" || !command.stop) return command.info + yield* command.stop(reason) + return command.info + }) + const readRange = (file: string, start: number, length: number) => length <= 0 ? Effect.succeed(Buffer.alloc(0)) @@ -249,9 +267,20 @@ const layer = () => } }) - const result = Effect.fn("Shell.result")(function* (started: Shell.Info) { + const result = Effect.fn("Shell.result")(function* ( + started: Shell.Info, + options?: { readonly wait?: Duration.Input }, + ) { yield* annotate(started) - const info = yield* wait(started.id).pipe( + const ended = wait(started.id).pipe(Effect.map(Option.some)) + const info = yield* ( + options?.wait === undefined + ? ended + : ended.pipe( + Effect.timeoutOrElse({ duration: options.wait, orElse: () => Effect.succeed(Option.none()) }), + ) + ).pipe( + Effect.flatMap((info) => (Option.isSome(info) ? Effect.succeed(info.value) : get(started.id))), Effect.catchTag("Shell.NotFoundError", () => Effect.succeed({ ...started, status: "killed" as const, time: { ...started.time, completed: Date.now() } }), ), @@ -407,25 +436,24 @@ const layer = () => const end = (outcome: Omit) => Effect.suspend(() => Deferred.succeed(ended, { ...outcome, completed: Date.now() })) + // A recorded stop must always kill. The kill runs detached, so interrupting the caller (a timer + // being retimed, removed or torn down) neither cancels it nor waits for the process to die. + command.stop = (reason) => + Effect.gen(function* () { + if (!(yield* end({ status: reason }))) return + runFork(handle.kill({ forceKillAfter: Duration.seconds(3) }).pipe(Effect.catch(() => Effect.void))) + }).pipe(Effect.uninterruptible) + command.timeout = (duration) => Effect.gen(function* () { if (Deferred.isDoneUnsafe(ended)) return if (command.timeoutFiber) yield* Fiber.interrupt(command.timeoutFiber) command.timeoutFiber = undefined if (duration === 0) return + const stop = command.stop + if (!stop) return command.timeoutFiber = runFork( - Effect.sleep(Duration.millis(duration)).pipe( - // A recorded timeout must always kill. The kill runs detached, so interrupting this - // timer (retime, remove, teardown) neither cancels it nor waits for the process to die. - Effect.andThen( - Effect.gen(function* () { - if (!(yield* end({ status: "timeout" }))) return - runFork( - handle.kill({ forceKillAfter: Duration.seconds(3) }).pipe(Effect.catch(() => Effect.void)), - ) - }).pipe(Effect.uninterruptible), - ), - ), + Effect.sleep(Duration.millis(duration)).pipe(Effect.andThen(stop("timeout"))), ) }) @@ -445,7 +473,7 @@ const layer = () => ), ) yield* end({ status: "exited", ...exited }) - // A timeout keeps its status but still records how the killed process exited. + // A stop keeps its status but still records how the killed process exited. const outcome = { ...(yield* Deferred.await(ended)), ...exited } // Report the terminal status only once captured output is complete, so a reader that // sees it never reads a partial file. @@ -475,6 +503,7 @@ const layer = () => // Keep exited history data-only. const timeoutFiber = command.timeoutFiber command.timeout = undefined + command.stop = undefined command.timeoutFiber = undefined if (timeoutFiber) yield* Fiber.interrupt(timeoutFiber) }), @@ -493,7 +522,7 @@ const layer = () => return command.info }) - return Service.of({ create, list, get, wait, result, timeout, output, remove }) + return Service.of({ create, list, get, wait, result, timeout, stop, output, remove }) }), ) diff --git a/packages/core/src/shell/result.ts b/packages/core/src/shell/result.ts index 2b68f05597a4..73d792765ac2 100644 --- a/packages/core/src/shell/result.ts +++ b/packages/core/src/shell/result.ts @@ -28,6 +28,21 @@ export function output(result: Result): Output { } } +// What the model gets for a command stopped because the user interrupted its call: the output so far, where the +// full output is, and the shell ID, even when the output fits (which `output` leaves unsaid). +export function interrupted(result: Result) { + const capture = result.capture + const saved = !capture + ? unavailable.output + : capture.truncated + ? capture.output + : capture.output === "(no output)" + ? `[no output; output file: ${result.info.file}]` + : `${capture.output.replace(/\n$/, "")}\n\n[full output saved to ${result.info.file}]` + const stopping = result.info.status === "running" ? "; it is still being stopped" : "" + return `${saved}\n\nCommand interrupted by the user (shell ID: ${result.info.id})${stopping}.` +} + export function notice(output: Pick, timeout?: number) { if (output.timeout) return `Command timed out${timeout ? ` after ${timeout / 1_000} seconds` : ""}. If it needs longer and isn't waiting for input, rerun with a larger timeout.\nExit code: ${exitCode(output)}` diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index 5965d6541380..99c47a673a89 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -75,6 +75,8 @@ export interface Snapshot { readonly messageID: SessionMessage.ID readonly call: ToolCall readonly progress?: (update: Tool.Metadata) => Effect.Effect + /** Completes when the user asks the call to stop; see `Tool.Context.cancel`. */ + readonly cancel?: Effect.Effect /** Surviving request definitions, keyed by the names advertised after session context hooks. */ readonly definitions?: ReadonlyMap }) => Effect.Effect @@ -307,6 +309,7 @@ const layer = Layer.effect( messageID: input.messageID, id: Tool.CallID.make(input.call.id), progress: input.progress ?? (() => Effect.void), + cancel: input.cancel, } const event = yield* beforeExecute(input.call.name, input.call.input, context) const requested = input.definitions?.get(event.tool) diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index 2590c96be988..e08eb084ae76 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -4,6 +4,7 @@ import { ToolFailure } from "@opencode/ai/effect" import type { Context } from "@opencode/plugin/effect/plugin" import type { SessionHooks } from "@opencode/plugin/effect/session" import type { ShellCreateBefore } from "@opencode/plugin/effect/shell" +import type { Shell as ShellSchema } from "@opencode/schema/shell" import type { Tool } from "@opencode/schema/tool" import { Deferred, Effect, Option, Schema, Scope } from "effect" import { Environment } from "../../environment/index.js" @@ -18,9 +19,12 @@ import { Shell } from "../../shell.js" import { ShellParse } from "../../shell/parse.js" import { ShellSelect } from "../../shell/select.js" import { ShellResult } from "../../shell/result.js" +import { toolFailure } from "../runtime.js" export const name = "shell" export const DEFAULT_TIMEOUT_MS = 2 * 60 * 1_000 +// How long a call the user interrupted waits for its stopped command to exit before settling with the output so far. +const INTERRUPT_WAIT = "500 millis" const BACKGROUND_INSTRUCTION = "You will be notified automatically when the command finishes. The notification will include the command's output. Unless the user explicitly asks otherwise, DO NOT poll for completion, even if you need the final result to continue. Repeatedly sleeping and reading or searching the output file is polling, not useful work. You may read the current output if it lets you do useful work now, but do not repeatedly check it while waiting for the command to finish. Keep working on anything that does not depend on the result. If you have nothing else to do, end your response; you will be resumed automatically when the command finishes." @@ -192,6 +196,20 @@ export const Plugin = { Effect.forkIn(scope, { startImmediately: true }), ) + // Stops the command of a call the user asked to stop, and fails the call with the output so far. The command + // stays observable, output file included. + const cancelled = Effect.fnUntraced(function* (info: ShellSchema.Info, jobID: string) { + yield* shell.stop(info.id, "killed").pipe(Effect.ignore) + // The stop escalates to SIGKILL on its own; the session does not wait for that to settle the call. + const result = yield* shell.result(info, { wait: INTERRUPT_WAIT }) + // The stopped job settles from the same exit; this only releases it. + yield* jobs.cancel(jobID) + return yield* new ToolFailure({ + message: ShellResult.interrupted(result), + metadata: { interrupted: true, truncated: result.capture?.truncated ?? false, shellID: info.id }, + }) + }) + yield* ctx.tool .transform((editor) => editor.add({ @@ -203,99 +221,109 @@ export const Plugin = { execute: (input, context) => { const timeout = input.background === true ? (input.timeout ?? 0) : (input.timeout ?? DEFAULT_TIMEOUT_MS) let finalTimeout = timeout - return Effect.gen(function* () { - const info = yield* shell.create( - { - command: input.command, - cwd: input.workdir, - timeout, - shell: yield* compatibleShell, - metadata: { sessionID: context.sessionID }, - }, - (invocation) => - Effect.gen(function* () { - invocation.env.AGENT = "1" - invocation.env.OPENCODE = "1" - invocation.env.AI_AGENT ||= "opencode" - invocation.env.OPENCODE_SESSION_ID = context.sessionID - finalTimeout = yield* prepare(invocation, context) - if (autoBackground) invocation.timeout = 0 - }), - ) - yield* context.progress({ shellID: info.id }) + // Uninterruptible from spawning to blocking, so an interrupt cannot orphan a started command. + return Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + const info = yield* shell.create( + { + command: input.command, + cwd: input.workdir, + timeout, + shell: yield* compatibleShell, + metadata: { sessionID: context.sessionID }, + }, + (invocation) => + Effect.gen(function* () { + invocation.env.AGENT = "1" + invocation.env.OPENCODE = "1" + invocation.env.AI_AGENT ||= "opencode" + invocation.env.OPENCODE_SESSION_ID = context.sessionID + finalTimeout = yield* restore(prepare(invocation, context)) + if (autoBackground) invocation.timeout = 0 + }), + ) + yield* context.progress({ shellID: info.id }) - const settled = yield* Deferred.make() - const run = Effect.gen(function* () { - const result = yield* shell.result(info) - if (!result.capture) return yield* new Shell.NotFoundError({ id: info.id }) - return { ...ShellResult.output(result), status: "completed" as const } - }).pipe( - Effect.tap((output) => Deferred.succeed(settled, output)), - Effect.map((output) => resultMessages(output, finalTimeout).join("\n\n")), - Effect.onInterrupt(() => shell.remove(info.id).pipe(Effect.ignore)), - ) - const job = yield* jobs.start({ - // CodeMode children share a tool-call ID, but each shell must own its job. - id: info.id, - type: name, - title: info.command, - metadata: { sessionID: context.sessionID, shellID: info.id }, - recovery: { - kind: "shell", - sessionID: context.sessionID, - shellID: info.id, - command: info.command, - }, - run, - }) + const settled = yield* Deferred.make() + const run = Effect.gen(function* () { + const result = yield* shell.result(info) + if (!result.capture) return yield* new Shell.NotFoundError({ id: info.id }) + return { ...ShellResult.output(result), status: "completed" as const } + }).pipe( + Effect.tap((output) => Deferred.succeed(settled, output)), + Effect.map((output) => resultMessages(output, finalTimeout).join("\n\n")), + // Cancelling the job stops the command but keeps it, output file included. + Effect.onInterrupt(() => shell.stop(info.id, "killed").pipe(Effect.ignore)), + ) + const job = yield* jobs.start({ + // CodeMode children share a tool-call ID, but each shell must own its job. + id: info.id, + type: name, + title: info.command, + metadata: { sessionID: context.sessionID, shellID: info.id }, + recovery: { + kind: "shell", + sessionID: context.sessionID, + shellID: info.id, + command: info.command, + }, + run, + }) - if (input.background === true) { - yield* jobs.background(job.id) - yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled) - return backgroundResult(info) - } + if (input.background === true) { + yield* jobs.background(job.id) + yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled) + return backgroundResult(info) + } - const waiting = jobs.block({ id: job.id, sessionID: context.sessionID }) - const result = yield* ( - autoBackground && finalTimeout > 0 - ? waiting.pipe( - Effect.timeoutOption(finalTimeout), - Effect.flatMap((result) => - Option.isSome(result) - ? Effect.succeed(result.value) - : jobs - .background(job.id) - .pipe( - Effect.map((info) => - info ? { type: "backgrounded" as const, info, timedOut: true } : undefined, + const waiting = jobs.block({ id: job.id, sessionID: context.sessionID }) + const blocked = + autoBackground && finalTimeout > 0 + ? waiting.pipe( + Effect.timeoutOption(finalTimeout), + Effect.flatMap((result) => + Option.isSome(result) + ? Effect.succeed(result.value) + : jobs + .background(job.id) + .pipe( + Effect.map((info) => + info ? { type: "backgrounded" as const, info, timedOut: true } : undefined, + ), ), - ), - ), - ) - : waiting - ).pipe(Effect.onInterrupt(() => jobs.cancel(job.id).pipe(Effect.ignore))) - if (result?.type === "backgrounded") { - yield* shell.timeout(info.id, 0) - const elapsed = "timedOut" in result ? finalTimeout : undefined - finalTimeout = 0 - yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled) - return backgroundResult(info, elapsed) - } - if (result?.info.status === "error") - return yield* Effect.fail(new Error(result.info.error ?? "Command failed")) - if (result?.info.status === "cancelled") return yield* Effect.fail(new Error("Command cancelled")) + ), + ) + : waiting + // A user's stop arrives through `cancel`; an interrupt (a server shutdown) cancels the job as before. + const outcome = yield* restore( + Effect.raceFirst( + blocked.pipe(Effect.map((result) => ({ type: "settled" as const, result }))), + (context.cancel ?? Effect.never).pipe(Effect.as({ type: "cancelled" as const })), + ), + ).pipe(Effect.onInterrupt(() => jobs.cancel(job.id).pipe(Effect.ignore))) + if (outcome.type === "cancelled") return yield* cancelled(info, job.id) + const result = outcome.result + if (result?.type === "backgrounded") { + yield* shell.timeout(info.id, 0) + const elapsed = "timedOut" in result ? finalTimeout : undefined + finalTimeout = 0 + yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled) + return backgroundResult(info, elapsed) + } + if (result?.info.status === "error") + return yield* Effect.fail(new Error(result.info.error ?? "Command failed")) + if (result?.info.status === "cancelled") return yield* Effect.fail(new Error("Command cancelled")) - return yield* Deferred.await(settled) - }).pipe( + return yield* Deferred.await(settled) + }), + ).pipe( // Shell spans, including the job that waits for a backgrounded command, name the call that started them. Effect.annotateSpans({ "gen_ai.tool.call.id": context.id, ...(input.background === true ? { "opencode.shell.background": true } : {}), }), Effect.map((output) => toolResult(output, finalTimeout)), - Effect.mapError( - (error) => new ToolFailure({ message: `Unable to execute command: ${input.command}`, error }), - ), + Effect.mapError(toolFailure(`Unable to execute command: ${input.command}`)), ) }, }), diff --git a/packages/core/test/codemode.test.ts b/packages/core/test/codemode.test.ts index dda8eb982cf5..417ee9b807b2 100644 --- a/packages/core/test/codemode.test.ts +++ b/packages/core/test/codemode.test.ts @@ -3,6 +3,9 @@ import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { Location } from "@opencode/core/location" import { AbsolutePath } from "@opencode/core/schema" import { Tool } from "@opencode/core/tool" +import { Agent } from "@opencode/core/agent" +import { Session } from "@opencode/core/session" +import { SessionMessage } from "@opencode/core/session/message" import { Effect, Schema } from "effect" import type { Info } from "@opencode/schema/tool" import { it } from "./lib/effect" @@ -49,6 +52,40 @@ describe("CodeMode", () => { }).pipe(Effect.scoped, Effect.provide(toolNode)), ) + it.effect("never hands a stop to a nested call, so its error cannot replace the execute call's result", () => + Effect.gen(function* () { + const tools = yield* Tool.Service + yield* tools.transform((editor) => { + editor.add({ + name: "stoppable", + description: "Stops on cancel", + input: Schema.Struct({}), + output: Schema.String, + execute: (_input, context) => + context.cancel + ? context.cancel.pipe(Effect.andThen(Effect.fail(new Tool.Error({ message: "nested stopped" })))) + : Effect.succeed({ output: "ran" }), + }) + }) + const snapshot = yield* tools.snapshot() + const result = yield* snapshot.execute({ + sessionID: Session.ID.make("ses_codemode_cancel"), + agent: Agent.ID.make("build"), + messageID: SessionMessage.ID.create(), + call: { + type: "tool-call", + id: "call-execute", + name: "execute", + input: { code: "return await tools.stoppable({})" }, + }, + // Already stopped: the execute call itself does not wait for it. + cancel: Effect.void, + }) + expect(JSON.stringify(result.content)).toContain("ran") + expect(JSON.stringify(result.content)).not.toContain("nested stopped") + }).pipe(Effect.scoped, Effect.provide(toolNode)), + ) + it.effect("renders Effect numbers in built-in tool signatures as number", () => Effect.gen(function* () { const tools = yield* Tool.Service diff --git a/packages/core/test/session-execution.test.ts b/packages/core/test/session-execution.test.ts index edc90d4495cd..efc08062535d 100644 --- a/packages/core/test/session-execution.test.ts +++ b/packages/core/test/session-execution.test.ts @@ -142,6 +142,28 @@ describe("SessionExecution lifecycle", () => { }), ) + it.effect("tells the drain once the user stopped it", () => + Effect.gen(function* () { + const database = yield* Database.Service + const sessionID = Session.ID.make("ses_interruption_user") + yield* seedSessions(database, [sessionID]) + const draining = yield* Deferred.make<(() => string | undefined) | undefined>() + const scope = yield* Scope.make() + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)) + const context = yield* buildExecution(scope, (input) => + Deferred.succeed(draining, input.interruption).pipe(Effect.andThen(Effect.never)), + ) + const execution = Context.get(context, SessionExecution.Service) + yield* execution.resume(sessionID).pipe(Effect.forkScoped) + const reason = yield* Deferred.await(draining) + // Teardown interrupts without a reason, so only a user's stop reads as one. + expect(reason?.()).toBeUndefined() + yield* execution.interrupt(sessionID) + expect(reason?.()).toBe("user") + yield* execution.awaitIdle(sessionID) + }), + ) + it.effect("reports an idle interrupt as a no-op", () => Effect.gen(function* () { const sessionID = Session.ID.make("ses_idle_cancel") diff --git a/packages/core/test/session-run-coordinator.test.ts b/packages/core/test/session-run-coordinator.test.ts index e02a84511d52..f1d28b66c1c5 100644 --- a/packages/core/test/session-run-coordinator.test.ts +++ b/packages/core/test/session-run-coordinator.test.ts @@ -314,6 +314,31 @@ describe("SessionRunCoordinator", () => { }), ) + it.effect("tells why an execution is being stopped while it cleans up", () => + Effect.gen(function* () { + const started = yield* Deferred.make() + const seen: Array = [] + const coordinator: SessionRunCoordinator.Coordinator = yield* SessionRunCoordinator.make< + string, + never, + "user" + >({ + drain: (key) => + Effect.sync(() => void seen.push(coordinator.interruption(key))).pipe( + Effect.andThen(Deferred.succeed(started, undefined)), + Effect.andThen(Effect.never), + Effect.ensuring(Effect.sync(() => void seen.push(coordinator.interruption(key)))), + ), + }) + const run = yield* coordinator.run("session").pipe(Effect.forkChild) + yield* Deferred.await(started) + expect(yield* coordinator.interrupt("session", "user")).toBeTrue() + yield* Fiber.await(run) + expect(seen).toEqual([undefined, "user"]) + expect(coordinator.interruption("session")).toBeUndefined() + }), + ) + it.effect("runs a wake registered during interruption cleanup", () => Effect.gen(function* () { const firstStarted = yield* Deferred.make() diff --git a/packages/core/test/session-runner.test.ts b/packages/core/test/session-runner.test.ts index 2f06620c2cea..d6bb961a25f5 100644 --- a/packages/core/test/session-runner.test.ts +++ b/packages/core/test/session-runner.test.ts @@ -1146,6 +1146,7 @@ describe("SessionRunnerLLM", () => { messageID: expect.stringMatching(/^msg_/), id: Tool.CallID.make("call-location"), progress: expect.any(Function), + cancel: expect.anything(), }, ]) expect(Array.from(yield* Fiber.join(progressFiber))[0]?.data.metadata).toEqual({ phase: "reading" }) diff --git a/packages/core/test/session-step.test.ts b/packages/core/test/session-step.test.ts index 513263e59007..4c6e339e8f2e 100644 --- a/packages/core/test/session-step.test.ts +++ b/packages/core/test/session-step.test.ts @@ -17,11 +17,12 @@ import { SessionRunnerModel } from "@opencode/core/session/runner/model" import { SessionStep } from "@opencode/core/session/runner/step" import { SessionMessageTable, SessionTable } from "@opencode/core/session/sql" import { Snapshot } from "@opencode/core/snapshot" +import { Tool } from "@opencode/core/tool" import { ToolOutput } from "@opencode/core/tool-output" import { Money } from "@opencode/schema/money" import { LayerNode } from "@opencode/util/effect/layer-node" import { asc, eq } from "drizzle-orm" -import { Effect, Exit, Layer } from "effect" +import { Deferred, Effect, Exit, Fiber, Layer } from "effect" import { testEffect } from "./lib/effect" const it = testEffect( @@ -227,3 +228,143 @@ it.effect("records the cost the endpoint reports instead of the catalog price", expect(yield* db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get()).toMatchObject({ cost: 0 }) }), ) + +// Interrupts an attempt running a tool that stops on `cancel` and one that never does, and returns how the step and +// its calls were recorded. +const stopTwoTools = (how: { reason: "user" | "shutdown"; locationClosed: boolean }) => + Effect.gen(function* () { + const db = (yield* Database.Service).db + const llm = yield* TestLLM.Test + const sessionID = Session.ID.create() + const assistantMessageID = SessionMessage.ID.create() + const steps = yield* SessionStep.make.pipe( + Effect.provide( + Layer.mock(Snapshot.Service)({ + capture: () => Effect.succeed(undefined), + files: () => Effect.succeed([]), + }), + ), + ) + yield* db + .insert(ProjectTable) + .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] }) + .onConflictDoNothing() + .run() + yield* db + .insert(SessionTable) + .values({ id: sessionID, project_id: Project.ID.global, slug: "step", directory: "/project", version: "test" }) + .run() + const model = SessionRunnerModel.resolved( + LanguageModel.make({ id: "test-model", provider: "test", route: OpenAIChat.route }), + { + capabilities: { tools: true, input: ["text"], output: ["text"] }, + limit: { context: 100_000, output: 1_000 }, + cost: [], + }, + ) + yield* llm.push( + TestLLM.complete( + { reason: { normalized: "tool-calls" }, usage: { inputTokens: 1, outputTokens: 1 } }, + LLMEvent.toolCall({ id: "call-cooperative", name: "test", input: {} }), + LLMEvent.toolCall({ id: "call-stuck", name: "test", input: {} }), + ), + ) + const listening = yield* Deferred.make() + const stuck = yield* Deferred.make() + let interrupted = false + const attempt = yield* steps + .attempt({ + isLocationClosed: () => how.locationClosed, + interruption: () => how.reason, + sessionID, + assistantMessageID, + agent: Agent.defaultID, + model, + prepared: { + retry: () => Effect.void, + request: ai.request({ model: model.model, prompt: "Run two tools" }), + options: {}, + executeTool: (input) => + input.call.id === "call-cooperative" + ? // Like the shell tool: stops on `cancel` and fails with what it has. + Deferred.succeed(listening, undefined).pipe( + Effect.andThen(input.cancel ?? Effect.never), + Effect.andThen( + Effect.fail(new Tool.Error({ message: "partial output", metadata: { interrupted: true } })), + ), + ) + : Deferred.succeed(stuck, undefined).pipe( + Effect.andThen(Effect.never), + Effect.onInterrupt(() => + Effect.sync(() => { + interrupted = true + }), + ), + ), + }, + retry: () => Effect.succeed({ retry: false }), + recoverContinuation: true, + recoverOverflow: Effect.succeed(false), + }) + .pipe(Effect.forkChild({ startImmediately: true })) + yield* Deferred.await(listening) + yield* Deferred.await(stuck) + yield* Fiber.interrupt(attempt) + const exit = yield* Fiber.await(attempt) + const message = yield* db + .select() + .from(SessionMessageTable) + .where(eq(SessionMessageTable.id, assistantMessageID)) + .get() + return { exit, data: message?.data, requests: (yield* llm.requests()).length, interrupted } + }) + +it.live("lets a tool the user stopped fail with its own error and interrupts the others at once", () => + Effect.gen(function* () { + const started = Date.now() + const { exit, data, requests, interrupted } = yield* stopTwoTools({ reason: "user", locationClosed: false }) + expect(Exit.hasInterrupts(exit)).toBe(true) + expect(requests).toBe(1) + expect(interrupted).toBe(true) + expect(Date.now() - started).toBeLessThan(2_000) + expect(data).toMatchObject({ + error: { type: "aborted", message: "Step interrupted" }, + content: [ + { + type: "tool", + id: "call-cooperative", + state: { + status: "error", + error: { type: "tool.execution", message: "partial output" }, + metadata: { interrupted: true }, + }, + }, + { + type: "tool", + id: "call-stuck", + state: { status: "error", error: { type: "aborted", message: "Tool execution interrupted" } }, + }, + ], + }) + }), +) + +for (const how of [ + { name: "a server shutdown", reason: "shutdown" as const, locationClosed: false }, + { name: "a closed Location", reason: "user" as const, locationClosed: true }, +]) + it.live(`interrupts every tool on ${how.name}`, () => + Effect.gen(function* () { + const { exit, data, requests } = yield* stopTwoTools(how) + expect(Exit.hasInterrupts(exit)).toBe(true) + expect(requests).toBe(1) + const generic = { status: "error", error: { type: "aborted", message: "Tool execution interrupted" } } + expect(data).toMatchObject({ + error: { type: "aborted", message: "Step interrupted" }, + content: [ + { type: "tool", id: "call-cooperative", state: generic }, + { type: "tool", id: "call-stuck", state: generic }, + ], + }) + }), + ) diff --git a/packages/core/test/shell-result.test.ts b/packages/core/test/shell-result.test.ts new file mode 100644 index 000000000000..079a4fe0222a --- /dev/null +++ b/packages/core/test/shell-result.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, test } from "bun:test" +import { ShellResult } from "@opencode/core/shell/result" +import { Shell } from "@opencode/schema/shell" + +const info = (status: Shell.Status): Shell.Info => ({ + id: Shell.ID.make("sh_result"), + status, + command: "work", + cwd: "/tmp", + shell: "/bin/sh", + file: "/tmp/sh_result.out", + metadata: {}, + time: { started: 0, completed: 1 }, +}) + +describe("ShellResult.interrupted", () => { + test("names the output file and the shell even when the output fits", () => { + expect(ShellResult.interrupted({ info: info("killed"), capture: { output: "partial\n", truncated: false } })).toBe( + "partial\n\n[full output saved to /tmp/sh_result.out]\n\nCommand interrupted by the user (shell ID: sh_result).", + ) + }) + + test("keeps a truncated tail's own notice", () => { + const output = "tail\n\n[showing lines 9-10 of 10; full output saved to /tmp/sh_result.out]" + expect(ShellResult.interrupted({ info: info("killed"), capture: { output, truncated: true } })).toBe( + `${output}\n\nCommand interrupted by the user (shell ID: sh_result).`, + ) + }) + + test("says once that there was no output, and that a command still stopping is not done", () => { + expect( + ShellResult.interrupted({ info: info("running"), capture: { output: "(no output)", truncated: false } }), + ).toBe( + "[no output; output file: /tmp/sh_result.out]\n\nCommand interrupted by the user (shell ID: sh_result); it is still being stopped.", + ) + }) +}) diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index 8d1ccd0c09e9..c4b9ff28c4ca 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -41,6 +41,7 @@ import { ID } from "@opencode/schema/shell" import { ShellTool } from "@opencode/core/tool/plugin/shell" import { ToolOutput } from "@opencode/core/tool-output" import { Tool } from "@opencode/core/tool" +import { PluginHooks } from "@opencode/core/plugin/hooks" import { tmpdir, tmpdirScoped, withTempDir } from "./fixture/tmpdir" import { tempGlobalLayer } from "./fixture/global" import { offlineModels } from "./fixture/models" @@ -1483,6 +1484,8 @@ describe("ShellTool", () => { expect((yield* shell.get(id)).status).toBe("running") const jobs = yield* Job.Service expect(yield* jobs.cancel(id)).toMatchObject({ id, status: "cancelled" }) + // Cancelling stops the command and keeps it, output file included. + expect((yield* shell.wait(id)).status).toBe("killed") expect(yield* shell.list()).toEqual([]) }), true, @@ -2054,3 +2057,146 @@ describe("ShellTool", () => { }), ) }) + +describe("ShellTool stopped", () => { + // Runs a foreground call the way a session step does, then stops it as the user does (through `cancel`), or + // interrupts it as a server shutdown does. + const stopCall = ( + registry: Tool.Interface, + command: string, + id: string, + how: "cancel" | "interrupt", + waitForOutput = true, + ) => + Effect.gen(function* () { + const shell = yield* Shell.Service + const cancel = yield* Deferred.make() + const started = yield* Deferred.make() + const fiber = yield* executeTool(registry, { + ...call({ command }, id), + progress: (update) => + typeof update.shellID === "string" + ? Deferred.succeed(started, update.shellID).pipe(Effect.asVoid) + : Effect.void, + cancel: Deferred.await(cancel), + }).pipe(Effect.forkChild({ startImmediately: true })) + const shellID = ID.make(yield* Deferred.await(started)) + while (waitForOutput && (yield* shell.output(shellID, { cursor: Number.MAX_SAFE_INTEGER })).size === 0) + yield* Effect.sleep(Duration.millis(10)) + if (how === "cancel") yield* Deferred.succeed(cancel, undefined) + if (how === "interrupt") yield* Fiber.interrupt(fiber) + const exit = yield* Fiber.await(fiber) + return { shellID, exit, result: Exit.isSuccess(exit) ? exit.value : undefined } + }) + + const test = isWindows ? it.live.skip : it.live + + test("stops a command the user stopped, keeps its file and fails the call with the tail, file and shell ID", () => + withTempDir((tmp) => { + reset() + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const shell = yield* Shell.Service + const jobs = yield* Job.Service + const { shellID, result } = yield* stopCall( + registry, + "printf 'first\\nsecond\\n'; sleep 60", + "call-stopped", + "cancel", + ) + const info = yield* shell.get(shellID) + expect(info.status).toBe("killed") + expect(yield* Effect.promise(() => fs.readFile(info.file, "utf8"))).toBe("first\nsecond\n") + expect(result).toEqual({ + status: "error", + error: { + type: "tool.execution", + message: `first\nsecond\n\n[full output saved to ${info.file}]\n\nCommand interrupted by the user (shell ID: ${shellID}).`, + }, + }) + expect((yield* jobs.get(shellID))?.status).not.toBe("running") + }), + ) + })) + + test("says once that a stopped command wrote nothing", () => + withTempDir((tmp) => { + reset() + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const shell = yield* Shell.Service + const { shellID, result } = yield* stopCall(registry, "sleep 60", "call-silent", "cancel", false) + const info = yield* shell.get(shellID) + expect(result?.error?.message).toBe( + `[no output; output file: ${info.file}]\n\nCommand interrupted by the user (shell ID: ${shellID}).`, + ) + }), + ) + })) + + test( + "settles a stopped call without waiting for a command that ignores SIGTERM", + () => + withTempDir((tmp) => { + reset() + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const shell = yield* Shell.Service + const started = Date.now() + const { shellID, result } = yield* stopCall( + registry, + "trap '' TERM; printf 'kept\\n'; while :; do sleep 1; done", + "call-stubborn", + "cancel", + ) + // Bounded by the short wait, not by the 3 s grace before SIGKILL. + expect(Date.now() - started).toBeLessThan(2_500) + const info = yield* shell.get(shellID) + expect(result?.error?.message).toBe( + `kept\n\n[full output saved to ${info.file}]\n\nCommand interrupted by the user (shell ID: ${shellID}); it is still being stopped.`, + ) + // The stop still ends it. + expect((yield* shell.wait(shellID)).status).toBe("killed") + }), + ) + }), + { timeout: 15_000 }, + ) + + test("lets an execute.after hook replace a stopped call's failure", () => + withTempDir((tmp) => { + reset() + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const hooks = yield* PluginHooks.Service + const seen: unknown[] = [] + yield* hooks.register("tool", "execute.after", (event) => + Effect.sync(() => { + if (event.status !== "error") return + seen.push(event.error.metadata) + event.error = new Tool.Error({ message: "rewritten by a plugin" }) + }), + ) + const { shellID, result } = yield* stopCall(registry, "printf ready; sleep 60", "call-hooked", "cancel") + expect(seen).toEqual([{ interrupted: true, truncated: false, shellID }]) + expect(result?.error?.message).toBe("rewritten by a plugin") + }), + ) + })) + + test("leaves a call a shutdown interrupted to the step", () => + withTempDir((tmp) => { + reset() + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const shell = yield* Shell.Service + const { shellID, exit } = yield* stopCall(registry, "printf ready; sleep 60", "call-teardown", "interrupt") + expect(Exit.hasInterrupts(exit)).toBe(true) + // The job is cancelled as before, which stops the command; its file stays. + const info = yield* shell.wait(shellID) + expect(info.status).toBe("killed") + expect(yield* Effect.promise(() => fs.readFile(info.file, "utf8"))).toBe("ready") + }), + ) + })) +}) diff --git a/packages/plugin/src/promise/tool.ts b/packages/plugin/src/promise/tool.ts index 5eb814e39807..7de64a8cbe2b 100644 --- a/packages/plugin/src/promise/tool.ts +++ b/packages/plugin/src/promise/tool.ts @@ -8,7 +8,7 @@ import type { SessionMessage } from "@opencode/schema/session-message" import type { Types } from "effect" import type { Hooks, Transform } from "./registration.js" -export interface ToolContext extends Omit { +export interface ToolContext extends Omit { readonly signal: AbortSignal readonly progress: (update: Tool.Metadata) => Promise } diff --git a/packages/schema/src/tool.ts b/packages/schema/src/tool.ts index 06dec1c0c57c..e271ed22a5f5 100644 --- a/packages/schema/src/tool.ts +++ b/packages/schema/src/tool.ts @@ -17,6 +17,11 @@ export interface Context { readonly messageID: SessionMessage.ID readonly id: CallID readonly progress: (update: Metadata) => Effect.Effect + /** + * Completes when the user asks the call to stop. A tool that awaits it can stop its work and fail with what it + * has; a tool that does not is interrupted. + */ + readonly cancel?: Effect.Effect } export interface Namespace { From 4d8c0dddc5d1a51c4bdb09ca1a4a9b0c04bcf0ee Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 10 Nov 2026 17:16:25 +0000 Subject: [PATCH 2/5] fix(core): listen for the user's stop for the whole shell call The shell tool now awaits `cancel` from the start of the call, before the command is created, and keeps listening until the call ends. A stop while the command starts therefore reaches the tool cooperatively instead of interrupting it: a stop while asking for permission ends the call before any command starts, and a stop during creation stops the command as soon as it exists. A user stop after a Location reload also goes through `cancel` now; the reloaded Location keeps serving the step that borrows it. User decisions: - The shell tool listens for the user's stop from the start of the call - A user stop after a Location reload also goes through cooperative cancel --- packages/core/src/session/runner/step.ts | 11 +- packages/core/src/tool/plugin/shell.ts | 200 +++++++++++++---------- packages/core/test/session-step.test.ts | 77 +++++---- packages/core/test/tool-shell.test.ts | 19 +++ 4 files changed, 177 insertions(+), 130 deletions(-) diff --git a/packages/core/src/session/runner/step.ts b/packages/core/src/session/runner/step.ts index 00136eb4d257..e3a74ef57b6a 100644 --- a/packages/core/src/session/runner/step.ts +++ b/packages/core/src/session/runner/step.ts @@ -105,7 +105,8 @@ export const make = Effect.gen(function* () { // A user's stop asks each tool awaiting `cancel` to stop and settle its own call, and interrupts every other // tool. A tool that does not settle in time is interrupted too. Teardown interrupts every tool. const stopTools = Effect.suspend(() => { - const user = input.interruption?.() === "user" && !input.isLocationClosed() + // A reloaded Location still serves the steps that borrow it, so its tools can stop on their own too. + const user = input.interruption?.() === "user" const immediate = toolRuns.flatMap((run) => (user && run.cancel.trigger() ? [] : [run.fiber])) return Fiber.interruptAll(immediate).pipe( Effect.andThen(Fiber.awaitAll(toolRuns.map((run) => run.fiber)).pipe(Effect.timeoutOption(COOPERATIVE_STOP))), @@ -356,9 +357,11 @@ const COOPERATIVE_STOP = "5 seconds" type Cancel = ReturnType -// A tool call's `cancel`. `trigger` completes it, and reports whether the tool was awaiting it, so would stop on its -// own; a tool that was not is interrupted instead. -const makeCancel = () => { +/** + * A tool call's `cancel`. `trigger` completes it, and reports whether the tool was awaiting it, so would stop on its + * own; a tool that was not is interrupted instead. + */ +export const makeCancel = () => { let listeners = 0 let cancelled = false const gate = Deferred.makeUnsafe() diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index e08eb084ae76..458b90ce3fd7 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -6,7 +6,7 @@ import type { SessionHooks } from "@opencode/plugin/effect/session" import type { ShellCreateBefore } from "@opencode/plugin/effect/shell" import type { Shell as ShellSchema } from "@opencode/schema/shell" import type { Tool } from "@opencode/schema/tool" -import { Deferred, Effect, Option, Schema, Scope } from "effect" +import { Deferred, Effect, Fiber, Option, Schema, Scope } from "effect" import { Environment } from "../../environment/index.js" import { Job } from "../../job.js" import { FileAccess } from "../../file-access.js" @@ -224,97 +224,123 @@ export const Plugin = { // Uninterruptible from spawning to blocking, so an interrupt cannot orphan a started command. return Effect.uninterruptibleMask((restore) => Effect.gen(function* () { - const info = yield* shell.create( - { - command: input.command, - cwd: input.workdir, - timeout, - shell: yield* compatibleShell, - metadata: { sessionID: context.sessionID }, - }, - (invocation) => - Effect.gen(function* () { - invocation.env.AGENT = "1" - invocation.env.OPENCODE = "1" - invocation.env.AI_AGENT ||= "opencode" - invocation.env.OPENCODE_SESSION_ID = context.sessionID - finalTimeout = yield* restore(prepare(invocation, context)) - if (autoBackground) invocation.timeout = 0 - }), - ) - yield* context.progress({ shellID: info.id }) + // Listens for the user's stop for the whole call, starting before the command does, so a stop always + // reaches this tool through `cancel` instead of interrupting it, even while the command starts. + const stopped = yield* Deferred.make() + const listener = context.cancel + ? yield* context.cancel.pipe( + Effect.andThen(Deferred.succeed(stopped, undefined)), + Effect.interruptible, + Effect.forkChild({ startImmediately: true }), + ) + : undefined + return yield* Effect.gen(function* () { + const info = yield* shell.create( + { + command: input.command, + cwd: input.workdir, + timeout, + shell: yield* compatibleShell, + metadata: { sessionID: context.sessionID }, + }, + (invocation) => + Effect.gen(function* () { + invocation.env.AGENT = "1" + invocation.env.OPENCODE = "1" + invocation.env.AI_AGENT ||= "opencode" + invocation.env.OPENCODE_SESSION_ID = context.sessionID + // Asking for permission can take a while; a stop then ends the call before any command starts. + finalTimeout = yield* restore( + Effect.raceFirst( + prepare(invocation, context), + Deferred.await(stopped).pipe( + Effect.andThen( + Effect.fail( + new ToolFailure({ message: "Command interrupted by the user before it started." }), + ), + ), + ), + ), + ) + if (autoBackground) invocation.timeout = 0 + }), + ) + yield* context.progress({ shellID: info.id }) - const settled = yield* Deferred.make() - const run = Effect.gen(function* () { - const result = yield* shell.result(info) - if (!result.capture) return yield* new Shell.NotFoundError({ id: info.id }) - return { ...ShellResult.output(result), status: "completed" as const } - }).pipe( - Effect.tap((output) => Deferred.succeed(settled, output)), - Effect.map((output) => resultMessages(output, finalTimeout).join("\n\n")), - // Cancelling the job stops the command but keeps it, output file included. - Effect.onInterrupt(() => shell.stop(info.id, "killed").pipe(Effect.ignore)), - ) - const job = yield* jobs.start({ - // CodeMode children share a tool-call ID, but each shell must own its job. - id: info.id, - type: name, - title: info.command, - metadata: { sessionID: context.sessionID, shellID: info.id }, - recovery: { - kind: "shell", - sessionID: context.sessionID, - shellID: info.id, - command: info.command, - }, - run, - }) + const settled = yield* Deferred.make() + const run = Effect.gen(function* () { + const result = yield* shell.result(info) + if (!result.capture) return yield* new Shell.NotFoundError({ id: info.id }) + return { ...ShellResult.output(result), status: "completed" as const } + }).pipe( + Effect.tap((output) => Deferred.succeed(settled, output)), + Effect.map((output) => resultMessages(output, finalTimeout).join("\n\n")), + // Cancelling the job stops the command but keeps it, output file included. + Effect.onInterrupt(() => shell.stop(info.id, "killed").pipe(Effect.ignore)), + ) + const job = yield* jobs.start({ + // CodeMode children share a tool-call ID, but each shell must own its job. + id: info.id, + type: name, + title: info.command, + metadata: { sessionID: context.sessionID, shellID: info.id }, + recovery: { + kind: "shell", + sessionID: context.sessionID, + shellID: info.id, + command: info.command, + }, + run, + }) + // Stopped while the command was starting: stop it now. + if (yield* Deferred.isDone(stopped)) return yield* cancelled(info, job.id) - if (input.background === true) { - yield* jobs.background(job.id) - yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled) - return backgroundResult(info) - } + if (input.background === true) { + yield* jobs.background(job.id) + yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled) + return backgroundResult(info) + } - const waiting = jobs.block({ id: job.id, sessionID: context.sessionID }) - const blocked = - autoBackground && finalTimeout > 0 - ? waiting.pipe( - Effect.timeoutOption(finalTimeout), - Effect.flatMap((result) => - Option.isSome(result) - ? Effect.succeed(result.value) - : jobs - .background(job.id) - .pipe( - Effect.map((info) => - info ? { type: "backgrounded" as const, info, timedOut: true } : undefined, + const waiting = jobs.block({ id: job.id, sessionID: context.sessionID }) + const blocked = + autoBackground && finalTimeout > 0 + ? waiting.pipe( + Effect.timeoutOption(finalTimeout), + Effect.flatMap((result) => + Option.isSome(result) + ? Effect.succeed(result.value) + : jobs + .background(job.id) + .pipe( + Effect.map((info) => + info ? { type: "backgrounded" as const, info, timedOut: true } : undefined, + ), ), - ), - ), - ) - : waiting - // A user's stop arrives through `cancel`; an interrupt (a server shutdown) cancels the job as before. - const outcome = yield* restore( - Effect.raceFirst( - blocked.pipe(Effect.map((result) => ({ type: "settled" as const, result }))), - (context.cancel ?? Effect.never).pipe(Effect.as({ type: "cancelled" as const })), - ), - ).pipe(Effect.onInterrupt(() => jobs.cancel(job.id).pipe(Effect.ignore))) - if (outcome.type === "cancelled") return yield* cancelled(info, job.id) - const result = outcome.result - if (result?.type === "backgrounded") { - yield* shell.timeout(info.id, 0) - const elapsed = "timedOut" in result ? finalTimeout : undefined - finalTimeout = 0 - yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled) - return backgroundResult(info, elapsed) - } - if (result?.info.status === "error") - return yield* Effect.fail(new Error(result.info.error ?? "Command failed")) - if (result?.info.status === "cancelled") return yield* Effect.fail(new Error("Command cancelled")) + ), + ) + : waiting + // A user's stop arrives through `cancel`; an interrupt (a server shutdown) cancels the job as before. + const outcome = yield* restore( + Effect.raceFirst( + blocked.pipe(Effect.map((result) => ({ type: "settled" as const, result }))), + Deferred.await(stopped).pipe(Effect.as({ type: "cancelled" as const })), + ), + ).pipe(Effect.onInterrupt(() => jobs.cancel(job.id).pipe(Effect.ignore))) + if (outcome.type === "cancelled") return yield* cancelled(info, job.id) + const result = outcome.result + if (result?.type === "backgrounded") { + yield* shell.timeout(info.id, 0) + const elapsed = "timedOut" in result ? finalTimeout : undefined + finalTimeout = 0 + yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled) + return backgroundResult(info, elapsed) + } + if (result?.info.status === "error") + return yield* Effect.fail(new Error(result.info.error ?? "Command failed")) + if (result?.info.status === "cancelled") return yield* Effect.fail(new Error("Command cancelled")) - return yield* Deferred.await(settled) + return yield* Deferred.await(settled) + }).pipe(Effect.ensuring(listener ? Fiber.interrupt(listener) : Effect.void)) }), ).pipe( // Shell spans, including the job that waits for a backgrounded command, name the call that started them. diff --git a/packages/core/test/session-step.test.ts b/packages/core/test/session-step.test.ts index 4c6e339e8f2e..8a9a324dd959 100644 --- a/packages/core/test/session-step.test.ts +++ b/packages/core/test/session-step.test.ts @@ -319,52 +319,51 @@ const stopTwoTools = (how: { reason: "user" | "shutdown"; locationClosed: boolea return { exit, data: message?.data, requests: (yield* llm.requests()).length, interrupted } }) -it.live("lets a tool the user stopped fail with its own error and interrupts the others at once", () => +for (const locationClosed of [false, true]) + it.live( + `lets a tool the user stopped fail with its own error and interrupts the others at once${locationClosed ? ", after a Location reload" : ""}`, + () => + Effect.gen(function* () { + const started = Date.now() + const { exit, data, requests, interrupted } = yield* stopTwoTools({ reason: "user", locationClosed }) + expect(Exit.hasInterrupts(exit)).toBe(true) + expect(requests).toBe(1) + expect(interrupted).toBe(true) + expect(Date.now() - started).toBeLessThan(2_000) + expect(data).toMatchObject({ + error: { type: "aborted", message: "Step interrupted" }, + content: [ + { + type: "tool", + id: "call-cooperative", + state: { + status: "error", + error: { type: "tool.execution", message: "partial output" }, + metadata: { interrupted: true }, + }, + }, + { + type: "tool", + id: "call-stuck", + state: { status: "error", error: { type: "aborted", message: "Tool execution interrupted" } }, + }, + ], + }) + }), + ) + +it.live("interrupts every tool on a server shutdown", () => Effect.gen(function* () { - const started = Date.now() - const { exit, data, requests, interrupted } = yield* stopTwoTools({ reason: "user", locationClosed: false }) + const { exit, data, requests } = yield* stopTwoTools({ reason: "shutdown", locationClosed: false }) expect(Exit.hasInterrupts(exit)).toBe(true) expect(requests).toBe(1) - expect(interrupted).toBe(true) - expect(Date.now() - started).toBeLessThan(2_000) + const generic = { status: "error", error: { type: "aborted", message: "Tool execution interrupted" } } expect(data).toMatchObject({ error: { type: "aborted", message: "Step interrupted" }, content: [ - { - type: "tool", - id: "call-cooperative", - state: { - status: "error", - error: { type: "tool.execution", message: "partial output" }, - metadata: { interrupted: true }, - }, - }, - { - type: "tool", - id: "call-stuck", - state: { status: "error", error: { type: "aborted", message: "Tool execution interrupted" } }, - }, + { type: "tool", id: "call-cooperative", state: generic }, + { type: "tool", id: "call-stuck", state: generic }, ], }) }), ) - -for (const how of [ - { name: "a server shutdown", reason: "shutdown" as const, locationClosed: false }, - { name: "a closed Location", reason: "user" as const, locationClosed: true }, -]) - it.live(`interrupts every tool on ${how.name}`, () => - Effect.gen(function* () { - const { exit, data, requests } = yield* stopTwoTools(how) - expect(Exit.hasInterrupts(exit)).toBe(true) - expect(requests).toBe(1) - const generic = { status: "error", error: { type: "aborted", message: "Tool execution interrupted" } } - expect(data).toMatchObject({ - error: { type: "aborted", message: "Step interrupted" }, - content: [ - { type: "tool", id: "call-cooperative", state: generic }, - { type: "tool", id: "call-stuck", state: generic }, - ], - }) - }), - ) diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index c4b9ff28c4ca..f0a21b213059 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -2119,6 +2119,25 @@ describe("ShellTool stopped", () => { ) })) + test("ends a call the user stopped before its command started, without starting it", () => + withTempDir((tmp) => { + reset() + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const shell = yield* Shell.Service + const result = yield* executeTool(registry, { + ...call({ command: "printf started > started" }, "call-early-stop"), + // Already stopped, as when the user stops the step while the call waits for permission. + cancel: Effect.void, + }) + expect(result.error?.message).toContain("Command interrupted by the user before it started.") + expect(yield* shell.list()).toEqual([]) + expect(yield* Effect.promise(() => Bun.file(path.join(tmp.path, "started")).exists())).toBe(false) + }), + ) + }), + ) + test("says once that a stopped command wrote nothing", () => withTempDir((tmp) => { reset() From b032f90634d27e89236eaf690780fdd2cbd596e6 Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 10 Nov 2026 18:36:39 +0000 Subject: [PATCH 3/5] fix(core): classify what tools raise while a user's stop settles them When a step was stopped while it waited for its tools, it classified the interrupted wait instead of the tools' own exits, so a decline, a cancelled question or a defect raised while the stop settled them was lost. It now reads each tool's exit once all have ended, and still counts the step as interrupted. `makeCancel` is no longer exported. User decisions: - Classify the tools' exits after the stop, keeping the step interrupted - Export makeCancel only where it is used --- packages/core/src/session/runner/step.ts | 20 +++++----- packages/core/test/session-step.test.ts | 50 +++++++++++++++++++++--- 2 files changed, 56 insertions(+), 14 deletions(-) diff --git a/packages/core/src/session/runner/step.ts b/packages/core/src/session/runner/step.ts index e3a74ef57b6a..d8096d740fd0 100644 --- a/packages/core/src/session/runner/step.ts +++ b/packages/core/src/session/runner/step.ts @@ -176,9 +176,12 @@ export const make = Effect.gen(function* () { return yield* Effect.failCause(stream.cause) if (publisher.hasStarted()) yield* publisher.streamed() if (streamInterrupted) yield* stopTools - const joined = yield* restore(Fiber.awaitAll(toolRuns.map((run) => run.fiber))).pipe(Effect.exit) + const fibers = toolRuns.map((run) => run.fiber) + const joined = yield* restore(Fiber.awaitAll(fibers)).pipe(Effect.exit) if (!streamInterrupted && Exit.isFailure(joined)) yield* stopTools - const tools = classifyToolExits(joined, toolRuns) + // Read each tool's exit once all have ended, so what they raised while stopping (a decline, a defect) counts. + const exits = Exit.isSuccess(joined) ? joined.value : yield* Fiber.awaitAll(fibers) + const tools = classifyToolExits(exits, toolRuns, Exit.hasInterrupts(joined)) if ( !publisher.record().outputStarted && @@ -328,10 +331,11 @@ const isInterruptedStream = (failure: AIError) => { /** Tool.Error settles in each fiber; only user declines remain in the typed error channel. */ const classifyToolExits = ( - settled: Exit.Exit>>, + exits: ReadonlyArray>, runs: ReadonlyArray<{ readonly call: ToolCall }>, + // The step was interrupted while it waited for its tools. + interruptedWhileWaiting: boolean, ) => { - const exits = Exit.isSuccess(settled) ? settled.value : [] const declines = exits.flatMap((exit, index) => Exit.isFailure(exit) ? exit.cause.reasons.flatMap((reason) => @@ -339,9 +343,7 @@ const classifyToolExits = ( ) : [], ) - const causes = Exit.isFailure(settled) - ? [settled.cause] - : exits.flatMap((exit) => (Exit.isFailure(exit) ? [exit.cause] : [])) + const causes = exits.flatMap((exit) => (Exit.isFailure(exit) ? [exit.cause] : [])) const failure = causes .flatMap((cause) => { if (Cause.hasInterrupts(cause)) return [] @@ -349,7 +351,7 @@ const classifyToolExits = ( return reasons.length > 0 ? [Cause.fromReasons(reasons)] : [] }) .at(0) - return { interrupted: causes.some(Cause.hasInterrupts), declines, failure } + return { interrupted: interruptedWhileWaiting || causes.some(Cause.hasInterrupts), declines, failure } } // How long a user's stop waits for the tools it asked to stop before interrupting them. @@ -361,7 +363,7 @@ type Cancel = ReturnType * A tool call's `cancel`. `trigger` completes it, and reports whether the tool was awaiting it, so would stop on its * own; a tool that was not is interrupted instead. */ -export const makeCancel = () => { +const makeCancel = () => { let listeners = 0 let cancelled = false const gate = Deferred.makeUnsafe() diff --git a/packages/core/test/session-step.test.ts b/packages/core/test/session-step.test.ts index 8a9a324dd959..18a98273861c 100644 --- a/packages/core/test/session-step.test.ts +++ b/packages/core/test/session-step.test.ts @@ -18,11 +18,12 @@ import { SessionStep } from "@opencode/core/session/runner/step" import { SessionMessageTable, SessionTable } from "@opencode/core/session/sql" import { Snapshot } from "@opencode/core/snapshot" import { Tool } from "@opencode/core/tool" +import { Permission } from "@opencode/core/permission" import { ToolOutput } from "@opencode/core/tool-output" import { Money } from "@opencode/schema/money" import { LayerNode } from "@opencode/util/effect/layer-node" import { asc, eq } from "drizzle-orm" -import { Deferred, Effect, Exit, Fiber, Layer } from "effect" +import { Cause, Deferred, Effect, Exit, Fiber, Layer } from "effect" import { testEffect } from "./lib/effect" const it = testEffect( @@ -231,7 +232,12 @@ it.effect("records the cost the endpoint reports instead of the catalog price", // Interrupts an attempt running a tool that stops on `cancel` and one that never does, and returns how the step and // its calls were recorded. -const stopTwoTools = (how: { reason: "user" | "shutdown"; locationClosed: boolean }) => +const stopTwoTools = (how: { + reason: "user" | "shutdown" + locationClosed: boolean + // What the cooperative tool does once asked to stop; by default it fails with its partial output. + stopped?: Effect.Effect +}) => Effect.gen(function* () { const db = (yield* Database.Service).db const llm = yield* TestLLM.Test @@ -269,6 +275,8 @@ const stopTwoTools = (how: { reason: "user" | "shutdown"; locationClosed: boolea LLMEvent.toolCall({ id: "call-stuck", name: "test", input: {} }), ), ) + const stopped: Effect.Effect = + how.stopped ?? Effect.fail(new Tool.Error({ message: "partial output", metadata: { interrupted: true } })) const listening = yield* Deferred.make() const stuck = yield* Deferred.make() let interrupted = false @@ -289,9 +297,7 @@ const stopTwoTools = (how: { reason: "user" | "shutdown"; locationClosed: boolea ? // Like the shell tool: stops on `cancel` and fails with what it has. Deferred.succeed(listening, undefined).pipe( Effect.andThen(input.cancel ?? Effect.never), - Effect.andThen( - Effect.fail(new Tool.Error({ message: "partial output", metadata: { interrupted: true } })), - ), + Effect.andThen(stopped), ) : Deferred.succeed(stuck, undefined).pipe( Effect.andThen(Effect.never), @@ -352,6 +358,40 @@ for (const locationClosed of [false, true]) }), ) +// The provider stream has completed when the step is stopped, so the stop arrives while the step waits for its tools. +it.live("classifies what a tool raises while the user's stop settles it: a decline", () => + Effect.gen(function* () { + const { exit, data } = yield* stopTwoTools({ + reason: "user", + locationClosed: false, + stopped: Effect.fail(new Permission.DeclinedError()), + }) + expect(Exit.hasInterrupts(exit)).toBe(true) + expect(data).toMatchObject({ + error: { type: "aborted", message: "Step interrupted" }, + content: [ + { + type: "tool", + id: "call-cooperative", + state: { status: "error", error: { type: "aborted", message: "The user declined this tool call" } }, + }, + { + type: "tool", + id: "call-stuck", + state: { status: "error", error: { type: "aborted", message: "Tool execution interrupted" } }, + }, + ], + }) + }), +) + +it.live("classifies what a tool raises while the user's stop settles it: a defect", () => + Effect.gen(function* () { + const { exit } = yield* stopTwoTools({ reason: "user", locationClosed: false, stopped: Effect.die("tool broke") }) + expect(Exit.isFailure(exit) && Cause.hasDies(exit.cause)).toBe(true) + }), +) + it.live("interrupts every tool on a server shutdown", () => Effect.gen(function* () { const { exit, data, requests } = yield* stopTwoTools({ reason: "shutdown", locationClosed: false }) From d4bd661bf7a216989d85667d969cebea505756bf Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 10 Nov 2026 20:06:54 +0000 Subject: [PATCH 4/5] fix(tui,session-ui): show a stopped shell call's output once A shell call the user stopped fails with its output followed by a notice (where the full output is, and the shell ID). The TUI showed that output twice, once in the card's output block and again in the error; the web renderer showed it only inside the error card. The tool now names the notice in the failure's metadata (`notice`), and both renderers show what precedes it through the normal shell output, clipped like a finished call's, then only the notice as the error. The model still gets the same text. An error a plugin rewrote is shown as is. User decisions: - Show the interrupted output once, clipped like a completed call, with the notice once - Keep the model-facing error text unchanged --- packages/core/src/shell/result.ts | 20 ++-- packages/core/src/tool/plugin/shell.ts | 11 +- packages/core/test/shell-result.test.ts | 29 +++-- packages/core/test/tool-shell.test.ts | 12 +- .../session-ui/src/tools/run-machine.test.ts | 22 ++++ packages/session-ui/src/tools/run-machine.ts | 16 +++ .../session-ui/src/tools/tool-renderer.tsx | 10 ++ packages/tui/src/routes/session/index.tsx | 14 ++- .../tui/test/session-shell-stopped.test.tsx | 107 ++++++++++++++++++ 9 files changed, 217 insertions(+), 24 deletions(-) create mode 100644 packages/tui/test/session-shell-stopped.test.tsx diff --git a/packages/core/src/shell/result.ts b/packages/core/src/shell/result.ts index 73d792765ac2..558d1b8c607d 100644 --- a/packages/core/src/shell/result.ts +++ b/packages/core/src/shell/result.ts @@ -28,19 +28,21 @@ export function output(result: Result): Output { } } -// What the model gets for a command stopped because the user interrupted its call: the output so far, where the -// full output is, and the shell ID, even when the output fits (which `output` leaves unsaid). +// What the model gets for a command stopped because the user interrupted its call (`message`): the output so far, +// where the full output is, and the shell ID, even when the output fits (which `output` leaves unsaid). `output` and +// `notice` are its two parts, so a renderer can show the output like a finished call's, then the notice. export function interrupted(result: Result) { const capture = result.capture - const saved = !capture - ? unavailable.output + const stopping = result.info.status === "running" ? "; it is still being stopped" : "" + const stopped = `Command interrupted by the user (shell ID: ${result.info.id})${stopping}.` + const [output, notice] = !capture + ? [unavailable.output, stopped] : capture.truncated - ? capture.output + ? [capture.output, stopped] : capture.output === "(no output)" - ? `[no output; output file: ${result.info.file}]` - : `${capture.output.replace(/\n$/, "")}\n\n[full output saved to ${result.info.file}]` - const stopping = result.info.status === "running" ? "; it is still being stopped" : "" - return `${saved}\n\nCommand interrupted by the user (shell ID: ${result.info.id})${stopping}.` + ? ["", `[no output; output file: ${result.info.file}]\n\n${stopped}`] + : [capture.output.replace(/\n$/, ""), `[full output saved to ${result.info.file}]\n\n${stopped}`] + return { output, notice, message: output ? `${output}\n\n${notice}` : notice } } export function notice(output: Pick, timeout?: number) { diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index 458b90ce3fd7..b2fbd18dc557 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -204,9 +204,16 @@ export const Plugin = { const result = yield* shell.result(info, { wait: INTERRUPT_WAIT }) // The stopped job settles from the same exit; this only releases it. yield* jobs.cancel(jobID) + const stopped = ShellResult.interrupted(result) return yield* new ToolFailure({ - message: ShellResult.interrupted(result), - metadata: { interrupted: true, truncated: result.capture?.truncated ?? false, shellID: info.id }, + message: stopped.message, + // The notice ends the message; renderers show what precedes it as the output, like a finished call's. + metadata: { + interrupted: true, + truncated: result.capture?.truncated ?? false, + shellID: info.id, + notice: stopped.notice, + }, }) }) diff --git a/packages/core/test/shell-result.test.ts b/packages/core/test/shell-result.test.ts index 079a4fe0222a..480028db69ab 100644 --- a/packages/core/test/shell-result.test.ts +++ b/packages/core/test/shell-result.test.ts @@ -15,23 +15,34 @@ const info = (status: Shell.Status): Shell.Info => ({ describe("ShellResult.interrupted", () => { test("names the output file and the shell even when the output fits", () => { - expect(ShellResult.interrupted({ info: info("killed"), capture: { output: "partial\n", truncated: false } })).toBe( - "partial\n\n[full output saved to /tmp/sh_result.out]\n\nCommand interrupted by the user (shell ID: sh_result).", - ) + expect( + ShellResult.interrupted({ info: info("killed"), capture: { output: "partial\n", truncated: false } }), + ).toEqual({ + output: "partial", + notice: "[full output saved to /tmp/sh_result.out]\n\nCommand interrupted by the user (shell ID: sh_result).", + message: + "partial\n\n[full output saved to /tmp/sh_result.out]\n\nCommand interrupted by the user (shell ID: sh_result).", + }) }) test("keeps a truncated tail's own notice", () => { const output = "tail\n\n[showing lines 9-10 of 10; full output saved to /tmp/sh_result.out]" - expect(ShellResult.interrupted({ info: info("killed"), capture: { output, truncated: true } })).toBe( - `${output}\n\nCommand interrupted by the user (shell ID: sh_result).`, - ) + expect(ShellResult.interrupted({ info: info("killed"), capture: { output, truncated: true } })).toEqual({ + output, + notice: "Command interrupted by the user (shell ID: sh_result).", + message: `${output}\n\nCommand interrupted by the user (shell ID: sh_result).`, + }) }) test("says once that there was no output, and that a command still stopping is not done", () => { expect( ShellResult.interrupted({ info: info("running"), capture: { output: "(no output)", truncated: false } }), - ).toBe( - "[no output; output file: /tmp/sh_result.out]\n\nCommand interrupted by the user (shell ID: sh_result); it is still being stopped.", - ) + ).toEqual({ + output: "", + notice: + "[no output; output file: /tmp/sh_result.out]\n\nCommand interrupted by the user (shell ID: sh_result); it is still being stopped.", + message: + "[no output; output file: /tmp/sh_result.out]\n\nCommand interrupted by the user (shell ID: sh_result); it is still being stopped.", + }) }) }) diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index f0a21b213059..e6b5d38f8198 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -2135,8 +2135,7 @@ describe("ShellTool stopped", () => { expect(yield* Effect.promise(() => Bun.file(path.join(tmp.path, "started")).exists())).toBe(false) }), ) - }), - ) + })) test("says once that a stopped command wrote nothing", () => withTempDir((tmp) => { @@ -2197,7 +2196,14 @@ describe("ShellTool stopped", () => { }), ) const { shellID, result } = yield* stopCall(registry, "printf ready; sleep 60", "call-hooked", "cancel") - expect(seen).toEqual([{ interrupted: true, truncated: false, shellID }]) + expect(seen).toEqual([ + { + interrupted: true, + truncated: false, + shellID, + notice: expect.stringContaining("Command interrupted by the user"), + }, + ]) expect(result?.error?.message).toBe("rewritten by a plugin") }), ) diff --git a/packages/session-ui/src/tools/run-machine.test.ts b/packages/session-ui/src/tools/run-machine.test.ts index fa1606dba1ec..e915586e040b 100644 --- a/packages/session-ui/src/tools/run-machine.test.ts +++ b/packages/session-ui/src/tools/run-machine.test.ts @@ -3,6 +3,7 @@ import { createShellRunState, INITIAL_SUBAGENT_RUN_STATE, shellRunProps, + stoppedShell, subagentRunProps, transitionShellRun, transitionSubagentRun, @@ -177,3 +178,24 @@ describe("transitionSubagentRun", () => { expect(viewSubagentRun(step(failed, { status: "error", metadata: {} }, true)).running).toBe(true) }) }) + +describe("stoppedShell", () => { + const notice = "[full output saved to /tmp/sh_1.out]\n\nCommand interrupted by the user (shell ID: sh_1)." + const stopped = { + tool: "shell", + status: "error", + metadata: { interrupted: true, shellID: "sh_1", notice }, + error: `step 1\nstep 2\n\n${notice}`, + } + + test("splits a stopped call's error into its output and the notice, each once", () => { + expect(stoppedShell(stopped)).toEqual({ output: "step 1\nstep 2", notice }) + }) + + test("leaves every other failure, and a stopped call whose error a plugin rewrote, as an error", () => { + expect(stoppedShell({ ...stopped, metadata: { notice } })).toBeUndefined() + expect(stoppedShell({ ...stopped, tool: "read" })).toBeUndefined() + expect(stoppedShell({ ...stopped, status: "completed" })).toBeUndefined() + expect(stoppedShell({ ...stopped, error: "rewritten by a plugin" })).toBeUndefined() + }) +}) diff --git a/packages/session-ui/src/tools/run-machine.ts b/packages/session-ui/src/tools/run-machine.ts index 7e0690928793..15aea20d21f8 100644 --- a/packages/session-ui/src/tools/run-machine.ts +++ b/packages/session-ui/src/tools/run-machine.ts @@ -116,6 +116,22 @@ function sameShellRun(a: ShellRunState, b: ShellRunState) { return a.shellID === b.shellID && a.streamed === b.streamed } +/** + * A shell call the user stopped fails with its output followed by a notice, which its metadata names. Its output shows + * like a finished call's and only the notice as the error. A plugin that rewrote the error gets it shown as is. + */ +export function stoppedShell(tool: { + readonly tool: string + readonly status?: string + readonly metadata: { readonly interrupted?: unknown; readonly notice?: unknown } + readonly error?: string +}) { + if (tool.tool !== "shell" || tool.status !== "error" || tool.metadata.interrupted !== true) return undefined + const notice = tool.metadata.notice + if (typeof notice !== "string" || !notice || !tool.error?.endsWith(notice)) return undefined + return { output: tool.error.slice(0, -notice.length).replace(/\n+$/, ""), notice } +} + /** A subagent call as the renderer decoded it. */ type SubagentTool = { readonly status: string | undefined diff --git a/packages/session-ui/src/tools/tool-renderer.tsx b/packages/session-ui/src/tools/tool-renderer.tsx index 8957f787ff73..37edb2a350b3 100644 --- a/packages/session-ui/src/tools/tool-renderer.tsx +++ b/packages/session-ui/src/tools/tool-renderer.tsx @@ -78,6 +78,7 @@ import { viewShellRun, viewSubagentRun, INITIAL_SUBAGENT_RUN_STATE, + stoppedShell, type ShellRunEvent, type SubagentRunState, } from "./run-machine" @@ -1364,12 +1365,21 @@ export function ToolDisplay( const errorSubtitle = createMemo(() => toolErrorSubtitle(props, i18n)) const error = createMemo(() => toolDisplayError(props)) + const stopped = createMemo(() => stoppedShell(props)) const render = createMemo(() => ToolRegistry.render(props.tool) ?? GenericTool) return (
+ + {(stopped) => ( + <> + + + + )} + {(error) => { const cleaned = error().replace("Error: ", "") diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index 33bd34340ec9..ed537b3641c8 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -2985,6 +2985,7 @@ function BlockTool(props: BlockToolProps) { const SHELL_DISPLAY_LIMIT = 1024 * 1024 function Shell(props: ToolProps) { + const stopped = createMemo(() => stoppedShell(props.part, props.metadata)) return ( ) } +// A call the user stopped fails with its output followed by a notice, which its metadata names. Its output shows like +// a finished call's and only the notice as the error. A plugin that rewrote the error gets it shown as is. +function stoppedShell(part: SessionMessageAssistantTool, metadata: Record) { + if (part.state.status !== "error" || metadata.interrupted !== true) return + const notice = stringValue(metadata.notice) + const message = part.state.error.message + if (!notice || !message.endsWith(notice)) return + return { output: message.slice(0, -notice.length).replace(/\n+$/, ""), notice } +} + function ShellDisplay(props: { part?: SessionMessageAssistantTool shellID?: string diff --git a/packages/tui/test/session-shell-stopped.test.tsx b/packages/tui/test/session-shell-stopped.test.tsx new file mode 100644 index 000000000000..60a00d1bc185 --- /dev/null +++ b/packages/tui/test/session-shell-stopped.test.tsx @@ -0,0 +1,107 @@ +import { expect, test } from "bun:test" +import { createTestRenderer } from "@opentui/core/testing" +import { Effect, FileSystem } from "effect" +import { Global } from "@opencode/util/global" +import type { SessionMessageInfo } from "@opencode/client" +import { createEventStream, createFetch, directory, json } from "./fixture/tui-client" +import { tmpdir } from "./fixture/fixture" + +const session = { + id: "ses_shell_stopped", + title: "Stopped shell", + projectID: "proj_test", + location: { directory }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: 0, updated: 0 }, +} +const model = { providerID: "fixture", id: "fixture" } +const steps = Array.from({ length: 15 }, (_, index) => `step ${index + 1}`).join("\n") +const notice = "[full output saved to /tmp/sh_stopped.out]\n\nCommand interrupted by the user (shell ID: sh_stopped)." +const shell = (id: string, command: string, state: object) => ({ + type: "tool" as const, + id, + name: "shell", + time: { created: 1, completed: 2 }, + state: { input: { command }, ...state }, +}) +const messages = [ + { type: "user", id: "user-1", text: "Run them", time: { created: 0 } }, + { + type: "assistant", + id: "assistant-1", + agent: "build", + model, + finish: "stop", + time: { created: 1, completed: 3 }, + content: [ + shell("call-completed", "seq-completed", { + status: "completed", + content: [{ type: "text", text: steps }], + metadata: { exit: 0, truncated: false }, + }), + // How a call the user stopped settles: its output, then the notice its metadata names. + shell("call-stopped", "seq-stopped", { + status: "error", + error: { type: "tool.execution", message: `${steps}\n\n${notice}` }, + metadata: { interrupted: true, truncated: false, shellID: "sh_stopped", notice }, + }), + { type: "text", text: "Both ran" }, + ], + }, +] as SessionMessageInfo[] + +test("a call the user stopped shows its output once, clipped like a finished call's, then the notice once", async () => { + await using state = await tmpdir() + const setup = await createTestRenderer({ width: 100, height: 60, kittyKeyboard: true }) + await setup.renderer.setupTerminal() + setup.renderer.start() + const calls = createFetch((url) => { + if (url.pathname === "/api/session") return json({ data: [session], cursor: {} }) + if (url.pathname === `/api/session/${session.id}`) return json({ data: session }) + if (url.pathname === `/api/session/${session.id}/message`) return json({ data: messages.toReversed(), cursor: {} }) + if (url.pathname === `/api/session/${session.id}/inbox` || url.pathname === `/api/session/${session.id}/permission`) + return json({ data: [] }) + }, createEventStream()) + const server = Bun.serve({ port: 0, idleTimeout: 0, fetch: (request) => calls.fetch(request) }) + const { run } = await import("../src/app") + const task = Effect.runPromise( + run({ + app: { name: "test", version: "test", channel: "test" }, + server: { endpoint: { url: server.url.toString() } }, + config: { + get: async () => ({ animations: false, tabs: { enabled: false }, session: { verbosity: "high" } }), + update: async () => ({}), + }, + packages: { prepare: async () => ({ directory: "" }) }, + args: { sessionID: session.id }, + terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }), + log: () => {}, + }).pipe(Effect.provide(Global.layerWith({ state: state.path })), Effect.provide(FileSystem.layerNoop({}))), + ) + try { + await setup.waitForFrame((frame) => frame.includes("Both ran")) + await setup.waitForVisualIdle({ quietFrames: 3 }) + const frame = setup.captureCharFrame() + const card = (command: string, next: string) => frame.slice(frame.indexOf(command), frame.indexOf(next)) + const completed = card("$ seq-completed", "$ seq-stopped") + const stopped = card("$ seq-stopped", "Both ran") + const body = (text: string) => text.split("\n").slice(1).join("\n") + // The same clipped tail as the finished call. + const tail = (text: string) => + text + .split("\n") + .map((line) => line.trim().replace(/[│┃]/g, "").trim()) + .filter((line) => /^step \d+$|earlier lines/.test(line)) + expect(tail(stopped)).toEqual(tail(completed)) + expect(tail(stopped)[0]).toMatch(/earlier lines/) + // Each line of output once; the notice once. + expect(body(stopped).match(/step 15\b/g)).toHaveLength(1) + expect(stopped.match(/Command interrupted by the user/g)).toHaveLength(1) + expect(stopped.match(/full output saved to/g)).toHaveLength(1) + } finally { + setup.renderer.destroy() + await task + await server.stop() + } +}) From 6e4f169c91aeadad8196e396f12bd7de57c64c80 Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 10 Nov 2026 20:13:02 +0000 Subject: [PATCH 5/5] fix(session-ui): decode a stopped shell call's notice at the metadata boundary Lint: no runtime typeof in stoppedShell; spacing. --- packages/session-ui/src/tools/run-machine.test.ts | 1 + packages/session-ui/src/tools/run-machine.ts | 7 +++++-- packages/session-ui/src/tools/tool-renderer.tsx | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/session-ui/src/tools/run-machine.test.ts b/packages/session-ui/src/tools/run-machine.test.ts index e915586e040b..85eacaa9f750 100644 --- a/packages/session-ui/src/tools/run-machine.test.ts +++ b/packages/session-ui/src/tools/run-machine.test.ts @@ -181,6 +181,7 @@ describe("transitionSubagentRun", () => { describe("stoppedShell", () => { const notice = "[full output saved to /tmp/sh_1.out]\n\nCommand interrupted by the user (shell ID: sh_1)." + const stopped = { tool: "shell", status: "error", diff --git a/packages/session-ui/src/tools/run-machine.ts b/packages/session-ui/src/tools/run-machine.ts index 15aea20d21f8..03f8b68ba84e 100644 --- a/packages/session-ui/src/tools/run-machine.ts +++ b/packages/session-ui/src/tools/run-machine.ts @@ -123,12 +123,15 @@ function sameShellRun(a: ShellRunState, b: ShellRunState) { export function stoppedShell(tool: { readonly tool: string readonly status?: string - readonly metadata: { readonly interrupted?: unknown; readonly notice?: unknown } + readonly metadata: { readonly interrupted?: boolean; readonly notice?: string } readonly error?: string }) { if (tool.tool !== "shell" || tool.status !== "error" || tool.metadata.interrupted !== true) return undefined + const notice = tool.metadata.notice - if (typeof notice !== "string" || !notice || !tool.error?.endsWith(notice)) return undefined + + if (!notice || !tool.error?.endsWith(notice)) return undefined + return { output: tool.error.slice(0, -notice.length).replace(/\n+$/, ""), notice } } diff --git a/packages/session-ui/src/tools/tool-renderer.tsx b/packages/session-ui/src/tools/tool-renderer.tsx index 37edb2a350b3..a7b01dec0430 100644 --- a/packages/session-ui/src/tools/tool-renderer.tsx +++ b/packages/session-ui/src/tools/tool-renderer.tsx @@ -163,6 +163,8 @@ const toolMetadata = Schema.decodeUnknownSync( shellID: optional(Schema.String), status: optional(Schema.String), background: optional(Schema.Boolean), + interrupted: optional(Schema.Boolean), + notice: optional(Schema.String), count: optional(Schema.Finite), matches: optional(Schema.Finite), files: optional(Schema.Array(Schema.Unknown)), @@ -1365,7 +1367,7 @@ export function ToolDisplay( const errorSubtitle = createMemo(() => toolErrorSubtitle(props, i18n)) const error = createMemo(() => toolDisplayError(props)) - const stopped = createMemo(() => stoppedShell(props)) + const stopped = createMemo(() => stoppedShell({ ...props, metadata: toolMetadata(props.metadata) })) const render = createMemo(() => ToolRegistry.render(props.tool) ?? GenericTool) return (