Skip to content

fix(cli): prevent terminal escape sequences from leaking on exit#22682

Merged
mattKorwel merged 7 commits intomainfrom
mk-odd-keyoutput
Mar 23, 2026
Merged

fix(cli): prevent terminal escape sequences from leaking on exit#22682
mattKorwel merged 7 commits intomainfrom
mk-odd-keyoutput

Conversation

@mattKorwel
Copy link
Collaborator

@mattKorwel mattKorwel commented Mar 16, 2026

Summary

This PR prevents terminal escape sequences (especially mouse tracking events) from leaking into the shell prompt after the Gemini CLI exits.

Details

  1. Reordered runExitCleanup: Updated the cleanup sequence in packages/cli/src/utils/cleanup.ts to execute cleanupFunctions (which disable terminal modes and unmount the UI) before draining stdin. This ensures "in-flight" terminal sequences are cleared while the terminal is still in raw mode.
  2. Increased Drain Timeout: Increased the drainStdin timeout from 50ms to 100ms for better reliability on slower terminals or during high-activity sessions.
  3. Enhanced Synchronous Cleanup: Updated TERMINAL_CLEANUP_SEQUENCE in packages/cli/src/ui/utils/terminalCapabilityManager.ts to include mouse tracking disable sequences. This provides a fallback if the process exits hard without running the full cleanup.
  4. Added Verification Test: Added a test case in packages/cli/src/utils/cleanup.test.ts to verify the execution order of cleanup functions relative to stdin draining.

Related Issues

Fixes #16801 (Partial)
Related to mouse/terminal stability issues in alternate buffer mode.

