Skip to content

Conversation

@ericcurtin
Copy link
Contributor

@ericcurtin ericcurtin commented Oct 15, 2025

Add Ctrl+C handling to basic interactive mode for consistency

Summary by Sourcery

Add context cancellation support for Ctrl+C during model response generation by integrating cancellable contexts and signal handling into interactive commands and HTTP client calls

Enhancements:

  • Enable Ctrl+C to cancel streaming chat responses in both basic and readline interactive modes
  • Refactor chat functions by introducing chatWithMarkdownContext and updating chatWithMarkdown to use a cancellable context
  • Extend the desktop client with ChatWithContext and doRequestWithAuthContext to propagate context cancellation through HTTP requests

Copilot AI review requested due to automatic review settings October 15, 2025 13:13
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 15, 2025

Reviewer's Guide

This PR adds Ctrl+C support for cancelling model responses in the interactive CLI by wrapping chat invocations in a cancellable context with signal handling and propagating that context through new context-aware chat and HTTP request APIs.

Sequence diagram for Ctrl+C cancellation during model response

sequenceDiagram
    actor User
    participant CLI
    participant DesktopClient
    participant ModelAPI
    User->>CLI: Enter prompt
    CLI->>DesktopClient: ChatWithContext(ctx, ...)
    DesktopClient->>ModelAPI: doRequestWithAuthContext(ctx, ...)
    ModelAPI-->>DesktopClient: Stream response
    DesktopClient-->>CLI: Stream content
    User-->>CLI: Press Ctrl+C
    CLI->>CLI: Cancel context
    CLI->>DesktopClient: Context cancelled
    DesktopClient->>ModelAPI: Abort request
    ModelAPI-->>DesktopClient: Return context.Canceled
    DesktopClient-->>CLI: Return context.Canceled
    CLI->>User: Print cancellation message
Loading

Class diagram for updated context-aware chat and request methods

classDiagram
    class Client {
        +Chat(backend, model, prompt, apiKey, outputFunc, shouldUseMarkdown) error
        +ChatWithContext(ctx, backend, model, prompt, apiKey, outputFunc, shouldUseMarkdown) error
        +doRequestWithAuth(method, path, body, backend, apiKey) (*http.Response, error)
        +doRequestWithAuthContext(ctx, method, path, body, backend, apiKey) (*http.Response, error)
    }
    Client <|-- ChatWithContext
    Client <|-- doRequestWithAuthContext
    ChatWithContext ..> doRequestWithAuthContext: uses context for cancellation
Loading

Flow diagram for signal handling and context cancellation in CLI

flowchart TD
    A["User input received"] --> B["Create cancellable context"]
    B --> C["Set up signal handler for Ctrl+C"]
    C --> D["Start chatWithMarkdownContext with context"]
    D --> E["User presses Ctrl+C?"]
    E -- Yes --> F["Cancel context"]
    F --> G["Abort chat request and clean up"]
    E -- No --> H["Continue streaming response"]
Loading

File-Level Changes

Change Details Files
Add Ctrl+C cancellation wrapper for interactive chat commands
  • Wrap interactive chat calls in a cancellable context
  • Set up SIGINT handler to invoke cancel on Ctrl+C
  • Replace chatWithMarkdown calls with chatWithMarkdownContext
  • Handle context.Canceled errors to suppress error output and print exit hints
cmd/cli/commands/run.go
Introduce chatWithMarkdownContext for context-aware streaming
  • Add chatWithMarkdownContext function accepting a context
  • Update chatWithMarkdown to forward to the new context variant
  • Use client.ChatWithContext inside both markdown and plain streams
cmd/cli/commands/run.go
Extend desktop client APIs with context support
  • Add ChatWithContext method accepting a context
  • Implement doRequestWithAuthContext using http.NewRequestWithContext
  • Modify Chat to delegate to ChatWithContext with background context
  • Check ctx.Done during streaming to respect cancellations
cmd/cli/desktop/desktop.go

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @ericcurtin, 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 enhances the command-line interface's interactive mode by integrating context cancellation. Users can now gracefully interrupt long-running model responses using Ctrl+C, providing a more responsive and controlled user experience during interactive sessions.

Highlights

  • Context Cancellation: Implemented context.Context to allow for the cancellation of ongoing model responses, particularly when the user presses Ctrl+C.
  • Ctrl+C Handling: Added signal handling for SIGINT (Ctrl+C) in the interactive chat modes, which triggers the cancellation of the active chat request.
  • API Refactoring: Refactored the chatWithMarkdown and Client.Chat functions to introduce chatWithMarkdownContext and Client.ChatWithContext respectively, enabling context propagation throughout the chat request lifecycle.
  • Error Handling: Improved error handling to specifically detect and respond to context.Canceled errors, providing a cleaner exit or message to the user.
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

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • The Ctrl+C signal handling code is duplicated in both interactive loops—consider extracting it into a reusable helper to DRY up and simplify cleanup.
  • Instead of setting up signal.Notify and a goroutine for every chat invocation, you could wire SIGINT cancellation into the root context at startup and pass that down to chatWithMarkdownContext for simpler, centralized handling.
  • Since you’ve introduced ChatWithContext and doRequestWithAuthContext, consider marking the old Chat and doRequestWithAuth methods as deprecated or removing them to avoid confusion and ensure consistent use of context-aware APIs.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The Ctrl+C signal handling code is duplicated in both interactive loops—consider extracting it into a reusable helper to DRY up and simplify cleanup.
