Skip to content

Add cancellation button for running tools#3

Open
kentcdodds wants to merge 6 commits intomainfrom
cursor/add-cancellation-button-for-running-tools-22d3
Open

Add cancellation button for running tools#3
kentcdodds wants to merge 6 commits intomainfrom
cursor/add-cancellation-button-for-running-tools-22d3

Conversation

@kentcdodds
Copy link
Copy Markdown
Owner

@kentcdodds kentcdodds commented Jul 30, 2025

Add a cancellation button for tool execution to allow users to stop long-running tool calls.

This PR leverages the existing AbortController infrastructure in makeRequest to provide a user-facing cancellation mechanism for tool calls. An AbortController is now managed in App.tsx for the current tool execution, and a "Cancel" button is displayed in ToolsTab.tsx when a tool is running, allowing users to abort the ongoing request.


Open in Cursor Open in Web

Learn more about Cursor Agents

Summary by CodeRabbit

  • New Features

    • Added the ability to cancel tool calls while they are running.
    • Introduced a "Cancel" button in the Tools tab that appears during tool execution.
    • The "Run Tool" button now shows a loading indicator and is disabled while a tool is running.
  • User Interface

    • Improved feedback for tool execution status, including clear indication when a tool is running or has been cancelled.
  • Tests

    • Added comprehensive tests for tool cancellation logic and UI behavior.
    • Enhanced existing tests to verify button states, cancellation functionality, and proper UI updates during tool execution.

Co-authored-by: me <me@kentcdodds.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 30, 2025

Walkthrough

Cancellation support for tool calls was added to the application. The App component now manages an abort controller for in-flight tool requests, allows users to cancel running tools, and differentiates between cancellation and error states. The ToolsTab component receives new props to enable UI-driven cancellation and reflect tool execution status.

Changes

Cohort / File(s) Change Summary
App Component Tool Cancellation Logic
client/src/App.tsx
Added abort controller state, cancellation logic, concurrency guard, enhanced error handling, and new props for tools.
ToolsTab Component UI and Props
client/src/components/ToolsTab.tsx
Updated to accept cancelTool and isToolRunning props, removed internal running state, added cancel button UI, updated run button behavior.
ToolsTab Component Tests
client/src/components/__tests__/ToolsTab.test.tsx
Refactored and extended tests for run and cancel button behavior, added cancellation UI tests, updated default props.
Tool Cancellation Logic Unit Tests
client/src/__tests__/toolCancellation.unit.test.tsx
Added comprehensive unit tests for tool call cancellation logic, error handling, concurrency, and abort controller lifecycle.
Tool Cancellation Test Documentation
client/CANCELLATION_TESTS.md
Added detailed test suite documentation describing UI and logic tests, coverage, scenarios, and instructions.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ToolsTab
    participant App
    participant ToolAPI

    User->>ToolsTab: Clicks "Run Tool"
    ToolsTab->>App: callTool(name, params)
    App->>ToolAPI: makeRequest(params, { signal })
    Note right of App: Creates AbortController, stores in state
    alt User cancels
        User->>ToolsTab: Clicks "Cancel"
        ToolsTab->>App: cancelTool()
        App->>ToolAPI: abort request via AbortController
        ToolAPI-->>App: Aborted error
        App->>ToolsTab: Set result as cancelled
    else Tool completes
        ToolAPI-->>App: Result
        App->>ToolsTab: Set result as success
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

A hop, a skip, a tool to run,
But sometimes tasks aren’t always fun.
With a twitchy nose, I now can stop,
Abort mid-hop, before I flop!
Buttons gleam, the UI’s neat—
Cancel or run, my work’s complete!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4b9653c and 98ce856.

📒 Files selected for processing (1)
  • client/src/__tests__/toolCancellation.unit.test.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/src/tests/toolCancellation.unit.test.tsx
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cursor/add-cancellation-button-for-running-tools-22d3

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@kentcdodds kentcdodds marked this pull request as ready for review July 30, 2025 19:46

