Skip to content

feat(cli): add macOS run-event notifications (interactive only)#19056

Draft
LyalinDotCom wants to merge 15 commits intomainfrom
gemini-cli-notification-macos
Draft

feat(cli): add macOS run-event notifications (interactive only)#19056
LyalinDotCom wants to merge 15 commits intomainfrom
gemini-cli-notification-macos

Conversation

@LyalinDotCom
Copy link
Collaborator

Summary

This PR adds macOS notifications for interactive Gemini CLI runs and tightens trigger behavior so notifications only fire for in-run events that require user awareness.

Fixes #14696

Final Behavior

  • Notifications are opt-in via general.enableMacOsNotifications (default: false).
  • Notifications are only attempted on macOS (process.platform === 'darwin').
  • Interactive notifications are emitted only for:
    • action-required states (tool approval, command confirmation, auth consent, filesystem permission confirmation, extension update confirmation, loop detection confirmation, and ask-user prompts)
    • response completion when a turn transitions Responding -> Idle
  • Notifications are not emitted on startup.
  • Notifications are not emitted on shutdown/quit.
  • Notifications are not emitted in headless/non-interactive mode.

Notification Transport

  • Uses terminal-native signaling in the TUI notification utility:
    • OSC 9 when supported terminal hints are detected
    • BEL fallback when OSC 9 is not supported
  • Keeps message content bounded and sanitized for terminal safety.
  • Failures are non-fatal and logged; the CLI does not crash if notification emission fails.

Focus Handling

  • Added focus-state reliability tracking (hasReceivedFocusEvent) so notifications still work when terminals do not emit focus events consistently.
  • When focus events are available, focused terminal state suppresses notifications.
  • When focus events are unavailable, in-run events still notify instead of silently failing.

Settings / Schema / Docs

  • Added general.enableMacOsNotifications to settings schema and docs.
  • Added coverage for schema presence and notification behavior.

Tests

Updated and added tests across:

  • packages/cli/src/utils/macosNotifications.test.ts
  • packages/cli/src/ui/AppContainer.test.tsx
  • packages/cli/src/ui/hooks/useFocus.test.tsx
  • packages/cli/src/gemini.test.tsx

Validated suites include:

  • npm test -w @google/gemini-cli -- src/utils/macosNotifications.test.ts
  • npm test -w @google/gemini-cli -- src/ui/AppContainer.test.tsx src/ui/hooks/useFocus.test.tsx
  • npm test -w @google/gemini-cli -- src/gemini.test.tsx

@LyalinDotCom LyalinDotCom requested review from a team as code owners February 14, 2026 02:21
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @LyalinDotCom, 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 introduces a significant user experience improvement for macOS users of the interactive Gemini CLI by adding native notifications. The primary goal is to alert users to critical interactive prompts or the completion of a response when the CLI application is not in focus, thereby reducing the need for constant monitoring. The implementation carefully considers user preferences, platform specifics, and terminal capabilities to deliver a reliable and non-intrusive notification system.

Highlights

  • macOS Notifications for Interactive CLI: Implemented opt-in macOS native notifications for the interactive Gemini CLI, triggered by action-required states (e.g., tool approval, command confirmation, auth consent, filesystem permissions, extension updates, loop detection, ask-user prompts) and response completion when a turn transitions from 'Responding' to 'Idle'.
  • Refined Notification Triggering: Notifications are now tightly controlled to fire only for in-run events that genuinely require user awareness. They are not emitted on startup, shutdown, or in headless/non-interactive modes. Focus handling logic was added to suppress notifications when the terminal is focused, but still notify if focus events are inconsistently reported by the terminal.
  • Terminal-Native Notification Transport: The system utilizes terminal-native signaling for notifications, preferring OSC 9 when supported by the terminal (e.g., iTerm2, WezTerm, Kitty) and falling back to the BEL character (bell sound) otherwise. Message content is bounded and sanitized for terminal safety, and failures are non-fatal.
  • Configuration and Documentation: A new setting, general.enableMacOsNotifications, was added to the configuration schema and documentation, allowing users to enable or disable this feature. It defaults to false.
  • Enhanced Focus State Tracking: The useFocus hook was refactored into useFocusState to provide more robust tracking of terminal focus, including whether focus events have been reliably received, which improves notification reliability.
  • Comprehensive Testing: New and updated tests were added across macosNotifications.test.ts, AppContainer.test.tsx, useFocus.test.tsx, and gemini.test.tsx to ensure correct behavior of the notification system, focus handling, and schema integration.
