Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/opencode/bin/silvercode
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ function run(target) {
const forwarders = {}
for (const signal of forwardedSignals) {
forwarders[signal] = () => {
// Windows has no POSIX signals: Ctrl+C is a console event that the
// console already delivered to every attached process, the child
// included, so there is nothing to forward. child.kill("SIGINT") cannot
// deliver a signal there - it maps to TerminateProcess and kills the
// child before its handlers can clean up (an external editor left
// running mid-session, #441). The listener still keeps the launcher
// alive, so the child decides what Ctrl+C means.
if (signal === "SIGINT" && process.platform === "win32") return
try {
child.kill(signal)
} catch {
Expand Down
77 changes: 45 additions & 32 deletions packages/opencode/src/cli/cmd/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { Filesystem } from "@/util/filesystem"
import { createOpencodeClient, type OpencodeClient, type ToolPart } from "@opencode-ai/sdk/v2"
import { FormatError, FormatUnknownError } from "../error"
import { INTERACTIVE_INPUT_ERROR, resolveInteractiveStdin } from "./run/runtime.stdin"
import { win32InstallCtrlCGuard } from "@opencode-ai/tui/terminal-win32"

type ModelInput = Parameters<OpencodeClient["session"]["prompt"]>[0]["model"]

Expand Down Expand Up @@ -1032,36 +1033,48 @@ type MiniCommandInput = {

export async function runMini(input: MiniCommandInput) {
if (!RunCommand.handler) throw new Error("Mini command handler is unavailable")
await RunCommand.handler({
$0: "silvercode",
_: ["mini"],
message: input.prompt ? [input.prompt] : [],
command: undefined,
continue: input.continue,
session: input.session,
fork: input.fork,
share: undefined,
model: input.model,
agent: input.agent,
format: "default",
file: undefined,
title: undefined,
attach: input.attach,
password: input.password,
username: input.username,
dir: input.directory,
port: undefined,
variant: undefined,
thinking: undefined,
mini: true,
interactive: false,
replay: input.replay ?? true,
"replay-limit": input.replayLimit,
replayLimit: input.replayLimit,
auto: false,
yolo: false,
"dangerously-skip-permissions": false,
dangerouslySkipPermissions: false,
demo: input.demo ?? false,
})
// Mini owns the console exactly like the full TUI: the split-footer renderer
// toggles raw mode, including across external-editor suspends. Keep the
// Windows Ctrl+C guard installed for the whole runtime so those toggles
// cannot turn Ctrl+C into a console event that kills the launcher's child
// abruptly (#441).
const unguard = win32InstallCtrlCGuard()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: The guard is installed in runMini() but RunCommand.handler is also reachable directly via silvercode run --mini (the handler is Effect.fn and runMini is only a thin wrapper). If a future caller invokes RunCommand.handler with mini: true without going through runMini, the guard will not be installed. Consider centralizing the guard installation so both entry points share it, or documenting that runMini is the only supported mini entry point.

try {
await RunCommand.handler({
$0: "silvercode",
_: ["mini"],
message: input.prompt ? [input.prompt] : [],
command: undefined,
continue: input.continue,
session: input.session,
fork: input.fork,
share: undefined,
model: input.model,
agent: input.agent,
format: "default",
file: undefined,
title: undefined,
attach: input.attach,
password: input.password,
username: input.username,
dir: input.directory,
port: undefined,
variant: undefined,
thinking: undefined,
mini: true,
interactive: false,
replay: input.replay ?? true,
"replay-limit": input.replayLimit,
replayLimit: input.replayLimit,
auto: false,
yolo: false,
"dangerously-skip-permissions": false,
dangerouslySkipPermissions: false,
demo: input.demo ?? false,
})
} finally {
try {
unguard?.()
} catch {}
}
}
45 changes: 45 additions & 0 deletions packages/opencode/test/cli/launcher-policy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Exercise the actual CJS launcher's signal branch without sending a host OS
// signal. This policy test runs on Windows too; it is not console-event proof.
import { expect, test } from "bun:test"
import { EventEmitter } from "node:events"
import path from "node:path"
import vm from "node:vm"

const filename = path.join(import.meta.dir, "../../bin/silvercode")
const source = await Bun.file(filename).text()

for (const platform of ["win32", "linux"]) {
test(`launcher ${platform} signal policy and exit cleanup`, () => {
const forwarded: string[] = []
const child = Object.assign(new EventEmitter(), { kill: (signal: string) => forwarded.push(signal) })
const exits: number[] = []
const proc = Object.assign(new EventEmitter(), {
platform,
arch: "x64",
argv: ["node", filename],
env: { OPENCODE_BIN_PATH: "fixture-binary" },
exit: (code: number) => exits.push(code),
})
vm.runInNewContext(source, {
__filename: filename,
process: proc,
console,
require: (name: string) => {
if (name === "child_process") return { spawn: () => child }
if (name === "fs") return { realpathSync: () => filename, existsSync: () => true }
if (name === "path") return path
if (name === "os") return { platform: () => platform, arch: () => "x64" }
throw new Error(`unexpected module ${name}`)
},
})
expect(proc.listenerCount("SIGINT")).toBe(1)
proc.emit("SIGINT")
expect(forwarded).toEqual(platform === "win32" ? [] : ["SIGINT"])
proc.emit("SIGTERM")
proc.emit("SIGHUP")
expect(forwarded.slice(-2)).toEqual(["SIGTERM", "SIGHUP"])
child.emit("exit", 7, null)
expect(exits).toEqual([7])
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) expect(proc.listenerCount(signal)).toBe(0)
})
}
87 changes: 87 additions & 0 deletions packages/opencode/test/cli/launcher.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// The npm launcher is a plain CJS bin that runs before any package code, so it
// is driven here as a real subprocess against a stub child. OPENCODE_BIN_PATH
// replaces the platform binary, and the launcher forwards its own arguments to
// it, so the stub script is passed as an argument to the launcher entry.
//
// Windows has no POSIX signals: Ctrl+C is a console event the console delivers
// to every attached process, and child.kill("SIGINT") maps to TerminateProcess.
// Forwarding it therefore kills SilverCode before its handlers can run (#441),
// so the win32 branch must keep listening (the launcher has to survive the
// event) without forwarding to the child. A real Ctrl+C console event cannot be
// raised from a test process, so the Windows case runs through a fixture that
// pins process.platform and asserts the launcher's policy: the child must not
// observe a forwarded SIGINT.
import { expect, test } from "bun:test"
import path from "node:path"

const launcher = path.join(import.meta.dir, "../../bin/silvercode")
const win32Launcher = path.join(import.meta.dir, "../fixture/win32-launcher.cjs")
const child = path.join(import.meta.dir, "../fixture/launcher-child.js")

type Result = {
stdout: string
stderr: string
exitCode: number | null
signalCode: string | null
}

async function launch(entry: string): Promise<Result> {
const proc = Bun.spawn({
cmd: [process.execPath, entry, child],
env: { ...process.env, OPENCODE_BIN_PATH: process.execPath },
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
})

const decoder = new TextDecoder()
let stdout = ""
let signalled = false
const pump = (async () => {
const reader = proc.stdout.getReader()
for (;;) {
const chunk = await reader.read()
if (chunk.done) return
stdout += decoder.decode(chunk.value)
// Signal once the child exists so a slow launcher start cannot turn this
// into "no child to signal yet".
if (!signalled && stdout.includes("child:ready")) {
signalled = true
proc.kill("SIGINT")
}
}
})()

const exitCode = await proc.exited
await pump
const stderr = await new Response(proc.stderr).text()
return { stdout, stderr, exitCode, signalCode: proc.signalCode }
}

// process.kill(pid, "SIGINT") terminates the target on Windows instead of
// delivering a signal, so the launcher's signal handling cannot be driven from
// a test process there. Both cases run on POSIX hosts; the Windows policy is
// covered by the platform-pinned fixture instead.
const noSignalDelivery = process.platform === "win32"

test.skipIf(noSignalDelivery)("forwards SIGINT to the child on POSIX hosts", async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Both launcher tests are skipIf(noSignalDelivery) where noSignalDelivery = process.platform === "win32". On Windows CI both tests are skipped, so the Windows signal policy — the core of this PR — is never exercised by the running suite. The platform-pinned win32-launcher.cjs fixture only runs on POSIX hosts (it pins process.platform on the child side but is itself launched and signalled from a POSIX host). A regression in the win32 branch would not be caught on the platform where the branch matters. Consider a unit test that calls the launcher's run() directly with process.platform pinned to win32 and asserts forwarders.SIGINT is a no-op, independent of signal delivery.

const result = await launch(launcher)

expect(result.stderr).toBe("")
expect(result.stdout).toContain("child:sigint")
expect(result.stdout).toContain("child:done")
expect(result.exitCode).toBe(7)
})

test.skipIf(noSignalDelivery)("does not force-kill the child on win32 (#441)", async () => {
const result = await launch(win32Launcher)

expect(result.stderr).toBe("")
// The console, not the launcher, delivers Ctrl+C to the child on Windows.
expect(result.stdout).not.toContain("child:sigint")
expect(result.stdout).toContain("child:done")
// The launcher itself still has to survive the console event so the child
// can finish its cleanup.
expect(result.signalCode).toBeNull()
expect(result.exitCode).toBe(7)
})
9 changes: 9 additions & 0 deletions packages/opencode/test/fixture/launcher-child.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Stub child for the npm launcher tests. It stays alive long enough to receive
// a forwarded signal, records any SIGINT it sees, then exits with a sentinel
// code so the launcher's exit propagation is observable.
process.on("SIGINT", () => process.stdout.write("child:sigint\n"))
process.stdout.write("child:ready\n")
setTimeout(() => {
process.stdout.write("child:done\n")
process.exit(7)
}, 750)
6 changes: 6 additions & 0 deletions packages/opencode/test/fixture/win32-launcher.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Test-only entry for the npm launcher: process.platform is pinned to win32
// before the launcher loads so its Windows signal policy runs on every host.
// The launcher passes process.argv.slice(2) to the child, so the child script
// follows this file on the command line unchanged.
Object.defineProperty(process, "platform", { value: "win32" })
require("../../bin/silvercode")
8 changes: 8 additions & 0 deletions packages/tui/src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import path from "node:path"
import { spawn } from "node:child_process"
import type { Stream } from "node:stream"
import { resolveZedDbPath, resolveZedSelection } from "./editor-zed"
import { win32DisableProcessedInput } from "./terminal-win32"

type EditorStdio = "inherit" | "pipe" | "ignore" | number | Stream

Expand All @@ -31,6 +32,13 @@ export async function openEditor(input: { value: string; renderer: CliRenderer;
await input.renderer.suspend()
input.renderer.currentRenderBuffer.clear()
try {
// suspend() restores the console mode it found, which re-enables processed
// input. On Windows that turns Ctrl+C into a console event for every process
// attached to the console (the editor, this process, and any npm launcher)
// instead of input the editor can handle. The Ctrl+C guard re-asserts this
// after raw-mode toggles, but it only wraps the stream it was installed on,
// so re-assert at the handoff as well (#441).
win32DisableProcessedInput()
await new Promise<void>((resolve, reject) => {
const parts = editor.split(" ")
const child = spawn(parts[0]!, [...parts.slice(1), file], {
Expand Down
Loading