|
| 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" |
0 commit comments