From 0bdb24695d6bea5e30b5c1bd2b48328bdf389eac Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 12:30:47 -0700 Subject: [PATCH 01/11] cai: mention continue workflow --- .github/workflows/respond-to-cubic.yaml | 215 ++++++++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 .github/workflows/respond-to-cubic.yaml diff --git a/.github/workflows/respond-to-cubic.yaml b/.github/workflows/respond-to-cubic.yaml new file mode 100644 index 000000000..5d3f40c56 --- /dev/null +++ b/.github/workflows/respond-to-cubic.yaml @@ -0,0 +1,215 @@ +name: Respond to @continuedev Comments + +on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + +permissions: + contents: write + pull-requests: write + issues: write + +jobs: + respond-to-comment: + # Only run on pull request comments + if: github.event_name == 'issue_comment' && github.event.issue.pull_request + runs-on: ubuntu-latest + + steps: + - name: Check if comment contains @continuedev + id: check-mention + run: | + if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then + echo "contains_mention=true" >> $GITHUB_OUTPUT + else + echo "contains_mention=false" >> $GITHUB_OUTPUT + fi + + - name: Checkout PR branch + if: steps.check-mention.outputs.contains_mention == 'true' + uses: actions/checkout@v4 + with: + token: ${{ secrets.GITHUB_TOKEN }} + fetch-depth: 0 + + - name: Get PR information + if: steps.check-mention.outputs.contains_mention == 'true' + id: pr-info + uses: actions/github-script@v7 + with: + script: | + const { data: pr } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.issue.number + }); + + core.setOutput('head_ref', pr.head.ref); + core.setOutput('head_sha', pr.head.sha); + return pr; + + - name: Checkout PR branch + if: steps.check-mention.outputs.contains_mention == 'true' + run: | + git checkout ${{ steps.pr-info.outputs.head_ref }} + + - name: Setup Node.js + if: steps.check-mention.outputs.contains_mention == 'true' + uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install Continue CLI globally + if: steps.check-mention.outputs.contains_mention == 'true' + run: npm i -g @continuedev/cli + + - name: Start remote session + if: steps.check-mention.outputs.contains_mention == 'true' + id: remote-session + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + run: | + # Create the prompt for remote session + PROMPT="Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}: + + ${{ github.event.comment.body }} + + Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch." + + # Start remote session and capture JSON output + SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --branch ${{ steps.pr-info.outputs.head_ref }}) + echo "Raw session output: $SESSION_OUTPUT" + + # Extract URL from JSON output + SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') + + if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then + echo "Failed to extract session URL from output: $SESSION_OUTPUT" + exit 1 + fi + + echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT + echo "✅ Started remote session: $SESSION_URL" + + - name: Comment with session URL + if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url + uses: actions/github-script@v7 + with: + script: | + const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request: + > ${{ github.event.comment.body }}`; + + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + body: commentBody + }); + + - name: Log session details + if: steps.check-mention.outputs.contains_mention == 'true' + run: | + echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}" + echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" + echo "Original comment: ${{ github.event.comment.body }}" + + respond-to-review-comment: + # Only run on pull request review comments + if: github.event_name == 'pull_request_review_comment' + runs-on: ubuntu-latest + + steps: + - name: Check if comment contains @continuedev + id: check-mention + run: | + if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then + echo "contains_mention=true" >> $GITHUB_OUTPUT + else + echo "contains_mention=false" >> $GITHUB_OUTPUT + fi + + - name: Checkout PR branch + if: steps.check-mention.outputs.contains_mention == 'true' + uses: actions/checkout@v4 + with: + token: ${{ secrets.GITHUB_TOKEN }} + fetch-depth: 0 + ref: ${{ github.event.pull_request.head.ref }} + + - name: Setup Node.js + if: steps.check-mention.outputs.contains_mention == 'true' + uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install Continue CLI globally + if: steps.check-mention.outputs.contains_mention == 'true' + run: npm i -g @continuedev/cli + + - name: Start remote session + if: steps.check-mention.outputs.contains_mention == 'true' + id: remote-session + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + run: | + # Create a temporary file for the prompt to handle special characters and newlines properly + cat > /tmp/prompt.txt << 'PROMPT_EOF' + Please help with the following code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}: + + **File:** ${{ github.event.comment.path }} + **Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }} + **Comment:** ${{ github.event.comment.body }} + + Please analyze the specific file and line mentioned, understand the review feedback, implement the necessary changes, and commit them to this branch. + PROMPT_EOF + + # Debug output + echo "PROMPT content:" + cat /tmp/prompt.txt + + # Start remote session and capture JSON output + echo "Starting cn with prompt..." + SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --branch ${{ github.event.pull_request.head.ref }}) + echo "Raw session output: $SESSION_OUTPUT" + + # Extract URL from JSON output + SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') + + if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then + echo "Failed to extract session URL from output: $SESSION_OUTPUT" + exit 1 + fi + + echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT + echo "✅ Started remote session: $SESSION_URL" + + - name: Comment with session URL + if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url + uses: actions/github-script@v7 + with: + script: | + const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request: + > ${{ github.event.comment.body }}`; + + const commentParams = { + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: ${{ github.event.pull_request.number }}, + body: commentBody, + commit_id: '${{ github.event.pull_request.head.sha }}', + path: '${{ github.event.comment.path }}', + in_reply_to: ${{ github.event.comment.id }} + }; + + await github.rest.pulls.createReviewComment(commentParams); + + - name: Log session details + if: steps.check-mention.outputs.contains_mention == 'true' + run: | + echo "✅ Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}" + echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" + echo "File: ${{ github.event.comment.path }}" + echo "Line: ${{ github.event.comment.line }}" + echo "Original comment: ${{ github.event.comment.body }}" From 141b3e91934dcdb20ae402bfaa2fcd1bed863977 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 13:14:28 -0700 Subject: [PATCH 02/11] feat: show session title in /info output --- extensions/cli/src/slashCommands.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index adcc15267..a739cc450 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -8,7 +8,7 @@ import { } from "./auth/workos.js"; import { getAllSlashCommands } from "./commands/commands.js"; import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; -import { getSessionFilePath } from "./session.js"; +import { getCurrentSession, getSessionFilePath } from "./session.js"; import { posthogService } from "./telemetry/posthogService.js"; import { SlashCommandResult } from "./ui/hooks/useChat.types.js"; import { getVersion } from "./version.js"; @@ -179,12 +179,19 @@ async function handleInfo() { infoLines.push(` ${chalk.red("Configuration service not available")}`); } - // Session history path + // Session info infoLines.push(""); - infoLines.push(chalk.white("Session History:")); - const sessionFilePath = getSessionFilePath(); - - infoLines.push(` File: ${chalk.blue(sessionFilePath)}`); + infoLines.push(chalk.white("Session:")); + try { + const currentSession = getCurrentSession(); + infoLines.push(` Title: ${chalk.green(currentSession.title)}`); + infoLines.push(` ID: ${chalk.gray(currentSession.sessionId)}`); + + const sessionFilePath = getSessionFilePath(); + infoLines.push(` File: ${chalk.blue(sessionFilePath)}`); + } catch { + infoLines.push(` ${chalk.red("Session not available")}`); + } return { exit: false, From 75b5bc9e8bb171a2ab853bd7254a0ad31a406f55 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 13:16:11 -0700 Subject: [PATCH 03/11] remove log --- core/util/chatDescriber.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 9c5c5c96b..873d07327 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -103,7 +103,6 @@ export class ChatDescriber { return undefined; } catch (error) { - console.debug("Error generating chat title:", error); return undefined; } } From 8517fd57bd826a83e65b7c4b7501f9b01e92d558 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 13:39:17 -0700 Subject: [PATCH 04/11] feat: pause and resume --- extensions/cli/src/ui/TUIChat.tsx | 2 + extensions/cli/src/ui/UserInput.tsx | 23 +- .../TUIChat.interruption.minimal.test.tsx | 198 ++++++++++++++++++ .../cli/src/ui/components/ScreenContent.tsx | 3 + extensions/cli/src/ui/hooks/useChat.ts | 60 +++++- packages/openai-adapters/package-lock.json | 1 + 6 files changed, 274 insertions(+), 13 deletions(-) create mode 100644 extensions/cli/src/ui/__tests__/TUIChat.interruption.minimal.test.tsx diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 3c0ac26df..2b6ce883a 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -188,6 +188,7 @@ const TUIChat: React.FC = ({ responseStartTime, inputMode, activePermissionRequest, + wasInterrupted, handleUserMessage, handleInterrupt, handleFileAttached, @@ -318,6 +319,7 @@ const TUIChat: React.FC = ({ handleInterrupt={handleInterrupt} handleFileAttached={handleFileAttached} isInputDisabled={isInputDisabled} + wasInterrupted={wasInterrupted} isRemoteMode={isRemoteMode} /> diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index cb0014952..86c2f1874 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -25,6 +25,7 @@ interface UserInputProps { inputMode: boolean; onInterrupt?: () => void; assistant?: AssistantConfig; + wasInterrupted?: boolean; onFileAttached?: (filePath: string, content: string) => void; disabled?: boolean; placeholder?: string; @@ -38,6 +39,7 @@ const UserInput: React.FC = ({ inputMode, onInterrupt, assistant, + wasInterrupted = false, onFileAttached, disabled = false, placeholder, @@ -406,12 +408,18 @@ const UserInput: React.FC = ({ return true; } - // Normal Enter behavior - submit if there's content - if (textBuffer.text.trim() && !isWaitingForResponse) { + // Normal Enter behavior - submit if there's content OR if resuming after interruption + if ((textBuffer.text.trim() || wasInterrupted) && !isWaitingForResponse) { // Expand all paste blocks before submitting textBuffer.expandAllPasteBlocks(); const submittedText = textBuffer.text.trim(); - inputHistory.addEntry(submittedText); + + // Only add to history if there's actual text (not when resuming) + if (submittedText) { + inputHistory.addEntry(submittedText); + } + + // Send empty string when resuming, actual text otherwise onSubmit(submittedText); textBuffer.clear(); setInputText(""); @@ -638,6 +646,15 @@ const UserInput: React.FC = ({ return ( + {/* Interruption message - shown just above the input box */} + {wasInterrupted && ( + + + ⚠ Interrupted by user - Press enter to resume + + + )} + {/* Input box */} { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.clearAllTimers(); + vi.useRealTimers(); + }); + + it("shows interruption message when wasInterrupted is true", () => { + const mockOnSubmit = vi.fn(); + const mockOnInterrupt = vi.fn(); + + const { lastFrame, rerender, unmount } = render( + React.createElement(UserInput, { + onSubmit: mockOnSubmit, + isWaitingForResponse: false, + inputMode: true, + onInterrupt: mockOnInterrupt, + wasInterrupted: false, // Initially false + }) + ); + + try { + // Initial render - no interruption message + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("⚠ Interrupted by user"); + expect(frame).not.toContain("Press enter to resume"); + + // Re-render with wasInterrupted: true + rerender( + React.createElement(UserInput, { + onSubmit: mockOnSubmit, + isWaitingForResponse: false, + inputMode: true, + onInterrupt: mockOnInterrupt, + wasInterrupted: true, // Now true + }) + ); + + // Should show interruption message + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("⚠ Interrupted by user"); + expect(frame).toContain("Press enter to resume"); + + } finally { + unmount(); + } + }); + + it("hides interruption message when wasInterrupted is false", () => { + const mockOnSubmit = vi.fn(); + const mockOnInterrupt = vi.fn(); + + const { lastFrame, rerender, unmount } = render( + React.createElement(UserInput, { + onSubmit: mockOnSubmit, + isWaitingForResponse: false, + inputMode: true, + onInterrupt: mockOnInterrupt, + wasInterrupted: true, // Initially true + }) + ); + + try { + // Initial render - should show interruption message + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("⚠ Interrupted by user"); + expect(frame).toContain("Press enter to resume"); + + // Re-render with wasInterrupted: false + rerender( + React.createElement(UserInput, { + onSubmit: mockOnSubmit, + isWaitingForResponse: false, + inputMode: true, + onInterrupt: mockOnInterrupt, + wasInterrupted: false, // Now false + }) + ); + + // Should not show interruption message + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("⚠ Interrupted by user"); + expect(frame).not.toContain("Press enter to resume"); + + } finally { + unmount(); + } + }); + + it("calls onSubmit with empty string when Enter is pressed while interrupted", () => { + const mockOnSubmit = vi.fn(); + const mockOnInterrupt = vi.fn(); + + const { stdin, unmount } = render( + React.createElement(UserInput, { + onSubmit: mockOnSubmit, + isWaitingForResponse: false, + inputMode: true, + onInterrupt: mockOnInterrupt, + wasInterrupted: true, // Interrupted state + }) + ); + + try { + // Press Enter while in interrupted state + stdin.write("\r"); + + // Should call onSubmit with empty string (for resume) + expect(mockOnSubmit).toHaveBeenCalledWith(""); + + } finally { + unmount(); + } + }); + + it("calls onSubmit with typed content when typing new message after interruption", () => { + const mockOnSubmit = vi.fn(); + const mockOnInterrupt = vi.fn(); + + const { stdin, unmount } = render( + React.createElement(UserInput, { + onSubmit: mockOnSubmit, + isWaitingForResponse: false, + inputMode: true, + onInterrupt: mockOnInterrupt, + wasInterrupted: true, // Interrupted state + }) + ); + + try { + // Type a new message + stdin.write("New message after interruption"); + stdin.write("\r"); + + // Should call onSubmit with the typed content + expect(mockOnSubmit).toHaveBeenCalledWith("New message after interruption"); + + } finally { + unmount(); + } + }); + + it("shows interruption message above input box in correct position", () => { + const mockOnSubmit = vi.fn(); + const mockOnInterrupt = vi.fn(); + + const { lastFrame, unmount } = render( + React.createElement(UserInput, { + onSubmit: mockOnSubmit, + isWaitingForResponse: false, + inputMode: true, + onInterrupt: mockOnInterrupt, + wasInterrupted: true, + }) + ); + + try { + const frame = lastFrame(); + expect(frame).toBeDefined(); + + // The interruption message should appear before the input box + const frameLines = frame?.split('\n') || []; + + let foundInterruptionLine = -1; + let foundInputBoxLine = -1; + + frameLines.forEach((line, index) => { + if (line.includes("⚠ Interrupted by user")) { + foundInterruptionLine = index; + } + if (line.includes("●") && line.includes("▋")) { + foundInputBoxLine = index; + } + }); + + // Interruption message should come before the input box + expect(foundInterruptionLine).toBeGreaterThan(-1); + expect(foundInputBoxLine).toBeGreaterThan(-1); + expect(foundInterruptionLine).toBeLessThan(foundInputBoxLine); + + } finally { + unmount(); + } + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 16b9ebb5a..a5c51630d 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -36,6 +36,7 @@ interface ScreenContentProps { handleInterrupt: () => void; handleFileAttached: (filePath: string, content: string) => void; isInputDisabled: boolean; + wasInterrupted?: boolean; isRemoteMode: boolean; } @@ -57,6 +58,7 @@ export const ScreenContent: React.FC = ({ handleInterrupt, handleFileAttached, isInputDisabled, + wasInterrupted = false, isRemoteMode, }) => { // Login prompt @@ -147,6 +149,7 @@ export const ScreenContent: React.FC = ({ inputMode={inputMode} onInterrupt={handleInterrupt} assistant={services.config?.config || undefined} + wasInterrupted={wasInterrupted} onFileAttached={handleFileAttached} disabled={isInputDisabled} isRemoteMode={isRemoteMode} diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 290fcd3b7..78142286e 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -106,6 +106,12 @@ export function useChat({ return null; }); + // Track interrupted history for resume functionality + const [interruptedHistory, setInterruptedHistory] = useState< + ChatHistoryItem[] | null + >(null); + const [wasInterrupted, setWasInterrupted] = useState(false); + // Clean up abort controller on unmount useEffect(() => { return () => { @@ -256,6 +262,32 @@ export function useChat({ }; const handleUserMessage = async (message: string) => { + // Check if this is a resume request (empty message after interruption) + if (message === "" && wasInterrupted && interruptedHistory) { + // Get the last user message to resume + const lastUserMessage = interruptedHistory[interruptedHistory.length - 1]; + if (lastUserMessage && lastUserMessage.message.role === "user") { + const originalMessage = lastUserMessage.message.content; + const messageString = typeof originalMessage === "string" + ? originalMessage + : originalMessage.map(part => part.type === "text" ? part.text : "").join(""); + + // Clear the interrupted state and resume + setWasInterrupted(false); + setInterruptedHistory(null); + + // Re-execute streaming with the clean history + await executeStreamingResponse(interruptedHistory, compactionIndex, messageString); + return; + } + } + + // Clear interrupted state if user types a new message + if (wasInterrupted && message !== "") { + setWasInterrupted(false); + setInterruptedHistory(null); + } + // Handle special commands const handled = await handleSpecialCommands({ message, @@ -372,16 +404,23 @@ export function useChat({ // Local mode: abort the controller if (abortController && isWaitingForResponse) { abortController.abort(); - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "[Interrupted by user]", - }, - contextItems: [], - }, - ]); + + // Remove the last message if it's from assistant (partial response) + setChatHistory((current) => { + const lastMessage = current[current.length - 1]; + if (lastMessage?.message.role === "assistant") { + const historyWithoutLastAssistant = current.slice(0, -1); + setInterruptedHistory(historyWithoutLastAssistant); + return historyWithoutLastAssistant; + } + setInterruptedHistory(current); + return current; + }); + + setWasInterrupted(true); + setIsWaitingForResponse(false); + setResponseStartTime(null); + setInputMode(true); } }; @@ -471,6 +510,7 @@ export function useChat({ inputMode, attachedFiles, activePermissionRequest, + wasInterrupted, handleUserMessage, handleInterrupt, handleFileAttached, diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 046b1dc37..806a98f2a 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -12528,6 +12528,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", "dev": true, + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" From 276e39eb8425f5f26c863ea8329582f0920f7296 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 14:14:41 -0700 Subject: [PATCH 05/11] fix: don't handle streamed response if aborted --- extensions/cli/src/stream/streamChatResponse.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index 0f5f5edd5..1c3803e66 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -341,6 +341,10 @@ export async function streamChatResponse( isHeadless, tools, }); + + if (abortController?.signal.aborted) { + return finalResponse || content || fullResponse; + } fullResponse += content; From 30de57993c14896cb7143281511313ff69d4bb55 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 14:22:11 -0700 Subject: [PATCH 06/11] fix: truncate to last user or tool call msg --- extensions/cli/src/ui/hooks/useChat.ts | 42 ++++++++++++-------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 78142286e..6d3e032a4 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -106,10 +106,7 @@ export function useChat({ return null; }); - // Track interrupted history for resume functionality - const [interruptedHistory, setInterruptedHistory] = useState< - ChatHistoryItem[] | null - >(null); + // Track interrupted state for resume functionality const [wasInterrupted, setWasInterrupted] = useState(false); // Clean up abort controller on unmount @@ -187,7 +184,6 @@ export function useChat({ const executeStreamingResponse = async ( newHistory: ChatHistoryItem[], currentCompactionIndex: number | null, - message: string, ) => { // Clean up previous abort controller if it exists if (abortController && !abortController.signal.aborted) { @@ -201,7 +197,6 @@ export function useChat({ setResponseStartTime(Date.now()); setInputMode(false); logger.debug("Starting chat response stream", { - messageLength: message.length, historyLength: newHistory.length, }); @@ -263,21 +258,26 @@ export function useChat({ const handleUserMessage = async (message: string) => { // Check if this is a resume request (empty message after interruption) - if (message === "" && wasInterrupted && interruptedHistory) { - // Get the last user message to resume - const lastUserMessage = interruptedHistory[interruptedHistory.length - 1]; - if (lastUserMessage && lastUserMessage.message.role === "user") { - const originalMessage = lastUserMessage.message.content; - const messageString = typeof originalMessage === "string" - ? originalMessage - : originalMessage.map(part => part.type === "text" ? part.text : "").join(""); + if (message === "" && wasInterrupted) { + // Find the index of the last user or tool message to resume from + let lastUserOrToolIndex = -1; + for (let i = chatHistory.length - 1; i >= 0; i--) { + if (chatHistory[i].message.role === "user" || !!chatHistory[i].toolCallStates?.length) { + lastUserOrToolIndex = i; + break; + } + } + + if (lastUserOrToolIndex >= 0) { + // Truncate history to include up to and including the user/tool message + const truncatedHistory = chatHistory.slice(0, lastUserOrToolIndex + 1); + setChatHistory(truncatedHistory); // Clear the interrupted state and resume setWasInterrupted(false); - setInterruptedHistory(null); - // Re-execute streaming with the clean history - await executeStreamingResponse(interruptedHistory, compactionIndex, messageString); + // Re-execute streaming with the truncated history + await executeStreamingResponse(truncatedHistory, compactionIndex); return; } } @@ -285,7 +285,6 @@ export function useChat({ // Clear interrupted state if user types a new message if (wasInterrupted && message !== "") { setWasInterrupted(false); - setInterruptedHistory(null); } // Handle special commands @@ -382,7 +381,7 @@ export function useChat({ setChatHistory(newHistory); // Execute the streaming response - await executeStreamingResponse(newHistory, currentCompactionIndex, message); + await executeStreamingResponse(newHistory, currentCompactionIndex); }; const handleInterrupt = () => { @@ -409,11 +408,8 @@ export function useChat({ setChatHistory((current) => { const lastMessage = current[current.length - 1]; if (lastMessage?.message.role === "assistant") { - const historyWithoutLastAssistant = current.slice(0, -1); - setInterruptedHistory(historyWithoutLastAssistant); - return historyWithoutLastAssistant; + return current.slice(0, -1); } - setInterruptedHistory(current); return current; }); From 38eb3ece2d619422f22da49ccae47157fcdc0c35 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 16:01:51 -0700 Subject: [PATCH 07/11] fix: clean up --- extensions/cli/src/ui/hooks/useChat.stream.helpers.ts | 1 - extensions/cli/src/ui/hooks/useChat.ts | 5 +---- packages/openai-adapters/package-lock.json | 1 - 3 files changed, 1 insertion(+), 6 deletions(-) diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index d8b15aab3..aa2c19579 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -232,7 +232,6 @@ export async function executeStreaming({ chatHistory, currentCompactionIndex, ); - const _originalLength = historyForLLM.length; await streamChatResponse( historyForLLM, diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 6d3e032a4..d360635e3 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -221,9 +221,6 @@ export function useChat({ // Save the updated session with the latest chat history that includes the assistant's reply // The streamCallbacks update setChatHistory during streaming, so we need to get the current state setChatHistory((currentHistory) => { - logger.debug("Saving session", { - historyLength: currentHistory.length, - }); const updatedSession: Session = { ...currentSession, history: currentHistory, @@ -407,7 +404,7 @@ export function useChat({ // Remove the last message if it's from assistant (partial response) setChatHistory((current) => { const lastMessage = current[current.length - 1]; - if (lastMessage?.message.role === "assistant") { + if (lastMessage?.message.role === "assistant" && !lastMessage.toolCallStates?.length) { return current.slice(0, -1); } return current; diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 806a98f2a..046b1dc37 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -12528,7 +12528,6 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", "dev": true, - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" From 035706d51aac7aab1639efc3619aee4ed7989efa Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 16:02:43 -0700 Subject: [PATCH 08/11] chore: format --- extensions/cli/src/slashCommands.ts | 2 +- .../cli/src/stream/streamChatResponse.ts | 2 +- extensions/cli/src/ui/UserInput.tsx | 6 ++-- .../TUIChat.interruption.minimal.test.tsx | 29 +++++++++---------- extensions/cli/src/ui/hooks/useChat.ts | 22 +++++++++----- package-lock.json | 1 + 6 files changed, 33 insertions(+), 29 deletions(-) diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index a739cc450..9c8b172a8 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -186,7 +186,7 @@ async function handleInfo() { const currentSession = getCurrentSession(); infoLines.push(` Title: ${chalk.green(currentSession.title)}`); infoLines.push(` ID: ${chalk.gray(currentSession.sessionId)}`); - + const sessionFilePath = getSessionFilePath(); infoLines.push(` File: ${chalk.blue(sessionFilePath)}`); } catch { diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index 1c3803e66..300ea5b24 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -341,7 +341,7 @@ export async function streamChatResponse( isHeadless, tools, }); - + if (abortController?.signal.aborted) { return finalResponse || content || fullResponse; } diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 86c2f1874..7e48b56ad 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -413,12 +413,12 @@ const UserInput: React.FC = ({ // Expand all paste blocks before submitting textBuffer.expandAllPasteBlocks(); const submittedText = textBuffer.text.trim(); - + // Only add to history if there's actual text (not when resuming) if (submittedText) { inputHistory.addEntry(submittedText); } - + // Send empty string when resuming, actual text otherwise onSubmit(submittedText); textBuffer.clear(); @@ -654,7 +654,7 @@ const UserInput: React.FC = ({ )} - + {/* Input box */} { inputMode: true, onInterrupt: mockOnInterrupt, wasInterrupted: false, // Initially false - }) + }), ); try { @@ -43,7 +43,7 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { inputMode: true, onInterrupt: mockOnInterrupt, wasInterrupted: true, // Now true - }) + }), ); // Should show interruption message @@ -51,7 +51,6 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { expect(frame).toBeDefined(); expect(frame).toContain("⚠ Interrupted by user"); expect(frame).toContain("Press enter to resume"); - } finally { unmount(); } @@ -68,7 +67,7 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { inputMode: true, onInterrupt: mockOnInterrupt, wasInterrupted: true, // Initially true - }) + }), ); try { @@ -86,7 +85,7 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { inputMode: true, onInterrupt: mockOnInterrupt, wasInterrupted: false, // Now false - }) + }), ); // Should not show interruption message @@ -94,7 +93,6 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { expect(frame).toBeDefined(); expect(frame).not.toContain("⚠ Interrupted by user"); expect(frame).not.toContain("Press enter to resume"); - } finally { unmount(); } @@ -111,7 +109,7 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { inputMode: true, onInterrupt: mockOnInterrupt, wasInterrupted: true, // Interrupted state - }) + }), ); try { @@ -120,7 +118,6 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { // Should call onSubmit with empty string (for resume) expect(mockOnSubmit).toHaveBeenCalledWith(""); - } finally { unmount(); } @@ -137,7 +134,7 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { inputMode: true, onInterrupt: mockOnInterrupt, wasInterrupted: true, // Interrupted state - }) + }), ); try { @@ -146,8 +143,9 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { stdin.write("\r"); // Should call onSubmit with the typed content - expect(mockOnSubmit).toHaveBeenCalledWith("New message after interruption"); - + expect(mockOnSubmit).toHaveBeenCalledWith( + "New message after interruption", + ); } finally { unmount(); } @@ -164,7 +162,7 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { inputMode: true, onInterrupt: mockOnInterrupt, wasInterrupted: true, - }) + }), ); try { @@ -172,8 +170,8 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { expect(frame).toBeDefined(); // The interruption message should appear before the input box - const frameLines = frame?.split('\n') || []; - + const frameLines = frame?.split("\n") || []; + let foundInterruptionLine = -1; let foundInputBoxLine = -1; @@ -190,9 +188,8 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { expect(foundInterruptionLine).toBeGreaterThan(-1); expect(foundInputBoxLine).toBeGreaterThan(-1); expect(foundInterruptionLine).toBeLessThan(foundInputBoxLine); - } finally { unmount(); } }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index d360635e3..8109d1991 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -259,26 +259,29 @@ export function useChat({ // Find the index of the last user or tool message to resume from let lastUserOrToolIndex = -1; for (let i = chatHistory.length - 1; i >= 0; i--) { - if (chatHistory[i].message.role === "user" || !!chatHistory[i].toolCallStates?.length) { + if ( + chatHistory[i].message.role === "user" || + !!chatHistory[i].toolCallStates?.length + ) { lastUserOrToolIndex = i; break; } } - + if (lastUserOrToolIndex >= 0) { // Truncate history to include up to and including the user/tool message const truncatedHistory = chatHistory.slice(0, lastUserOrToolIndex + 1); setChatHistory(truncatedHistory); - + // Clear the interrupted state and resume setWasInterrupted(false); - + // Re-execute streaming with the truncated history await executeStreamingResponse(truncatedHistory, compactionIndex); return; } } - + // Clear interrupted state if user types a new message if (wasInterrupted && message !== "") { setWasInterrupted(false); @@ -400,16 +403,19 @@ export function useChat({ // Local mode: abort the controller if (abortController && isWaitingForResponse) { abortController.abort(); - + // Remove the last message if it's from assistant (partial response) setChatHistory((current) => { const lastMessage = current[current.length - 1]; - if (lastMessage?.message.role === "assistant" && !lastMessage.toolCallStates?.length) { + if ( + lastMessage?.message.role === "assistant" && + !lastMessage.toolCallStates?.length + ) { return current.slice(0, -1); } return current; }); - + setWasInterrupted(true); setIsWaitingForResponse(false); setResponseStartTime(null); diff --git a/package-lock.json b/package-lock.json index b4289d422..b3ddaef8f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,7 @@ "requires": true, "packages": { "": { + "name": "continue", "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "concurrently": "^9.1.2", From b281c4a9c8c63ebaf63416908ef703bc56e0d256 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 16:33:20 -0700 Subject: [PATCH 09/11] fix test --- extensions/cli/src/slashCommands.test.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index 72ab421ff..ac9ec69b3 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -83,6 +83,9 @@ vi.mock("./session.js", () => ({ () => "/home/test/.continue/cli-sessions/continue-cli-pid-12345.json", ), hasSession: vi.fn(() => false), + getCurrentSession: vi.fn(() => { + throw new Error("Session not available"); + }), })); describe("slashCommands", () => { @@ -141,8 +144,8 @@ describe("slashCommands", () => { expect(result?.output).toContain("Not logged in"); expect(result?.output).toContain("Configuration:"); expect(result?.output).toContain("/test/config.yaml"); - expect(result?.output).toContain("Session History:"); - expect(result?.output).toContain(".json"); + expect(result?.output).toContain("Session:"); + expect(result?.output).toContain("Session not available"); expect(result?.exit).toBe(false); }); @@ -244,12 +247,16 @@ describe("slashCommands", () => { it("should use test session directory when in test mode", async () => { const { isAuthenticated } = await import("./auth/workos.js"); const { services } = await import("./services/index.js"); - const { getSessionFilePath } = await import("./session.js"); + const { getSessionFilePath, getCurrentSession } = await import("./session.js"); - // Mock the session path for this specific test + // Mock the session functions for this specific test (getSessionFilePath as any).mockReturnValue( "/test-home/.continue/cli-sessions/continue-cli-test-123.json", ); + (getCurrentSession as any).mockReturnValue({ + sessionId: "test-123", + title: "Test Session", + }); ( isAuthenticated as MockedFunction @@ -265,7 +272,7 @@ describe("slashCommands", () => { const result = await handleSlashCommands("/info", mockAssistant); - expect(result?.output).toContain("/test-home/.continue/cli-sessions/"); + expect(result?.output).toContain("Session:"); expect(result?.output).toContain(".json"); }); }); From e2bb07bc03575b166ea3fbc6e6d6ef926de74db0 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 17:28:43 -0700 Subject: [PATCH 10/11] fix tests --- extensions/cli/src/slashCommands.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index ac9ec69b3..3c871b16b 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -273,6 +273,8 @@ describe("slashCommands", () => { const result = await handleSlashCommands("/info", mockAssistant); expect(result?.output).toContain("Session:"); + expect(result?.output).toContain("Test Session"); + expect(result?.output).toContain("/test-home/.continue/cli-sessions/"); expect(result?.output).toContain(".json"); }); }); From 0bfb9345d3a10c3e0707f8ee7e6eabe2e5f41940 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 17:37:32 -0700 Subject: [PATCH 11/11] format --- extensions/cli/src/slashCommands.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index 3c871b16b..83514dac3 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -247,7 +247,9 @@ describe("slashCommands", () => { it("should use test session directory when in test mode", async () => { const { isAuthenticated } = await import("./auth/workos.js"); const { services } = await import("./services/index.js"); - const { getSessionFilePath, getCurrentSession } = await import("./session.js"); + const { getSessionFilePath, getCurrentSession } = await import( + "./session.js" + ); // Mock the session functions for this specific test (getSessionFilePath as any).mockReturnValue(