Skip to content

Commit aa145a3

Browse files
committed
fix(tui): make stderr capture concurrency-safe and restore idempotent
restore() ran its dup2/close sequence on every call; the fd numbers it closed can be reused by other descriptors between calls, so a second call could corrupt unrelated fds. acquireRelease fires it once, and a guard keeps a repeated call a no-op. tui-stderr.log is shared by every TUI on the host. Truncating per run overwrote a live or crashed run's capture; switch to O_APPEND with a single rotation past 10 MiB (the size-cap option from review) and surface the capture's starting size so the exit note reports what the current run wrote rather than any pre-existing bytes. Cover the capture path in tests: while captured, fd 2 maps to the capture file, a write to fd 2 lands in the log, restore() stops the mapping, and a repeated restore is a no-op. Add the variable to the V2 docs (services/www/src/docs/content/cli/ config.mdx, Terminal section) alongside the v1 docs row.
1 parent 6d9ce03 commit aa145a3

5 files changed

Lines changed: 68 additions & 18 deletions

File tree

‎packages/tui/src/app.tsx‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { Service, type Endpoint } from "@opencode/client/effect/service"
77
import { OpenCode, type SessionInfo } from "@opencode/client"
88
import { Global } from "@opencode/util/global"
99
import { noTimeoutFetch } from "@opencode/util/no-timeout-fetch"
10-
import { captureStderr } from "#stderr-capture"
10+
import { captureStderr, type StderrCapture } from "#stderr-capture"
1111
import { ClipboardProvider, useClipboard } from "./context/clipboard"
1212
import { LogProvider, type LogSink } from "./context/log"
1313
import { ExitProvider, useExit } from "./context/exit"
@@ -247,7 +247,7 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
247247
updatedVersion: undefined as string | undefined,
248248
reason: undefined as unknown,
249249
}
250-
let stderrCapturePath: string | undefined
250+
let stderrCapture: StderrCapture | undefined
251251
const result = yield* Effect.scoped(
252252
Effect.gen(function* () {
253253
// The renderer owns the terminal surface for this scope; any native or
@@ -258,7 +258,7 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
258258
Effect.sync(() => captureStderr(global.log)),
259259
(captured) => Effect.sync(() => captured?.restore()),
260260
)
261-
stderrCapturePath = captured?.path
261+
stderrCapture = captured
262262
if (!captured) {
263263
if (process.stderr.isTTY)
264264
log("debug", "failed to capture stderr for the TUI; native output may repaint the screen", {})
@@ -498,12 +498,12 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
498498
}),
499499
)
500500
yield* Effect.sync(() => {
501-
if (stderrCapturePath) {
502-
// The capture file only has bytes when the run actually produced native
503-
// output; tell the user where a crash or noisy child's output went.
501+
if (stderrCapture) {
502+
// The capture file may predate this run (append mode, shared file);
503+
// report only what the run actually wrote.
504504
try {
505-
if (statSync(stderrCapturePath).size > 0)
506-
process.stderr.write(`stderr output for this run was captured to ${stderrCapturePath}\n`)
505+
if (statSync(stderrCapture.path).size > stderrCapture.startSize)
506+
process.stderr.write(`stderr output for this run was captured to ${stderrCapture.path}\n`)
507507
} catch {}
508508
}
509509
if (result.reason !== undefined)

‎packages/tui/src/stderr-capture.bun.ts‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@
66
// audio probe), those lines paint directly over the rendered screen. Capturing
77
// stderr at the renderer scope keeps stray output in a log file instead.
88
import { dlopen } from "bun:ffi"
9-
import { closeSync, mkdirSync, openSync, readFileSync } from "node:fs"
9+
import { closeSync, fstatSync, mkdirSync, openSync, readFileSync, renameSync, statSync } from "node:fs"
1010
import { join } from "node:path"
1111

1212
export type StderrCapture = {
1313
readonly path: string
14+
readonly startSize: number
1415
restore(): void
1516
}
1617

@@ -22,6 +23,10 @@ const symbols = {
2223

2324
const staticCandidates = ["libc.so.6", "libc.so", "libc.dylib", "libSystem.B.dylib"]
2425

26+
// Every TUI shares one capture file, so bound it: once past this size the file
27+
// is rotated aside at the start of a run rather than truncated.
28+
const CAPTURE_MAX_BYTES = 10 * 1024 * 1024
29+
2530
function loadLibc(): ReturnType<typeof dlopen<typeof symbols>> | undefined {
2631
const candidates = new Set(staticCandidates)
2732
if (process.platform === "linux") {
@@ -50,10 +55,19 @@ export function captureStderr(dir: string): StderrCapture | undefined {
5055
try {
5156
mkdirSync(dir, { recursive: true })
5257
const path = join(dir, "tui-stderr.log")
53-
// Truncate per run instead of appending across sessions: a noisy native
54-
// library would otherwise grow the file without bound, and each run's
55-
// captured output stays readable in one piece.
56-
const fd = openSync(path, "w")
58+
// Append rather than truncate per run: several TUIs can be open at once and
59+
// share this file, and O_APPEND writes interleave instead of overwriting at
60+
// independent offsets. Rotation (below, past CAPTURE_MAX_BYTES) replaces
61+
// the never-trimmed growth, and starting a run no longer wipes the capture
62+
// of a crashed run — the moment the user is most likely to read it. A run
63+
// holding the old inode keeps appending into the rotated copy.
64+
try {
65+
if (statSync(path).size > CAPTURE_MAX_BYTES) renameSync(path, `${path}.1`)
66+
} catch {
67+
// Missing file, or another TUI already rotated it; append to whatever is there.
68+
}
69+
const fd = openSync(path, "a")
70+
const startSize = fstatSync(fd).size
5771
// Take a fresh reference to fd 2 before dup2 clobbers it, to restore the
5872
// terminal stderr when the renderer scope ends.
5973
const saved = libc.symbols.dup(2)
@@ -66,9 +80,15 @@ export function captureStderr(dir: string): StderrCapture | undefined {
6680
closeSync(fd)
6781
return undefined
6882
}
83+
let restored = false
6984
return {
7085
path,
86+
startSize,
7187
restore() {
88+
// acquireRelease fires this once per renderer scope; guard anyway so a
89+
// repeated call cannot dup2 or close a reused fd number.
90+
if (restored) return
91+
restored = true
7292
libc.symbols.dup2(saved, 2)
7393
libc.symbols.close(saved)
7494
closeSync(fd)

‎packages/tui/src/stderr-capture.node.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// here, so stderr stays attached to the terminal under the node runtime.
33
export type StderrCapture = {
44
readonly path: string
5+
readonly startSize: number
56
restore(): void
67
}
78

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { expect, test } from "bun:test"
2+
import { fstatSync, mkdtempSync, readFileSync, statSync, writeSync } from "node:fs"
3+
import { tmpdir } from "node:os"
4+
import { join } from "node:path"
25
import { captureStderr } from "#stderr-capture"
36

4-
// Setup and restore an own-property isTTY on process.stderr; the runner's
5-
// stderr is a pipe (isTTY false or undefined), and the instance descriptor is
6-
// replaced for the duration of each test.
7+
// Replace the own-property isTTY on process.stderr for the duration of fn; the
8+
// runner's stderr is a pipe (isTTY false or undefined).
79
function withStderrTTY<T>(value: boolean, fn: () => T): T {
810
const descriptor = Object.getOwnPropertyDescriptor(process.stderr, "isTTY")
911
Object.defineProperty(process.stderr, "isTTY", { value, configurable: true })
@@ -15,17 +17,42 @@ function withStderrTTY<T>(value: boolean, fn: () => T): T {
1517
}
1618
}
1719

20+
const dir = () => mkdtempSync(join(tmpdir(), "opencode-tui-stderr-"))
21+
1822
test("capture is skipped when explicitly disabled via OPENCODE_TUI_STDERR", () => {
1923
const previous = process.env.OPENCODE_TUI_STDERR
2024
process.env.OPENCODE_TUI_STDERR = "inherit"
2125
try {
22-
expect(withStderrTTY(true, () => captureStderr("/tmp/opencode-tui-stderr-capture-test"))).toBeUndefined()
26+
expect(withStderrTTY(true, () => captureStderr(dir()))).toBeUndefined()
2327
} finally {
2428
if (previous === undefined) delete process.env.OPENCODE_TUI_STDERR
2529
else process.env.OPENCODE_TUI_STDERR = previous
2630
}
2731
})
2832

2933
test("capture is skipped when stderr is redirected away from the terminal", () => {
30-
expect(withStderrTTY(false, () => captureStderr("/tmp/opencode-tui-stderr-capture-test"))).toBeUndefined()
34+
expect(withStderrTTY(false, () => captureStderr(dir()))).toBeUndefined()
35+
})
36+
37+
// Exercises the real capture: fd 2 is repointed at the log file under the test.
38+
test.skipIf(process.platform === "win32")("fd 2 writes land in tui-stderr.log and restore reattaches stderr", () => {
39+
const captured = withStderrTTY(true, () => captureStderr(dir()))
40+
if (!captured) throw new Error("capture should be available on this platform")
41+
// While the capture holds fd 2, fd 2 maps to the capture file itself.
42+
expect(fstatSync(2).ino).toBe(statSync(captured.path).ino)
43+
try {
44+
writeSync(2, "captured-during\n")
45+
captured.restore()
46+
// restore() points fd 2 back at the runner's stderr, so the file is no
47+
// longer the fd 2 target and nothing written now reaches it.
48+
expect(fstatSync(2).ino).not.toBe(statSync(captured.path).ino)
49+
const text = readFileSync(captured.path, "utf8")
50+
expect(text).toContain("captured-during")
51+
// restore() must be safe to repeat without corrupting reused fds.
52+
captured.restore()
53+
expect(fstatSync(2).ino).not.toBe(statSync(captured.path).ino)
54+
expect(readFileSync(captured.path, "utf8")).not.toContain("restored-after")
55+
} finally {
56+
captured.restore()
57+
}
3158
})

‎services/www/src/docs/content/cli/config.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,8 @@ Configure terminal integration:
275275

276276
</div>
277277

278+
While a session runs, output a native library or child process sends to the terminal's stderr is captured to `log/tui-stderr.log` in the data directory instead of painting over the interface. When the session ends and something was captured, the file's path is printed on the terminal. Set `OPENCODE_TUI_STDERR=inherit` to keep process stderr on the terminal.
279+
278280
## Mini
279281

280282
The `mini` group controls [`opencode mini`](/cli#mini), the minimal interactive interface:

0 commit comments

Comments
 (0)