Skip to content

Commit 4bd8ccc

Browse files
Jerwandclaude
andcommitted
fix(core): prevent mouse escape sequences from leaking into keyboard input
The stdin input pipeline used an all-or-nothing approach: either an entire chunk was treated as mouse data, or entirely as keyboard input. When mouse sequences were split across stdin chunks (which happens regularly under high mouse activity), partial sequences were silently dropped and their remaining bytes leaked into the keyboard handler as text input. This caused raw SGR mouse tracking data (e.g. ";25;5M") to appear as typed text in input fields, making the application unusable. Changes: - Add parseAllMouseEventsWithOffset() to MouseParser that returns consumed byte count and partial-sequence detection - Add isPartialMouseSequence() to recognize truncated SGR/Basic mouse sequences at chunk boundaries - Add _mousePartialBuffer to CliRenderer that preserves partial mouse sequences between stdin chunks - Rewrite stdinListener to properly route unconsumed non-mouse data to StdinBuffer instead of dropping it - Update split-height test: mouse events above render area are now correctly ignored instead of leaking to input handlers Fixes anomalyco/opencode#8614, related to #7316, #11636 Co-Authored-By: Claude Opus 4.6 <[email protected]>
1 parent 44cb164 commit 4bd8ccc

4 files changed

Lines changed: 223 additions & 15 deletions

File tree

‎packages/core/src/lib/parse.mouse.test.ts‎

Lines changed: 109 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, test, expect, beforeEach } from "bun:test"
2-
import { MouseParser, type RawMouseEvent } from "./parse.mouse"
2+
import { MouseParser, type RawMouseEvent, type MouseParseResult } from "./parse.mouse"
33

44
// Encode a basic/X10 mouse event: ESC [ M Cb Cx Cy
55
// buttonByte is the logical value (before the +32 wire offset), x/y are 0-based.
@@ -519,6 +519,114 @@ describe("MouseParser parseAllMouseEvents (multi-event chunks)", () => {
519519
})
520520
})
521521

522+
describe("MouseParser parseAllMouseEventsWithOffset (split sequences & mixed data)", () => {
523+
let parser: MouseParser
524+
525+
beforeEach(() => {
526+
parser = new MouseParser()
527+
})
528+
529+
test("pure mouse data: consumed equals total length, partial is false", () => {
530+
const buf = Buffer.concat([encodeSGR(0, 10, 5, true), encodeSGR(0, 10, 5, false)])
531+
const result = parser.parseAllMouseEventsWithOffset(buf)
532+
expect(result.events).toHaveLength(2)
533+
expect(result.consumed).toBe(buf.length)
534+
expect(result.partial).toBe(false)
535+
})
536+
537+
test("mouse followed by non-mouse data: consumed < length, partial is false", () => {
538+
const mouseData = encodeSGR(0, 10, 5, true)
539+
const keyData = Buffer.from("hello")
540+
const buf = Buffer.concat([mouseData, keyData])
541+
const result = parser.parseAllMouseEventsWithOffset(buf)
542+
expect(result.events).toHaveLength(1)
543+
expect(result.consumed).toBe(mouseData.length)
544+
expect(result.partial).toBe(false)
545+
})
546+
547+
test("mouse followed by partial mouse sequence: partial is true", () => {
548+
const completeEvent = encodeSGR(0, 10, 5, true)
549+
const partialEvent = Buffer.from("\x1b[<35;20")
550+
const buf = Buffer.concat([completeEvent, partialEvent])
551+
const result = parser.parseAllMouseEventsWithOffset(buf)
552+
expect(result.events).toHaveLength(1)
553+
expect(result.consumed).toBe(completeEvent.length)
554+
expect(result.partial).toBe(true)
555+
})
556+
557+
test("only partial SGR mouse sequence: 0 events, partial is true", () => {
558+
const buf = Buffer.from("\x1b[<35;20;5")
559+
const result = parser.parseAllMouseEventsWithOffset(buf)
560+
expect(result.events).toHaveLength(0)
561+
expect(result.consumed).toBe(0)
562+
expect(result.partial).toBe(true)
563+
})
564+
565+
test("bare ESC-[ < without digits is partial", () => {
566+
const buf = Buffer.from("\x1b[<")
567+
const result = parser.parseAllMouseEventsWithOffset(buf)
568+
expect(result.events).toHaveLength(0)
569+
expect(result.consumed).toBe(0)
570+
expect(result.partial).toBe(true)
571+
})
572+
573+
test("partial basic mouse: ESC[M + 1 byte (needs 3)", () => {
574+
const buf = Buffer.from("\x1b[M\x20")
575+
const result = parser.parseAllMouseEventsWithOffset(buf)
576+
expect(result.events).toHaveLength(0)
577+
expect(result.consumed).toBe(0)
578+
expect(result.partial).toBe(true)
579+
})
580+
581+
test("non-mouse data followed by mouse: consumed is 0, partial is false", () => {
582+
const keyData = Buffer.from("abc")
583+
const mouseData = encodeSGR(0, 10, 5, true)
584+
const buf = Buffer.concat([keyData, mouseData])
585+
const result = parser.parseAllMouseEventsWithOffset(buf)
586+
// Parser starts at offset 0, 'a' is not a mouse introducer — breaks immediately
587+
expect(result.events).toHaveLength(0)
588+
expect(result.consumed).toBe(0)
589+
expect(result.partial).toBe(false)
590+
})
591+
592+
test("empty buffer: 0 events, consumed 0, partial false", () => {
593+
const result = parser.parseAllMouseEventsWithOffset(Buffer.from(""))
594+
expect(result.events).toHaveLength(0)
595+
expect(result.consumed).toBe(0)
596+
expect(result.partial).toBe(false)
597+
})
598+
599+
test("non-mouse CSI sequence is not detected as partial", () => {
600+
// ESC[A (Cursor Up) — valid CSI but not a mouse sequence
601+
const buf = Buffer.from("\x1b[A")
602+
const result = parser.parseAllMouseEventsWithOffset(buf)
603+
expect(result.events).toHaveLength(0)
604+
expect(result.consumed).toBe(0)
605+
expect(result.partial).toBe(false)
606+
})
607+
608+
test("simulated split: chunk 1 with partial, chunk 2 completes it", () => {
609+
// Chunk 1: complete event + beginning of a second one
610+
const complete = encodeSGR(35, 20, 10, true) // move event
611+
const partial = "\x1b[<35;21"
612+
const chunk1 = Buffer.concat([complete, Buffer.from(partial)])
613+
614+
const result1 = parser.parseAllMouseEventsWithOffset(chunk1)
615+
expect(result1.events).toHaveLength(1)
616+
expect(result1.consumed).toBe(complete.length)
617+
expect(result1.partial).toBe(true)
618+
619+
// Chunk 2: remainder of the partial sequence
620+
const remainder = chunk1.toString().slice(result1.consumed)
621+
const chunk2str = remainder + ";11M" // completes \x1b[<35;21;11M
622+
const result2 = parser.parseAllMouseEventsWithOffset(Buffer.from(chunk2str))
623+
expect(result2.events).toHaveLength(1)
624+
expect(result2.events[0]).toMatchObject({ type: "move", x: 20, y: 10 })
625+
expect(result2.consumed).toBe(chunk2str.length)
626+
expect(result2.partial).toBe(false)
627+
})
628+
})
629+
522630
describe("MouseParser protocol precedence", () => {
523631
let parser: MouseParser
524632

‎packages/core/src/lib/parse.mouse.ts‎

Lines changed: 70 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,21 @@ export type RawMouseEvent = {
1414
scroll?: ScrollInfo
1515
}
1616

17+
/** Result of parsing a single mouse event, including how many bytes it consumed. */
1718
type ParsedMouseSequence = {
1819
event: RawMouseEvent
1920
consumed: number
2021
}
2122

23+
/** Result of parseAllMouseEventsWithOffset — contains parsed events, consumed byte count, and partial-sequence detection. */
24+
export type MouseParseResult = {
25+
events: RawMouseEvent[]
26+
/** Number of bytes successfully parsed as mouse events. */
27+
consumed: number
28+
/** True if the buffer ends with an incomplete mouse sequence that needs more data. */
29+
partial: boolean
30+
}
31+
2232
export class MouseParser {
2333
private mouseButtonsPressed = new Set<number>()
2434

@@ -48,23 +58,77 @@ export class MouseParser {
4858
}
4959

5060
public parseAllMouseEvents(data: Buffer): RawMouseEvent[] {
61+
return this.parseAllMouseEventsWithOffset(data).events
62+
}
63+
64+
/**
65+
* Parse all mouse events from the buffer, returning how many bytes were
66+
* consumed and whether the buffer ends with an incomplete mouse sequence.
67+
* This allows callers to forward unconsumed data to keyboard handlers
68+
* and buffer partial sequences for the next stdin chunk.
69+
*/
70+
public parseAllMouseEventsWithOffset(data: Buffer): MouseParseResult {
5171
const str = this.decodeInput(data)
5272
const events: RawMouseEvent[] = []
5373
let offset = 0
74+
let partial = false
5475

5576
while (offset < str.length) {
5677
const parsed = this.parseMouseSequenceAt(str, offset)
57-
if (!parsed) {
58-
// Stop at the first non-mouse sequence. Callers can decide whether to
59-
// route any remaining data through keyboard/terminal input handling.
78+
if (parsed) {
79+
events.push(parsed.event)
80+
offset += parsed.consumed
81+
continue
82+
}
83+
84+
// No complete mouse event at this position.
85+
// Check if there is a partial (truncated) mouse sequence starting here.
86+
if (this.isPartialMouseSequence(str, offset)) {
87+
partial = true
6088
break
6189
}
6290

63-
events.push(parsed.event)
64-
offset += parsed.consumed
91+
// Not a mouse sequence at all — stop. Caller routes the remainder
92+
// through keyboard/terminal input handling.
93+
break
94+
}
95+
96+
return { events, consumed: offset, partial }
97+
}
98+
99+
/**
100+
* Check whether an incomplete mouse sequence starts at the given offset.
101+
* For example, "\x1b[<35;20" is a truncated SGR sequence (missing the
102+
* terminating "M" or "m").
103+
*/
104+
private isPartialMouseSequence(str: string, offset: number): boolean {
105+
if (!str.startsWith("\x1b[", offset)) return false
106+
const remaining = str.slice(offset)
107+
108+
// Partial SGR mouse: \x1b[< followed by digits/semicolons but no M/m terminator
109+
if (remaining.startsWith("\x1b[<")) {
110+
// Just "\x1b[" or "\x1b[<" — clearly incomplete
111+
if (remaining.length <= 3) return true
112+
// Verify the rest consists only of valid SGR mouse characters (digits, semicolons)
113+
for (let i = 3; i < remaining.length; i++) {
114+
const ch = remaining.charCodeAt(i)
115+
if (ch >= 48 && ch <= 57) continue // digit
116+
if (ch === 59) continue // semicolon
117+
// M or m means the sequence is actually complete (should have been parsed above)
118+
if (ch === 77 || ch === 109) return false
119+
// Any other character — not a valid mouse sequence
120+
return false
121+
}
122+
// Only digits/semicolons without a terminator — partial
123+
return true
124+
}
125+
126+
// Partial basic (X10) mouse: \x1b[M needs 3 payload bytes (6 total)
127+
if (remaining.startsWith("\x1b[M")) {
128+
return remaining.length < 6
65129
}
66130

67-
return events
131+
return false
68132
}
69133

70134
private parseMouseSequenceAt(str: string, offset: number): ParsedMouseSequence | null {

‎packages/core/src/renderer.ts‎

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,6 +1013,7 @@ export class CliRenderer extends EventEmitter implements RenderContext {
10131013
this._useMouse = false
10141014
this.setCapturedRenderable(undefined)
10151015
this.mouseParser.reset()
1016+
this._mousePartialBuffer = ""
10161017
this.lib.disableMouse(this.rendererPtr)
10171018
}
10181019

@@ -1059,13 +1060,40 @@ export class CliRenderer extends EventEmitter implements RenderContext {
10591060
this.queryPixelResolution()
10601061
}
10611062

1063+
/** Buffers partial mouse sequences that span across stdin chunk boundaries. */
1064+
private _mousePartialBuffer: string = ""
1065+
10621066
private stdinListener: (data: Buffer) => void = ((data: Buffer) => {
1063-
// Mouse first (consume and stop if handled)
1064-
if (this._useMouse && this.handleMouseData(data)) {
1067+
if (this._useMouse) {
1068+
// Prepend any leftover partial mouse data from the previous chunk
1069+
let str = data.toString()
1070+
if (this._mousePartialBuffer.length > 0) {
1071+
str = this._mousePartialBuffer + str
1072+
this._mousePartialBuffer = ""
1073+
}
1074+
1075+
const result = this.mouseParser.parseAllMouseEventsWithOffset(Buffer.from(str))
1076+
1077+
// Dispatch parsed mouse events
1078+
for (const mouseEvent of result.events) {
1079+
this.processSingleMouseEvent(mouseEvent)
1080+
}
1081+
1082+
// Buffer any trailing partial sequence for the next chunk
1083+
if (result.partial) {
1084+
this._mousePartialBuffer = str.slice(result.consumed)
1085+
return
1086+
}
1087+
1088+
// Forward non-mouse remainder to the keyboard input pipeline
1089+
const remainder = str.slice(result.consumed)
1090+
if (remainder.length > 0) {
1091+
this._stdinBuffer.process(remainder)
1092+
}
10651093
return
10661094
}
10671095

1068-
// Everything else goes through the sequence buffer
1096+
// Mouse disabled — send everything to the keyboard input pipeline
10691097
this._stdinBuffer.process(data)
10701098
}).bind(this)
10711099

@@ -1201,13 +1229,17 @@ export class CliRenderer extends EventEmitter implements RenderContext {
12011229
return event
12021230
}
12031231

1232+
/**
1233+
* @deprecated No longer called by stdinListener directly.
1234+
* Kept for potential external callers.
1235+
*/
12041236
private handleMouseData(data: Buffer): boolean {
1205-
const mouseEvents = this.mouseParser.parseAllMouseEvents(data)
1237+
const result = this.mouseParser.parseAllMouseEventsWithOffset(data)
12061238

1207-
if (mouseEvents.length === 0) return false
1239+
if (result.events.length === 0) return false
12081240

12091241
let anyHandled = false
1210-
for (const mouseEvent of mouseEvents) {
1242+
for (const mouseEvent of result.events) {
12111243
if (this.processSingleMouseEvent(mouseEvent)) {
12121244
anyHandled = true
12131245
}
@@ -1515,6 +1547,7 @@ export class CliRenderer extends EventEmitter implements RenderContext {
15151547

15161548
this.setCapturedRenderable(undefined)
15171549
this.mouseParser.reset()
1550+
this._mousePartialBuffer = ""
15181551

15191552
if (this._splitHeight > 0) {
15201553
// TODO: Handle resizing split mode properly

‎packages/core/src/tests/renderer.mouse.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1246,7 +1246,7 @@ describe("renderer handleMouseData split height", () => {
12461246
}
12471247
})
12481248

1249-
test("split height returns false for input above render area", async () => {
1249+
test("split height ignores mouse input above render area without leaking to keyboard", async () => {
12501250
try {
12511251
const sequences: string[] = []
12521252
renderer.addInputHandler((sequence) => {
@@ -1261,7 +1261,10 @@ describe("renderer handleMouseData split height", () => {
12611261
await mockMouse.click(1, Math.max(0, renderOffset - 1))
12621262
await Bun.sleep(10)
12631263

1264-
expect(sequences.length).toBeGreaterThan(beforeSequences)
1264+
// Mouse events above the render area are silently ignored.
1265+
// They must NOT leak through as keyboard sequences to input handlers,
1266+
// which would cause raw escape codes to appear as typed text.
1267+
expect(sequences.length).toBe(beforeSequences)
12651268
} finally {
12661269
renderer.destroy()
12671270
}

0 commit comments

Comments
 (0)