gemini-cli icon indicating copy to clipboard operation
gemini-cli copied to clipboard

fix: enable cancellation of slash commands and background processes

Open akhil29 opened this issue 5 months ago • 6 comments

Summary

Enables proper cancellation when users press Escape during slash command execution, including termination of background processes spawned by shell commands. Addresses issue #6066 where slash commands did not respect the top-level cancellation signal.

Key Changes

  • AbortSignal propagation: Added signal parameter to slash command processor chain
  • Background process termination: Implemented killAllBackgroundProcesses() with cross-platform support
  • Global PID tracking: Added tracking for background processes across async boundaries
  • Signal integration: Connected cancellation hooks throughout command execution flow
  • Comprehensive tests: Added test coverage for new functionality

Technical Implementation

Core Cancellation Flow

  1. User presses Escape → useGeminiStream.cancelOngoingRequest()
  2. Calls killAllBackgroundProcesses() to terminate spawned processes
  3. AbortSignal propagates through handleSlashCommandcreateCommandContext
  4. Commands receive signal and can respond to cancellation appropriately

Background Process Management

  • Cross-platform termination: Uses process groups (SIGTERM/SIGKILL) on Unix, taskkill on Windows
  • Global PID tracking: Maintains Set of background PIDs for cleanup on cancellation
  • Graceful shutdown: SIGTERM followed by SIGKILL after timeout

Code Quality Improvements

  • Refactored to useCallback: Addressed memoization code smell from PR feedback
  • Signal parameter pattern: Changed from creating dummy signals to accepting signal as parameter
  • App-level AbortController: Added for programmatic command lifecycle management

Test Coverage

  • Background process termination: Tests Unix/Windows process killing, error handling, PID tracking
  • Integration tests: Verifies cancellation flow in useGeminiStream
  • Signal propagation: Tests AbortSignal parameter passing through command chain
  • Cross-platform support: Tests both Unix and Windows process termination methods

Fixes

  • Background processes now properly terminate when cancellation occurs (addresses #6066)
  • Shell commands like /tmp/long_counter.sh & can be cancelled with Escape
  • Proper signal propagation prevents zombie processes and resource leaks
  • useCallback pattern eliminates memoization code smell from previous implementation

Fixes #6066

akhil29 avatar Sep 05 '25 12:09 akhil29