Skip to content

[Bug]: TUI word wrap, LaTeX parsing, and bracketed paste can run without a bound #613

Open

Description

@Coff0xc

Summary

Three interactive TUI paths can run without a bound and take down the client. External pull requests are not accepted from this account. The fix branch is linked below.

Searched existing issues first. #32 is a LaTeX display question, and #491 is a clipboard-paste contribution question. Neither is this recursion or buffer bound.

Product or interface

CLI - interactive TUI. Source build.

Version

Source main at 3c21163 (chore(sdk-python): release 0.1.1). Node.js v24.19.0. pnpm 9.12.0.

Platform

Windows 11 Pro, build 26200.

Issue area

UI / UX.

Steps to reproduce

On 3c21163:

  1. Word wrap: render a line that contains one wide grapheme, such as a CJK character or an emoji, with wordWrapLine when the terminal content width is 1 column.
  2. LaTeX: call renderLatex with a few hundred unmatched { characters, or with environments nested a few hundred levels deep.
  3. Paste: send a bracketed-paste start (ESC [200~) and keep sending data with no end marker until the buffer passes 1 MiB. The same buffer exists in StdinBuffer, Input, and Editor.

Expected and actual behavior

  • Expected: a single wide grapheme is emitted as its own visual chunk; LaTeX deeper than a small fixed depth is treated as unsupported; an oversized or unterminated paste is dropped and the input path accepts later keystrokes.
  • Actual: wordWrapLine recurses on that same grapheme until the stack overflows; renderLatex recurses once per nested group or environment until the stack overflows; the paste buffer grows for as long as the end marker is absent.

Branch

https://github.com/Coff0xc/minimax-code/tree/fix/code-defects

Head b1bfc9a. Commits from 203278f through b1bfc9a, based on 3c21163.

  • wordWrapLine recurses only when a segment contains more than one grapheme.
  • LaTeX parsing shares a depth of 64 across nested braces and nested environment parsers.
  • StdinBuffer, Input, and Editor drop a bracketed paste larger than 1 MiB and leave paste mode.

Validation

Windows, Node.js v24.19.0, Vitest 4.1.11, on the committed sources:

npx --yes pnpm@9.12.0 exec vitest run --config vitest.oss.config.mjs packages/tui/test/unit/tui-word-wrap-wide-grapheme.test.ts packages/tui/test/unit/tui-latex-parse-depth.test.ts packages/tui/test/unit/tui-terminal-text-paste.test.ts

21 passed: word wrap 5, LaTeX depth 3, paste 13.

NOT RUN: pnpm verify, and Linux or macOS CI. The paste cap was exercised with synthetic input, not a physical terminal paste.

Checklist

  • I have searched existing issues.
  • I have included the version and removed sensitive information.

Activity

  1. Ralle1976 commented on Nov 20, 2026

    @Ralle1976
    Contributor

    Windows-side measurements for the three unbounded paths: the exact thresholds, the paste framing origin, and one Windows hypothesis I could rule out

    Versionsanker

    Source read main = 3c21163 (chore(sdk-python): release 0.1.1; packages/tui/package.json version 0.7.2) — the revision your report anchors to
    Toolchain Node v24.18.0 (your report: v24.19.0), npm for the one dependency below
    Platform Microsoft Windows 11 Pro, 10.0.26200, x64
    Measurement setup verbatim copies of the 3c21163 sources (packages/tui/src/tui/engine/latex.ts, .../utils.ts, .../stdin-buffer.ts, .../components/editor.ts lines 114–222) staged in %TEMP%, plus get-east-asian-width@1.6.0 (the version pinned in pnpm-lock.yaml:3150); no patch of yours applied, no repo file changed

    Repro command (Windows, one block, run from the repository root)

    node --experimental-strip-types --input-type=module -e "import {readFileSync,writeFileSync,mkdirSync} from 'node:fs';import {execFileSync} from 'node:child_process';import {tmpdir} from 'node:os';import {join} from 'node:path';import {pathToFileURL} from 'node:url';const d=join(tmpdir(),'w18-latex-probe');mkdirSync(d,{recursive:true});writeFileSync(join(d,'package.json'),'{\"type\":\"module\"}');execFileSync(process.platform==='win32'?'npm.cmd':'npm',['i','--no-audit','--no-fund','get-east-asian-width@1.6.0'],{cwd:d,stdio:'ignore',shell:true});const src='packages/tui/src/tui/engine';for(const f of ['utils','latex'])writeFileSync(join(d,f+'.ts'),readFileSync(join(src,f+'.ts'),'utf8').replace('./utils.js','./utils.ts'));const {renderLatex}=await import(pathToFileURL(join(d,'latex.ts')).href);for(const n of [500,9000,10000,20000]){try{const r=renderLatex('{'.repeat(n));console.log(n,'ok',r===undefined?'undefined':'len='+r.length)}catch(e){console.log(n,e.name+': '+e.message)}}"

    (The two staged files are byte-identical copies of 3c21163 except for the one import specifier ./utils.js → ./utils.ts, which Node's type stripping needs; the dependency is the version pinned in pnpm-lock.yaml:3150.)


    1. The three paths, measured on 3c21163 (Windows, Node v24.18.0). The word-wrap and the paste path reproduce at the magnitude you give; the LaTeX recursion is real but does not overflow at "a few hundred" — the useful addition is the magnitude of all three.

    path input measured result
    packages/tui/src/tui/engine/components/editor.ts:114 wordWrapLine one wide grapheme, maxWidth=1 RangeError: Maximum call stack size exceeded after ~14 ms — same for U+6F22, U+1F600 and a ZWJ sequence; maxWidth=2 returns normally (1 chunk)
    same a TAB in the line, maxWidth=2 RangeError: Maximum call stack size exceeded (~15 ms) — wordWrapLine("a\tb", 2) crashes the same way
    packages/tui/src/tui/engine/latex.ts:1362 renderLatex nested { 500 levels → returns undefined (graceful "unsupported"); overflow flips between 9 000 and 10 000 levels and moves by a few hundred between runs; 20 000 levels → always RangeError
    packages/tui/src/tui/engine/stdin-buffer.ts:339-340 ESC[200~ + 8 MiB, no ESC[201~ 0 paste events, still in paste mode; heap +58.09 MiB before GC, +8.09 MiB retained after GC, RSS +12.67 MiB

    Two details in that table matter for the report itself:

    • "A few hundred unmatched {" does not exhaust the stack here. With 500 levels renderLatex returns undefined: the innermost parseSequence("}") reaches the end of the source and sets supported = false (packages/tui/src/tui/engine/latex.ts:901-903), and packages/tui/src/tui/engine/components/markdown.ts:552 then falls back to the raw text. The graceful path exists, but it is reached after the recursion has already gone N levels deep — so it only saves you while N stays below the stack limit. The depth that actually crashes on this host is ~9 000–10 000, i.e. one to two orders of magnitude above the "few hundred" in your report.
    • The word-wrap trigger is exactly visibleWidth(grapheme) > maxWidth (editor.ts:175-181), and contentWidth is floored at 1 (editor.ts:594), so a 1–2 column viewport is enough. maxWidth=2 is safe for the graphemes I measured (CJK, Hangul, hiragana, emoji, ZWJ sequence, flag, keycap, fullwidth all report 2), but a TAB reports 3 (visibleWidth normalises tabs to three spaces, packages/tui/src/tui/engine/utils.ts:269-270), so a tab in the line reaches the same recursion at maxWidth=2 — measured: wordWrapLine("a\tb", 2) → RangeError, while wordWrapLine("a\tb", 3) is fine. The trigger set is therefore "any grapheme wider than the viewport", not only "one wide grapheme at width 1".

    2. On Windows the paste framing comes from the terminal, not from the app. packages/tui/src/tui/engine/terminal.ts:257 enables mode 2004 on every platform. The only Windows-specific console-mode handling in the TUI engine is enableWindowsVTInput() (terminal.ts:455), which loads packages/tui/native/win32/prebuilds/win32-x64/win32-console-mode.node; its source is third_party/pi-mono/packages/tui/native/win32/src/win32-console-mode.c, and the whole helper does is OR ENABLE_VIRTUAL_TERMINAL_INPUT into the console mode of GetStdHandle(STD_INPUT_HANDLE). Measured on this host: enableVirtualTerminalInput() returns false — i.e. it is a no-op whenever stdin is not a Win32 console handle, which is exactly the ConPTY case (stdin is a pipe). So under ConPTY the ESC[201~ end marker is produced by the terminal emulator, and the application cannot rely on the host to terminate the paste. Whatever cap is chosen has to live inside the app.

    3. The retained cost of an unterminated paste is 1:1 with the pasted bytes, and it is paid again downstream. terminal.ts:306 re-wraps the buffered content as ESC[200~…ESC[201~ and hands it to the input handler, which accumulates it again in packages/tui/src/tui/engine/components/editor.ts:753 (and components/input.ts:79). Measured: 8 MiB pasted → 8.09 MiB retained in StdinBuffer alone, and the same content then exists as the re-wrapped string and as the editor's pasteBuffer. A byte cap is therefore cheaper to enforce at the earliest consumer (stdin-buffer.ts:339-340) than at each consumer.

    4. Ruled out: "Windows has a smaller thread stack, so the two recursion paths crash earlier there." node.exe on this host reserves 8 MiB of stack (PE optional header SizeOfStackReserve = 8 388 608), but V8's own limit binds first. Measured maximum recursion depth for a trivial recursive function: 12 499 frames with default settings, versus 13 010 with --stack-size=1024, 26 110 with --stack-size=2048 and 6 446 with --stack-size=512. The budget is V8's (~1 MiB), not the OS thread stack, so with the same Node version the two stack-exhaustion paths should have the same threshold on POSIX. A cross-platform test should assert the bound, not the crash depth — the crash depth is a property of the V8 stack limit and moves by a few hundred between runs.

    5. The width model is the only thing that decides the word-wrap recursion, and the repo already records that Windows hosts disagree with it. The trigger is visibleWidth(grapheme) > maxWidth (editor.ts:175-181), while packages/tui/src/tui/engine/LOCAL_CHANGES.json:183 records that a host can draw a grapheme cluster wider than visibleWidth() reports ("ZWJ emoji in VS Code") — that is why the differential renderer truncates an over-wide row instead of wrapping it. The two facts sit in the same place: on a host whose real cell width differs from the app's model, the app's model is what selects the recursion.

    6. Reachability in the public projection. All three are on the shipped CLI path: packages/tui/src/index.ts → packages/tui/src/cli/main.ts:86 (runTuiCli) → packages/tui/src/tui/renderer/interactive-renderer.ts → packages/tui/src/tui/engine/public.ts → packages/tui/src/tui/engine/index.ts:90 (exports renderLatex). The LaTeX source in the product path is the transcript text rendered by the Markdown component (packages/tui/src/tui/engine/components/markdown.ts:551 and :690), and the paste path is the interactive input path (terminal.ts:292 → stdin-buffer.ts → editor.ts:745). None of these paths appear in scripts/lib/retired-sources.mjs (the only retired TUI path is packages/tui/src/auth/identity.ts).

    7. One related Windows asymmetry in the same module, outside the three paths you list. terminal.ts:158 writes straight to process.stdout.write when process.platform === "win32", while POSIX TTYs use the bounded 64 KiB queue with EINTR/EAGAIN backpressure (terminal.ts:163-211). The "bounded writer" invariant therefore currently only exists on POSIX. I am not proposing a change; it is the same bounded-vs-unbounded shape as your report, in the output direction.

    Two questions (not a proposal for your branch)

    1. Given that on Windows the end marker arrives from the terminal emulator — and the app's own Win32 helper is a no-op under ConPTY (measured false) — is the intended byte cap meant to be enforced once in StdinBuffer before the re-wrap at terminal.ts:306, rather than in each consumer (stdin-buffer.ts:339-340, input.ts:79, editor.ts:753)? The retained cost is 1:1 with the pasted bytes and is currently paid twice.
    2. For the two recursion paths: is the intended contract "deeper than a fixed depth → unsupported" (the parser already answers undefined for unmatched braces at latex.ts:901-903, and markdown.ts:552 falls back to the raw text)? If so, the value to assert in a cross-platform test is that bound — not the ~10 000 at which the stack happens to overflow on a given host and V8 build.

    What I could not measure

    • I did not perform a physical paste, and I could not measure a host-side bound for the paste: this session's stdin is not a Win32 console handle (enableVirtualTerminalInput() → false), so I could neither exercise the console input buffer nor observe how a real Windows Terminal frames a large paste. Everything in point 2 and 3 is a read of the code plus a synthetic ESC[200~ stream.
    • The classic Windows console's screen buffer on this host is 120 × 9001 rows (measured via the console API), but that bounds history, not the paste buffer, and the TUI keeps its transcript in the host's scrollback — I could not show a Windows-specific bound for the three paths in your report.
    • No Linux/macOS run: point 4 concludes from the measured V8 flag scaling on this host that the OS stack is not the binding constraint, not from a POSIX measurement.
    • I did not run your branch, pnpm verify, or the Linux/macOS CI, and I did not measure the depth at which your depth-64 bound would reject input.
  2. Coff0xc commented on Nov 20, 2026

    @Coff0xc
    Author

    Thanks for measuring this on 3c21163 without the branch applied. The two questions are already answered on fix/code-defects at b1bfc9a.

    Paste cap. StdinBuffer.takePaste drops a bracketed paste once its content exceeds 1 MiB (MAX_BRACKETED_PASTE_CHARS) and leaves paste mode without emitting paste. terminal.ts re-wraps the payload as ESC[200~…ESC[201~ only in that paste listener, so an over-cap paste never reaches the re-wrap or the second copy in Editor / Input. Those two keep the same cap for a payload that is already under the limit, and for input that does not pass through StdinBuffer. The 1:1 retention you measured on unpatched 3c21163 stops at this first consumer. The end marker still comes from the terminal emulator; the cap stays in the app. I did not repeat a physical paste.

    Recursion contract. The value to assert is the fixed bound, not the depth at which a given V8 build overflows.

    • Nested groups and nested environment parsers share MAX_LATEX_PARSE_DEPTH (64). At that depth the parser marks the input unsupported and renderLatex returns undefined, which is the fallback markdown.ts already uses.
    • wordWrapLine recurses only when visibleWidth(grapheme) > maxWidth and splitting that segment yields more than one grapheme. A single grapheme is emitted as its own chunk and the running width is clamped to maxWidth. A tab is one grapheme and visibleWidth counts it as three columns, so wordWrapLine("a\tb", 2) takes that path. The committed tests cover a 1-column CJK character and an emoji; they do not mention the tab.

    Your measurement is the right correction to this report: on unpatched 3c21163, 500 unmatched { returns undefined, and the stack overflow sits near 9 000–10 000 and moves with V8's stack limit. "A few hundred" was the wrong crash threshold. I am not treating that host-specific depth as the assertion.

    Not run here: Linux or macOS, or a physical terminal paste. The paste cap on the branch is still synthetic input.

  3. Ralle1976 commented on Nov 20, 2026

    @Ralle1976
    Contributor

    Thanks — that answers both questions, and the fixed-bound assertion (MAX_LATEX_PARSE_DEPTH, and the single-grapheme clamp in wordWrapLine) is the right contract.

    One concrete input for the test gap you noted: the committed tests cover a 1-column CJK character and an emoji, but not the tab. On unpatched 3c21163 (Node v24.18.0, Windows), wordWrapLine("a\tb", 2) hits the same recursion as the 1-column case, because visibleWidth normalises a tab to three columns (packages/tui/src/tui/engine/utils.ts:269-270) while contentWidth is floored at 1 (editor.ts:594). So "a\tb" at maxWidth=2 is a minimal reproducer for the "grapheme wider than the viewport" path that does not rely on a wide Unicode character — a plain ASCII tab is enough.

    I have not run fix/code-defects, so I cannot assert the bounded output on your branch; the input above is offered only as a test case for the width-3-grapheme-at-width-2 path. With the single-grapheme clamp you describe, it should emit the tab as its own chunk rather than recurse.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions