Skip to content

fix(mobile): slice large terminal writes before xterm parses them - #25503

Closed
kargnas wants to merge 3 commits into
stablyai:mainfrom
kargnas:fix/mobile-terminal-write-slices
Closed

kargnas wants to merge 3 commits into
stablyai:mainfrom
kargnas:fix/mobile-terminal-write-slices

Conversation

@kargnas

@kargnas kargnas commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When a lot of terminal output arrived at once, the phone handed all of it to the terminal renderer in one piece, and the app could not react to taps or typing until that piece was processed. Now large pieces are cut into small ones, so the app gets regular chances to respond while they are processed.

What Changed

Before: document/write-queue.ts queued each incoming write unchanged, so a large PTY burst or a scrollback replay reached xterm.write() as one string. xterm.js parses a single write without yielding and yields to the event loop only between writes, so the WebView's main thread stayed busy for the whole burst.

After:

  • enqueueWrite splits any write longer than 4,096 UTF-16 code units (TERMINAL_WRITE_SLICE_UNITS) into ordered slices. Shorter writes are queued unchanged, as before.
  • A slice never ends on a high surrogate, so an emoji or another astral character is never cut in half.
  • Both paths still receive the status-dot-normalized text, because normalizeStatusDotPresentation runs before slicing.
  • xterm's write buffer checks its 12 ms time budget between writes and yields to the event loop once the budget is spent (WriteBuffer._innerWrite). With slices, a burst holds the thread for about one budget plus one slice at a time, instead of until all of it is parsed. Consecutive slices still run in the same task until the budget is spent, which keeps throughput the same as today.
  • A write frame that carries no text is still queued unchanged, as before. Only strings are sliced, matching how normalizeStatusDotPresentation and the mouse-mode scan already tolerate such frames.

Why

Slicing only the oversized writes keeps the order and the boundaries of every other write, and needs no change to xterm or to the host. Normal interactive output is far below 4,096 code units, so it is unaffected.

Alternatives considered:

  • Slicing every write: adds work for small writes and changes nothing useful for them.
  • Having the host send smaller frames: needs a host change, and older hosts would still send large frames, because clients and hosts update independently.

Linked Issue

Fixes #25501

This change was first part of #20489, which I have split into smaller PRs.

Visual Proof

N/A: there is no UI change. The terminal shows the same output; only the way it is fed to xterm changes.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Prebuilt APK for trying this on a phone: https://github.com/kargnas/orca/releases/tag/preview-mobile-20261005-f1d7719. It contains this PR and my other open mobile PRs on top of main 40f9e7a3fc, and installs next to the regular app as "Orca Preview". On an Android 13 emulator it launched, paired with mobile/scripts/mock-server.ts and painted the terminal. It was built from this PR's first commit, b093d63402, before the review follow-up below.

On this branch (c1970ce136, on main 40f9e7a3fc):

  • Mobile tsc --noEmit, check:tests-typecheck, oxlint and format:check pass.
  • Full mobile vitest run: 925 files passed, 2 skipped; 10,008 tests passed, 6 skipped. The only failures are two tests in src/tasks/mobile-agent-launch-architecture.test.ts, which fail the same way on plain main on my machine.
  • The four mobile web closure suites (mobile-web-app-session-terminal-closure, mobile-web-app-page-closure-families, mobile-web-terminal-engine-closure, mobile-web-app-push-subsystem-closure) pass.

New or updated tests (write-queue.test.ts):

  • a large write is sliced in order, without splitting a surrogate pair at the slice boundary;
  • the normalized status dot reaches xterm both below and above the slice size;
  • the existing retention test now uses one-slice chunks, so it still counts exactly the chunks the queue was handed;
  • a write frame that carries no text is queued unchanged instead of throwing (c1970ce136, from the Pullfrog review). This test fails on b093d63402.

Device: this change was in the #20489 build I ran on a physical Galaxy Z Fold7 (Android 16). That build also contained #20489's other changes. This branch on its own has not been rebuilt into an APK.

AI Disclosure

OpenAI Codex (GPT-5.6 Sol and GPT-5.6 Luna) assisted with the original investigation and implementation in #20489. The rebase, the review fixes and this split were done with Claude Code (Claude Opus 5.5). The author ran the combined build on a physical device.

Review

  • Security: no permissions, network endpoints, credentials or host-execution paths were added.
  • Cross-platform: the document runs in the native WebView on Android and iOS and in the page, and the slicing applies the same way to all of them.
  • SSH/remote/local: nothing new crosses the host–client wire, and the terminal receives the same bytes in the same order.
  • Agents/integrations: output handling is provider-neutral and applies equally to Codex, Claude Code and ordinary shell commands.
  • Performance: only writes over 4,096 code units are split, and the queue order is unchanged. Each extra slice costs one more write callback.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

No README, environment-variable, API, deployment, privacy or remote-wire contract changed.

Author

X (Twitter): @kargnas

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred): mobile typecheck, tests-typecheck, lint, format and tests pass locally, apart from the two main failures above; root lint, typecheck and build are left to CI

큰 PTY 출력이나 스크롤백 재생이 xterm.write() 한 번으로 들어가, xterm이 전부 파싱할 때까지 WebView 스레드를 붙잡았다. 4,096 UTF-16 코드 유닛을 넘는 쓰기만 순서대로 나눠 큐에 넣고, 서로게이트 쌍은 자르지 않는다. 큐는 조각 사이마다 xterm의 write 콜백을 기다리므로 입력과 그리기가 끼어들 수 있다. 짧은 쓰기는 지금처럼 그대로 넣는다.

stablyai/orca#20489에서 출력 분할 부분만 분리한 변경이다.

Rejected: 모든 쓰기 분할 | 짧은 쓰기의 경계와 기존 동작을 바꿀 이유가 없음
Related: stablyai#20489
@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7cff23e8-a44d-4b0f-8920-30e994183bc6
Commits

Reviewing files that changed from the base of the PR and between c1970ce and e576cb3.

Files selected for processing: 2
  • mobile/src/terminal/document/write-queue.test.ts
  • mobile/src/terminal/document/write-queue.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Walkthrough

The terminal write queue accepts undefined and splits strings longer than 4,096 code units into bounded chunks. It adjusts chunk boundaries to keep surrogate pairs intact. Tests cover retained chunks, large writes, status-dot text presentation for short and long inputs, and enqueueing undefined.

Priority: Normal

Severity of issue fixed: Medium

Merge Risk: Minimal · up to e576c

Large terminal writes are sliced without an identified regression in output order or presentation. The change is ready for normal merge checks.

Architecture risk: Low · up to c1970

The change affects 1 system.

Changed systems: mobile

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — mobile (service) was modified; 2 changed files map to changed impact.

Before / after behavior

  • observed — Modified behavior in mobile/src/terminal/document/write-queue.test.ts: The test file now imports TERMINAL_WRITE_SLICE_UNITS from write-queue.
  • observed — Modified behavior in mobile/src/terminal/document/write-queue.test.ts: The comment now explains that distinct chunk contents expose whether dequeued chunks were released, rather than describing repeated 64 KB strings.
  • observed — Modified behavior in mobile/src/terminal/document/write-queue.test.ts: The retention test now sizes each chunk from TERMINAL_WRITE_SLICE_UNITS instead of using a fixed 65,536 code units.
  • observed — Modified behavior in mobile/src/terminal/document/write-queue.test.ts: Adds a test that enqueues text with an emoji crossing the slice boundary, then checks that drained writes reconstruct the input, use two chunks within the slice limit, and keep the emoji intact at the start of the second chunk.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: slicing large mobile terminal writes before xterm parses them.
