diff --git a/.github/workflows/cla.yaml b/.github/workflows/cla.yaml index 78e6f209b..8a93c3285 100644 --- a/.github/workflows/cla.yaml +++ b/.github/workflows/cla.yaml @@ -27,5 +27,5 @@ jobs: path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md" branch: cla-signatures # Bots and CLAs signed outside of GitHub - allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline,agent@continue.dev + allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline,agent@continue.dev,action@github.com signed-commit-message: "CLA signed in $pullRequestNo" diff --git a/.github/workflows/runloop-blueprint-template.json b/.github/workflows/runloop-blueprint-template.json index 244897cdd..d1626d81f 100644 --- a/.github/workflows/runloop-blueprint-template.json +++ b/.github/workflows/runloop-blueprint-template.json @@ -4,6 +4,7 @@ "npm i -g @continuedev/cli@latest", "sudo apt update", "sudo apt install -y ripgrep", - "sudo apt install asciinema" + "sudo apt install asciinema", + "sudo apt install expect" ] } diff --git a/core/nextEdit/NextEditLoggingService.ts b/core/nextEdit/NextEditLoggingService.ts index 430cb576a..5c67760e8 100644 --- a/core/nextEdit/NextEditLoggingService.ts +++ b/core/nextEdit/NextEditLoggingService.ts @@ -246,6 +246,9 @@ export class NextEditLoggingService { }), }, ); - } catch (error) {} + console.debug("Feedback: ", resp); + } catch (error: any) { + console.debug(`Error capturing feedback: ${error.message}`); + } } } diff --git a/docs/docs.json b/docs/docs.json index 4c69ea6ea..7b1d5e1ba 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -2,6 +2,10 @@ "$schema": "https://mintlify.com/docs.json", "theme": "mint", "name": "Continue", + "banner": { + "content": "Continue CLI v1.4.49 is live 🚀 Learn how you can [leverage the CLI with our MCP Cookbooks](/guides/overview#mcp-integration-cookbooks)", + "dismissable": true + }, "colors": { "primary": "#6b7280", "light": "#ffffff", diff --git a/extensions/cli/src/config.ts b/extensions/cli/src/config.ts index 6c97767bc..90734d835 100644 --- a/extensions/cli/src/config.ts +++ b/extensions/cli/src/config.ts @@ -7,7 +7,6 @@ import { import { Configuration, DefaultApi, - DefaultApiInterface, } from "@continuedev/sdk/dist/api/dist/index.js"; import { @@ -15,9 +14,7 @@ import { getAccessToken, getOrganizationId, } from "./auth/workos.js"; -import { loadConfiguration } from "./configLoader.js"; import { env } from "./env.js"; -import { MCPService } from "./services/MCPService.js"; /** * Creates an LLM API instance from a ModelConfig and auth configuration @@ -96,23 +93,3 @@ export function getApiClient( }), ); } - -export async function initialize( - authConfig: AuthConfig, - configPath: string | undefined, -): Promise<{ - config: AssistantUnrolled; - llmApi: BaseLlmApi; - model: ModelConfig; - mcpService: MCPService; - apiClient: DefaultApiInterface; -}> { - const apiClient = getApiClient(authConfig?.accessToken); - const result = await loadConfiguration(authConfig, configPath, apiClient); - const config = result.config; - const [llmApi, model] = getLlmApi(config, authConfig); - const mcpService = new MCPService(); - await mcpService.initialize(config, false); - - return { config, llmApi, model, mcpService, apiClient }; -} diff --git a/extensions/cli/src/onboarding.test.ts b/extensions/cli/src/onboarding.test.ts index 1864e6368..1dee85c8d 100644 --- a/extensions/cli/src/onboarding.test.ts +++ b/extensions/cli/src/onboarding.test.ts @@ -5,7 +5,7 @@ import * as path from "path"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import type { AuthConfig } from "./auth/workos.js"; -import { runNormalFlow } from "./onboarding.js"; +import { initializeWithOnboarding } from "./onboarding.js"; describe("onboarding config flag handling", () => { let tempDir: string; @@ -40,7 +40,9 @@ describe("onboarding config flag handling", () => { expect(fs.existsSync(configPath)).toBe(false); // Should throw an error that mentions both the path and the failure - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow( /Failed to load config from ".*non-existent\.yaml": .*ENOENT/, ); }); @@ -64,9 +66,9 @@ models: expect(fs.existsSync(configPath)).toBe(true); // Should throw an error mentioning the path and failure to load - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( - /Failed to load config from ".*malformed\.yaml": .+/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow(/Failed to load config from ".*malformed\.yaml": .+/); }); test("should fail loudly when --config points to file with missing required fields", async () => { @@ -85,9 +87,9 @@ name: "Incomplete Config" expect(fs.existsSync(configPath)).toBe(true); // Should throw with our specific error format and include path - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( - /^Failed to load config from ".*": .+/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow(/^Failed to load config from ".*": .+/); }); test("should handle different config path formats with proper error messages", async () => { @@ -99,16 +101,18 @@ name: "Incomplete Config" ]; for (const configPath of testPaths) { - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( - /Failed to load config from ".*": .+/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow(/Failed to load config from ".*": .+/); } }); test("should handle empty string config path", async () => { // Empty string should be treated differently from undefined // Note: empty string triggers onboarding flow, but should still fail in our error format - await expect(runNormalFlow(mockAuthConfig, "")).rejects.toThrow(); + await expect( + initializeWithOnboarding(mockAuthConfig, ""), + ).rejects.toThrow(); }); test("should not fall back to default config when explicit config fails", async () => { @@ -117,7 +121,7 @@ name: "Incomplete Config" // Create a bad config file fs.writeFileSync(configPath, "invalid: yaml: content: ["); - const promise = runNormalFlow(mockAuthConfig, configPath); + const promise = initializeWithOnboarding(mockAuthConfig, configPath); await expect(promise).rejects.toThrow(); @@ -144,13 +148,13 @@ name: "Incomplete Config" fs.writeFileSync(badConfigPath, "invalid yaml ["); // Case 1: Explicit --config that fails should throw our specific error - await expect(runNormalFlow(mockAuthConfig, badConfigPath)).rejects.toThrow( - /^Failed to load config from "/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, badConfigPath), + ).rejects.toThrow(/^Failed to load config from "/); // Case 2: No explicit config should follow different logic try { - await runNormalFlow(mockAuthConfig, undefined); + await initializeWithOnboarding(mockAuthConfig, undefined); // If it succeeds, that's fine - the point is it's different behavior } catch (error) { const errorMessage = @@ -213,9 +217,9 @@ describe("CONTINUE_USE_BEDROCK environment variable", () => { vi.resetModules(); const { runOnboardingFlow } = await import("./onboarding.js"); - const result = await runOnboardingFlow(undefined, mockAuthConfig); + const result = await runOnboardingFlow(undefined); - expect(result.wasOnboarded).toBe(true); + expect(result).toBe(true); expect(mockConsoleLog).toHaveBeenCalledWith( expect.stringContaining( "✓ Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)", @@ -235,7 +239,7 @@ describe("CONTINUE_USE_BEDROCK environment variable", () => { process.stdin.isTTY = false; try { - await runOnboardingFlow(undefined, mockAuthConfig); + await runOnboardingFlow(undefined); // Verify the Bedrock message was NOT called by checking all calls const allCalls = mockConsoleLog.mock.calls.flat(); diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts index 0108baa90..a8f780591 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -1,16 +1,12 @@ import * as fs from "fs"; import * as path from "path"; -import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { BaseLlmApi } from "@continuedev/openai-adapters"; -import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; -import { AuthConfig, isAuthenticated, login } from "./auth/workos.js"; -import { initialize } from "./config.js"; +import { AuthConfig, login } from "./auth/workos.js"; +import { getApiClient } from "./config.js"; +import { loadConfiguration } from "./configLoader.js"; import { env } from "./env.js"; -import { processRule } from "./hubLoader.js"; -import { MCPService } from "./services/MCPService.js"; import { getApiKeyValidationError, isValidAnthropicApiKey, @@ -20,15 +16,6 @@ import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); -export interface OnboardingResult { - config: AssistantUnrolled; - llmApi: BaseLlmApi; - model: ModelConfig; - mcpService: MCPService; - apiClient: DefaultApiInterface; - wasOnboarded: boolean; -} - export async function checkHasAcceptableModel( configPath: string, ): Promise { @@ -61,12 +48,10 @@ export async function createOrUpdateConfig(apiKey: string): Promise { export async function runOnboardingFlow( configPath: string | undefined, - authConfig: AuthConfig, -): Promise { +): Promise { // Step 1: Check if --config flag is provided if (configPath !== undefined) { - const result = await initialize(authConfig, configPath); - return { ...result, wasOnboarded: false }; + return false; } // Step 2: Check for CONTINUE_USE_BEDROCK environment variable first (before test env check) @@ -74,8 +59,7 @@ export async function runOnboardingFlow( console.log( chalk.blue("✓ Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)"), ); - const result = await initialize(authConfig, CONFIG_PATH); - return { ...result, wasOnboarded: true }; + return true; } // Step 3: Check if we're in a test/CI environment - if so, skip interactive prompts @@ -92,13 +76,11 @@ export async function runOnboardingFlow( console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment")); await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); - const result = await initialize(authConfig, CONFIG_PATH); - return { ...result, wasOnboarded: false }; + return false; } // Otherwise return a minimal working configuration - const result = await initialize(authConfig, undefined); - return { ...result, wasOnboarded: false }; + return false; } // Step 4: Present user with two options @@ -114,13 +96,8 @@ export async function runOnboardingFlow( ); if (choice === "1" || choice === "") { - const newAuthConfig = await login(); - - const { ensureOrganization } = await import("./auth/workos.js"); - const finalAuthConfig = await ensureOrganization(newAuthConfig); - - const result = await initialize(finalAuthConfig, undefined); - return { ...result, wasOnboarded: true }; + await login(); + return true; } else if (choice === "2") { const apiKey = await question( chalk.white("\nEnter your Anthropic API key: "), @@ -135,89 +112,12 @@ export async function runOnboardingFlow( chalk.green(`✓ Config file updated successfully at ${CONFIG_PATH}`), ); - const result = await initialize(authConfig, CONFIG_PATH); - return { ...result, wasOnboarded: true }; + return true; } else { throw new Error(`Invalid choice. Please select "1" or "2"`); } } -export async function runNormalFlow( - authConfig: AuthConfig, - configPath?: string, - rules?: string[], -): Promise { - // Step 1: Check if --config flag is provided - if (configPath !== undefined) { - // Empty string is invalid and should be treated as an error - if (configPath === "") { - throw new Error( - `Failed to load config from "": Config path cannot be empty`, - ); - } - - try { - const result = await initialize(authConfig, configPath); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } catch (error) { - // If user explicitly provided --config flag, fail loudly instead of falling back - const errorMessage = - error instanceof Error ? error.message : String(error); - throw new Error( - `Failed to load config from "${configPath}": ${errorMessage}`, - ); - } - } - - // Step 2: If user is logged in, look for first assistant in selected org - if (isAuthenticated()) { - try { - const result = await initialize(authConfig, undefined); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } catch { - // Silently ignore errors when loading default assistant - } - } - - // Step 3: Look for local ~/.continue/config.yaml - if (fs.existsSync(CONFIG_PATH)) { - try { - const result = await initialize(authConfig, CONFIG_PATH); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } catch { - console.log(chalk.yellow("⚠ Invalid config file found")); - } - } - - // Step 4: Look for ANTHROPIC_API_KEY in environment - if (process.env.ANTHROPIC_API_KEY) { - console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment")); - await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); - console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); - const result = await initialize(authConfig, CONFIG_PATH); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } - - // Step 5: Fall back to onboarding flow - return runOnboardingFlow(configPath, authConfig); -} - export async function isFirstTime(): Promise { return !fs.existsSync(path.join(env.continueHome, ".onboarding_complete")); } @@ -233,71 +133,31 @@ export async function markOnboardingComplete(): Promise { fs.writeFileSync(flagPath, new Date().toISOString()); } -/** - * Process rules and inject them into the assistant config - * @param config - The assistant config to modify - * @param rules - Array of rule specifications to process and inject - * @returns The modified config with injected rules - */ -async function injectRulesIntoConfig( - config: AssistantUnrolled, - rules: string[], -): Promise { - if (!rules || rules.length === 0) { - return config; - } +export async function initializeWithOnboarding( + authConfig: AuthConfig, + configPath: string | undefined, +) { + const firstTime = await isFirstTime(); - const processedRules: string[] = []; - for (const ruleSpec of rules) { + if (configPath !== undefined) { + // throw an early error is configPath is invalid or has errors try { - const processedRule = await processRule(ruleSpec); - processedRules.push(processedRule); - } catch (error: any) { - console.warn( - chalk.yellow( - `Warning: Failed to process rule "${ruleSpec}": ${error.message}`, - ), + await loadConfiguration( + authConfig, + configPath, + getApiClient(authConfig?.accessToken), + ); + } catch (errorMessage) { + throw new Error( + `Failed to load config from "${configPath}": ${errorMessage}`, ); } } - if (processedRules.length === 0) { - return config; + if (!firstTime) return; + + const wasOnboarded = await runOnboardingFlow(configPath); + if (wasOnboarded) { + await markOnboardingComplete(); } - - // Clone the config to avoid mutating the original - const modifiedConfig = { ...config }; - - // Add processed rules to the config's rules array - // Each processed rule is a string, which is a valid Rule type - const existingRules = modifiedConfig.rules || []; - modifiedConfig.rules = [...existingRules, ...processedRules]; - - return modifiedConfig; -} - -export async function initializeWithOnboarding( - authConfig: AuthConfig, - configPath: string | undefined, - rules?: string[], -): Promise { - const firstTime = await isFirstTime(); - - let result: OnboardingResult; - - if (firstTime) { - result = await runOnboardingFlow(configPath, authConfig); - if (result.wasOnboarded) { - await markOnboardingComplete(); - } - } else { - result = await runNormalFlow(authConfig, configPath, rules); - } - - // Inject rules into the config if provided (for onboarding flow which doesn't handle rules directly) - if (rules && rules.length > 0 && !result.wasOnboarded) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - - return result; } diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index a8d209d88..9ff58f365 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -23,7 +23,6 @@ import { ConfigServiceState, SERVICE_NAMES, ServiceInitOptions, - ServiceInitResult, WorkflowServiceState, } from "./types.js"; import { UpdateService } from "./UpdateService.js"; @@ -48,23 +47,15 @@ const systemMessageService = new SystemMessageService(); * Initialize all services and register them with the service container * Handles onboarding internally for TUI mode unless skipOnboarding is true */ -export async function initializeServices( - initOptions: ServiceInitOptions = {}, -): Promise { +export async function initializeServices(initOptions: ServiceInitOptions = {}) { logger.debug("Initializing service registry"); - let wasOnboarded = false; const commandOptions = initOptions.options || {}; // Handle onboarding for TUI mode (headless: false) unless explicitly skipped if (!initOptions.headless && !initOptions.skipOnboarding) { const authConfig = loadAuthConfig(); - const onboardingResult = await initializeWithOnboarding( - authConfig, - commandOptions.config, - commandOptions.rule, - ); - wasOnboarded = onboardingResult.wasOnboarded; + await initializeWithOnboarding(authConfig, commandOptions.config); } // Handle ANTHROPIC_API_KEY in headless mode when no config path is provided @@ -287,8 +278,6 @@ export async function initializeServices( await serviceContainer.initializeAll(); logger.debug("Service registry initialized"); - - return { wasOnboarded }; } /** diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx new file mode 100644 index 000000000..c56bec21a --- /dev/null +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -0,0 +1,202 @@ +/** + * @vitest-environment jsdom + */ +import { render } from "@testing-library/react"; +import type { ChatHistoryItem } from "core/index.js"; +import React from "react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import { EditMessageSelector } from "./EditMessageSelector.js"; + +describe("EditMessageSelector", () => { + const createMockChatHistory = (count: number): ChatHistoryItem[] => { + const history: ChatHistoryItem[] = []; + for (let i = 0; i < count; i++) { + // Alternate between user and assistant messages + if (i % 2 === 0) { + history.push({ + message: { role: "user", content: `User message ${i + 1}` }, + contextItems: [], + }); + } else { + history.push({ + message: { role: "assistant", content: `Assistant message ${i + 1}` }, + contextItems: [], + }); + } + } + return history; + }; + + let mockOnEdit: ReturnType; + let mockOnExit: ReturnType; + + beforeEach(() => { + mockOnEdit = vi.fn(); + mockOnExit = vi.fn(); + vi.clearAllMocks(); + }); + + describe("Initialization", () => { + it("should render 'no user messages' when chat history is empty", () => { + const { container } = render( + , + ); + + expect(container.textContent).toContain("No user messages to edit"); + }); + + it("should render 'no user messages' when chat history has only assistant messages", () => { + const chatHistory: ChatHistoryItem[] = [ + { + message: { role: "assistant", content: "Hello" }, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + expect(container.textContent).toContain("No user messages to edit"); + }); + + it("should render user messages list", () => { + const chatHistory = createMockChatHistory(4); // Will have 2 user messages + + const { container } = render( + , + ); + + expect(container.textContent).toContain("Message 1:"); + expect(container.textContent).toContain("Message 2:"); + expect(container.textContent).toContain("User message 1"); + expect(container.textContent).toContain("User message 3"); + }); + + it("should filter out non-user messages", () => { + const chatHistory: ChatHistoryItem[] = [ + { message: { role: "user", content: "User 1" }, contextItems: [] }, + { + message: { role: "assistant", content: "Assistant 1" }, + contextItems: [], + }, + { message: { role: "system", content: "System 1" }, contextItems: [] }, + { message: { role: "user", content: "User 2" }, contextItems: [] }, + ]; + + const { container } = render( + , + ); + + // Should only show 2 user messages + expect(container.textContent).toContain("User 1"); + expect(container.textContent).toContain("User 2"); + expect(container.textContent).not.toContain("Assistant 1"); + expect(container.textContent).not.toContain("System 1"); + }); + + it("should show instruction text in selection mode", () => { + const chatHistory = createMockChatHistory(2); + + const { container } = render( + , + ); + + expect(container.textContent).toContain("↑/↓ to navigate"); + expect(container.textContent).toContain("Enter to edit"); + expect(container.textContent).toContain("Esc to exit"); + }); + }); + + describe("Message preview", () => { + it("should truncate long messages in preview", () => { + const longMessage = "a".repeat(100); + const chatHistory: ChatHistoryItem[] = [ + { message: { role: "user", content: longMessage }, contextItems: [] }, + ]; + + const { container } = render( + , + ); + + // Should show truncation indicator + expect(container.textContent).toContain("..."); + // Should not show full message (preview is limited to 60 chars) + expect(container.textContent).not.toContain(longMessage); + }); + + it("should show only first line in multiline message preview", () => { + const multilineMessage = "First line\nSecond line\nThird line"; + const chatHistory: ChatHistoryItem[] = [ + { + message: { role: "user", content: multilineMessage }, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + expect(container.textContent).toContain("First line"); + expect(container.textContent).not.toContain("Second line"); + }); + }); + + describe("Complex message content", () => { + it("should handle message parts array", () => { + const chatHistory: ChatHistoryItem[] = [ + { + message: { + role: "user", + content: [ + { type: "text", text: "Hello" }, + { type: "text", text: " world" }, + ], + } as any, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + // Should render something (component handles non-string content gracefully) + expect(container.textContent).toBeDefined(); + }); + }); +}); diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx new file mode 100644 index 000000000..60c8a23c0 --- /dev/null +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -0,0 +1,292 @@ +import { Box, Text, useInput } from "ink"; +import React, { useMemo, useState } from "react"; + +import type { ChatHistoryItem } from "../../../../core/index.js"; + +import { defaultBoxStyles } from "./styles.js"; +import { TextBuffer } from "./TextBuffer.js"; + +// Infer the Key type from useInput's callback parameters +type UseInputHandler = Parameters[0]; +type Key = Parameters[1]; + +interface EditMessageSelectorProps { + chatHistory: ChatHistoryItem[]; + onEdit: (messageIndex: number, newContent: string) => void; + onExit: () => void; +} + +export function EditMessageSelector({ + chatHistory, + onEdit, + onExit, +}: EditMessageSelectorProps) { + // Filter to only show user messages + const userMessages = useMemo(() => { + return chatHistory + .map((item, originalIndex) => ({ item, originalIndex })) + .filter(({ item }) => item.message.role === "user"); + }, [chatHistory]); + + const [selectedIndex, setSelectedIndex] = useState( + Math.max(0, userMessages.length - 1), + ); + const [isEditing, setIsEditing] = useState(false); + const [textBuffer] = useState(() => new TextBuffer()); + const [editText, setEditText] = useState(""); + const [cursorPosition, setCursorPosition] = useState(0); + + // Stable callback for TextBuffer state changes (e.g., paste finalization) + const onStateChange = React.useCallback(() => { + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + }, [textBuffer]); + + // Set up callback for when TextBuffer state changes asynchronously + React.useEffect(() => { + textBuffer.setStateChangeCallback(onStateChange); + + return () => { + // Clear any pending timers on unmount + textBuffer.clear(); + }; + }, [textBuffer, onStateChange]); + + // Initialize edit text when selection changes + React.useEffect(() => { + if (!isEditing && userMessages[selectedIndex]) { + const content = + typeof userMessages[selectedIndex].item.message.content === "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setText(content); + setEditText(content); + setCursorPosition(content.length); + } + }, [selectedIndex, isEditing, userMessages, textBuffer]); + + // Helper to get message content safely + const getMessageContent = React.useCallback( + (index: number): string => { + return typeof userMessages[index]?.item.message.content === "string" + ? userMessages[index].item.message.content + : ""; + }, + [userMessages], + ); + + // Handle input when in editing mode + const handleEditModeInput = React.useCallback( + (input: string, key: Key) => { + if (key.escape) { + setIsEditing(false); + // Reset text to original + const content = getMessageContent(selectedIndex); + textBuffer.setText(content); + setEditText(content); + setCursorPosition(content.length); + } else if (key.return && !key.shift) { + // Submit the edit + // Expand all paste blocks before submission to restore original content + textBuffer.expandAllPasteBlocks(); + const trimmedText = textBuffer.text.trim(); + if (trimmedText && userMessages[selectedIndex]) { + onEdit(userMessages[selectedIndex].originalIndex, trimmedText); + } + } else if (key.return && key.shift) { + // Handle newline + textBuffer.handleInput("\n", key); + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + } else { + // Let TextBuffer handle the input + textBuffer.handleInput(input, key); + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + } + }, + [ + getMessageContent, + selectedIndex, + textBuffer, + userMessages, + onEdit, + setIsEditing, + setEditText, + setCursorPosition, + ], + ); + + // Handle input when in navigation mode + const handleNavigationInput = React.useCallback( + (input: string, key: Key) => { + if (key.upArrow || input === "k") { + // Only navigate if there are messages + if (userMessages.length > 0) { + setSelectedIndex((prev) => + prev > 0 ? prev - 1 : userMessages.length - 1, + ); + } + } else if (key.downArrow || input === "j") { + // Only navigate if there are messages + if (userMessages.length > 0) { + setSelectedIndex((prev) => + prev < userMessages.length - 1 ? prev + 1 : 0, + ); + } + } else if (key.return) { + // Start editing the selected message - set cursor to end + // Only allow editing if there are messages + if (userMessages.length > 0) { + const content = getMessageContent(selectedIndex); + textBuffer.setCursor(content.length); + setCursorPosition(content.length); + setIsEditing(true); + } + } else if (key.escape || (key.ctrl && input === "d")) { + onExit(); + } + }, + [ + userMessages.length, + getMessageContent, + selectedIndex, + textBuffer, + onExit, + setSelectedIndex, + setCursorPosition, + setIsEditing, + ], + ); + + useInput((input, key) => { + if (isEditing) { + handleEditModeInput(input, key); + } else { + handleNavigationInput(input, key); + } + }); + + if (userMessages.length === 0) { + return ( + + No user messages to edit. + Press Esc to exit + + ); + } + + const renderEditText = () => { + if (editText.length === 0) { + return ( + + ▋(empty message) + + ); + } + + // Handle multi-line text with cursor + const lines = editText.split("\n"); + let charCount = 0; + let cursorLine = 0; + let cursorCol = 0; + + // Find which line and column the cursor is on + for (let i = 0; i < lines.length; i++) { + if (cursorPosition <= charCount + lines[i].length) { + cursorLine = i; + cursorCol = cursorPosition - charCount; + break; + } + charCount += lines[i].length + 1; // +1 for the newline character + } + + // Handle cursor at the very end + if (cursorPosition >= editText.length) { + cursorLine = lines.length - 1; + cursorCol = lines[cursorLine].length; + } + + return ( + + {lines.map((line, lineIndex) => { + if (lineIndex === cursorLine) { + // Line with cursor + const beforeCursor = line.slice(0, cursorCol); + const atCursor = line.slice(cursorCol, cursorCol + 1); + const afterCursor = line.slice(cursorCol + 1); + + return ( + + {beforeCursor} + {atCursor || " "} + {afterCursor} + + ); + } else { + // Regular line - ensure empty lines still render + return {line || " "}; + } + })} + + ); + }; + + return ( + + + Edit Message (Rewind Conversation) + + + {isEditing + ? "Enter to submit, Esc to cancel, Shift+Enter for newline" + : "↑/↓ to navigate, Enter to edit, Esc to exit"} + + + + {!isEditing && ( + <> + Select a message to edit: + + {userMessages.map((msg, index) => { + const isSelected = index === selectedIndex; + const indicator = isSelected ? "➤ " : " "; + const color = isSelected ? "yellow" : "white"; + const content = + typeof msg.item.message.content === "string" + ? msg.item.message.content + : ""; + const preview = content.split("\n")[0].slice(0, 60); + const truncated = content.length > 60 ? "..." : ""; + + return ( + + + {indicator}Message {index + 1}: {preview} + {truncated} + + + ); + })} + + )} + + {isEditing && ( + <> + + Editing Message {selectedIndex + 1} (will rewind to this point): + + + + {renderEditText()} + + + )} + + ); +} diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index aea25bc19..dfcd19060 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -212,7 +212,7 @@ const TUIChat: React.FC = ({ ); // Use login handlers - const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers( + const { handleLoginTokenSubmit } = useLoginHandlers( navigateTo, navState, closeCurrentScreen, @@ -266,6 +266,7 @@ const TUIChat: React.FC = ({ handleInterrupt, handleFileAttached, resetChatHistory, + handleEditMessage, handleToolPermissionResponse, } = useChat({ assistant: services.config?.config || undefined, @@ -281,9 +282,9 @@ const TUIChat: React.FC = ({ onShowMCPSelector: () => navigateTo("mcp"), onShowUpdateSelector: () => navigateTo("update"), onShowSessionSelector: () => navigateTo("session"), - onLoginPrompt: handleLoginPrompt, onReload: handleReload, onClear: handleClear, + onRefreshStatic: () => setStaticRefreshTrigger((prev) => prev + 1), // Remote mode configuration isRemoteMode, remoteUrl, @@ -420,6 +421,9 @@ const TUIChat: React.FC = ({ isRemoteMode={isRemoteMode} onImageInClipboardChange={setHasImageInClipboard} diffContent={diffContent} + chatHistory={chatHistory} + handleEditMessage={handleEditMessage} + onShowEditSelector={() => navigateTo("edit")} /> {/* Resource debug bar - only in verbose mode */} diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 834bd68e4..fb31e4e5c 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -1,7 +1,7 @@ /* eslint-disable max-lines */ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text, useApp, useInput } from "ink"; -import React, { useCallback, useState } from "react"; +import React, { useCallback, useRef, useState } from "react"; import { getAllSlashCommands } from "../commands/commands.js"; import { useServices } from "../hooks/useService.js"; @@ -109,6 +109,7 @@ interface UserInputProps { hideNormalUI?: boolean; isRemoteMode?: boolean; onImageInClipboardChange?: (hasImage: boolean) => void; + onShowEditSelector?: () => void; } const UserInput: React.FC = ({ @@ -125,9 +126,11 @@ const UserInput: React.FC = ({ hideNormalUI = false, isRemoteMode = false, onImageInClipboardChange, + onShowEditSelector, }) => { const [textBuffer] = useState(() => new TextBuffer()); const [inputHistory] = useState(() => new InputHistory()); + const lastEscapePressRef = useRef(0); // Stable callback for TextBuffer state changes to prevent race conditions const onStateChange = useCallback(() => { @@ -625,6 +628,25 @@ const UserInput: React.FC = ({ return true; } + // Handle double Esc to open edit message selector + const now = Date.now(); + if ( + inputMode && + !showSlashCommands && + !showFileSearch && + !showBashMode && + onShowEditSelector && + now - lastEscapePressRef.current < 500 + ) { + // Double escape detected + onShowEditSelector(); + lastEscapePressRef.current = 0; // Reset to prevent triple-escape + return true; + } + + // Track single escape press + lastEscapePressRef.current = now; + return false; }; diff --git a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx new file mode 100644 index 000000000..9e6a92874 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -0,0 +1,277 @@ +import { testBothModes, renderInMode } from "./TUIChat.dualModeHelper.js"; + +/** + * Integration tests for the message edit feature in TUIChat + * + * Tests the full flow: + * 1. Double Esc opens EditMessageSelector + * 2. User navigates and selects a message + * 3. User edits the message + * 4. History is rewound and new message is submitted + * 5. Chat updates correctly + */ + +describe("TUIChat - Message Edit Feature", () => { + testBothModes("double Esc should open edit selector", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Verify selector is not open initially + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + + // Press Esc twice quickly (within 500ms) + stdin.write("\u001b"); // First Esc + stdin.write("\u001b"); // Second Esc + + // Wait for UI to update + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector is now open + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + }); + + testBothModes("edit selector should handle navigation", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector (double Esc) + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector is open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + + // Try navigation keys + stdin.write("j"); // Down + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("k"); // Up + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Verify selector is still open after navigation + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + }); + + testBothModes("edit selector should exit with Esc", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify edit selector is open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + + // Press Esc to exit + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify edit selector is closed + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + }); + + testBothModes("should handle edit flow without crashing", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // This test verifies the basic flow doesn't crash + // Actual behavior depends on having chat history + + // Open edit selector + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Try to edit (Enter) + stdin.write("\r"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Type something + stdin.write("Test edit"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Exit without submitting (Esc) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should not crash + expect(frame).toBeDefined(); + }); + + testBothModes( + "should maintain UI stability during edit operations", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Perform various operations + stdin.write("\u001b"); + stdin.write("\u001b"); // Open edit with separate Esc presses + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector opened + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + + stdin.write("k"); // Navigate (no-op with 0 messages) + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("\u001b"); // Close + await new Promise((resolve) => setTimeout(resolve, 100)); + + frame = lastFrame(); + + // UI should remain stable and edit selector should be closed + expect(frame).toBeDefined(); + expect(frame!.length).toBeGreaterThan(0); + expect(frame).not.toContain("No user messages to edit"); + }, + ); +}); + +describe("TUIChat - Edit Selector Navigation", () => { + testBothModes("should handle rapid navigation commands", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Rapid navigation + stdin.write("jjjjkkk"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should handle rapid input without crashing + expect(frame).toBeDefined(); + }); + + testBothModes("should handle arrow keys in edit selector", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Use arrow keys (ANSI escape sequences) + stdin.write("\u001b[A"); // Up arrow + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("\u001b[B"); // Down arrow + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should handle arrow keys + expect(frame).toBeDefined(); + }); +}); + +describe("TUIChat - Edit Feature Edge Cases", () => { + testBothModes( + "should handle opening edit selector with no chat history", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Try to open edit selector immediately (no history) + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should either show "no messages" or handle gracefully + expect(frame).toBeDefined(); + expect(frame!.length).toBeGreaterThan(0); + }, + ); + + testBothModes("should handle single Esc (not double)", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Single Esc (should not open edit selector) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 600)); // Wait longer than 500ms threshold + + // Verify selector did not open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + + stdin.write("\u001b"); // Another single Esc after timeout + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector still did not open + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + }); + + testBothModes( + "should prevent triple escape from causing issues", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Triple Esc quickly + stdin.write("\u001b\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should handle gracefully (open then close, or just open) + expect(frame).toBeDefined(); + }, + ); +}); + +describe("TUIChat - Edit Feature Compatibility", () => { + testBothModes( + "edit feature should not interfere with normal input", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Type normal input + stdin.write("Hello world"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should show typed text + expect(frame).toBeDefined(); + // Normal input should work + }, + ); + + testBothModes( + "should not conflict with other Esc-based features", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Type something + stdin.write("test"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Single Esc (might clear input or do other things) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 600)); + + const frame = lastFrame(); + + // Should handle without conflicts + expect(frame).toBeDefined(); + }, + ); +}); diff --git a/extensions/cli/src/ui/components/ChatScreenContent.tsx b/extensions/cli/src/ui/components/ChatScreenContent.tsx new file mode 100644 index 000000000..7c3225da6 --- /dev/null +++ b/extensions/cli/src/ui/components/ChatScreenContent.tsx @@ -0,0 +1,76 @@ +import type { AssistantConfig } from "@continuedev/sdk"; +import React from "react"; + +import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; +import { UserInput } from "../UserInput.js"; + +import { ToolPermissionSelector } from "./ToolPermissionSelector.js"; + +interface ChatScreenContentProps { + activePermissionRequest: ActivePermissionRequest | null; + handleToolPermissionResponse: ( + requestId: string, + approved: boolean, + createPolicy?: boolean, + stopStream?: boolean, + ) => void; + handleUserMessage: (message: string, imageMap?: Map) => void; + isWaitingForResponse: boolean; + isCompacting: boolean; + inputMode: boolean; + handleInterrupt: () => void; + assistant?: AssistantConfig; + wasInterrupted: boolean; + handleFileAttached: (filePath: string, content: string) => void; + isInputDisabled: boolean; + isRemoteMode: boolean; + onImageInClipboardChange?: (hasImage: boolean) => void; + onShowEditSelector?: () => void; +} + +export const ChatScreenContent: React.FC = ({ + activePermissionRequest, + handleToolPermissionResponse, + handleUserMessage, + isWaitingForResponse, + isCompacting, + inputMode, + handleInterrupt, + assistant, + wasInterrupted, + handleFileAttached, + isInputDisabled, + isRemoteMode, + onImageInClipboardChange, + onShowEditSelector, +}) => { + if (activePermissionRequest) { + return ( + + ); + } + + return ( + + ); +}; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 977d6954a..694c8f215 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -3,18 +3,21 @@ import React from "react"; import { UpdateServiceState } from "src/services/types.js"; +import type { ChatHistoryItem } from "../../../../../core/index.js"; import { ConfigSelector } from "../ConfigSelector.js"; import type { NavigationScreen } from "../context/NavigationContext.js"; import { DiffViewer } from "../DiffViewer.js"; +import { EditMessageSelector } from "../EditMessageSelector.js"; import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; +import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; import { MCPSelector } from "../MCPSelector.js"; import { ModelSelector } from "../ModelSelector.js"; import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; import { UpdateSelector } from "../UpdateSelector.js"; import { UserInput } from "../UserInput.js"; +import { ChatScreenContent } from "./ChatScreenContent.js"; import { SessionSelectorWithLoading } from "./SessionSelectorWithLoading.js"; -import { ToolPermissionSelector } from "./ToolPermissionSelector.js"; interface ScreenContentProps { isScreenActive: (screen: NavigationScreen) => boolean; @@ -26,7 +29,7 @@ interface ScreenContentProps { handleSessionSelect: (sessionId: string) => Promise; handleReload: () => Promise; closeCurrentScreen: () => void; - activePermissionRequest: any; + activePermissionRequest: ActivePermissionRequest | null; handleToolPermissionResponse: ( requestId: string, approved: boolean, @@ -44,6 +47,9 @@ interface ScreenContentProps { isRemoteMode: boolean; onImageInClipboardChange?: (hasImage: boolean) => void; diffContent?: string; + chatHistory?: ChatHistoryItem[]; + handleEditMessage?: (messageIndex: number, newContent: string) => void; + onShowEditSelector?: () => void; } function hideScreenContent(state?: UpdateServiceState) { @@ -77,6 +83,9 @@ export const ScreenContent: React.FC = ({ isRemoteMode, onImageInClipboardChange, diffContent, + chatHistory = [], + handleEditMessage, + onShowEditSelector, }) => { if (hideScreenContent(services.update)) { return null; @@ -162,33 +171,40 @@ export const ScreenContent: React.FC = ({ ); } + // Edit message selector + if (isScreenActive("edit")) { + return ( + { + if (handleEditMessage) { + handleEditMessage(messageIndex, newContent); + } + closeCurrentScreen(); + }} + onExit={closeCurrentScreen} + /> + ); + } + // Chat screen with input area if (isScreenActive("chat")) { - if (activePermissionRequest) { - return ( - - ); - } return ( - ); } diff --git a/extensions/cli/src/ui/context/NavigationContext.tsx b/extensions/cli/src/ui/context/NavigationContext.tsx index fd922ca51..6d43414dd 100644 --- a/extensions/cli/src/ui/context/NavigationContext.tsx +++ b/extensions/cli/src/ui/context/NavigationContext.tsx @@ -20,6 +20,7 @@ export type NavigationScreen = | "session" // Session selector | "diff" // Full-screen diff overlay | "update" // Update selector + | "edit" // Edit message selector | "session"; // Session selector interface NavigationState { diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 4503bae53..fe3dc8d05 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -58,8 +58,8 @@ export function useChat({ onShowUpdateSelector, onShowMCPSelector, onShowSessionSelector, - onLoginPrompt: _onLoginPrompt, onClear, + onRefreshStatic, isRemoteMode = false, remoteUrl, onShowDiff, @@ -455,7 +455,11 @@ export function useChat({ message: string, imageMap?: Map, isQueuedMessage: boolean = false, + baseHistory?: ChatHistoryItem[], ) => { + // Use baseHistory if provided (e.g., when editing a message), + // otherwise use current chatHistory + const currentHistory = baseHistory ?? chatHistory; // Handle special commands const handled = await handleSpecialCommands({ message, @@ -524,7 +528,7 @@ export function useChat({ let currentChatHistory, currentCompactionIndex; try { const result = await handleAutoCompaction({ - chatHistory, + chatHistory: currentHistory, model, llmApi, compactionIndex, @@ -591,7 +595,7 @@ export function useChat({ let currentChatHistory, currentCompactionIndex; try { const result = await handleAutoCompaction({ - chatHistory, + chatHistory: currentHistory, model, llmApi, compactionIndex, @@ -721,6 +725,42 @@ export function useChat({ setQueuedMessages([]); }; + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + logger.debug("handleEditMessage called", { + messageIndex, + currentHistoryLength: chatHistory.length, + }); + + // Rewind chat history to exclude the message being edited + const rewindedHistory = chatHistory.slice(0, messageIndex); + + logger.debug("Rewinding history for edit", { + from: chatHistory.length, + to: rewindedHistory.length, + }); + + // Clear any queued messages + setQueuedMessages([]); + + // Clear attached files + setAttachedFiles([]); + + // Update the session with the rewound history + updateSessionHistory(rewindedHistory); + + // Force refresh of StaticChatContent to show truncated history + if (onRefreshStatic) { + onRefreshStatic(); + } + + // Resubmit the edited message with the rewound history as the base + // This ensures processMessage uses the correct base history + await processMessage(newContent, undefined, false, rewindedHistory); + }; + const handleToolPermissionResponse = async ( requestId: string, approved: boolean, @@ -803,6 +843,7 @@ export function useChat({ handleInterrupt, handleFileAttached, resetChatHistory, + handleEditMessage, handleToolPermissionResponse, }; } diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index bf449191b..2fe0b0b81 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -18,9 +18,9 @@ export interface UseChatProps { onShowUpdateSelector: () => void; onShowModelSelector?: () => void; onShowSessionSelector?: () => void; - onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; onClear?: () => void; + onRefreshStatic?: () => void; // Remote mode props isRemoteMode?: boolean; remoteUrl?: string; @@ -38,6 +38,7 @@ export interface ActivePermissionRequest { toolArgs: any; requestId: string; toolCallPreview?: ToolCallPreview[]; + hasDynamicEvaluation?: boolean; } export interface RemoteServerState { diff --git a/extensions/vscode/src/stubs/SecretStorage.ts b/extensions/vscode/src/stubs/SecretStorage.ts index 202713cbd..12cc98c35 100644 --- a/extensions/vscode/src/stubs/SecretStorage.ts +++ b/extensions/vscode/src/stubs/SecretStorage.ts @@ -62,6 +62,14 @@ export class SecretStorage { const key = await this.getOrCreateEncryptionKey(); const data = fs.readFileSync(filePath); + // Validate minimum data size to detect corruption early + const minSize = this.saltLength + this.ivLength + this.tagLength; + if (data.length < minSize) { + throw new Error( + `Corrupted cache file: insufficient data (${data.length} bytes, expected at least ${minSize})`, + ); + } + const salt = data.subarray(0, this.saltLength); const iv = data.subarray(this.saltLength, this.saltLength + this.ivLength); const tag = data.subarray( @@ -105,4 +113,12 @@ export class SecretStorage { } return undefined; } + + async delete(key: string): Promise { + const filePath = this.keyToFilepath(key); + if (fs.existsSync(filePath)) { + fs.unlinkSync(filePath); + console.log(`Successfully deleted cache file: ${filePath}`); + } + } } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index f0af9770d..1c0e60bba 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -161,22 +161,34 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { scopes?: string[], ): Promise { // await this.hasAttemptedRefresh; - const data = await this.secretStorage.get(SESSIONS_SECRET_KEY); - if (!data) { - return []; - } - try { + const data = await this.secretStorage.get(SESSIONS_SECRET_KEY); + if (!data) { + return []; + } + const value = JSON.parse(data) as ContinueAuthenticationSession[]; return value; } catch (e: any) { - // Capture session file parsing errors to Sentry + // Capture session decrypt and parsing errors to Sentry Logger.error(e, { - context: "workOS_sessions_json_parse", - dataLength: data.length, + context: "workOS_sessions_retrieval", + errorMessage: e.message, }); - console.warn(`Error parsing sessions.json: ${e}`); + console.warn(`Error retrieving or parsing sessions: ${e.message}`); + + // Delete the corrupted cache file to allow fresh start on next attempt + // This handles cases where decryption succeeded but JSON parsing failed + try { + await this.secretStorage.delete(SESSIONS_SECRET_KEY); + } catch (deleteError: any) { + console.error( + `Failed to delete corrupted sessions cache:`, + deleteError.message, + ); + } + return []; } } diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 12eebae1c..ee262d782 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -50,25 +50,27 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ const currentOrg = useAppSelector(selectCurrentOrg); const selectedProfile = useAppSelector(selectSelectedProfile); - const login: AuthContextType["login"] = (useOnboarding: boolean) => { - return new Promise(async (resolve) => { - await ideMessenger - .request("getControlPlaneSessionInfo", { - silent: false, - useOnboarding, - }) - .then((result) => { - if (result.status === "error") { - resolve(false); - return; - } + const login: AuthContextType["login"] = async (useOnboarding: boolean) => { + try { + const result = await ideMessenger.request("getControlPlaneSessionInfo", { + silent: false, + useOnboarding, + }); - const session = result.content; - setSession(session); + if (result.status === "error") { + console.error("Login failed:", result.error); + return false; + } - resolve(true); - }); - }); + const session = result.content; + setSession(session); + + return true; + } catch (error: any) { + console.error("Login request failed:", error); + // Let the error propagate so the caller can handle it + throw error; + } }; const logout = () => { diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 510733da9..e0a2dcf37 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -22,7 +22,10 @@ import { setTTSActive } from "../redux/slices/uiSlice"; import { modelSupportsReasoning } from "core/llm/autodetect"; import { cancelStream } from "../redux/thunks/cancelStream"; import { handleApplyStateUpdate } from "../redux/thunks/handleApplyStateUpdate"; -import { refreshSessionMetadata } from "../redux/thunks/session"; +import { + loadLastSession, + refreshSessionMetadata, +} from "../redux/thunks/session"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; import { setDocumentStylesFromLocalStorage, @@ -104,6 +107,7 @@ function ParallelListeners() { await handleConfigUpdate(true, result.content); } dispatch(setConfigLoading(false)); + await dispatch(loadLastSession()); } void initialLoadConfig(); const interval = setInterval(() => { diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 61fc0a859..871188cee 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -45,6 +45,7 @@ import { ToolCallDiv } from "./ToolCallDiv"; import { useStore } from "react-redux"; import { CliInstallBanner } from "../../components/CliInstallBanner"; + import { FatalErrorIndicator } from "../../components/config/FatalErrorNotice"; import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage"; import { RootState } from "../../redux/store"; @@ -441,11 +442,7 @@ export function Chat() { {history.length === 0 && lastSessionId && !isInEdit && ( { - await dispatch( - loadLastSession({ - saveCurrentSession: true, - }), - ); + await dispatch(loadLastSession()); }} className="flex items-center gap-2" > diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 0bd38f1fd..73b425f5d 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -35,7 +35,6 @@ const rootReducer = combineReducers({ const saveSubsetFilters = [ createFilter("session", [ - "history", "id", "lastSessionId", "title", @@ -73,7 +72,6 @@ const migrations: MigrationManifest = { defaultModelTitle: oldState?.state?.defaultModelTitle ?? undefined, }, session: { - history: oldState?.state?.history ?? [], id: oldState?.state?.sessionId ?? "", }, tabs: { diff --git a/gui/src/redux/thunks/edit.ts b/gui/src/redux/thunks/edit.ts index 700d49d55..c2192ab9e 100644 --- a/gui/src/redux/thunks/edit.ts +++ b/gui/src/redux/thunks/edit.ts @@ -109,11 +109,7 @@ export const exitEdit = createAsyncThunk< if (openNewSession || state.editModeState.lastNonEditSessionWasEmpty) { dispatch(newSession()); } else { - await dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); + await dispatch(loadLastSession()); } dispatch(setMode(state.editModeState.returnToMode)); diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index f6314cbb0..e89acb78f 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -67,11 +67,7 @@ export const deleteSession = createAsyncThunk( dispatch(deleteSessionMetadata(id)); // optimistic const state = getState(); if (id === state.session.id) { - await dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); + await dispatch(loadLastSession()); } const result = await extra.ideMessenger.request("history/delete", { id }); if (result.status === "error") { @@ -146,27 +142,31 @@ export const loadRemoteSession = createAsyncThunk< }, ); -export const loadLastSession = createAsyncThunk< - void, - { - saveCurrentSession: boolean; - }, - ThunkApiType ->( +export const loadLastSession = createAsyncThunk( "session/loadLast", - async ({ saveCurrentSession }, { extra, dispatch, getState }) => { - const state = getState(); + async (_, { extra, dispatch, getState }) => { + let lastSessionId = getState().session.lastSessionId; - if (state.session.id && saveCurrentSession) { - } - const lastSessionId = getState().session.lastSessionId; + // const lastSessionResult = await extra.ideMessenger.request("history/list", { + // limit: 1, + // }); + // if (lastSessionResult.status === "success") { + // lastSessionId = lastSessionResult.content.at(0)?.sessionId; + // } if (!lastSessionId) { dispatch(newSession()); return; } - const session = await getSession(extra.ideMessenger, lastSessionId); + let session: Session; + try { + session = await getSession(extra.ideMessenger, lastSessionId); + } catch { + // retry again after 1 sec + await new Promise((resolve) => setTimeout(resolve, 1000)); + session = await getSession(extra.ideMessenger, lastSessionId); + } dispatch(newSession(session)); }, );