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
8 changes: 8 additions & 0 deletions packages/opencode/src/cli/cmd/run/runtime.lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui"
import { Global } from "@opencode-ai/core/global"
import { openEditor } from "@opencode-ai/tui/editor"
import { registerOpencodeKeymap } from "@opencode-ai/tui/keymap"
import { watchTerminalResize } from "@opencode-ai/tui/util/resize-watch"
import { Session as SessionApi } from "@/session/session"
import * as Locale from "@/util/locale"
import { resolveInteractiveStdin } from "./runtime.stdin"
Expand Down Expand Up @@ -176,6 +177,7 @@ function queueSplash(
export async function createRuntimeLifecycle(input: LifecycleInput): Promise<Lifecycle> {
const source = resolveInteractiveStdin()
let unregisterKeymap: (() => void) | undefined
let stopResizeWatch: (() => void) | undefined

try {
const renderer = await createCliRenderer({
Expand All @@ -193,6 +195,10 @@ export async function createRuntimeLifecycle(input: LifecycleInput): Promise<Lif
consoleMode: "disabled",
clearOnShutdown: false,
})
// ConPTY-hosted window resizes never reach OpenTUI's SIGWINCH-derived
// RESIZE event on Bun (#439); poll the console size and synthesize it so
// onResize subscribers keep fresh geometry.
stopResizeWatch = watchTerminalResize(renderer)
const theme = await resolveRunTheme(renderer)
renderer.setBackgroundColor(theme.background)
const keymap = createDefaultOpenTuiKeymap(renderer)
Expand Down Expand Up @@ -342,6 +348,7 @@ export async function createRuntimeLifecycle(input: LifecycleInput): Promise<Lif
await footer.idle().catch(() => {})
footer.destroy()
unregisterKeymap?.()
stopResizeWatch?.()
shutdown(renderer)
if (!wroteExit) {
process.stdout.write("\n")
Expand Down Expand Up @@ -400,6 +407,7 @@ export async function createRuntimeLifecycle(input: LifecycleInput): Promise<Lif
}
} catch (error) {
unregisterKeymap?.()
stopResizeWatch?.()
source.cleanup?.()
throw error
}
Expand Down
1 change: 1 addition & 0 deletions packages/tui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"./util/locale": "./src/util/locale.ts",
"./util/persistence": "./src/util/persistence.ts",
"./util/record": "./src/util/record.ts",
"./util/resize-watch": "./src/util/resize-watch.ts",
"./logo": "./src/logo.ts",
"./ui/dialog": "./src/ui/dialog.tsx",
"./ui/spinner": "./src/ui/spinner.ts",
Expand Down
7 changes: 7 additions & 0 deletions packages/tui/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ import { createTuiAttention } from "./attention"
import * as TuiAudio from "./audio"
import { win32DisableProcessedInput, win32FlushInputBuffer } from "./terminal-win32"
import { destroyRenderer } from "./util/renderer"
import { watchTerminalResize } from "./util/resize-watch"
import { cliErrorMessage, errorFormat } from "./util/error"

registerOpencodeSpinner()
Expand Down Expand Up @@ -219,6 +220,12 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
(renderer) => Effect.promise(() => destroyRenderer(renderer)),
)
win32DisableProcessedInput()
// ConPTY-hosted window resizes never reach OpenTUI's SIGWINCH-derived
// RESIZE event on Bun (#439); poll the console size and synthesize it.
yield* Effect.acquireRelease(
Effect.sync(() => watchTerminalResize(renderer)),
(stop) => Effect.sync(stop),
)
const keymap = createDefaultOpenTuiKeymap(renderer)
yield* Effect.acquireRelease(
Effect.sync(() => registerOpencodeKeymap(keymap, renderer, input.config)),
Expand Down
56 changes: 56 additions & 0 deletions packages/tui/src/util/resize-watch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import type { CliRenderer } from "@opentui/core"

// Windows Terminal hosts the app inside ConPTY, where Bun does not deliver the
// resize SIGWINCH that OpenTUI 0.6.6 still derives its RESIZE event from, so
// both interfaces keep stale layout/scrollback/mouse geometry on window resize
// (#439). This poll closes the gap without the signal: re-query the live
// console size and feed the renderer's own resize path when the dimensions
// change. Bun caches process.stdout.columns/rows at startup and only refreshes
// them on SIGWINCH (oven-sh/bun#17803), so each poll starts with _refreshSize()
// - that is a live GetConsoleScreenBufferInfo query on win32 and works under
// ConPTY, unlike the signal.

type ResizeTarget = Pick<CliRenderer, "requestResize" | "terminalWidth" | "terminalHeight" | "isDestroyed">

type ResizeSource = {
/** Reads the current terminal size in columns/rows. Defaults to process stdout. */
getSize?: () => { columns: number; rows: number }
/** Busts the cached stdout size before getSize reads it. Defaults to the tty `_refreshSize` hook. */
refreshSize?: () => void
}

const refreshStdoutSize = () => {
// Undocumented tty hook (Node/Bun) that re-queries the live window size and
// updates the cached columns/rows.
;(process.stdout as typeof process.stdout & { _refreshSize?: () => void })._refreshSize?.()
}

const readStdoutSize = () => ({ columns: process.stdout.columns ?? 0, rows: process.stdout.rows ?? 0 })

/** One poll step: refresh the cached stdout size, then forward a change to the renderer's resize path. */
export function syncTerminalSize(target: ResizeTarget, options: ResizeSource = {}): void {
;(options.refreshSize ?? refreshStdoutSize)()
const { columns, rows } = (options.getSize ?? readStdoutSize)()
if (columns <= 0 || rows <= 0) return
if (target.isDestroyed) return
if (columns === target.terminalWidth && rows === target.terminalHeight) return
target.requestResize(columns, rows)
}

/**
* Low-frequency size-poll fallback for hosts that never deliver resize SIGWINCH.
* Polling only matters on win32 (ConPTY); elsewhere the signal is reliable and
* the returned disposer is a no-op. The timer is unref'd so it can never keep
* the process alive.
*/
export function watchTerminalResize(
target: ResizeTarget,
options: ResizeSource & { intervalMs?: number; platform?: typeof process.platform } = {},
): () => void {
if ((options.platform ?? process.platform) !== "win32") return () => {}
const step = () => syncTerminalSize(target, options)
const interval = setInterval(step, options.intervalMs ?? 500)
interval.unref?.()
step()
return () => clearInterval(interval)
}
93 changes: 93 additions & 0 deletions packages/tui/test/util/resize-watch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { expect, mock, test } from "bun:test"
import { syncTerminalSize, watchTerminalResize } from "../../src/util/resize-watch"

// #439: Bun under ConPTY never delivers the SIGWINCH OpenTUI derives RESIZE
// from, so win32 polls the console size and synthesizes the renderer's resize
// path. ConPTY delivery itself cannot be exercised on linux; these tests pin
// the poll/dedup logic and the platform gate.

function fakeTarget(width = 80, height = 24) {
const target = {
terminalWidth: width,
terminalHeight: height,
isDestroyed: false,
// Mirrors the renderer contract: terminalWidth/Height converge to the
// requested geometry once the resize is applied.
requestResize: mock((nextWidth: number, nextHeight: number) => {
target.terminalWidth = nextWidth
target.terminalHeight = nextHeight
}),
}
return { target, requestResize: target.requestResize }
}

test("forwards a polled size change to the renderer's resize path", () => {
const { target, requestResize } = fakeTarget()
syncTerminalSize(target, { refreshSize: () => {}, getSize: () => ({ columns: 120, rows: 40 }) })
expect(requestResize).toHaveBeenCalledTimes(1)
expect(requestResize).toHaveBeenCalledWith(120, 40)
})

test("does not re-request while the polled size is unchanged", () => {
const { target, requestResize } = fakeTarget(100, 30)
syncTerminalSize(target, { refreshSize: () => {}, getSize: () => ({ columns: 100, rows: 30 }) })
expect(requestResize).not.toHaveBeenCalled()
})

test("ignores missing or non-positive polled sizes", () => {
const { target, requestResize } = fakeTarget()
syncTerminalSize(target, { refreshSize: () => {}, getSize: () => ({ columns: 0, rows: 24 }) })
syncTerminalSize(target, { refreshSize: () => {}, getSize: () => ({ columns: 80, rows: 0 }) })
expect(requestResize).not.toHaveBeenCalled()
})

test("ignores a destroyed renderer", () => {
const { target, requestResize } = fakeTarget()
target.isDestroyed = true
syncTerminalSize(target, { refreshSize: () => {}, getSize: () => ({ columns: 120, rows: 40 }) })
expect(requestResize).not.toHaveBeenCalled()
})

test("refreshes the cached size before reading it", () => {
const { target } = fakeTarget()
const order: string[] = []
syncTerminalSize(target, {
refreshSize: () => order.push("refresh"),
getSize: () => {
order.push("get")
return { columns: 90, rows: 30 }
},
})
expect(order).toEqual(["refresh", "get"])
})

test("watchTerminalResize polls nothing outside win32", async () => {
const { target, requestResize } = fakeTarget()
const getSize = mock(() => ({ columns: 200, rows: 50 }))
const stop = watchTerminalResize(target, { platform: "linux", intervalMs: 5, refreshSize: () => {}, getSize })
try {
await Bun.sleep(30)
expect(getSize).not.toHaveBeenCalled()
expect(requestResize).not.toHaveBeenCalled()
} finally {
stop()
}
})

test("watchTerminalResize polls on win32, dedupes repeats, and stops when disposed", async () => {
const { target, requestResize } = fakeTarget()
const getSize = mock(() => ({ columns: 200, rows: 50 }))
const stop = watchTerminalResize(target, { platform: "win32", intervalMs: 5, refreshSize: () => {}, getSize })
try {
// The first poll runs immediately; repeated identical polls stay deduped
// against the renderer's current geometry.
await Bun.sleep(40)
expect(requestResize).toHaveBeenCalledTimes(1)
expect(requestResize).toHaveBeenCalledWith(200, 50)
} finally {
stop()
}
const after = getSize.mock.calls.length
await Bun.sleep(30)
expect(getSize.mock.calls.length).toBe(after)
})
Loading