Skip to content

Commit fcb658a

Browse files
author
mike.wang
committed
fix: restore terminal state on exit to prevent mouse escape sequence garbage
After the TUI exits, the terminal was left with mouse tracking enabled (\x1b[?1003l / \x1b[?1006l SGR mode), causing subsequent terminal input to print raw escape sequences like ^[<35;61;11M instead of being interpreted normally. Root cause: renderer.destroy() relies on native destroyRenderer() to send the mouse-disable sequences, but process.exit() in index.ts fires before those writes are flushed to stdout. Fixes: - exit.tsx: explicitly write mouse-disable + cursor-restore sequences to stdout before renderer.destroy(), and register a process 'exit' handler as a last-resort guarantee that fires synchronously on process exit. - prompt/index.tsx + session/index.tsx: add double-confirm for Ctrl+C exit (press twice within 3 s) matching the behaviour of claude code and similar TUI tools; inline hint replaces the toast for the first press. - win32.ts: tighten the ENABLE_PROCESSED_INPUT enforcement poll from 100 ms to 16 ms so the guard reacts faster after console-mode resets. Closes anomalyco#13276
1 parent ae614d9 commit fcb658a

4 files changed

Lines changed: 121 additions & 5 deletions

File tree

‎packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx‎

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ import { useKV } from "../../context/kv"
3737
import { useTextareaKeybindings } from "../textarea-keybindings"
3838
import { DialogSkill } from "../dialog-skill"
3939

40+
const EXIT_CONFIRM_MS = 3000
41+
4042
export type PromptProps = {
4143
sessionID?: string
4244
workspaceID?: string
@@ -95,8 +97,28 @@ export function Prompt(props: PromptProps) {
9597
const list = createMemo(() => props.placeholders?.normal ?? [])
9698
const shell = createMemo(() => props.placeholders?.shell ?? [])
9799
const [auto, setAuto] = createSignal<AutocompleteRef>()
100+
const [exitConfirmArmed, setExitConfirmArmed] = createSignal(false)
101+
const [exitPending, setExitPending] = createSignal(false)
98102
const currentProviderLabel = createMemo(() => local.model.parsed().provider)
99103
const hasRightContent = createMemo(() => Boolean(props.right))
104+
let exitConfirmTimeout: ReturnType<typeof setTimeout> | undefined
105+
106+
const clearExitConfirm = () => {
107+
setExitConfirmArmed(false)
108+
if (exitConfirmTimeout) {
109+
clearTimeout(exitConfirmTimeout)
110+
exitConfirmTimeout = undefined
111+
}
112+
}
113+
114+
const armExitConfirm = () => {
115+
setExitConfirmArmed(true)
116+
if (exitConfirmTimeout) clearTimeout(exitConfirmTimeout)
117+
exitConfirmTimeout = setTimeout(() => {
118+
setExitConfirmArmed(false)
119+
exitConfirmTimeout = undefined
120+
}, EXIT_CONFIRM_MS)
121+
}
100122

101123
function promptModelWarning() {
102124
toast.show({
@@ -429,6 +451,7 @@ export function Prompt(props: PromptProps) {
429451
}
430452

431453
onCleanup(() => {
454+
clearExitConfirm()
432455
props.ref?.(undefined)
433456
})
434457

@@ -919,6 +942,13 @@ export function Prompt(props: PromptProps) {
919942
e.preventDefault()
920943
return
921944
}
945+
if (exitPending()) {
946+
e.preventDefault()
947+
return
948+
}
949+
if (exitConfirmArmed() && !keybind.match("app_exit", e)) {
950+
clearExitConfirm()
951+
}
922952
// Check clipboard for images before terminal-handled paste runs.
923953
// This helps terminals that forward Ctrl+V to the app; Windows
924954
// Terminal 1.25+ usually handles Ctrl+V before this path.
@@ -936,6 +966,7 @@ export function Prompt(props: PromptProps) {
936966
// If no image, let the default paste behavior continue
937967
}
938968
if (keybind.match("input_clear", e) && store.prompt.input !== "") {
969+
clearExitConfirm()
939970
input.clear()
940971
input.extmarks.clear()
941972
setStore("prompt", {
@@ -947,9 +978,15 @@ export function Prompt(props: PromptProps) {
947978
}
948979
if (keybind.match("app_exit", e)) {
949980
if (store.prompt.input === "") {
950-
await exit()
951-
// Don't preventDefault - let textarea potentially handle the event
952981
e.preventDefault()
982+
if (exitConfirmArmed()) {
983+
clearExitConfirm()
984+
setExitPending(true)
985+
await exit()
986+
return
987+
}
988+
989+
armExitConfirm()
953990
return
954991
}
955992
}
@@ -1144,7 +1181,20 @@ export function Prompt(props: PromptProps) {
11441181
/>
11451182
</box>
11461183
<box width="100%" flexDirection="row" justifyContent="space-between">
1147-
<Show when={status().type !== "idle"} fallback={props.hint ?? <text />}>
1184+
<Show
1185+
when={status().type !== "idle"}
1186+
fallback={
1187+
<Show
1188+
when={exitConfirmArmed()}
1189+
fallback={props.hint ?? <text />}
1190+
children={
1191+
<text fg={theme.warning}>
1192+
{keybind.print("app_exit")} <span style={{ fg: theme.textMuted }}>again to exit</span>
1193+
</text>
1194+
}
1195+
/>
1196+
}
1197+
>
11481198
<box
11491199
flexDirection="row"
11501200
gap={1}

‎packages/opencode/src/cli/cmd/tui/context/exit.tsx‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,16 @@ export const { use: useExit, provider: ExitProvider } = createSimpleContext({
3636
await input.onBeforeExit?.()
3737
// Reset window title before destroying renderer
3838
renderer.setTerminalTitle("")
39+
// Disable mouse tracking synchronously before destroy.
40+
// renderer.destroy() may defer native cleanup when called during a
41+
// render frame, so we also register a process 'exit' handler as a
42+
// last-resort safeguard that runs right before the process terminates.
43+
const MOUSE_RESET =
44+
"\x1b[?1003l" + // disable any-event mouse tracking
45+
"\x1b[?1006l" + // disable SGR mouse mode
46+
"\x1b[?1000l" + // disable normal mouse tracking
47+
"\x1b[?25h" // show cursor
48+
process.stdout.write(MOUSE_RESET)
3949
renderer.destroy()
4050
win32FlushInputBuffer()
4151
if (reason) {
@@ -55,6 +65,16 @@ export const { use: useExit, provider: ExitProvider } = createSimpleContext({
5565
},
5666
)
5767
process.on("SIGHUP", () => exit())
68+
// Last-resort: if process.exit() fires before renderer cleanup finishes,
69+
// 'exit' event still runs synchronously and can write terminal reset sequences.
70+
process.on("exit", () => {
71+
process.stdout.write(
72+
"\x1b[?1003l" + // disable any-event mouse tracking
73+
"\x1b[?1006l" + // disable SGR mouse mode
74+
"\x1b[?1000l" + // disable normal mouse tracking
75+
"\x1b[?25h", // show cursor
76+
)
77+
})
5878
return exit
5979
},
6080
})

‎packages/opencode/src/cli/cmd/tui/routes/session/index.tsx‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
For,
88
Match,
99
on,
10+
onCleanup,
1011
onMount,
1112
Show,
1213
Switch,
@@ -84,6 +85,8 @@ import { useTuiConfig } from "../../context/tui-config"
8485
import { getScrollAcceleration } from "../../util/scroll"
8586
import { TuiPluginRuntime } from "../../plugin"
8687

88+
const EXIT_CONFIRM_MS = 3000
89+
8790
addDefaultParsers(parsers.parsers)
8891

8992
const context = createContext<{
@@ -217,9 +220,32 @@ export function Session() {
217220
const keybind = useKeybind()
218221
const dialog = useDialog()
219222
const renderer = useRenderer()
223+
const [exitConfirmArmed, setExitConfirmArmed] = createSignal(false)
224+
const [exitPending, setExitPending] = createSignal(false)
225+
let exitConfirmTimeout: ReturnType<typeof setTimeout> | undefined
220226

221227
// Allow exit when in child session (prompt is hidden)
222228
const exit = useExit()
229+
const clearExitConfirm = () => {
230+
setExitConfirmArmed(false)
231+
if (exitConfirmTimeout) {
232+
clearTimeout(exitConfirmTimeout)
233+
exitConfirmTimeout = undefined
234+
}
235+
}
236+
237+
const armExitConfirm = () => {
238+
setExitConfirmArmed(true)
239+
if (exitConfirmTimeout) clearTimeout(exitConfirmTimeout)
240+
exitConfirmTimeout = setTimeout(() => {
241+
setExitConfirmArmed(false)
242+
exitConfirmTimeout = undefined
243+
}, EXIT_CONFIRM_MS)
244+
}
245+
246+
onCleanup(() => {
247+
clearExitConfirm()
248+
})
223249

224250
createEffect(() => {
225251
const title = Locale.truncate(session()?.title ?? "", 50)
@@ -242,8 +268,28 @@ export function Session() {
242268

243269
useKeyboard((evt) => {
244270
if (!session()?.parentID) return
271+
if (exitPending()) {
272+
evt.preventDefault()
273+
return
274+
}
275+
if (exitConfirmArmed() && !keybind.match("app_exit", evt)) {
276+
clearExitConfirm()
277+
}
245278
if (keybind.match("app_exit", evt)) {
246-
exit()
279+
evt.preventDefault()
280+
if (exitConfirmArmed()) {
281+
clearExitConfirm()
282+
setExitPending(true)
283+
exit()
284+
return
285+
}
286+
287+
armExitConfirm()
288+
toast.show({
289+
message: `Press ${keybind.print("app_exit")} again to exit`,
290+
variant: "info",
291+
duration: EXIT_CONFIRM_MS,
292+
})
247293
}
248294
})
249295

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ export function win32InstallCtrlCGuard() {
108108
// Ensure it's cleared immediately too (covers any earlier mode changes).
109109
later()
110110

111-
const interval = setInterval(enforce, 100)
111+
const interval = setInterval(enforce, 16)
112112
interval.unref()
113113

114114
let done = false

0 commit comments

Comments
 (0)