const cancelTool = () => {
if (toolAbortController) {
toolAbortController.abort();
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Tool Call Race Conditions and Cancellation Issues

Concurrent tool calls introduce several race conditions and inconsistencies: Rapid "Run Tool" clicks can overwrite the toolAbortController state, making earlier calls uncancellable. The finally block unconditionally clears toolAbortController, which can prematurely clear the controller for a still-running or subsequent call, leading to an inconsistent UI state (tool appears not running while active) and making the active call uncancellable. Additionally, the cancellation detection logic is unreliable, checking abortController.signal.aborted instead of e.name === 'AbortError', potentially misclassifying natural failures as cancellations. Finally, errors are not cleared upon tool cancellation, leaving stale error messages visible in the UI.

Locations (1)
Fix in Cursor Fix in Web

cursoragent and others added 2 commits July 30, 2025 19:56
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
client/src/components/__tests__/ToolsTab.test.tsx (2)

199-202: Consider using more specific button identification.

The cancel button is identified by { name: "" } which relies on it being an icon-only button. Consider adding a more explicit test identifier or accessible name.

-      const cancelButton = screen.getByRole("button", { name: "" }); // X icon button
+      const cancelButton = screen.getByRole("button", { name: /cancel/i });

Or add an aria-label to the cancel button in the component for better accessibility and testing.


213-220: Same button identification issue in interaction test.

The same pattern of using { name: "" } appears here. Consistent with the previous comment, this should use a more specific identifier.

Apply the same fix as suggested above for better test reliability and accessibility.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86c0bab and 1e51ba4.

📒 Files selected for processing (3)
  • client/CANCELLATION_TESTS.md (1 hunks)
  • client/src/__tests__/toolCancellation.unit.test.tsx (1 hunks)
  • client/src/components/__tests__/ToolsTab.test.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • client/CANCELLATION_TESTS.md
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{ts,tsx}: Use TypeScript with proper type annotations
Use PascalCase for component names and types

Files:

  • client/src/__tests__/toolCancellation.unit.test.tsx
  • client/src/components/__tests__/ToolsTab.test.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{js,jsx,ts,tsx}: Use ES modules (import/export) not CommonJS
Use camelCase for variables and functions
Use async/await for asynchronous operations
Implement proper error handling with try/catch blocks

Files:

  • client/src/__tests__/toolCancellation.unit.test.tsx
  • client/src/components/__tests__/ToolsTab.test.tsx
**/*.{js,jsx,ts,tsx,json,css,md}

📄 CodeRabbit Inference Engine (CLAUDE.md)

Use Prettier for formatting (auto-formatted on commit)

Files:

  • client/src/__tests__/toolCancellation.unit.test.tsx
  • client/src/components/__tests__/ToolsTab.test.tsx
**/*.{js,jsx,ts,tsx,css,scss}

📄 CodeRabbit Inference Engine (CLAUDE.md)

Use kebab-case for file names

Files:

  • client/src/__tests__/toolCancellation.unit.test.tsx
  • client/src/components/__tests__/ToolsTab.test.tsx
🔇 Additional comments (10)
client/src/__tests__/toolCancellation.unit.test.tsx (7)

1-42: Well-structured test setup with comprehensive mocking.

The test setup properly mocks all necessary dependencies and creates realistic error objects for testing different scenarios. The mock implementation for setToolAbortController correctly handles both direct values and function updates.


44-119: Excellent implementation of the core cancellation logic for testing.

The createCallToolFunction accurately mirrors the real implementation with proper:

  • Concurrent call prevention
  • AbortController lifecycle management
  • Race condition protection through controller identity checks
  • Proper error handling for AbortError vs other errors

The logic correctly handles the complex scenarios that could occur in the actual application.


129-171: Thorough testing of concurrent call prevention.

These tests effectively verify that:

  • Multiple concurrent calls are prevented when a tool is already running
  • New calls are allowed after previous calls complete
  • The abort controller state is properly managed

The promise-based approach to simulate long-running requests is well-designed.


173-211: Comprehensive AbortError detection testing.

The tests properly distinguish between cancellation (AbortError) and regular errors, ensuring:

  • AbortError results in cancellation message with isError: false
  • Regular errors are treated as failures with isError: true
  • Appropriate state management for each scenario

213-251: Excellent race condition protection tests.

These tests cover critical edge cases where the abort controller might change during execution, ensuring:

  • State updates are skipped if the controller is no longer active
  • Cleanup only occurs for the correct controller
  • No stale state updates occur

253-274: Solid cancellation function testing.

The tests verify that:

  • cancelTool properly calls abort() on the active controller
  • It handles gracefully when no tool is running
  • No errors are thrown in edge cases

276-309: Comprehensive state lifecycle management tests.

These tests ensure the abort controller is properly managed throughout all scenarios:

  • Normal completion
  • Error conditions
  • Cancellation scenarios
  • Proper cleanup in finally blocks

The assertion counts verify the exact sequence of setter calls.

client/src/components/__tests__/ToolsTab.test.tsx (3)

53-54: Proper addition of new props to test setup.

The cancelTool mock function and isToolRunning boolean are correctly added to defaultProps, aligning with the updated component interface.


139-180: Improved test using explicit state management.

The refactored test is much clearer by using rerender with explicit isToolRunning values instead of relying on promise timing. This approach:

  • Makes the test more deterministic and readable
  • Tests all three states: not running → running → completed
  • Verifies button text and disabled state at each stage

182-264: Comprehensive cancellation UI testing.

The new test suite thoroughly covers:

  • Cancel button visibility based on running state
  • Proper button styling and layout
  • Cancel button interaction and callback invocation
  • Integration between run and cancel buttons
  • Edge cases like no active tool

The tests properly use accessible queries and verify the expected UI behavior.

- Replace 'any' types with proper function signatures
- Use jest.MockedFunction with specific type parameters
- Fix mock function implementations to satisfy TypeScript strict mode
- All tests still pass and linting is clean
- Apply Prettier formatting to unit test file
- Maintain consistent code style across the project
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.

2 participants