Skip to content

Commit 0933648

Browse files
committed
fix(tui): resolve VSCode terminal hang on quit (anomalyco#193)
Force-kill PTY process groups in the pty adapters on instance dispose, and restore terminal modes plus flush stdout before the process exits. Prevents orphaned PTY children and truncated ANSI restore sequences from hanging the VSCode integrated terminal after long TUI runs.
1 parent 4c715ae commit 0933648

8 files changed

Lines changed: 219 additions & 3 deletions

File tree

‎packages/opencode/src/cli/cmd/tui/app.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ import { DialogAlert } from "./ui/dialog-alert"
5555
import { DialogConfirm } from "./ui/dialog-confirm"
5656
import { ToastProvider, useToast } from "./ui/toast"
5757
import { createExit, ExitProvider, useExit, type Exit } from "./context/exit"
58+
import { restoreTerminal } from "./exit-flush"
5859
import { Session as SessionApi } from "@/session/session"
5960
import { TuiEvent } from "./event"
6061
import { KVProvider, useKV } from "./context/kv"
@@ -325,6 +326,9 @@ function createTuiLifecycle(input: {
325326
const exit = createExit(async (reason, message) => {
326327
exiting = true
327328
await cleanup()
329+
// Restore terminal modes before destroying the renderer so the terminal is
330+
// left in a usable state even if renderer.destroy() itself hangs.
331+
restoreTerminal(process.stdout)
328332
if (!input.renderer.isDestroyed) {
329333
input.renderer.setTerminalTitle("")
330334
input.renderer.destroy()
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Pure helpers for the TUI exit path. Streams are injected so the logic is
2+
// unit-testable without touching the real stdout.
3+
4+
type RestoreStream = {
5+
write(chunk: string): unknown
6+
}
7+
8+
type FlushStream = {
9+
write(chunk: string, cb?: () => void): boolean | undefined
10+
once?(ev: "drain", cb: () => void): void
11+
}
12+
13+
// Explicitly restore terminal modes before the renderer is destroyed: leave
14+
// alt-screen, disable SGR mouse reporting, and disable mouse-motion tracking.
15+
// Written before renderer.destroy() so the terminal is restored even if the
16+
// destroy itself hangs.
17+
export function restoreTerminal(stream: RestoreStream): void {
18+
stream.write("\x1b[?1003l") // disable mouse-motion tracking
19+
stream.write("\x1b[?1006l") // disable SGR mouse reporting
20+
stream.write("\x1b[?1049l") // leave alt-screen
21+
}
22+
23+
// Wait for the stdout buffer to drain before the process exits, so the ANSI
24+
// restore sequence written by renderer.destroy() is not truncated. The empty
25+
// write callback fires in order after prior writes flush; if the write returns
26+
// false (buffer full) we fall back to the drain event. A bounded timeout
27+
// guarantees the exit path never hangs forever if the terminal freezes and
28+
// neither the callback nor drain fires.
29+
export function flushStdout(stream: FlushStream, timeoutMs = 1000): Promise<void> {
30+
return new Promise((resolve) => {
31+
const ok = stream.write("", resolve)
32+
if (ok === false) stream.once?.("drain", resolve)
33+
const timer = setTimeout(resolve, timeoutMs)
34+
if (typeof timer.unref === "function") timer.unref()
35+
})
36+
}

‎packages/opencode/src/cli/cmd/tui/thread.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
sanitizedProcessEnv,
2222
} from "@opencode-ai/core/util/opencode-process"
2323
import { validateSession } from "./validate-session"
24+
import { flushStdout } from "./exit-flush"
2425
import { BINARY_NAME } from "../../../../../ellamaka/branding"
2526

2627
declare global {
@@ -259,6 +260,10 @@ export const TuiThreadCommand = cmd({
259260
} finally {
260261
unguard?.()
261262
}
263+
// Flush stdout so the ANSI restore sequence written by renderer.destroy()
264+
// is not truncated by the synchronous process.exit(0). EPIPE and other
265+
// errors must not block exit.
266+
await flushStdout(process.stdout).catch(() => {})
262267
process.exit(0)
263268
},
264269
})

‎packages/opencode/src/pty/index.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,10 +135,10 @@ export const makeLayer = (graceMs: number = DEFAULT_GRACE_MS) =>
135135
const bus = yield* Bus.Service
136136
const plugin = yield* Plugin.Service
137137

138-
function teardown(session: Active) {
138+
function teardown(session: Active, signal?: string) {
139139
cancelReaper(session)
140140
try {
141-
session.process.kill()
141+
session.process.kill(signal)
142142
} catch {}
143143
for (const [sub, ws] of session.subscribers.entries()) {
144144
try {
@@ -158,7 +158,7 @@ export const makeLayer = (graceMs: number = DEFAULT_GRACE_MS) =>
158158
yield* Effect.addFinalizer(() =>
159159
Effect.sync(() => {
160160
for (const session of state.sessions.values()) {
161-
teardown(session)
161+
teardown(session, "SIGKILL")
162162
}
163163
state.sessions.clear()
164164
}),

‎packages/opencode/src/pty/pty.bun.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,18 @@ export function spawn(file: string, args: string[], opts: Opts): Proc {
2020
pty.resize(cols, rows)
2121
},
2222
kill(signal) {
23+
// bun-pty's FFI kill only receives the handle; the signal argument is
24+
// used solely for the JS-side onExit payload, and native side always
25+
// sends SIGHUP to the single child pid. To force-kill the whole process
26+
// group (the child is spawned with setsid, so it is the session leader),
27+
// send the signal to the negative pid on unix. On win32 there is no
28+
// negative-pid kill, so keep the native kill as-is.
2329
pty.kill(signal)
30+
if (process.platform !== "win32" && signal) {
31+
try {
32+
process.kill(-this.pid, signal)
33+
} catch {}
34+
}
2435
},
2536
}
2637
}

‎packages/opencode/src/pty/pty.node.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,21 @@ export function spawn(file: string, args: string[], opts: Opts): Proc {
2020
proc.resize(cols, rows)
2121
},
2222
kill(signal) {
23+
// node-pty unix kill(signal) only signals the single child pid. The child
24+
// is spawned with setsid (session/process-group leader), so to force-kill
25+
// the whole group we send the signal to the negative pid on unix. On
26+
// win32 node-pty throws when a signal argument is passed, so fall back to
27+
// the no-arg kill() (TerminateProcess, equivalent to a hard kill).
28+
if (process.platform === "win32") {
29+
proc.kill()
30+
return
31+
}
2332
proc.kill(signal)
33+
if (signal) {
34+
try {
35+
process.kill(-proc.pid, signal)
36+
} catch {}
37+
}
2438
},
2539
}
2640
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import { describe, expect } from "bun:test"
2+
import { Bus } from "../../src/bus"
3+
import { Config } from "../../src/config/config"
4+
import { Plugin } from "../../src/plugin"
5+
import { Pty } from "../../src/pty"
6+
import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
7+
import { Effect, Layer } from "effect"
8+
import { testEffect, pollWithTimeout } from "../lib/effect"
9+
import { disposeAllInstances, provideTmpdirInstance } from "../fixture/fixture"
10+
import * as ptyNode from "../../src/pty/pty.node"
11+
12+
const it = testEffect(
13+
Pty.layer.pipe(
14+
Layer.provideMerge(Bus.layer),
15+
Layer.provideMerge(Config.defaultLayer),
16+
Layer.provideMerge(Plugin.defaultLayer),
17+
Layer.provideMerge(CrossSpawnSpawner.defaultLayer),
18+
),
19+
)
20+
21+
const ptyTest = process.platform === "win32" ? it.live.skip : it.live
22+
23+
// A child that ignores SIGHUP. `trap '' HUP` sets SIG_IGN, which persists across
24+
// exec, so the resulting `sleep` ignores SIGHUP. The default kill signal (SIGHUP
25+
// to a single pid) cannot kill it; only a process-group SIGKILL can. This makes
26+
// the test distinguish force-kill from the baseline signal semantics.
27+
const HUP_IMMUNE = ["-c", "trap '' HUP; exec sleep 300"]
28+
29+
// Wait until the given pid no longer exists (process.kill(pid, 0) throws ESRCH).
30+
const waitDead = (pid: number) =>
31+
pollWithTimeout(
32+
Effect.sync(() => {
33+
try {
34+
process.kill(pid, 0)
35+
return undefined
36+
} catch (err) {
37+
return (err as NodeJS.ErrnoException).code === "ESRCH" ? (true as const) : undefined
38+
}
39+
}),
40+
"child process still alive after dispose",
41+
)
42+
43+
describe("pty dispose kill", () => {
44+
ptyTest(
45+
"kills a HUP-immune child with SIGKILL when the instance is disposed (bun adapter)",
46+
() =>
47+
provideTmpdirInstance(() =>
48+
Effect.gen(function* () {
49+
const pty = yield* Pty.Service
50+
const info = yield* pty.create({ command: "sh", args: HUP_IMMUNE })
51+
52+
// Windows ConPTY assigns the pid asynchronously; on other platforms it
53+
// is already non-zero at create time. Poll until it is assigned.
54+
const pid = yield* pollWithTimeout(
55+
Effect.sync(() => (info.pid > 0 ? info.pid : undefined)),
56+
"pty pid never assigned",
57+
)
58+
59+
// Trigger the InstanceState finalizer (disposeAllInstances) which must
60+
// SIGKILL the running child process group.
61+
yield* Effect.promise(() => disposeAllInstances())
62+
63+
yield* waitDead(pid)
64+
}),
65+
),
66+
)
67+
68+
ptyTest(
69+
"kills a HUP-immune child with SIGKILL via the node adapter kill()",
70+
() =>
71+
Effect.gen(function* () {
72+
const proc = ptyNode.spawn("sh", HUP_IMMUNE, { name: "xterm-256color" })
73+
const pid = proc.pid
74+
expect(pid).toBeGreaterThan(0)
75+
76+
proc.kill("SIGKILL")
77+
78+
yield* waitDead(pid)
79+
}),
80+
)
81+
})
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { flushStdout, restoreTerminal } from "@/cli/cmd/tui/exit-flush"
3+
4+
type FakeStream = {
5+
writes: string[]
6+
writeReturn: boolean | undefined
7+
drainCb?: () => void
8+
write: (chunk: string, cb?: () => void) => boolean | undefined
9+
once: (ev: "drain", cb: () => void) => void
10+
}
11+
12+
function makeStream(writeReturn: boolean | undefined = true): FakeStream {
13+
const writes: string[] = []
14+
const stream: FakeStream = {
15+
writes,
16+
writeReturn,
17+
drainCb: undefined,
18+
write(chunk, cb) {
19+
writes.push(chunk)
20+
if (writeReturn !== false && cb) cb()
21+
return writeReturn
22+
},
23+
once(ev, cb) {
24+
if (ev === "drain") stream.drainCb = cb
25+
},
26+
}
27+
return stream
28+
}
29+
30+
describe("restoreTerminal", () => {
31+
test("writes the three ANSI restore sequences in order", () => {
32+
const stream = makeStream()
33+
restoreTerminal(stream)
34+
expect(stream.writes).toEqual(["\x1b[?1003l", "\x1b[?1006l", "\x1b[?1049l"])
35+
})
36+
})
37+
38+
describe("flushStdout", () => {
39+
test("resolves immediately when write returns true (no buffering)", async () => {
40+
const stream = makeStream(true)
41+
await flushStdout(stream)
42+
expect(stream.writes).toEqual([""])
43+
})
44+
45+
test("resolves on drain when write returns false (buffer full)", async () => {
46+
const stream = makeStream(false)
47+
let resolved = false
48+
const promise = flushStdout(stream).then(() => {
49+
resolved = true
50+
})
51+
// Not resolved yet because write returned false and drain has not fired.
52+
await Promise.resolve()
53+
expect(resolved).toBe(false)
54+
stream.drainCb?.()
55+
await promise
56+
expect(resolved).toBe(true)
57+
})
58+
59+
test("resolves after the timeout when neither callback nor drain fires", async () => {
60+
const stream = makeStream(false)
61+
const start = Date.now()
62+
await flushStdout(stream, 50)
63+
expect(Date.now() - start).toBeGreaterThanOrEqual(40)
64+
})
65+
})

0 commit comments

Comments
 (0)