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
3 changes: 2 additions & 1 deletion packages/opencode/src/cli/cmd/run/runtime.lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,10 +176,11 @@ function queueSplash(
// the entry splash, RunFooter takes over the footer region.
export async function createRuntimeLifecycle(input: LifecycleInput): Promise<Lifecycle> {
const source = resolveInteractiveStdin()
const unguard = win32InstallCtrlCGuard(source.stdin)
let unguard: (() => void) | undefined
let unregisterKeymap: (() => void) | undefined

try {
unguard = win32InstallCtrlCGuard(source.stdin)
const renderer = await createCliRenderer({
stdin: source.stdin,
targetFps: 30,
Expand Down
28 changes: 28 additions & 0 deletions packages/opencode/test/cli/run/runtime.guard-cleanup.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { expect, test } from "bun:test"
import vm from "node:vm"

// Drive the actual lifecycle entry through its early setup failure, without
// booting a native renderer. All later runtime dependencies remain unused.
const sourceFile = new URL("../../../src/cli/cmd/run/runtime.lifecycle.ts", import.meta.url)
const source = new Bun.Transpiler({ loader: "ts" })
.transformSync(await Bun.file(sourceFile).text())
.replace(/^import[\s\S]*?from ["'][^"']+["'];?\n/gm, "")
.replaceAll("export ", "")

test("closes resolved terminal input when guard installation throws", async () => {
let closed = 0
const failure = new Error("guard install failed")
const create = vm.runInNewContext(`(() => { ${source}; return createRuntimeLifecycle })()`, {
resolveInteractiveStdin: () => ({
stdin: { isTTY: true },
cleanup: () => {
closed++
},
}),
win32InstallCtrlCGuard: () => {
throw failure
},
})
await expect(create({})).rejects.toBe(failure)
expect(closed).toBe(1)
})
50 changes: 26 additions & 24 deletions packages/tui/src/terminal-win32.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,34 +120,36 @@ export function win32InstallCtrlCGuard(stdin: NodeJS.ReadStream = process.stdin)

let wrapped: NodeJS.ReadStream["setRawMode"] | undefined

if (typeof original === "function") {
wrapped = (mode: boolean) => {
const result = original.call(stdin, mode)
later()
return result
}

stdin.setRawMode = wrapped
}

// Ensure it's cleared immediately too (covers any earlier mode changes).
later()

const interval = setInterval(enforce, 100)
interval.unref()

unhook = () => {
let interval: ReturnType<typeof setInterval> | undefined
const cleanup = () => {
if (done) return
done = true

clearInterval(interval)
if (wrapped && stdin.setRawMode === wrapped) {
stdin.setRawMode = original
if (interval) clearInterval(interval)
try {
if (wrapped && stdin.setRawMode === wrapped) stdin.setRawMode = original
k32!.symbols.SetConsoleMode(handle, initial)
} finally {
source.close()
unhook = undefined
}
}

k32!.symbols.SetConsoleMode(handle, initial)
source.close()
unhook = undefined
try {
if (typeof original === "function") {
wrapped = (mode: boolean) => {
const result = original.call(stdin, mode)
later()
return result
}
stdin.setRawMode = wrapped
}
later()
interval = setInterval(enforce, 100)
interval.unref()
unhook = cleanup
} catch (error) {
cleanup()
throw error
}

return unhook
Expand Down
33 changes: 31 additions & 2 deletions packages/tui/test/terminal-win32.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,16 @@ const source = new Bun.Transpiler({ loader: "ts" }).transformSync(
.replaceAll("export function ", "function "),
)

function fixture(input: { platform?: string; tty?: boolean; open?: number; modeFails?: boolean } = {}) {
function fixture(
input: {
platform?: string
tty?: boolean
open?: number
modeFails?: boolean
intervalThrows?: boolean
rawThrows?: boolean
} = {},
) {
let mode = 7
const opened: unknown[][] = []
const closed: number[] = []
Expand All @@ -32,6 +41,13 @@ function fixture(input: { platform?: string; tty?: boolean; open?: number; modeF
},
}
const original = conin.setRawMode
if (input.rawThrows)
Object.defineProperty(conin, "setRawMode", {
get: () => original,
set: () => {
throw new Error("raw setter failed")
},
})
const api = vm.runInNewContext(
`(() => { ${source}; return { win32InstallCtrlCGuard, win32DisableProcessedInput } })()`,
{
Expand Down Expand Up @@ -64,6 +80,7 @@ function fixture(input: { platform?: string; tty?: boolean; open?: number; modeF
},
setImmediate: (fn: () => void) => immediates.push(fn),
setInterval: (fn: () => void) => {
if (input.intervalThrows) throw new Error("timer setup failed")
intervals.add(fn)
return { unref() {} }
},
Expand Down Expand Up @@ -137,7 +154,7 @@ test("normal tty stdin retains the borrowed standard handle", () => {
})

test("failed CONIN$ open does not install a guard or close an invalid handle", () => {
const f = fixture({ open: -1 })
const f = fixture({ open: 0xffffffffffffffff })
expect(f.api.win32InstallCtrlCGuard(f.conin)).toBeUndefined()
expect(f.reads).toEqual([])
expect(f.closed).toEqual([])
Expand All @@ -157,3 +174,15 @@ test("POSIX does not open console handles", () => {
f.api.win32DisableProcessedInput(f.conin)
expect(f.opened).toEqual([])
})

for (const failure of ["rawThrows", "intervalThrows"] as const) {
test(`closes the owned console handle when ${failure} interrupts guard setup`, () => {
const f = fixture({ [failure]: true })
expect(() => f.api.win32InstallCtrlCGuard(f.conin)).toThrow()
expect(f.closed).toEqual([22])
expect(f.conin.setRawMode).toBe(f.original)
const reads = f.reads.length
for (const immediate of f.immediates) immediate()
expect(f.reads.length).toBe(reads)
})
}
Loading