Skip to content

Commit 235c26c

Browse files
committed
fix(tui): route console output to log file to protect TUI display
Library console output (Ajv compiling third-party MCP schemas, plugin dependencies, ...) wrote raw lines into the TUI's alternate screen and corrupted the display. In TUI mode the console methods are now redirected into the opencode log file in all TUI entrypoints and the server worker, respecting OPENCODE_LOG_LEVEL. anomalyco#31002
1 parent 5a83358 commit 235c26c

6 files changed

Lines changed: 118 additions & 0 deletions

File tree

‎packages/opencode/src/cli/cmd/attach.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { UI } from "@/cli/ui"
33
import { errorMessage } from "@opencode-ai/tui/util/error"
44
import { validateSession } from "../tui/validate-session"
55
import { ServerAuth } from "@/server/auth"
6+
import { installConsoleGuard } from "@/util/console-guard"
67

78
export const AttachCommand = cmd({
89
command: "attach <url>",
@@ -60,6 +61,8 @@ export const AttachCommand = cmd({
6061
describe: "cap visible mini replay to the newest N messages",
6162
}),
6263
handler: async (args) => {
64+
// The TUI renders on the alternate screen; console output must go to the log file.
65+
installConsoleGuard()
6366
if (args.replay === true) {
6467
UI.error("--replay is not supported; replay is enabled by default")
6568
process.exitCode = 1

‎packages/opencode/src/cli/cmd/run.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,9 @@ export const RunCommand = effectCmd({
261261
describe: "enable direct interactive demo slash commands; pass one as the message to run it immediately",
262262
}),
263263
handler: Effect.fn("Cli.run")(function* (args) {
264+
const { installConsoleGuard } = yield* Effect.promise(() => import("@/util/console-guard"))
265+
// The TUI renders on the alternate screen; console output must go to the log file.
266+
installConsoleGuard()
264267
const { Agent } = yield* Effect.promise(() => import("@/agent/agent"))
265268
const { RuntimeFlags } = yield* Effect.promise(() => import("@/effect/runtime-flags"))
266269
const { InstanceRef } = yield* Effect.promise(() => import("@/effect/instance-ref"))

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { writeHeapSnapshot } from "v8"
1414
import { ServerAuth } from "@/server/auth"
1515
import { validateSession } from "../tui/validate-session"
1616
import { win32InstallCtrlCGuard } from "@opencode-ai/tui/terminal-win32"
17+
import { installConsoleGuard } from "@/util/console-guard"
1718

1819
declare global {
1920
const OPENCODE_WORKER_PATH: string
@@ -142,6 +143,8 @@ export const TuiThreadCommand = cmd({
142143
hidden: true,
143144
}),
144145
handler: async (args) => {
146+
// The TUI renders on the alternate screen; console output must go to the log file.
147+
installConsoleGuard()
145148
if (args.replay === true) {
146149
UI.error("--replay is not supported; replay is enabled by default")
147150
process.exitCode = 1

‎packages/opencode/src/cli/tui/worker.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,13 @@ import { Heap } from "@/cli/heap"
1010
import { AppRuntime } from "@/effect/app-runtime"
1111
import { Effect } from "effect"
1212
import { disposeAllInstancesAndEmitGlobalDisposed } from "@/server/global-lifecycle"
13+
import { installConsoleGuard } from "@/util/console-guard"
1314

1415
Heap.start()
1516

17+
// The worker shares the TUI terminal; library console output must never reach it.
18+
installConsoleGuard()
19+
1620
const onUnhandledRejection = (_error: unknown) => {}
1721

1822
const onUncaughtException = (_error: Error) => {}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import path from "node:path"
2+
import { appendFile } from "node:fs/promises"
3+
import { inspect } from "node:util"
4+
import { Global } from "@opencode-ai/core/global"
5+
import { Logging } from "@opencode-ai/core/observability/logging"
6+
7+
// The TUI renders on the alternate screen while the server worker shares the
8+
// same terminal. Any library that calls console.* (Ajv compiling third-party
9+
// MCP schemas, plugin dependencies, ...) would write raw lines straight into
10+
// the TUI and corrupt it. In TUI mode the console methods are redirected into
11+
// the opencode log file instead of the terminal, so no output can ever break
12+
// the display. Non-TUI entrypoints (serve, mcp list, ...) never install this.
13+
// https://github.com/anomalyco/opencode/issues/31002
14+
15+
const LEVELS = { Debug: 0, Info: 1, Warn: 2, Error: 3 } as const
16+
17+
function installConsole() {
18+
const format = (...args: unknown[]) => {
19+
try {
20+
return args.map((arg) => (typeof arg === "string" ? arg : inspect(arg, { depth: 3 }))).join(" ")
21+
} catch {
22+
return "<unformattable console output>"
23+
}
24+
}
25+
26+
const write = (level: keyof typeof LEVELS, args: unknown[]) => {
27+
if (LEVELS[level] < LEVELS[Logging.minimumLogLevel()]) return
28+
const line = `timestamp=${new Date().toISOString()} level=${level.toLowerCase()} service=console message=${JSON.stringify(format(...args))}\n`
29+
void appendFile(path.join(Global.Path.log, "opencode.log"), line).catch(() => {})
30+
}
31+
32+
console.debug = (...args: unknown[]) => write("Debug", args)
33+
console.info = (...args: unknown[]) => write("Info", args)
34+
console.log = (...args: unknown[]) => write("Info", args)
35+
console.warn = (...args: unknown[]) => write("Warn", args)
36+
console.error = (...args: unknown[]) => write("Error", args)
37+
}
38+
39+
/** Redirect all console output to the log file. For TUI mode only. */
40+
export function installConsoleGuard() {
41+
installConsole()
42+
}
43+
44+
export * as ConsoleGuard from "./console-guard"
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { describe, expect, test } from "bun:test"
2+
import path from "node:path"
3+
import { Global } from "@opencode-ai/core/global"
4+
import { ConsoleGuard } from "../../src/util/console-guard"
5+
6+
function logFile() {
7+
return path.join(Global.Path.log, "opencode.log")
8+
}
9+
10+
async function readLog() {
11+
const file = Bun.file(logFile())
12+
return (await file.exists()) ? await file.text() : ""
13+
}
14+
15+
const original = {
16+
debug: console.debug,
17+
info: console.info,
18+
log: console.log,
19+
warn: console.warn,
20+
error: console.error,
21+
}
22+
23+
describe("ConsoleGuard.installConsoleGuard", () => {
24+
test("routes console output to the log file instead of the terminal", async () => {
25+
try {
26+
ConsoleGuard.installConsoleGuard()
27+
console.warn("unknown format ignored in schema at path", { format: "uint64" })
28+
await new Promise((resolve) => setTimeout(resolve, 100))
29+
const log = await readLog()
30+
expect(log).toContain('service=console message="unknown format ignored in schema at path')
31+
expect(log).toContain("level=warn")
32+
} finally {
33+
restoreConsole()
34+
}
35+
})
36+
37+
test("suppresses entries below the configured minimum level", async () => {
38+
const previous = process.env.OPENCODE_LOG_LEVEL
39+
process.env.OPENCODE_LOG_LEVEL = "ERROR"
40+
try {
41+
ConsoleGuard.installConsoleGuard()
42+
console.warn("guard should suppress this warn")
43+
console.error("guard should keep this error")
44+
await new Promise((resolve) => setTimeout(resolve, 100))
45+
const log = await readLog()
46+
expect(log).toContain("guard should keep this error")
47+
expect(log).not.toContain("guard should suppress this warn")
48+
} finally {
49+
restoreConsole()
50+
process.env.OPENCODE_LOG_LEVEL = previous
51+
}
52+
})
53+
})
54+
55+
function restoreConsole() {
56+
console.debug = original.debug
57+
console.info = original.info
58+
console.log = original.log
59+
console.warn = original.warn
60+
console.error = original.error
61+
}

0 commit comments

Comments
 (0)