- Instead of setting up signal.Notify and a goroutine for every chat invocation, you could wire SIGINT cancellation into the root context at startup and pass that down to chatWithMarkdownContext for simpler, centralized handling.
- Since you’ve introduced ChatWithContext and doRequestWithAuthContext, consider marking the old Chat and doRequestWithAuth methods as deprecated or removing them to avoid confusion and ensure consistent use of context-aware APIs.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds support for Ctrl+C cancellation during model response generation in both interactive modes (readline and basic). When a user presses Ctrl+C while the model is responding, the request is now gracefully cancelled instead of terminating the entire CLI session.

Key changes:

  • Added context-aware versions of chat methods (ChatWithContext, chatWithMarkdownContext) to support cancellation
  • Implemented signal handlers in both interactive modes to detect Ctrl+C and cancel ongoing requests
  • Updated HTTP request methods to accept and propagate context for proper cancellation

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
cmd/cli/desktop/desktop.go Added context-aware variants of Chat and doRequestWithAuth methods, with cancellation checks in the response streaming loop
cmd/cli/commands/run.go Implemented Ctrl+C signal handling in both interactive modes and updated to use new context-aware chat methods

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Copilot AI review requested due to automatic review settings October 15, 2025 13:15
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.


Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

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 adds support for canceling model responses using Ctrl+C. The implementation correctly uses context.Context to propagate cancellation signals through the call stack, from the command-line interface down to the HTTP requests. My review includes suggestions to improve the robustness of the signal handling goroutine and to refactor duplicated code for better maintainability.

Comment on lines +215 to +216
select {
case <-sigChan:
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The current implementation of the signal-handling goroutine can be made more robust and idiomatic. A select statement listening on both the signal channel and the context's Done() channel will prevent the goroutine from leaking if the operation completes without a signal, and makes the cleanup path clearer. When cancelChat() is called during cleanup, the chatCtx.Done() case will be triggered, allowing the goroutine to exit gracefully.

This same improvement should be applied to the similar logic in generateInteractiveBasic at lines 271-272.

select {
case <-sigChan:
    cancelChat()
case <-chatCtx.Done():
}

Comment on lines 207 to 235
// Create a cancellable context for the chat request
// This allows us to cancel the request if the user presses Ctrl+C during response generation
chatCtx, cancelChat := context.WithCancel(context.Background())

// Set up signal handler to cancel the context on Ctrl+C
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT)
go func() {
select {
case <-sigChan:
cancelChat()
case <-chatCtx.Done():
// Context cancelled, exit goroutine
}
}()

err := chatWithMarkdownContext(chatCtx, cmd, desktopClient, backend, model, userInput, apiKey)

// Clean up signal handler
signal.Stop(sigChan)
close(sigChan)
cancelChat()

if err != nil {
// Check if the error is due to context cancellation (Ctrl+C during response)
if errors.Is(err, context.Canceled) {
cmd.Println()
} else {
cmd.PrintErr(handleClientError(err, "Failed to generate a response"))
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This block of code for setting up context cancellation and signal handling is almost identical to the one in generateInteractiveBasic (lines 263-290). This duplication can make future maintenance harder.

To improve maintainability, please consider refactoring this logic into a shared helper function.

@ericcurtin ericcurtin force-pushed the implement-exit-behavior branch from 303a652 to 0c13915 Compare October 15, 2025 13:16
Copilot AI review requested due to automatic review settings October 15, 2025 13:17
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.


Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

@ericcurtin ericcurtin force-pushed the implement-exit-behavior branch from aa642e7 to 51f035a Compare October 15, 2025 13:18
Copilot AI review requested due to automatic review settings October 15, 2025 13:23
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.


Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Copilot AI review requested due to automatic review settings October 15, 2025 13:25
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.


Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

cancelChat()
case <-chatCtx.Done():
// Context cancelled, exit goroutine
// Context cancelled, exit goroutine
Copy link

Copilot AI Oct 15, 2025

Choose a reason for hiding this comment

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

Duplicate comment on line 280; remove the redundant entry.

Suggested change
// Context cancelled, exit goroutine

Copilot uses AI. Check for mistakes.
Add Ctrl+C handling to basic interactive mode for consistency

Signed-off-by: Eric Curtin <eric.curtin@docker.com>
@ericcurtin ericcurtin force-pushed the implement-exit-behavior branch from 6511d31 to 8b98ec5 Compare October 15, 2025 13:27
@ericcurtin ericcurtin merged commit 97a5f3e into main Oct 15, 2025
4 of 5 checks passed
@ericcurtin ericcurtin deleted the implement-exit-behavior branch October 15, 2025 13:27
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.

3 participants