Changelog
  • docs/get-started/configuration.md
    • Added documentation for the new general.enableMacOsNotifications setting.
  • packages/cli/src/config/settingsSchema.test.ts
    • Added a test case to verify the presence and properties of the enableMacOsNotifications setting in the schema.
  • packages/cli/src/config/settingsSchema.ts
    • Included the enableMacOsNotifications boolean setting in the general configuration schema, defaulting to false.
  • packages/cli/src/gemini.test.tsx
    • Added hoisted mocks for macOS notification functions (notifyMacOs, buildMacNotificationContent).
    • Asserted that macOS notification functions are not called during non-interactive CLI runs.
  • packages/cli/src/ui/AppContainer.test.tsx
    • Imported ToolCallStatus for new test cases.
    • Added hoisted mocks for macOS notification functions (notifyMacOs, buildMacNotificationContent).
    • Mocked macosNotifications.js and useFocus.js to control notification and focus behavior in tests.
    • Introduced a mock for useFocusState to simulate focus and focus event reception.
    • Added tests to verify macOS notifications are sent for pending confirmations when unfocused or when focus reporting is unavailable.
    • Added tests to verify macOS notifications are not sent for pending confirmations when focused.
    • Added tests to verify macOS notifications are sent upon response completion when unfocused or when focus reporting is unavailable.
  • packages/cli/src/ui/AppContainer.tsx
    • Imported IndividualToolCallDisplay type and buildMacNotificationContent, notifyMacOs, MacOsNotificationEvent from ../utils/macosNotifications.js.
    • Replaced useFocus with useFocusState to leverage detailed focus information.
    • Added helper functions getFirstConfirmingTool and getPendingAttentionNotification to identify notification triggers.
    • Implemented useEffect hooks to manage and trigger macOS notifications based on pending attention states (tool confirmations, auth, etc.) and streaming state changes (response completion).
    • Incorporated logic for notification cooldown, focus suppression, and handling cases where focus events are not consistently reported.
    • Updated the dependency array for the useCallback hook to include settings.
  • packages/cli/src/ui/hooks/useFocus.test.tsx
    • Imported useFocusState alongside useFocus.
    • Added a new test utility renderFocusStateHook to test the useFocusState hook.
    • Added a test to confirm hasReceivedFocusEvent correctly tracks whether any focus event has been received.
  • packages/cli/src/ui/hooks/useFocus.ts
    • Defined FocusState interface to include isFocused and hasReceivedFocusEvent.
    • Refactored useFocus into useFocusState to return the FocusState object.
    • Added hasReceivedFocusEvent state and updated handleData to set it when focus events are detected.
    • Modified the original useFocus export to be a derived value from useFocusState().isFocused.
  • packages/cli/src/utils/macosNotifications.test.ts
    • Added a new test file for macOS notification utilities.
    • Included tests for platform checks, settings enablement, and terminal environment variable detection for OSC 9 support.
    • Verified correct emission of OSC 9 and BEL notifications based on terminal capabilities.
    • Tested error handling for terminal write failures.
    • Validated truncation logic for notification content and the buildMacNotificationContent function for various event types.
  • packages/cli/src/utils/macosNotifications.ts
    • Added a new utility file containing functions for macOS notifications.
    • Defined constants for maximum notification content lengths and terminal escape codes.
    • Implemented MacOsNotificationContent and MacOsNotificationEvent types.
    • Provided normalizeText and truncateForMacNotification for text processing.
    • Created sanitizeNotificationContent to ensure notification content adheres to length limits.
    • Developed buildMacNotificationContent to construct notification messages from various event types.
    • Included isMacOsNotificationEnabled for checking settings and platform.
    • Implemented supportsOsc9Notifications to detect terminal support for OSC 9 escape codes.
    • Added buildTerminalNotificationMessage and stripTerminalControlChars for safe terminal output.
    • Provided emitOsc9Notification and emitBellNotification for sending terminal notifications.
    • Exported notifyMacOs as the main function to send notifications, handling settings, platform, and terminal capabilities.
  • schemas/settings.schema.json
    • Added the enableMacOsNotifications property to the general section of the settings JSON schema, including title, description, markdown description, default value, and type.
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 introduces a valuable feature by adding macOS native notifications for interactive runs, improving user awareness for action-required states and response completions. The implementation is robust, with thoughtful handling of different terminal capabilities (OSC 9 with a BEL fallback) and unreliable focus event reporting. The logic for triggering notifications is comprehensive and well-tested. I've identified one area for improvement regarding string truncation to ensure correct handling of multi-byte Unicode characters, which is detailed in a specific comment. Overall, this is a great addition to the CLI.