Description check Passed The description is complete and follows the repository template. It explains the user impact, implementation, rationale, linked issue, lack of visual changes, testing results, AI use, compatibility co…
Linked Issues check Passed Issue [#25501] requires the mobile terminal to avoid sending a large PTY burst or scrollback replay to xterm as one synchronous write. enqueueWrite now splits strings above `TERMINAL_WRITE_SLICE_UNI…
Out of Scope Changes check Passed The reviewed changes are limited to write-queue.ts and its tests. The implementation, queue behavior, and regression tests directly support issue [#25501]. No unrelated change is shown in the availa…
Full details: Description check

Explanation

The description is complete and follows the repository template. It explains the user impact, implementation, rationale, linked issue, lack of visual changes, testing results, AI use, compatibility considerations, and checklist status. It also identifies that root lint, typecheck, and build remain for CI.

Full details: Linked Issues check

Explanation

Issue [#25501] requires the mobile terminal to avoid sending a large PTY burst or scrollback replay to xterm as one synchronous write. enqueueWrite now splits strings above TERMINAL_WRITE_SLICE_UNITS into ordered slices and preserves surrogate pairs. pumpWrites submits one queued slice at a time through xterm's write callback. Tests cover slice order, surrogate boundaries, status-dot normalization, and no-text frames.

Full details: Out of Scope Changes check

Explanation

The reviewed changes are limited to write-queue.ts and its tests. The implementation, queue behavior, and regression tests directly support issue [#25501]. No unrelated change is shown in the available PR evidence.

  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one minor robustness note inline.

Reviewed changes

  • Large writes are sliced before xterm parses them — enqueueWrite now normalizes first, then splits any write longer than 4,096 UTF-16 code units into ordered slices, decrementing the boundary when it would land on a high surrogate so astral characters stay whole; writes at or below the limit are queued unchanged.
  • Tests cover the new paths — a boundary-straddling emoji verifies order, slice count and pair integrity; a status dot is checked below and above the slice limit; the retention test now hands the queue exactly one slice per chunk so its code-unit counts stay exact.

I verified the slice loop cannot produce an empty slice (the decrement only runs when the slice is a full 4,096 units), that splitting escape sequences across term.write calls is safe for xterm's streaming parser, and that updateMouseModeFromData runs on the un-sliced data in write() so the mouse-mode scan and its tail are unaffected. The generated document bundle is gitignored and rebuilt at postinstall, so no committed artifact needs regenerating for the bundle-digest test.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

분할 코드가 정규화 결과의 length를 무조건 읽어서, data가 빠진 write 프레임이 오면 예외를 던졌다. 정규화와 마우스 모드 스캔은 문자열이 아닌 data를 그대로 넘기므로, 분할 전에도 문자열인지 확인해 예전처럼 그대로 큐에 넣도록 했다. pullfrog 리뷰에서 나온 지적이다.

Tested: 새 테스트가 수정 전 코드에서 실패하고 수정 후 통과, 문서 번들 재생성 후 write-queue·native-document-bundle 21개 통과, mobile tsc·tests-typecheck·oxlint·oxfmt 통과, 전체 vitest 10,008개 통과(기존 main 실패 2개 제외)
Related: stablyai#25503

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Yield before pumping the next terminal slice. · write-queue.ts:75-91

mobile/src/terminal/document/write-queue.ts:75-91
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Yield before pumping the next terminal slice.

When a large live write is split, pumpWrites calls term.write() again from xterm’s write callback. In @xterm/[email protected], that callback runs before _bufferOffset advances. The reentrant write() therefore appends to the active buffer, and _innerWrite() continues parsing the next slices in the same task until xterm’s 12 ms budget expires. The slices do not guarantee host-event-loop time for taps, typing, or painting.

Schedule the next pump in a macrotask after the callback returns.

Suggested fix
     scope.writesDraining = false
-    pumpWrites(scope, gen)
+    setTimeout(() => pumpWrites(scope, gen), 0)

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ac3ec195-fe26-4ee9-970f-055fdd265981
📥 Commits

Reviewing files that changed from the base of the PR and between b093d63 and c1970ce.

📒 Files selected for processing (2)
  • mobile/src/terminal/document/write-queue.test.ts
  • mobile/src/terminal/document/write-queue.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Text-less write frames no longer throw — enqueueWrite now checks typeof normalized !== 'string' before reading .length, so a bridge frame that arrives without data is queued unchanged, restoring the previous tolerance; the fix matches how normalizeStatusDotPresentation and the mouse-mode scan already handle such frames.
  • Regression test added — queues a write frame that carries no text instead of throwing enqueues undefined, asserts no throw, and asserts the slot is retained; it fails on the prior commit and passes on c1970ce136.

The incremental delta is exactly the robustness fix requested in the prior review, and its thread is resolved. The guard short-circuits before the length read, so the previously reachable undefined.length throw is gone, and the slicing loop and its surrogate handling are unchanged from the version reviewed earlier.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@kargnas

kargnas commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

On the outside-diff note in CodeRabbit's last review ("Yield before pumping the next terminal slice"):

It is right that consecutive slices are not each a separate task. In @xterm/xterm 6.1.0-beta.303, WriteBuffer._innerWrite calls a chunk's callback inside its loop (src/common/input/WriteBuffer.ts, lines 290–291), so the next term.write() from pumpWrites just appends to the active buffer. But the same loop then checks its 12 ms budget (line 295), breaks, and reschedules itself with _scheduleInnerWrite(), which yields to the event loop. That check only runs between writes: InputHandler.parse handles one write in a synchronous loop over 128 KiB pieces. So before this PR a single large write blocked until it was fully parsed, and with slices the thread is held for about one budget plus one slice at a time. I've reworded the PR description, which overstated this as "between slices".

I'm leaving the drain as it is rather than adding setTimeout(() => pumpWrites(scope, gen), 0). That would put a timer hop between every queued write, not only slices, and browsers clamp nested zero-delay timers to at least 4 ms. A 1 MiB burst is 256 slices, so the hops alone would add about a second, while xterm's budget already provides the yield.

최신 main을 병합하고 출력 분할과 유니코드 경계 보존 테스트를 업스트림의 직접 모듈 실행 방식에 맞췄다. 텍스트 없는 프레임의 입력 타입을 명시하고 큐 메모리 회수 검증도 분할 크기에 맞춰 유지했다.

Tested: 관련 테스트 25개, 모바일 타입 검사, check:changed 11개 검사 통과
Related: stablyai#25503
@AmoabaKelvin

Copy link
Copy Markdown
Collaborator

Thanks for this, and for the clear report in #25501. We just merged #38953, which fixes it the same way by slicing large terminal writes before xterm parses them, so I'm closing this one. Your report is what got it fixed.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Mobile terminal parses a large output burst as a single xterm write

2 participants