fix(core): keep a shell command's output when the user interrupts its call (#62977)

This commit is contained in:
James Long
2026-11-10 14:28:23 -06:00
committed by GitHub
Unverified
parent 95aa28e5c8
commit 05d347d750
24 changed files with 980 additions and 124 deletions
+2
View File
@@ -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 })),
)
+11 -1
View File
@@ -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,
+13 -1
View File
@@ -20,6 +20,8 @@ export interface Coordinator<Key, E, Reason = never> {
* interrupted.
*/
readonly interrupt: (key: Key, reason?: Reason) => Effect.Effect<boolean>
/** 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<void>
}
@@ -170,5 +172,15 @@ export const make = <Key, E, Reason = never>(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,
}
})
@@ -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<DrainResult, RunError>
}
+7 -2
View File
@@ -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,
+66 -13
View File
@@ -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<Outcome>()
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,21 @@ export const make = Effect.gen(function* () {
const toolRuns: Array<{
readonly call: ToolCall
readonly fiber: Fiber.Fiber<void, Permission.DeclinedError | QuestionTool.CancelledError>
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(() => {
// 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))),
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 +122,7 @@ export const make = Effect.gen(function* () {
messageID: input.assistantMessageID,
call,
progress: (update) => publisher.progress(call.id, update),
cancel: cancel.effect,
})
}
@@ -126,10 +141,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,10 +175,13 @@ export const make = Effect.gen(function* () {
)
return yield* Effect.failCause(stream.cause)
if (publisher.hasStarted()) yield* publisher.streamed()
if (streamInterrupted) yield* interruptTools
const joined = yield* restore(Fiber.awaitAll(toolRuns.map((run) => run.fiber))).pipe(Effect.exit)
if (Exit.isFailure(joined)) yield* interruptTools
const tools = classifyToolExits(joined, toolRuns)
if (streamInterrupted) yield* stopTools
const fibers = toolRuns.map((run) => run.fiber)
const joined = yield* restore(Fiber.awaitAll(fibers)).pipe(Effect.exit)
if (!streamInterrupted && Exit.isFailure(joined)) yield* stopTools
// 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 &&
@@ -311,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<Array<Exit.Exit<void, Permission.DeclinedError | QuestionTool.CancelledError>>>,
exits: ReadonlyArray<Exit.Exit<void, Permission.DeclinedError | QuestionTool.CancelledError>>,
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) =>
@@ -322,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 []
@@ -332,5 +351,39 @@ const classifyToolExits = (
return reasons.length > 0 ? [Cause.fromReasons<never>(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.
const COOPERATIVE_STOP = "5 seconds"
type Cancel = ReturnType<typeof 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.
*/
const makeCancel = () => {
let listeners = 0
let cancelled = false
const gate = Deferred.makeUnsafe<void>()
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
},
}
}
+48 -19
View File
@@ -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<Info, NotFoundError>
timeoutFiber?: Fiber.Fiber<void>
timeout?: (duration: number) => Effect.Effect<void>
stop?: (reason: StopReason) => Effect.Effect<void>
}
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<Shell.Info, NotFoundError>
// A known shell's terminal state and bounded tail. Missing capture remains distinct from its exit status.
readonly result: (started: Shell.Info) => Effect.Effect<ShellResult.Result>
// 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<ShellResult.Result>
// 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<Shell.Info, NotFoundError>
// 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<Shell.Info, NotFoundError>
readonly output: (id: Shell.ID, input?: Shell.OutputInput) => Effect.Effect<Shell.Output, NotFoundError>
readonly remove: (id: Shell.ID) => Effect.Effect<void, NotFoundError>
}
@@ -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<Info>()) }),
)
).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<Ended, "completed">) =>
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 })
}),
)
+17
View File
@@ -28,6 +28,23 @@ export function output(result: Result): Output {
}
}
// 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 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, stopped]
: capture.output === "(no output)"
? ["", `[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<Output, "exit" | "signal" | "timeout">, 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)}`
+3
View File
@@ -75,6 +75,8 @@ export interface Snapshot {
readonly messageID: SessionMessage.ID
readonly call: ToolCall
readonly progress?: (update: Tool.Metadata) => Effect.Effect<void>
/** Completes when the user asks the call to stop; see `Tool.Context.cancel`. */
readonly cancel?: Effect.Effect<void>
/** Surviving request definitions, keyed by the names advertised after session context hooks. */
readonly definitions?: ReadonlyMap<string, ToolDefinition>
}) => Effect.Effect<NormalizedResult, Tool.Error>
@@ -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)
+146 -85
View File
@@ -4,8 +4,9 @@ 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 { 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"
@@ -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,27 @@ 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)
const stopped = ShellResult.interrupted(result)
return yield* new ToolFailure({
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,
},
})
})
yield* ctx.tool
.transform((editor) =>
editor.add({
@@ -203,99 +228,135 @@ 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 })
const settled = yield* Deferred.make<Output>()
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,
})
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,
// Uninterruptible from spawning to blocking, so an interrupt cannot orphan a started command.
return Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
// 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<void>()
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." }),
),
),
),
)
: 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"))
),
),
)
if (autoBackground) invocation.timeout = 0
}),
)
yield* context.progress({ shellID: info.id })
return yield* Deferred.await(settled)
}).pipe(
const settled = yield* Deferred.make<Output>()
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)
}
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 }))),
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)
}).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.
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}`)),
)
},
}),
+37
View File
@@ -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
@@ -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")
@@ -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<void>()
const seen: Array<string | undefined> = []
const coordinator: SessionRunCoordinator.Coordinator<string, never, "user"> = 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<void>()
@@ -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" })
+181 -1
View File
@@ -17,11 +17,13 @@ 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 { 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 { Effect, Exit, Layer } from "effect"
import { Cause, Deferred, Effect, Exit, Fiber, Layer } from "effect"
import { testEffect } from "./lib/effect"
const it = testEffect(
@@ -227,3 +229,181 @@ 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
// What the cooperative tool does once asked to stop; by default it fails with its partial output.
stopped?: Effect.Effect<never, Permission.DeclinedError>
}) =>
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 stopped: Effect.Effect<never, Permission.DeclinedError | Tool.Error> =
how.stopped ?? Effect.fail(new Tool.Error({ message: "partial output", metadata: { interrupted: true } }))
const listening = yield* Deferred.make<void>()
const stuck = yield* Deferred.make<void>()
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(stopped),
)
: 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 }
})
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" } },
},
],
})
}),
)
// 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 })
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 },
],
})
}),
)
+48
View File
@@ -0,0 +1,48 @@
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 } }),
).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 } })).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 } }),
).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.",
})
})
})
+171
View File
@@ -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,171 @@ 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<void>()
const started = yield* Deferred.make<string>()
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("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()
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,
notice: expect.stringContaining("Command interrupted by the user"),
},
])
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")
}),
)
}))
})
+1 -1
View File
@@ -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<Tool.Context, "progress"> {
export interface ToolContext extends Omit<Tool.Context, "progress" | "cancel"> {
readonly signal: AbortSignal
readonly progress: (update: Tool.Metadata) => Promise<void>
}
+5
View File
@@ -17,6 +17,11 @@ export interface Context {
readonly messageID: SessionMessage.ID
readonly id: CallID
readonly progress: (update: Metadata) => Effect.Effect<void>
/**
* 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<void>
}
export interface Namespace {
@@ -3,6 +3,7 @@ import {
createShellRunState,
INITIAL_SUBAGENT_RUN_STATE,
shellRunProps,
stoppedShell,
subagentRunProps,
transitionShellRun,
transitionSubagentRun,
@@ -177,3 +178,25 @@ 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()
})
})
@@ -116,6 +116,25 @@ 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?: 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 (!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
@@ -78,6 +78,7 @@ import {
viewShellRun,
viewSubagentRun,
INITIAL_SUBAGENT_RUN_STATE,
stoppedShell,
type ShellRunEvent,
type SubagentRunState,
} from "./run-machine"
@@ -162,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)),
@@ -1364,12 +1367,21 @@ export function ToolDisplay(
const errorSubtitle = createMemo(() => toolErrorSubtitle(props, i18n))
const error = createMemo(() => toolDisplayError(props))
const stopped = createMemo(() => stoppedShell({ ...props, metadata: toolMetadata(props.metadata) }))
const render = createMemo(() => ToolRegistry.render(props.tool) ?? GenericTool)
return (
<Show when={!hideQuestion()}>
<div data-component="tool-part-wrapper" data-timeline-part-id={props.id}>
<Switch>
<Match when={stopped()}>
{(stopped) => (
<>
<Dynamic component={render()} {...props} output={stopped().output} />
<ToolErrorCard tool={props.tool} error={stopped().notice} subtitle={errorSubtitle()} />
</>
)}
</Match>
<Match when={error()}>
{(error) => {
const cleaned = error().replace("Error: ", "")
+13 -1
View File
@@ -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 (
<ShellDisplay
part={props.part}
@@ -2993,11 +2994,22 @@ function Shell(props: ToolProps) {
workdir={stringValue(props.input.workdir)}
status={props.part.state.status}
background={props.part.state.status === "completed" && props.metadata.status === "running"}
output={stringValue(props.metadata.shellID) ? undefined : props.output}
output={stopped()?.output ?? (stringValue(props.metadata.shellID) ? undefined : props.output)}
error={stopped()?.notice}
/>
)
}
// 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<string, unknown>) {
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
@@ -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()
}
})