Comment on lines 40 to 58
export function truncateForMacNotification(
input: string,
maxChars: number,
): string {
if (maxChars <= 0) {
return '';
}

const normalized = normalizeText(input);
if (normalized.length <= maxChars) {
return normalized;
}

if (maxChars <= ELLIPSIS.length) {
return ELLIPSIS.slice(0, maxChars);
}

return `${normalized.slice(0, maxChars - ELLIPSIS.length)}${ELLIPSIS}`;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The current implementation of truncateForMacNotification uses string.length and string.slice, which operate on UTF-16 code units. This can lead to incorrect truncation and broken characters if the notification text contains multi-byte Unicode characters like emojis or certain international characters.

To ensure correct handling of all Unicode characters, it's better to operate on grapheme clusters.

export function truncateForMacNotification(
  input: string,
  maxChars: number,
): string {
  if (maxChars <= 0) {
    return '';
  }

  const normalized = normalizeText(input);
  const graphemes = Array.from(normalized);

  if (graphemes.length <= maxChars) {
    return normalized;
  }

  if (maxChars <= ELLIPSIS.length) {
    return ELLIPSIS.slice(0, maxChars);
  }

  return `${graphemes.slice(0, maxChars - ELLIPSIS.length).join('')}${ELLIPSIS}`;
}
References
  1. When truncating strings that may contain multi-byte Unicode characters (e.g., emojis), use methods that operate on grapheme clusters (like Intl.Segmenter or Array.from()) instead of UTF-16 code units (string.length, string.slice()) to prevent character splitting.

Copy link
Contributor

Choose a reason for hiding this comment

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

please revert and switch to a standard shared helper method for truncation

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed: replaced bespoke truncation path with shared helpers from ui/utils/textUtils and removed the old macosNotifications module. (commit b8ba941)

@gemini-cli gemini-cli bot added priority/p2 Important but can be addressed in a future release. area/core Issues related to User Interface, OS Support, Core Functionality help wanted We will accept PRs from all issues marked as "help wanted". Thanks for your support! labels Feb 14, 2026
@LyalinDotCom LyalinDotCom marked this pull request as draft February 16, 2026 01:44
@github-actions
Copy link

github-actions bot commented Feb 16, 2026

Size Change: +12.1 kB (+0.05%)

Total Size: 24.4 MB

Filename Size Change
./bundle/gemini.js 24.4 MB +12.1 kB (+0.05%)
ℹ️ View Unchanged
Filename Size
./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

compressed-size-action

Copy link
Contributor

@jackwotherspoon jackwotherspoon left a comment

Choose a reason for hiding this comment

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

What do you think about having the setting be general.enableNotifications instead of general.enableMacOsNotifications to be future proof.

A single setting vs 3 seems nicer to me.

- **Description:** Enable update notification prompts.
- **Default:** `true`

- **`general.enableMacOsNotifications`** (boolean):
Copy link
Contributor

Choose a reason for hiding this comment

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

I think i would rather see this be future proof. With the description saying macOS only.

That way we don't have 3 different settings in our docs and /settings.

We already do a darwin check i believe so for now this setting would be a no-op for non macOS users.

Suggested change
- **`general.enableMacOsNotifications`** (boolean):
- **`general.enableNotifications`** (boolean):

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed: renamed to general.enableNotifications and updated schema/docs/settings UI. behavior remains darwin-gated and no-op on non-macOS. (commit b8ba941)

!!validationRequest ||
!!customDialog;

const pendingAttentionNotification = useMemo(
Copy link
Contributor

@jacob314 jacob314 Feb 16, 2026

Choose a reason for hiding this comment

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

this needs to be its own hook and needs to be refactored to be integrated with hooks

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed: moved notification side effect and transition logic out of AppContainer into useRunEventNotifications and integrated it with existing hooks/selectors. (commit b8ba941)

export function supportsOsc9Notifications(
env: NodeJS.ProcessEnv = process.env,
): boolean {
if (env['WT_SESSION']) {
Copy link
Contributor

Choose a reason for hiding this comment

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

there has to be a better way to check for OSC9 notification support. this is way too hard coded and has dupes (e.g. WzTerm and wezterm). Typically there are capability detection queries you can run or other terminal capabilities you can link to. For example, do Kitty compatible terminals typically support this?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed: tightened OSC9 support detection and now pass terminal capability-query signal (terminalName from terminalCapabilityManager) into the decision path. (commit b8ba941)

const ELLIPSIS = '...';
const BEL = '\x07';
const OSC9_PREFIX = '\x1b]9;';
const MAX_OSC9_MESSAGE_CHARS = 220;
Copy link
Contributor

Choose a reason for hiding this comment

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

why is this 220?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed: removed the hardcoded 220 literal. OSC9 payload limit is now derived from title/subtitle/body caps plus separator length. (commit b8ba941)

const PM_START_CODE = '^'.charCodeAt(0);
const APC_START_CODE = '_'.charCodeAt(0);

let graphemeSegmenter: Intl.Segmenter | undefined;
Copy link
Contributor

Choose a reason for hiding this comment

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

need to reuse existing truncation code rather than writing another version.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed: reused existing shared truncation/sanitization utilities instead of maintaining a separate truncation implementation. (commit b8ba941)

const originalPlatform = process.platform;
const originalTermProgram = process.env['TERM_PROGRAM'];
const originalTerm = process.env['TERM'];
const originalItTermSessionId = process.env['ITERM_SESSION_ID'];
Copy link
Contributor

Choose a reason for hiding this comment

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

ITERM_SESSION_ID should not be used as it will mean an vscode window opened from iterm will be incorrectly classified as iterm

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed: removed ITERM_SESSION_ID usage from detection/tests to avoid VSCode launched from iTerm misclassification. (commit b8ba941)


beforeEach(() => {
vi.resetAllMocks();
delete process.env['TERM_PROGRAM'];
Copy link
Contributor

Choose a reason for hiding this comment

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

this is not how env vars are mocked in the project

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed: updated tests to follow project env-mocking conventions via vi.stubEnv and vi.unstubAllEnvs. (commit b8ba941)

@@ -0,0 +1,276 @@
/**
Copy link
Contributor

Choose a reason for hiding this comment

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

This whole file is named wrong OSC9 works on terminals that are not Mac.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed: renamed the module from macosNotifications.ts to terminalNotifications.ts to match OSC9 plus BEL terminal transport scope. (commit b8ba941)

return true;
}

if (env['ITERM_SESSION_ID']) {
Copy link
Contributor

Choose a reason for hiding this comment

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

you must use TERM_PROGRAM for ITERM so avoid the IDEs launched from ITERM issue.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed: iTerm detection now relies on TERM_PROGRAM and terminal-name signatures; ITERM_SESSION_ID check is removed. (commit b8ba941)

@gemini-cli gemini-cli bot added the 🔒 maintainer only ⛔ Do not contribute. Internal roadmap item. label Feb 16, 2026
@LyalinDotCom
Copy link
Collaborator Author

I caught a few things I want to clean up before we merge.

[ ] Refactor AppContainer: I realized I put too much one-off notification logic here. I’m going to move the state transitions into a dedicated hook composed of our existing selectors.

[ ] DRY up string handling: I'm going to swap my bespoke string pipeline for the shared truncation/sanitization helpers we already have.

[ ] Fix logic duplication: I need to reuse the existing confirmation queue/head selection logic rather than duplicating the pending-tool traversal.

[ ] Terminal Capabilities: I'll replace the hardcoded OSC9 allowlists with actual capability detection (or at least centralized constants) and document the fallback paths.

[ ] Magic Numbers: I need to remove the magic numbers (like the 220 cap) and encode them as documented constraints.

[ ] Tests: I need to align the tests with vi.stubEnv conventions and add behavior tests for the cooldown/repeated prompts to ensure I haven't regressed notification delivery.

[ ] Naming: I’m going to rename the scope to reflect transport semantics (OSC9 + BEL) rather than platform branding.

@LyalinDotCom
Copy link
Collaborator Author

Following up on my checklist, here is what I have fixed:

  • Refactor AppContainer: I've fixed this by moving run-event notification transitions/effects into useRunEventNotifications and wiring it through existing hooks/selectors.
  • DRY up string handling: I've fixed this by replacing the bespoke notification string pipeline with shared helpers from ui/utils/textUtils.
  • Fix logic duplication: I've fixed this by extracting/reusing shared confirming-tool queue logic (getConfirmingToolState) instead of duplicating traversal.
  • Terminal capabilities: I've fixed this by tightening OSC9 detection and passing terminal capability-query signal (terminalName) into notification support checks, with BEL fallback preserved.
  • Magic numbers: I've fixed this by removing the hardcoded 220 and deriving OSC9 payload limits from title/subtitle/body caps + separator.
  • Tests: I've fixed this by aligning env mocking to vi.stubEnv/vi.unstubAllEnvs and adding behavior coverage for repeated prompt delivery / notification gating.
  • Naming: I've fixed this by renaming macosNotifications to terminalNotifications so scope matches transport semantics (OSC9 + BEL).

Implemented in commit b8ba941dd (with follow-up branch sync/review cleanup commits after that).

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 help wanted We will accept PRs from all issues marked as "help wanted". Thanks for your support! 🔒 maintainer only ⛔ Do not contribute. Internal roadmap item. priority/p2 Important but can be addressed in a future release.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement Desktop Notification for User Permission Prompts

3 participants