How to Validate

  1. Enable alternate buffer in settings.
  2. Start an interactive session.
  3. Move the mouse vigorously or scroll rapidly while typing /exit or /quit.
  4. Verify that no escape sequences (e.g., ^[[<65;...) appear in the shell prompt after exit.
  5. Run tests: npm test -w @google/gemini-cli -- src/utils/cleanup.test.ts

Pre-Merge Checklist

  • Updated relevant documentation and README (if needed)
  • Added/updated tests (if needed)
  • Noted breaking changes (if any)
  • Validated on required platforms/methods:
    • MacOS
      • npm run
      • npx
      • Docker
      • Podman
      • Seatbelt
    • Windows
      • npm run
      • npx
      • Docker
    • Linux
      • npm run
      • npx
      • Docker

Reorders cleanup sequence to disable terminal modes before draining stdin and increases drain timeout. Also adds fallback mouse tracking disable to synchronous cleanup.
@mattKorwel mattKorwel requested a review from a team as a code owner March 16, 2026 17:17
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses an issue where terminal escape sequences could leak into the shell prompt after the CLI exits, leading to a messy or unresponsive terminal. The changes improve terminal stability and user experience by refining the exit cleanup process, ensuring all terminal modes are properly reset and input buffers are cleared before the application fully terminates.

Highlights

  • Cleanup Order Reversal: The runExitCleanup sequence was reordered to execute asynchronous cleanup functions (which disable terminal modes and unmount the UI) before draining stdin. This ensures terminal sequences are cleared while the terminal is still in raw mode, preventing leaks.
  • Increased Stdin Drain Timeout: The drainStdin timeout was increased from 50ms to 100ms to improve reliability, especially on slower terminals or during high-activity sessions.
  • Enhanced Synchronous Cleanup: The TERMINAL_CLEANUP_SEQUENCE was updated to include additional mouse tracking disable sequences, providing a more robust fallback for scenarios where the process exits abruptly without full cleanup.
  • New Test Case: A new test case was added to verify the precise execution order of cleanup functions relative to stdin draining, ensuring the intended cleanup flow is maintained.
Changelog
  • packages/cli/src/ui/utils/terminalCapabilityManager.ts
    • Imported disableMouseEvents from @google/gemini-cli-core.
    • Updated TERMINAL_CLEANUP_SEQUENCE to include additional escape codes for disabling mouse events.
    • Added a call to disableMouseEvents() within cleanupTerminalOnExit.
  • packages/cli/src/utils/cleanup.test.ts
    • Added a new test case to assert the execution order of cleanupFunctions, drainStdin, and runSyncCleanup.
  • packages/cli/src/utils/cleanup.ts
    • Reordered the runExitCleanup function to execute cleanupFunctions before drainStdin and runSyncCleanup.
    • Increased the drainStdin timeout from 50ms to 100ms.
Activity
  • The author has completed the 'Added/updated tests' checklist item.
  • The author has validated the changes on MacOS using 'npm run'.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request correctly addresses an issue where terminal escape sequences could leak on exit by reordering the cleanup operations. Running the async cleanup (including UI unmounting) before draining stdin and disabling raw mode is the right approach. The addition of more comprehensive escape sequences for hard exits is also a good defensive measure. I've found one issue in the new test case where the assertion for the cleanup order seems to be incorrect, which I've detailed in a comment.

@github-actions
Copy link

github-actions bot commented Mar 16, 2026

Size Change: +86 B (0%)

Total Size: 26.1 MB

Filename Size Change
./bundle/chunk-LF37MDAV.js 0 B -3.64 MB (removed) 🏆
./bundle/chunk-NJQNU3EW.js 0 B -14.5 MB (removed) 🏆
./bundle/core-4BAKFZ6E.js 0 B -42.4 kB (removed) 🏆
./bundle/devtoolsService-7UT5DERJ.js 0 B -27.7 kB (removed) 🏆
./bundle/interactiveCli-22OEK2WG.js 0 B -1.62 MB (removed) 🏆
./bundle/oauth2-provider-AE5ALODU.js 0 B -9.16 kB (removed) 🏆
./bundle/chunk-24RJOY37.js 14.5 MB +14.5 MB (new file) 🆕
./bundle/chunk-BC6WV2RT.js 3.64 MB +3.64 MB (new file) 🆕
./bundle/core-PC7OSJJP.js 42.4 kB +42.4 kB (new file) 🆕
./bundle/devtoolsService-R7ZR26TS.js 27.7 kB +27.7 kB (new file) 🆕
./bundle/interactiveCli-MV3T35K2.js 1.62 MB +1.62 MB (new file) 🆕
./bundle/oauth2-provider-IUC5WGDZ.js 9.16 kB +9.16 kB (new file) 🆕
ℹ️ View Unchanged
Filename Size
./bundle/chunk-34MYV7JD.js 2.45 kB
./bundle/chunk-5AUYMPVF.js 858 B
./bundle/chunk-5WHECDMU.js 1.95 MB
./bundle/chunk-664ZODQF.js 124 kB
./bundle/chunk-DAHVX5MI.js 206 kB
./bundle/chunk-IUUIT4SU.js 56.5 kB
./bundle/chunk-RJTRUG2J.js 39.8 kB
./bundle/devtools-36NN55EP.js 696 kB
./bundle/dist-T73EYRDX.js 356 B
./bundle/gemini.js 519 kB
./bundle/getMachineId-bsd-TXG52NKR.js 1.55 kB
./bundle/getMachineId-darwin-7OE4DDZ6.js 1.55 kB
./bundle/getMachineId-linux-SHIFKOOX.js 1.34 kB
./bundle/getMachineId-unsupported-5U5DOEYY.js 1.06 kB
./bundle/getMachineId-win-6KLLGOI4.js 1.72 kB
./bundle/memoryDiscovery-DL6LDUAP.js 922 B
./bundle/multipart-parser-KPBZEGQU.js 11.7 kB
./bundle/node_modules/@google/gemini-cli-devtools/dist/client/main.js 221 kB
./bundle/node_modules/@google/gemini-cli-devtools/dist/src/_client-assets.js 227 kB
./bundle/node_modules/@google/gemini-cli-devtools/dist/src/index.js 11.5 kB
./bundle/node_modules/@google/gemini-cli-devtools/dist/src/types.js 132 B
./bundle/sandbox-macos-permissive-open.sb 890 B
./bundle/sandbox-macos-permissive-proxied.sb 1.31 kB
./bundle/sandbox-macos-restrictive-open.sb 3.36 kB
./bundle/sandbox-macos-restrictive-proxied.sb 3.56 kB
./bundle/sandbox-macos-strict-open.sb 4.82 kB
./bundle/sandbox-macos-strict-proxied.sb 5.02 kB
./bundle/src-QVCVGIUX.js 47 kB
./bundle/tree-sitter-7U6MW5PS.js 274 kB
./bundle/tree-sitter-bash-34ZGLXVX.js 1.84 MB

compressed-size-action

@gemini-cli gemini-cli bot added the priority/p3 Backlog - a good idea but not currently a priority. label Mar 16, 2026
@mattKorwel mattKorwel self-assigned this Mar 16, 2026
@mattKorwel mattKorwel added the area/core Issues related to User Interface, OS Support, Core Functionality label Mar 16, 2026
@mattKorwel
Copy link
Collaborator Author

image

@jacob314
Copy link
Contributor

jacob314 commented Mar 17, 2026

Great to see this fixed. Others had tried and failed to fix this. Nit: did you reference the wrong issue? #1680 seems unrelated

Impressively Gemini fixed this as part of the code review noting that you meant issue #16801

Copy link
Contributor

@jacob314 jacob314 left a comment

Choose a reason for hiding this comment

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

Looks great! This is a solid fix for the escape sequences leaking on exit. The reordering of the cleanup sequence and the added mouse disabling sequences to the fallback are very robust.

One minor note: in packages/cli/src/utils/cleanup.ts and the PR description, you reference issue #1680, but the correct issue number for the garbage on exit bug is #16801. Could you update the PR description and the code comment?

Otherwise, the changes look excellent and the test successfully validates the cleanup order.

disableKittyKeyboardProtocol();
disableModifyOtherKeys();
disableBracketedPasteMode();
disableMouseEvents();
Copy link
Contributor

Choose a reason for hiding this comment

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

disableMouseEvents is getting called from AppContainer. that is likely not needed if we are doing it here.
as a follow up we should also track whether we have called enableMouseEvents and make disableMouseEvents a no-op if we have not enabled it. unless you are in alternate buffer mode we have not enabled mouse events.

Copy link
Contributor

@jacob314 jacob314 left a comment

Choose a reason for hiding this comment

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

lgtm

@mattKorwel mattKorwel added this pull request to the merge queue Mar 20, 2026
@mattKorwel mattKorwel removed this pull request from the merge queue due to a manual request Mar 20, 2026
mattKorwel and others added 3 commits March 19, 2026 23:32
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@mattKorwel mattKorwel enabled auto-merge March 20, 2026 06:34
@gemini-cli gemini-cli bot added the 🔒 maintainer only ⛔ Do not contribute. Internal roadmap item. label Mar 23, 2026
@mattKorwel mattKorwel added this pull request to the merge queue Mar 23, 2026
Merged via the queue into main with commit b58d79c Mar 23, 2026
27 checks passed
@mattKorwel mattKorwel deleted the mk-odd-keyoutput branch March 23, 2026 18:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core Issues related to User Interface, OS Support, Core Functionality 🔒 maintainer only ⛔ Do not contribute. Internal roadmap item. priority/p3 Backlog - a good idea but not currently a priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gemini CLI often shows 9;5u on exit in Ghostty

2 participants