From 18a4fbba3a6ccf7a13a61bc39a90501927a08d81 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 24 Sep 2025 21:45:49 +0530 Subject: [PATCH 01/37] chore: remove chat history from redux persistent storage --- gui/src/redux/store.ts | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 0bd38f1fd..959fa610b 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -4,7 +4,6 @@ import { ThunkDispatch, UnknownAction, } from "@reduxjs/toolkit"; -import { createLogger } from "redux-logger"; import { createMigrate, MigrationManifest, @@ -35,7 +34,6 @@ const rootReducer = combineReducers({ const saveSubsetFilters = [ createFilter("session", [ - "history", "id", "lastSessionId", "title", @@ -73,7 +71,6 @@ const migrations: MigrationManifest = { defaultModelTitle: oldState?.state?.defaultModelTitle ?? undefined, }, session: { - history: oldState?.state?.history ?? [], id: oldState?.state?.sessionId ?? "", }, tabs: { @@ -108,13 +105,6 @@ const persistedReducer = persistReducer>( export function setupStore(options: { ideMessenger?: IIdeMessenger }) { const ideMessenger = options.ideMessenger ?? new IdeMessenger(); - const logger = createLogger({ - // Customize logger options if needed - collapsed: true, // Collapse console groups by default - timestamp: false, // Remove timestamps from log - diff: true, // Show diff between states - }); - return configureStore({ // persistedReducer causes type errors with async thunks reducer: persistedReducer as unknown as typeof rootReducer, From e78456c82dcfc94a46cdcb48d3edcc707f20d1cb Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 25 Sep 2025 17:46:44 +0530 Subject: [PATCH 02/37] remove unused variables in load session --- gui/src/pages/gui/Chat.tsx | 10 +++------- gui/src/redux/thunks/edit.ts | 6 +----- gui/src/redux/thunks/session.ts | 22 ++++------------------ 3 files changed, 8 insertions(+), 30 deletions(-) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 08ca69498..f7e9c308d 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -43,14 +43,14 @@ import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { ToolCallDiv } from "./ToolCallDiv"; +import { useStore } from "react-redux"; import { FatalErrorIndicator } from "../../components/config/FatalErrorNotice"; import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage"; +import { RootState } from "../../redux/store"; import { cancelStream } from "../../redux/thunks/cancelStream"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { useAutoScroll } from "./useAutoScroll"; -import { useStore } from "react-redux"; -import { RootState } from "../../redux/store"; // Helper function to find the index of the latest conversation summary function findLatestSummaryIndex(history: ChatHistoryItem[]): number { @@ -431,11 +431,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/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 c2fe35c36..8172d7b7c 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -1,5 +1,5 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { ChatMessage, Session, BaseSessionMetadata } from "core"; +import { BaseSessionMetadata, ChatMessage, Session } from "core"; import { RemoteSessionMetadata } from "core/control-plane/client"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { renderChatMessage } from "core/util/messageContent"; @@ -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,19 +142,9 @@ 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(); - - if (state.session.id && saveCurrentSession) { - } + async (_, { extra, dispatch, getState }) => { const lastSessionId = getState().session.lastSessionId; if (!lastSessionId) { From a6daeb8dde3ba73f2376a8e6c254bc8053bfcc38 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 25 Sep 2025 17:55:15 +0530 Subject: [PATCH 03/37] add loading to last session --- gui/src/pages/gui/Chat.tsx | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index f7e9c308d..ede1aa607 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -114,8 +114,8 @@ export function Chat() { const showChatScrollbar = useAppSelector( (state) => state.config.config.ui?.showChatScrollbar, ); - const codeToEdit = useAppSelector((state) => state.editModeState.codeToEdit); const isInEdit = useAppSelector((store) => store.session.isInEdit); + const [sessionLastLoading, setLastSessionLoading] = useState(false); const lastSessionId = useAppSelector((state) => state.session.lastSessionId); const hasDismissedExploreDialog = useAppSelector( @@ -431,12 +431,21 @@ export function Chat() { {history.length === 0 && lastSessionId && !isInEdit && ( { + if (sessionLastLoading) return; + setLastSessionLoading(true); await dispatch(loadLastSession()); + setLastSessionLoading(false); }} className="flex items-center gap-2" > - - Last Session + {sessionLastLoading ? ( + loading last session... + ) : ( + <> + + Last Session + + )} )} From 93cf238b5b0a6fc8cbeaeaf9c1dbc50e7dc29d0a Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 26 Sep 2025 11:15:58 +0530 Subject: [PATCH 04/37] Revert "add loading to last session" This reverts commit a6daeb8dde3ba73f2376a8e6c254bc8053bfcc38. --- gui/src/pages/gui/Chat.tsx | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index ede1aa607..f7e9c308d 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -114,8 +114,8 @@ export function Chat() { const showChatScrollbar = useAppSelector( (state) => state.config.config.ui?.showChatScrollbar, ); + const codeToEdit = useAppSelector((state) => state.editModeState.codeToEdit); const isInEdit = useAppSelector((store) => store.session.isInEdit); - const [sessionLastLoading, setLastSessionLoading] = useState(false); const lastSessionId = useAppSelector((state) => state.session.lastSessionId); const hasDismissedExploreDialog = useAppSelector( @@ -431,21 +431,12 @@ export function Chat() { {history.length === 0 && lastSessionId && !isInEdit && ( { - if (sessionLastLoading) return; - setLastSessionLoading(true); await dispatch(loadLastSession()); - setLastSessionLoading(false); }} className="flex items-center gap-2" > - {sessionLastLoading ? ( - loading last session... - ) : ( - <> - - Last Session - - )} + + Last Session )} From a8f1d30ec6449cdcedb7ba7991f38374c5457a1a Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 26 Sep 2025 11:45:13 +0530 Subject: [PATCH 05/37] load last session on first load --- gui/src/hooks/ParallelListeners.tsx | 9 ++++++++- gui/src/redux/store.ts | 1 - gui/src/redux/thunks/session.ts | 9 ++++++++- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 510733da9..2d3413327 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, @@ -240,6 +243,10 @@ function ParallelListeners() { migrateLocalStorage(dispatch); }, []); + useEffect(() => { + void dispatch(loadLastSession()); + }, []); + return <>; } diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 959fa610b..8ffb22dc2 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -35,7 +35,6 @@ const rootReducer = combineReducers({ const saveSubsetFilters = [ createFilter("session", [ "id", - "lastSessionId", "title", // Persist edit mode in case closes in middle diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index 8172d7b7c..5fadfb685 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -145,7 +145,14 @@ export const loadRemoteSession = createAsyncThunk< export const loadLastSession = createAsyncThunk( "session/loadLast", async (_, { extra, dispatch, getState }) => { - const lastSessionId = getState().session.lastSessionId; + let 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()); From 915214a26f384ba792fb3b424b338b2feb260bbe Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 6 Oct 2025 19:44:13 +0530 Subject: [PATCH 06/37] revert logger and storing sessionid --- gui/src/redux/store.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 8ffb22dc2..73b425f5d 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -4,6 +4,7 @@ import { ThunkDispatch, UnknownAction, } from "@reduxjs/toolkit"; +import { createLogger } from "redux-logger"; import { createMigrate, MigrationManifest, @@ -35,6 +36,7 @@ const rootReducer = combineReducers({ const saveSubsetFilters = [ createFilter("session", [ "id", + "lastSessionId", "title", // Persist edit mode in case closes in middle @@ -104,6 +106,13 @@ const persistedReducer = persistReducer>( export function setupStore(options: { ideMessenger?: IIdeMessenger }) { const ideMessenger = options.ideMessenger ?? new IdeMessenger(); + const logger = createLogger({ + // Customize logger options if needed + collapsed: true, // Collapse console groups by default + timestamp: false, // Remove timestamps from log + diff: true, // Show diff between states + }); + return configureStore({ // persistedReducer causes type errors with async thunks reducer: persistedReducer as unknown as typeof rootReducer, From a58ddfa17552e7cc03d63577d5ca7438364fa3a8 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 6 Oct 2025 19:45:35 +0530 Subject: [PATCH 07/37] comment out lastSessionResult --- gui/src/redux/thunks/session.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index 5fadfb685..a4404095a 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -147,12 +147,12 @@ export const loadLastSession = createAsyncThunk( async (_, { extra, dispatch, getState }) => { let lastSessionId = getState().session.lastSessionId; - const lastSessionResult = await extra.ideMessenger.request("history/list", { - limit: 1, - }); - if (lastSessionResult.status === "success") { - lastSessionId = lastSessionResult.content.at(0)?.sessionId; - } + // const lastSessionResult = await extra.ideMessenger.request("history/list", { + // limit: 1, + // }); + // if (lastSessionResult.status === "success") { + // lastSessionId = lastSessionResult.content.at(0)?.sessionId; + // } if (!lastSessionId) { dispatch(newSession()); From 0122c6bee82da2197780b564f27d81ae512cb456 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 7 Oct 2025 18:30:06 +0530 Subject: [PATCH 08/37] try catch loadLastSession --- gui/src/redux/thunks/session.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index a4404095a..e89acb78f 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -159,7 +159,14 @@ export const loadLastSession = createAsyncThunk( 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)); }, ); From 91adad26077ffe93d680c3bdfa0440d946408667 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 11:11:28 -0700 Subject: [PATCH 09/37] feat: go back in history --- extensions/cli/src/ui/EditMessageSelector.tsx | 222 ++++++++++++++++++ extensions/cli/src/ui/TUIChat.tsx | 5 + extensions/cli/src/ui/UserInput.tsx | 22 ++ .../cli/src/ui/components/ScreenContent.tsx | 25 ++ .../cli/src/ui/context/NavigationContext.tsx | 1 + extensions/cli/src/ui/hooks/useChat.ts | 30 +++ extensions/cli/src/ui/hooks/useChat.types.ts | 1 + 7 files changed, 306 insertions(+) create mode 100644 extensions/cli/src/ui/EditMessageSelector.tsx diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx new file mode 100644 index 000000000..ef86afd6c --- /dev/null +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -0,0 +1,222 @@ +import { Box, Text, useInput } from "ink"; +import React, { useMemo, useState } from "react"; + +import type { ChatHistoryItem } from "../../../../core/index.js"; + +import { TextBuffer } from "./TextBuffer.js"; +import { defaultBoxStyles } from "./styles.js"; + +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(0); + const [isEditing, setIsEditing] = useState(false); + const [textBuffer] = useState(() => new TextBuffer()); + const [editText, setEditText] = useState(""); + const [cursorPosition, setCursorPosition] = useState(0); + + // 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]); + + useInput((input, key) => { + // If not editing, handle navigation + if (!isEditing) { + if (key.upArrow || input === "k") { + setSelectedIndex((prev) => + prev > 0 ? prev - 1 : userMessages.length - 1, + ); + } else if (key.downArrow || input === "j") { + setSelectedIndex((prev) => + prev < userMessages.length - 1 ? prev + 1 : 0, + ); + } else if (key.return) { + setIsEditing(true); + } else if (key.escape || (key.ctrl && input === "d")) { + onExit(); + } + } else { + // In edit mode, handle text input + if (key.escape) { + setIsEditing(false); + // Reset text to original + const content = + typeof userMessages[selectedIndex].item.message.content === "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setText(content); + setEditText(content); + setCursorPosition(content.length); + } else if (key.return && !key.shift) { + // Submit the edit + 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); + } + } + }); + + 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 || " "}; + } + })} + + ); + }; + + const selectedMessage = userMessages[selectedIndex]; + const messageContent = + typeof selectedMessage?.item.message.content === "string" + ? selectedMessage.item.message.content + : ""; + + 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 555c32829..9b96bdef7 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -227,6 +227,7 @@ const TUIChat: React.FC = ({ handleInterrupt, handleFileAttached, resetChatHistory, + handleEditMessage, handleToolPermissionResponse, } = useChat({ assistant: services.config?.config || undefined, @@ -242,6 +243,7 @@ const TUIChat: React.FC = ({ onShowMCPSelector: () => navigateTo("mcp"), onShowUpdateSelector: () => navigateTo("update"), onShowSessionSelector: () => navigateTo("session"), + onShowEditSelector: () => navigateTo("edit"), onLoginPrompt: handleLoginPrompt, onReload: handleReload, onClear: handleClear, @@ -377,6 +379,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..7e6abd34a 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -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 [lastEscapePress, setLastEscapePress] = useState(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 - lastEscapePress < 500 + ) { + // Double escape detected + onShowEditSelector(); + setLastEscapePress(0); // Reset to prevent triple-escape + return true; + } + + // Track single escape press + setLastEscapePress(now); + return false; }; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 977d6954a..3be048246 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -1,11 +1,13 @@ import { Box, Text } from "ink"; import React from "react"; +import type { ChatHistoryItem } from "../../../../../core/index.js"; import { UpdateServiceState } from "src/services/types.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 { MCPSelector } from "../MCPSelector.js"; import { ModelSelector } from "../ModelSelector.js"; @@ -44,6 +46,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 +82,9 @@ export const ScreenContent: React.FC = ({ isRemoteMode, onImageInClipboardChange, diffContent, + chatHistory = [], + handleEditMessage, + onShowEditSelector, }) => { if (hideScreenContent(services.update)) { return null; @@ -162,6 +170,22 @@ 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) { @@ -189,6 +213,7 @@ export const ScreenContent: React.FC = ({ disabled={isInputDisabled} isRemoteMode={isRemoteMode} onImageInClipboardChange={onImageInClipboardChange} + onShowEditSelector={onShowEditSelector} /> ); } 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..5029435f1 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -58,6 +58,7 @@ export function useChat({ onShowUpdateSelector, onShowMCPSelector, onShowSessionSelector, + onShowEditSelector, onLoginPrompt: _onLoginPrompt, onClear, isRemoteMode = false, @@ -721,6 +722,34 @@ export function useChat({ setQueuedMessages([]); }; + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + // Close the edit selector if callback is available + if (onShowEditSelector) { + // The screen will be closed automatically by the navigation system + } + + // Rewind chat history to the selected message index + const rewindedHistory = chatHistory.slice(0, messageIndex); + + // Update the chat history with the rewound version + setChatHistory(rewindedHistory); + + // Clear any queued messages + setQueuedMessages([]); + + // Clear attached files + setAttachedFiles([]); + + // Update the session with the rewound history + updateSessionHistory(rewindedHistory); + + // Resubmit the edited message + await processMessage(newContent, undefined, false); + }; + const handleToolPermissionResponse = async ( requestId: string, approved: boolean, @@ -803,6 +832,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..d85962b78 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -18,6 +18,7 @@ export interface UseChatProps { onShowUpdateSelector: () => void; onShowModelSelector?: () => void; onShowSessionSelector?: () => void; + onShowEditSelector?: () => void; onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; onClear?: () => void; From 23ba9a54007ec60f40feabdf82fce7afb9189d7f Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 11:42:23 -0700 Subject: [PATCH 10/37] improv: message history ux --- extensions/cli/src/ui/EditMessageSelector.tsx | 17 ++++++- extensions/cli/src/ui/TUIChat.tsx | 3 ++ .../cli/src/ui/components/ScreenContent.tsx | 3 ++ extensions/cli/src/ui/hooks/useChat.ts | 50 +++++++++++++++---- extensions/cli/src/ui/hooks/useChat.types.ts | 1 + 5 files changed, 64 insertions(+), 10 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index ef86afd6c..7797b297f 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -9,12 +9,14 @@ import { defaultBoxStyles } from "./styles.js"; interface EditMessageSelectorProps { chatHistory: ChatHistoryItem[]; onEdit: (messageIndex: number, newContent: string) => void; + onMessageSelected?: (originalIndex: number) => void; onExit: () => void; } export function EditMessageSelector({ chatHistory, onEdit, + onMessageSelected, onExit, }: EditMessageSelectorProps) { // Filter to only show user messages @@ -24,7 +26,9 @@ export function EditMessageSelector({ .filter(({ item }) => item.message.role === "user"); }, [chatHistory]); - const [selectedIndex, setSelectedIndex] = useState(0); + const [selectedIndex, setSelectedIndex] = useState( + Math.max(0, userMessages.length - 1), + ); const [isEditing, setIsEditing] = useState(false); const [textBuffer] = useState(() => new TextBuffer()); const [editText, setEditText] = useState(""); @@ -55,6 +59,17 @@ export function EditMessageSelector({ prev < userMessages.length - 1 ? prev + 1 : 0, ); } else if (key.return) { + // Notify parent that a message was selected for editing + if (onMessageSelected && userMessages[selectedIndex]) { + const originalIndex = userMessages[selectedIndex].originalIndex; + console.log("EditMessageSelector: User pressed Enter", { + selectedIndex, + originalIndex, + totalUserMessages: userMessages.length, + totalChatHistory: chatHistory.length, + }); + onMessageSelected(originalIndex); + } setIsEditing(true); } else if (key.escape || (key.ctrl && input === "d")) { onExit(); diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 9b96bdef7..bf8414cc2 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -227,6 +227,7 @@ const TUIChat: React.FC = ({ handleInterrupt, handleFileAttached, resetChatHistory, + handleSelectMessageForEdit, handleEditMessage, handleToolPermissionResponse, } = useChat({ @@ -247,6 +248,7 @@ const TUIChat: React.FC = ({ onLoginPrompt: handleLoginPrompt, onReload: handleReload, onClear: handleClear, + onRefreshStatic: () => setStaticRefreshTrigger((prev) => prev + 1), // Remote mode configuration isRemoteMode, remoteUrl, @@ -380,6 +382,7 @@ const TUIChat: React.FC = ({ onImageInClipboardChange={setHasImageInClipboard} diffContent={diffContent} chatHistory={chatHistory} + handleSelectMessageForEdit={handleSelectMessageForEdit} handleEditMessage={handleEditMessage} onShowEditSelector={() => navigateTo("edit")} /> diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 3be048246..77aa58ee4 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -47,6 +47,7 @@ interface ScreenContentProps { onImageInClipboardChange?: (hasImage: boolean) => void; diffContent?: string; chatHistory?: ChatHistoryItem[]; + handleSelectMessageForEdit?: (originalIndex: number) => void; handleEditMessage?: (messageIndex: number, newContent: string) => void; onShowEditSelector?: () => void; } @@ -83,6 +84,7 @@ export const ScreenContent: React.FC = ({ onImageInClipboardChange, diffContent, chatHistory = [], + handleSelectMessageForEdit, handleEditMessage, onShowEditSelector, }) => { @@ -175,6 +177,7 @@ export const ScreenContent: React.FC = ({ return ( { if (handleEditMessage) { handleEditMessage(messageIndex, newContent); diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 5029435f1..6c7fd65e4 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -61,6 +61,7 @@ export function useChat({ onShowEditSelector, onLoginPrompt: _onLoginPrompt, onClear, + onRefreshStatic, isRemoteMode = false, remoteUrl, onShowDiff, @@ -722,17 +723,22 @@ export function useChat({ setQueuedMessages([]); }; - const handleEditMessage = async ( - messageIndex: number, - newContent: string, + const handleSelectMessageForEdit = ( + originalIndex: number, + onComplete?: () => void, ) => { - // Close the edit selector if callback is available - if (onShowEditSelector) { - // The screen will be closed automatically by the navigation system - } + logger.debug("handleSelectMessageForEdit called", { + originalIndex, + currentHistoryLength: chatHistory.length, + }); - // Rewind chat history to the selected message index - const rewindedHistory = chatHistory.slice(0, messageIndex); + // Rewind chat history to the selected message index (up to and including the message) + const rewindedHistory = chatHistory.slice(0, originalIndex + 1); + + logger.debug("Rewinding history", { + from: chatHistory.length, + to: rewindedHistory.length, + }); // Update the chat history with the rewound version setChatHistory(rewindedHistory); @@ -746,6 +752,31 @@ export function useChat({ // Update the session with the rewound history updateSessionHistory(rewindedHistory); + // Force refresh of StaticChatContent to show truncated history + if (onRefreshStatic) { + onRefreshStatic(); + } + + // Call onComplete callback if provided + if (onComplete) { + onComplete(); + } + }; + + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + // At this point, history is already rewound to the selected message + // We need to rewind one more step to exclude the original message, then resubmit + const rewindedHistory = chatHistory.slice(0, messageIndex); + + // Update the chat history to exclude the message being edited + setChatHistory(rewindedHistory); + + // Update the session + updateSessionHistory(rewindedHistory); + // Resubmit the edited message await processMessage(newContent, undefined, false); }; @@ -832,6 +863,7 @@ export function useChat({ handleInterrupt, handleFileAttached, resetChatHistory, + handleSelectMessageForEdit, handleEditMessage, handleToolPermissionResponse, }; diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index d85962b78..fa0e6fd13 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -22,6 +22,7 @@ export interface UseChatProps { onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; onClear?: () => void; + onRefreshStatic?: () => void; // Remote mode props isRemoteMode?: boolean; remoteUrl?: string; From 9de20396ce1faebbae555f93b69d0ca918faad21 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 13:22:19 -0700 Subject: [PATCH 11/37] improv: architecture --- extensions/cli/src/ui/EditMessageSelector.tsx | 14 +---- extensions/cli/src/ui/TUIChat.tsx | 2 - .../cli/src/ui/components/ScreenContent.tsx | 3 -- extensions/cli/src/ui/hooks/useChat.ts | 53 ++++++------------- 4 files changed, 18 insertions(+), 54 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 7797b297f..24fdcc408 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -9,14 +9,12 @@ import { defaultBoxStyles } from "./styles.js"; interface EditMessageSelectorProps { chatHistory: ChatHistoryItem[]; onEdit: (messageIndex: number, newContent: string) => void; - onMessageSelected?: (originalIndex: number) => void; onExit: () => void; } export function EditMessageSelector({ chatHistory, onEdit, - onMessageSelected, onExit, }: EditMessageSelectorProps) { // Filter to only show user messages @@ -59,17 +57,7 @@ export function EditMessageSelector({ prev < userMessages.length - 1 ? prev + 1 : 0, ); } else if (key.return) { - // Notify parent that a message was selected for editing - if (onMessageSelected && userMessages[selectedIndex]) { - const originalIndex = userMessages[selectedIndex].originalIndex; - console.log("EditMessageSelector: User pressed Enter", { - selectedIndex, - originalIndex, - totalUserMessages: userMessages.length, - totalChatHistory: chatHistory.length, - }); - onMessageSelected(originalIndex); - } + // Start editing the selected message setIsEditing(true); } else if (key.escape || (key.ctrl && input === "d")) { onExit(); diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index bf8414cc2..0ecaa0fe8 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -227,7 +227,6 @@ const TUIChat: React.FC = ({ handleInterrupt, handleFileAttached, resetChatHistory, - handleSelectMessageForEdit, handleEditMessage, handleToolPermissionResponse, } = useChat({ @@ -382,7 +381,6 @@ const TUIChat: React.FC = ({ onImageInClipboardChange={setHasImageInClipboard} diffContent={diffContent} chatHistory={chatHistory} - handleSelectMessageForEdit={handleSelectMessageForEdit} handleEditMessage={handleEditMessage} onShowEditSelector={() => navigateTo("edit")} /> diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 77aa58ee4..3be048246 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -47,7 +47,6 @@ interface ScreenContentProps { onImageInClipboardChange?: (hasImage: boolean) => void; diffContent?: string; chatHistory?: ChatHistoryItem[]; - handleSelectMessageForEdit?: (originalIndex: number) => void; handleEditMessage?: (messageIndex: number, newContent: string) => void; onShowEditSelector?: () => void; } @@ -84,7 +83,6 @@ export const ScreenContent: React.FC = ({ onImageInClipboardChange, diffContent, chatHistory = [], - handleSelectMessageForEdit, handleEditMessage, onShowEditSelector, }) => { @@ -177,7 +175,6 @@ export const ScreenContent: React.FC = ({ return ( { if (handleEditMessage) { handleEditMessage(messageIndex, newContent); diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 6c7fd65e4..2b1028be1 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -457,7 +457,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, @@ -526,7 +530,7 @@ export function useChat({ let currentChatHistory, currentCompactionIndex; try { const result = await handleAutoCompaction({ - chatHistory, + chatHistory: currentHistory, model, llmApi, compactionIndex, @@ -593,7 +597,7 @@ export function useChat({ let currentChatHistory, currentCompactionIndex; try { const result = await handleAutoCompaction({ - chatHistory, + chatHistory: currentHistory, model, llmApi, compactionIndex, @@ -723,26 +727,23 @@ export function useChat({ setQueuedMessages([]); }; - const handleSelectMessageForEdit = ( - originalIndex: number, - onComplete?: () => void, + const handleEditMessage = async ( + messageIndex: number, + newContent: string, ) => { - logger.debug("handleSelectMessageForEdit called", { - originalIndex, + logger.debug("handleEditMessage called", { + messageIndex, currentHistoryLength: chatHistory.length, }); - // Rewind chat history to the selected message index (up to and including the message) - const rewindedHistory = chatHistory.slice(0, originalIndex + 1); + // Rewind chat history to exclude the message being edited + const rewindedHistory = chatHistory.slice(0, messageIndex); - logger.debug("Rewinding history", { + logger.debug("Rewinding history for edit", { from: chatHistory.length, to: rewindedHistory.length, }); - // Update the chat history with the rewound version - setChatHistory(rewindedHistory); - // Clear any queued messages setQueuedMessages([]); @@ -757,28 +758,9 @@ export function useChat({ onRefreshStatic(); } - // Call onComplete callback if provided - if (onComplete) { - onComplete(); - } - }; - - const handleEditMessage = async ( - messageIndex: number, - newContent: string, - ) => { - // At this point, history is already rewound to the selected message - // We need to rewind one more step to exclude the original message, then resubmit - const rewindedHistory = chatHistory.slice(0, messageIndex); - - // Update the chat history to exclude the message being edited - setChatHistory(rewindedHistory); - - // Update the session - updateSessionHistory(rewindedHistory); - - // Resubmit the edited message - await processMessage(newContent, undefined, false); + // 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 ( @@ -863,7 +845,6 @@ export function useChat({ handleInterrupt, handleFileAttached, resetChatHistory, - handleSelectMessageForEdit, handleEditMessage, handleToolPermissionResponse, }; From 82a681bc8420df5a361b282602766ca4ef3ec058 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 13:38:32 -0700 Subject: [PATCH 12/37] fix: message input --- extensions/cli/src/ui/EditMessageSelector.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 24fdcc408..9aa876e1e 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -57,7 +57,13 @@ export function EditMessageSelector({ prev < userMessages.length - 1 ? prev + 1 : 0, ); } else if (key.return) { - // Start editing the selected message + // Start editing the selected message - set cursor to end + const content = + typeof userMessages[selectedIndex]?.item.message.content === "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setCursor(content.length); + setCursorPosition(content.length); setIsEditing(true); } else if (key.escape || (key.ctrl && input === "d")) { onExit(); From 5247d08f59f051c4d54472e38c2262b5b8482e37 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 13:55:00 -0700 Subject: [PATCH 13/37] test: message history edits --- .../cli/src/ui/EditMessageSelector.test.tsx | 238 +++++++++++++ .../ui/__tests__/TUIChat.editMessage.test.tsx | 265 ++++++++++++++ .../cli/src/ui/hooks/useChat.edit.test.ts | 337 ++++++++++++++++++ 3 files changed, 840 insertions(+) create mode 100644 extensions/cli/src/ui/EditMessageSelector.test.tsx create mode 100644 extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx create mode 100644 extensions/cli/src/ui/hooks/useChat.edit.test.ts diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx new file mode 100644 index 000000000..06d090ae9 --- /dev/null +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -0,0 +1,238 @@ +/** + * @vitest-environment jsdom + */ +import { render } from "@testing-library/react"; +import type { ChatHistoryItem } from "core/index.js"; +import { Box } from "ink"; +import React from "react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import { EditMessageSelector } from "./EditMessageSelector.js"; +import { TextBuffer } from "./TextBuffer.js"; + +// Mock TextBuffer for controlled testing +vi.mock("./TextBuffer.js", () => { + return { + TextBuffer: vi.fn().mockImplementation(() => ({ + text: "", + cursor: 0, + setText: vi.fn(), + setCursor: vi.fn(), + handleInput: vi.fn(), + })), + }; +}); + +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("Cursor positioning bug fix", () => { + it("should position cursor at end when entering edit mode", () => { + const chatHistory: ChatHistoryItem[] = [ + { message: { role: "user", content: "Hello world" }, contextItems: [] }, + ]; + + const mockTextBuffer = new TextBuffer(); + const mockSetCursor = vi.fn(); + mockTextBuffer.setCursor = mockSetCursor; + + // This test verifies the fix: when Enter is pressed to start editing, + // setCursor should be called with content.length + // The actual implementation test would require simulating Enter keypress + // which is complex with Ink components + + // For now, this test documents the expected behavior + const messageContent = "Hello world"; + expect(messageContent.length).toBe(11); + }); + }); + + 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/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx new file mode 100644 index 000000000..21e62c7b2 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -0,0 +1,265 @@ +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); + + // 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)); + + const frame = lastFrame(); + + // Should show edit message selector + // The exact text depends on implementation, but should indicate edit mode + if (mode === "local") { + // In local mode, edit selector should be available + expect(frame).toBeDefined(); + // Note: The actual UI content will depend on chat history + // This test verifies the component doesn't crash + } + }); + + 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)); + + // 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)); + + const frame = lastFrame(); + + // Should handle navigation without crashing + expect(frame).toBeDefined(); + }); + + 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)); + + // Press Esc to exit + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should return to normal chat view + expect(frame).toBeDefined(); + expect(frame).toContain("Ask anything"); + }); + + 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\u001b"); // Open edit + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("k"); // Navigate + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("\u001b"); // Close + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // UI should remain stable + expect(frame).toBeDefined(); + expect(frame.length).toBeGreaterThan(0); + + // Should still show chat interface + if (mode === "local") { + expect(frame).toContain("Continue CLI"); + } else { + expect(frame).toContain("Remote Mode"); + } + }, + ); +}); + +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 + + stdin.write("\u001b"); // Another single Esc after timeout + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should not open edit selector (requires double Esc within 500ms) + // Instead should just remain in normal mode + expect(frame).toBeDefined(); + }); + + 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/hooks/useChat.edit.test.ts b/extensions/cli/src/ui/hooks/useChat.edit.test.ts new file mode 100644 index 000000000..c45259dc4 --- /dev/null +++ b/extensions/cli/src/ui/hooks/useChat.edit.test.ts @@ -0,0 +1,337 @@ +import type { ChatHistoryItem } from "core/index.js"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +/** + * Tests for the message edit feature in useChat hook + * + * This test suite covers: + * - handleEditMessage: Rewinds history and resubmits edited message + * - processMessage with baseHistory: Uses explicit base history instead of state + * - Integration: Full edit flow produces correct final history + */ + +describe("useChat - Message Edit Feature", () => { + const createMockChatHistory = (count: number): ChatHistoryItem[] => { + return Array.from({ length: count }, (_, i) => ({ + message: { + role: i % 2 === 0 ? "user" : "assistant", + content: `Message ${i + 1}`, + }, + contextItems: [], + })); + }; + + describe("handleEditMessage", () => { + it("should rewind history to exclude the message being edited", () => { + const chatHistory = createMockChatHistory(5); // [user, asst, user, asst, user] + let currentHistory = chatHistory; + + const setChatHistory = vi.fn(); + const setQueuedMessages = vi.fn(); + const setAttachedFiles = vi.fn(); + const updateSessionHistory = vi.fn(); + const onRefreshStatic = vi.fn(); + const processMessage = vi.fn(); + + // Mock handleEditMessage behavior + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + const rewindedHistory = currentHistory.slice(0, messageIndex); + setQueuedMessages([]); + setAttachedFiles([]); + updateSessionHistory(rewindedHistory); + if (onRefreshStatic) { + onRefreshStatic(); + } + await processMessage(newContent, undefined, false, rewindedHistory); + }; + + // Edit message at index 2 (third message) + handleEditMessage(2, "Edited message"); + + // Verify history was rewound to [0, 1] + expect(updateSessionHistory).toHaveBeenCalledWith( + chatHistory.slice(0, 2), + ); + + // Verify state was cleared + expect(setQueuedMessages).toHaveBeenCalledWith([]); + expect(setAttachedFiles).toHaveBeenCalledWith([]); + + // Verify refresh was called + expect(onRefreshStatic).toHaveBeenCalled(); + + // Verify processMessage was called with correct baseHistory + expect(processMessage).toHaveBeenCalledWith( + "Edited message", + undefined, + false, + chatHistory.slice(0, 2), + ); + }); + + it("should handle editing the first message", () => { + const chatHistory = createMockChatHistory(5); + let currentHistory = chatHistory; + + const updateSessionHistory = vi.fn(); + const processMessage = vi.fn(); + + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + const rewindedHistory = currentHistory.slice(0, messageIndex); + updateSessionHistory(rewindedHistory); + await processMessage(newContent, undefined, false, rewindedHistory); + }; + + // Edit first message (index 0) + handleEditMessage(0, "New first message"); + + // Should rewind to empty history + expect(updateSessionHistory).toHaveBeenCalledWith([]); + expect(processMessage).toHaveBeenCalledWith( + "New first message", + undefined, + false, + [], + ); + }); + + it("should handle editing the last message", () => { + const chatHistory = createMockChatHistory(5); + let currentHistory = chatHistory; + + const updateSessionHistory = vi.fn(); + const processMessage = vi.fn(); + + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + const rewindedHistory = currentHistory.slice(0, messageIndex); + updateSessionHistory(rewindedHistory); + await processMessage(newContent, undefined, false, rewindedHistory); + }; + + // Edit last message (index 4) + handleEditMessage(4, "Edited last message"); + + // Should rewind to [0, 1, 2, 3] + expect(updateSessionHistory).toHaveBeenCalledWith( + chatHistory.slice(0, 4), + ); + expect(processMessage).toHaveBeenCalledWith( + "Edited last message", + undefined, + false, + chatHistory.slice(0, 4), + ); + }); + }); + + describe("processMessage with baseHistory", () => { + it("should use baseHistory instead of chatHistory when provided", () => { + // Simulate the scenario where chatHistory state hasn't updated yet + const oldChatHistory = createMockChatHistory(5); + const baseHistory = oldChatHistory.slice(0, 2); // Rewound history + + // Mock processMessage that uses baseHistory parameter + const processMessage = ( + message: string, + imageMap?: Map, + isQueuedMessage: boolean = false, + baseHistory?: ChatHistoryItem[], + ) => { + const currentHistory = baseHistory ?? oldChatHistory; + return currentHistory; + }; + + // Call with baseHistory + const result = processMessage( + "New message", + undefined, + false, + baseHistory, + ); + + // Should use baseHistory, not oldChatHistory + expect(result).toEqual(baseHistory); + expect(result).not.toEqual(oldChatHistory); + }); + + it("should fall back to chatHistory when baseHistory is not provided", () => { + const chatHistory = createMockChatHistory(3); + + const processMessage = ( + message: string, + imageMap?: Map, + isQueuedMessage: boolean = false, + baseHistory?: ChatHistoryItem[], + ) => { + const currentHistory = baseHistory ?? chatHistory; + return currentHistory; + }; + + // Call without baseHistory + const result = processMessage("New message"); + + // Should use chatHistory + expect(result).toEqual(chatHistory); + }); + }); + + describe("Edit flow integration", () => { + it("should produce correct history after edit and resubmit", async () => { + // Initial history: [user1, asst1, user2, asst2, user3] + const initialHistory = createMockChatHistory(5); + let chatHistory = initialHistory; + + const setChatHistory = vi.fn((updater: any) => { + if (typeof updater === "function") { + chatHistory = updater(chatHistory); + } else { + chatHistory = updater; + } + }); + + // Simulate editing user2 (index 2) + const messageIndexToEdit = 2; + const newContent = "Edited user2"; + + // Step 1: Rewind history + const rewindedHistory = initialHistory.slice(0, messageIndexToEdit); + // Result: [user1, asst1] + + // Step 2: Simulate processMessage adding new user message + const newUserMessage: ChatHistoryItem = { + message: { role: "user", content: newContent }, + contextItems: [], + }; + + const expectedHistory = [...rewindedHistory, newUserMessage]; + // Expected: [user1, asst1, edited_user2] + + setChatHistory(expectedHistory); + + // Verify final history + expect(chatHistory).toHaveLength(3); + expect(chatHistory[0]).toEqual(initialHistory[0]); // user1 + expect(chatHistory[1]).toEqual(initialHistory[1]); // asst1 + expect(chatHistory[2].message.content).toBe(newContent); // edited message + + // Verify old messages are gone + expect(chatHistory).not.toContain(initialHistory[2]); // old user2 + expect(chatHistory).not.toContain(initialHistory[3]); // asst2 + expect(chatHistory).not.toContain(initialHistory[4]); // user3 + }); + + it("should handle editing with queued messages", () => { + const chatHistory = createMockChatHistory(3); + const queuedMessages = ["queued1", "queued2"]; + + const setQueuedMessages = vi.fn(); + const setAttachedFiles = vi.fn(); + + // When editing, should clear queued messages + const handleEdit = () => { + setQueuedMessages([]); + setAttachedFiles([]); + }; + + handleEdit(); + + expect(setQueuedMessages).toHaveBeenCalledWith([]); + expect(setAttachedFiles).toHaveBeenCalledWith([]); + }); + + it("should handle editing with attached files", () => { + const attachedFiles = [ + { path: "/test.txt", content: "test" }, + { path: "/test2.txt", content: "test2" }, + ]; + + const setAttachedFiles = vi.fn(); + + // When editing, should clear attached files + const handleEdit = () => { + setAttachedFiles([]); + }; + + handleEdit(); + + expect(setAttachedFiles).toHaveBeenCalledWith([]); + }); + }); + + describe("Edge cases", () => { + it("should handle editing with empty chat history", () => { + const chatHistory: ChatHistoryItem[] = []; + + const updateSessionHistory = vi.fn(); + const processMessage = vi.fn(); + + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + const rewindedHistory = chatHistory.slice(0, messageIndex); + updateSessionHistory(rewindedHistory); + await processMessage(newContent, undefined, false, rewindedHistory); + }; + + // Attempt to edit (should handle gracefully) + handleEditMessage(0, "New message"); + + expect(updateSessionHistory).toHaveBeenCalledWith([]); + expect(processMessage).toHaveBeenCalledWith( + "New message", + undefined, + false, + [], + ); + }); + + it("should handle editing with out-of-bounds index", () => { + const chatHistory = createMockChatHistory(3); + + const updateSessionHistory = vi.fn(); + + const handleEditMessage = (messageIndex: number) => { + const rewindedHistory = chatHistory.slice(0, messageIndex); + updateSessionHistory(rewindedHistory); + }; + + // Index beyond history length + handleEditMessage(10); + + // slice(0, 10) on array of length 3 returns full array + expect(updateSessionHistory).toHaveBeenCalledWith(chatHistory); + }); + + it("should preserve message structure during edit", () => { + const chatHistory: ChatHistoryItem[] = [ + { + message: { role: "user", content: "Original" }, + contextItems: [{ name: "file.txt", content: "data" }], + }, + ]; + + const rewindedHistory = chatHistory.slice(0, 0); // Empty + const newMessage: ChatHistoryItem = { + message: { role: "user", content: "Edited" }, + contextItems: [], // New message may have different contextItems + }; + + const expectedHistory = [...rewindedHistory, newMessage]; + + expect(expectedHistory).toHaveLength(1); + expect(expectedHistory[0].message.content).toBe("Edited"); + // Original message with its contextItems is gone + expect(expectedHistory[0]).not.toEqual(chatHistory[0]); + }); + }); +}); From b76212fc703d09ee6a34c77ebc972fdb859db8e5 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 14:06:05 -0700 Subject: [PATCH 14/37] improv: tests --- .../src/ui/__tests__/TUIChat.editMessage.test.tsx | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx index 21e62c7b2..6d2c0885f 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -63,15 +63,19 @@ describe("TUIChat - Message Edit Feature", () => { 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)); - const frame = lastFrame(); - - // Should return to normal chat view + // Verify edit selector is closed + frame = lastFrame(); expect(frame).toBeDefined(); - expect(frame).toContain("Ask anything"); + expect(frame).not.toContain("No user messages to edit"); }); testBothModes("should handle edit flow without crashing", async (mode) => { From 8d119691235c17ba575adf95824ce122d2948189 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 14:15:52 -0700 Subject: [PATCH 15/37] improv: tests --- .../ui/__tests__/TUIChat.editMessage.test.tsx | 52 ++++++++++--------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx index 6d2c0885f..e50f59948 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -15,6 +15,11 @@ 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 @@ -22,16 +27,10 @@ describe("TUIChat - Message Edit Feature", () => { // Wait for UI to update await new Promise((resolve) => setTimeout(resolve, 100)); - const frame = lastFrame(); - - // Should show edit message selector - // The exact text depends on implementation, but should indicate edit mode - if (mode === "local") { - // In local mode, edit selector should be available - expect(frame).toBeDefined(); - // Note: The actual UI content will depend on chat history - // This test verifies the component doesn't crash - } + // 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) => { @@ -42,6 +41,11 @@ describe("TUIChat - Message Edit Feature", () => { 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)); @@ -49,10 +53,10 @@ describe("TUIChat - Message Edit Feature", () => { stdin.write("k"); // Up await new Promise((resolve) => setTimeout(resolve, 50)); - const frame = lastFrame(); - - // Should handle navigation without crashing + // 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) => { @@ -124,16 +128,10 @@ describe("TUIChat - Message Edit Feature", () => { const frame = lastFrame(); - // UI should remain stable + // UI should remain stable and edit selector should be closed expect(frame).toBeDefined(); expect(frame.length).toBeGreaterThan(0); - - // Should still show chat interface - if (mode === "local") { - expect(frame).toContain("Continue CLI"); - } else { - expect(frame).toContain("Remote Mode"); - } + expect(frame).not.toContain("No user messages to edit"); }, ); }); @@ -202,14 +200,18 @@ describe("TUIChat - Edit Feature Edge Cases", () => { 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)); - const frame = lastFrame(); - - // Should not open edit selector (requires double Esc within 500ms) - // Instead should just remain in normal mode + // Verify selector still did not open + frame = lastFrame(); expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); }); testBothModes( From 45e9a944e74d7197e5610e47d6331ba344443c85 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 14:24:33 -0700 Subject: [PATCH 16/37] fix: linter errors --- .../cli/src/ui/__tests__/TUIChat.editMessage.test.tsx | 4 ++-- extensions/cli/src/ui/hooks/useChat.edit.test.ts | 9 ++++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx index e50f59948..1f33fb1be 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -130,7 +130,7 @@ describe("TUIChat - Message Edit Feature", () => { // UI should remain stable and edit selector should be closed expect(frame).toBeDefined(); - expect(frame.length).toBeGreaterThan(0); + expect(frame!.length).toBeGreaterThan(0); expect(frame).not.toContain("No user messages to edit"); }, ); @@ -189,7 +189,7 @@ describe("TUIChat - Edit Feature Edge Cases", () => { // Should either show "no messages" or handle gracefully expect(frame).toBeDefined(); - expect(frame.length).toBeGreaterThan(0); + expect(frame!.length).toBeGreaterThan(0); }, ); diff --git a/extensions/cli/src/ui/hooks/useChat.edit.test.ts b/extensions/cli/src/ui/hooks/useChat.edit.test.ts index c45259dc4..b1fc2adb3 100644 --- a/extensions/cli/src/ui/hooks/useChat.edit.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.edit.test.ts @@ -316,7 +316,14 @@ describe("useChat - Message Edit Feature", () => { const chatHistory: ChatHistoryItem[] = [ { message: { role: "user", content: "Original" }, - contextItems: [{ name: "file.txt", content: "data" }], + contextItems: [ + { + name: "file.txt", + content: "data", + description: "file.txt", + id: { providerTitle: "file", itemId: "file.txt" }, + }, + ], }, ]; From 7b82f4fc3d791c335ee2ced3b06c533bdc71de80 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 14:30:36 -0700 Subject: [PATCH 17/37] fix: linter errors --- extensions/cli/src/ui/EditMessageSelector.test.tsx | 1 - extensions/cli/src/ui/EditMessageSelector.tsx | 2 +- extensions/cli/src/ui/components/ScreenContent.tsx | 2 +- extensions/cli/src/ui/hooks/useChat.edit.test.ts | 8 ++++---- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx index 06d090ae9..06c7f8358 100644 --- a/extensions/cli/src/ui/EditMessageSelector.test.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -3,7 +3,6 @@ */ import { render } from "@testing-library/react"; import type { ChatHistoryItem } from "core/index.js"; -import { Box } from "ink"; import React from "react"; import { describe, it, expect, vi, beforeEach } from "vitest"; diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 9aa876e1e..ce898afe5 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -3,8 +3,8 @@ import React, { useMemo, useState } from "react"; import type { ChatHistoryItem } from "../../../../core/index.js"; -import { TextBuffer } from "./TextBuffer.js"; import { defaultBoxStyles } from "./styles.js"; +import { TextBuffer } from "./TextBuffer.js"; interface EditMessageSelectorProps { chatHistory: ChatHistoryItem[]; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 3be048246..ab963b62c 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -1,9 +1,9 @@ import { Box, Text } from "ink"; import React from "react"; -import type { ChatHistoryItem } from "../../../../../core/index.js"; 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"; diff --git a/extensions/cli/src/ui/hooks/useChat.edit.test.ts b/extensions/cli/src/ui/hooks/useChat.edit.test.ts index b1fc2adb3..dd4020021 100644 --- a/extensions/cli/src/ui/hooks/useChat.edit.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.edit.test.ts @@ -1,5 +1,5 @@ import type { ChatHistoryItem } from "core/index.js"; -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi } from "vitest"; /** * Tests for the message edit feature in useChat hook @@ -24,7 +24,7 @@ describe("useChat - Message Edit Feature", () => { describe("handleEditMessage", () => { it("should rewind history to exclude the message being edited", () => { const chatHistory = createMockChatHistory(5); // [user, asst, user, asst, user] - let currentHistory = chatHistory; + const currentHistory = chatHistory; const setChatHistory = vi.fn(); const setQueuedMessages = vi.fn(); @@ -74,7 +74,7 @@ describe("useChat - Message Edit Feature", () => { it("should handle editing the first message", () => { const chatHistory = createMockChatHistory(5); - let currentHistory = chatHistory; + const currentHistory = chatHistory; const updateSessionHistory = vi.fn(); const processMessage = vi.fn(); @@ -103,7 +103,7 @@ describe("useChat - Message Edit Feature", () => { it("should handle editing the last message", () => { const chatHistory = createMockChatHistory(5); - let currentHistory = chatHistory; + const currentHistory = chatHistory; const updateSessionHistory = vi.fn(); const processMessage = vi.fn(); From 4582ab2df3eed7b3608d8b3fdefac25b9f827203 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 14:44:25 -0700 Subject: [PATCH 18/37] fix: linter errors --- extensions/cli/src/ui/EditMessageSelector.tsx | 53 ++++++------- .../src/ui/components/ChatScreenContent.tsx | 76 +++++++++++++++++++ .../cli/src/ui/components/ScreenContent.tsx | 29 +++---- extensions/cli/src/ui/hooks/useChat.ts | 2 +- extensions/cli/src/ui/hooks/useChat.types.ts | 1 + 5 files changed, 112 insertions(+), 49 deletions(-) create mode 100644 extensions/cli/src/ui/components/ChatScreenContent.tsx diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index ce898afe5..02219261c 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -46,29 +46,8 @@ export function EditMessageSelector({ }, [selectedIndex, isEditing, userMessages, textBuffer]); useInput((input, key) => { - // If not editing, handle navigation - if (!isEditing) { - if (key.upArrow || input === "k") { - setSelectedIndex((prev) => - prev > 0 ? prev - 1 : userMessages.length - 1, - ); - } else if (key.downArrow || input === "j") { - setSelectedIndex((prev) => - prev < userMessages.length - 1 ? prev + 1 : 0, - ); - } else if (key.return) { - // Start editing the selected message - set cursor to end - const content = - typeof userMessages[selectedIndex]?.item.message.content === "string" - ? userMessages[selectedIndex].item.message.content - : ""; - textBuffer.setCursor(content.length); - setCursorPosition(content.length); - setIsEditing(true); - } else if (key.escape || (key.ctrl && input === "d")) { - onExit(); - } - } else { + // If editing, handle text input + if (isEditing) { // In edit mode, handle text input if (key.escape) { setIsEditing(false); @@ -97,6 +76,28 @@ export function EditMessageSelector({ setEditText(textBuffer.text); setCursorPosition(textBuffer.cursor); } + } else { + // If not editing, handle navigation + if (key.upArrow || input === "k") { + setSelectedIndex((prev) => + prev > 0 ? prev - 1 : userMessages.length - 1, + ); + } else if (key.downArrow || input === "j") { + setSelectedIndex((prev) => + prev < userMessages.length - 1 ? prev + 1 : 0, + ); + } else if (key.return) { + // Start editing the selected message - set cursor to end + const content = + typeof userMessages[selectedIndex]?.item.message.content === "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setCursor(content.length); + setCursorPosition(content.length); + setIsEditing(true); + } else if (key.escape || (key.ctrl && input === "d")) { + onExit(); + } } }); @@ -165,12 +166,6 @@ export function EditMessageSelector({ ); }; - const selectedMessage = userMessages[selectedIndex]; - const messageContent = - typeof selectedMessage?.item.message.content === "string" - ? selectedMessage.item.message.content - : ""; - return ( 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 ab963b62c..694c8f215 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -9,14 +9,15 @@ 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; @@ -28,7 +29,7 @@ interface ScreenContentProps { handleSessionSelect: (sessionId: string) => Promise; handleReload: () => Promise; closeCurrentScreen: () => void; - activePermissionRequest: any; + activePermissionRequest: ActivePermissionRequest | null; handleToolPermissionResponse: ( requestId: string, approved: boolean, @@ -188,29 +189,19 @@ export const ScreenContent: React.FC = ({ // Chat screen with input area if (isScreenActive("chat")) { - if (activePermissionRequest) { - return ( - - ); - } return ( - Date: Tue, 7 Oct 2025 14:46:20 -0700 Subject: [PATCH 19/37] improv: clean up code --- extensions/cli/src/ui/TUIChat.tsx | 4 +--- extensions/cli/src/ui/hooks/useChat.ts | 2 -- extensions/cli/src/ui/hooks/useChat.types.ts | 2 -- 3 files changed, 1 insertion(+), 7 deletions(-) diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 0ecaa0fe8..30729d35e 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -173,7 +173,7 @@ const TUIChat: React.FC = ({ ); // Use login handlers - const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers( + const { handleLoginTokenSubmit } = useLoginHandlers( navigateTo, navState, closeCurrentScreen, @@ -243,8 +243,6 @@ const TUIChat: React.FC = ({ onShowMCPSelector: () => navigateTo("mcp"), onShowUpdateSelector: () => navigateTo("update"), onShowSessionSelector: () => navigateTo("session"), - onShowEditSelector: () => navigateTo("edit"), - onLoginPrompt: handleLoginPrompt, onReload: handleReload, onClear: handleClear, onRefreshStatic: () => setStaticRefreshTrigger((prev) => prev + 1), diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 09d7cf8a6..fe3dc8d05 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -58,8 +58,6 @@ export function useChat({ onShowUpdateSelector, onShowMCPSelector, onShowSessionSelector, - onShowEditSelector: _onShowEditSelector, - onLoginPrompt: _onLoginPrompt, onClear, onRefreshStatic, isRemoteMode = false, diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index 6340355fe..2fe0b0b81 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -18,8 +18,6 @@ export interface UseChatProps { onShowUpdateSelector: () => void; onShowModelSelector?: () => void; onShowSessionSelector?: () => void; - onShowEditSelector?: () => void; - onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; onClear?: () => void; onRefreshStatic?: () => void; From a68b804d707ae50ddf8529f3591d70894988584e Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Tue, 7 Oct 2025 15:23:01 -0700 Subject: [PATCH 20/37] fix: handle corrupted VSCode auth cache with automatic cleanup and recovery --- extensions/vscode/src/stubs/SecretStorage.ts | 89 ++++++++++++++----- .../vscode/src/stubs/WorkOsAuthProvider.ts | 18 ++-- gui/src/context/Auth.tsx | 36 ++++---- 3 files changed, 93 insertions(+), 50 deletions(-) diff --git a/extensions/vscode/src/stubs/SecretStorage.ts b/extensions/vscode/src/stubs/SecretStorage.ts index 202713cbd..029ad1e5b 100644 --- a/extensions/vscode/src/stubs/SecretStorage.ts +++ b/extensions/vscode/src/stubs/SecretStorage.ts @@ -59,31 +59,50 @@ export class SecretStorage { } async decrypt(filePath: string): Promise { - const key = await this.getOrCreateEncryptionKey(); - const data = fs.readFileSync(filePath); + try { + const key = await this.getOrCreateEncryptionKey(); + const data = fs.readFileSync(filePath); - const salt = data.subarray(0, this.saltLength); - const iv = data.subarray(this.saltLength, this.saltLength + this.ivLength); - const tag = data.subarray( - this.saltLength + this.ivLength, - this.saltLength + this.ivLength + this.tagLength, - ); - const encrypted = data.subarray( - this.saltLength + this.ivLength + this.tagLength, - ); + // 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 decipher: crypto.DecipherGCM = crypto.createDecipheriv( - this.algorithm, - key, - iv, - ) as crypto.DecipherGCM; - decipher.setAuthTag(tag); + const salt = data.subarray(0, this.saltLength); + const iv = data.subarray( + this.saltLength, + this.saltLength + this.ivLength, + ); + const tag = data.subarray( + this.saltLength + this.ivLength, + this.saltLength + this.ivLength + this.tagLength, + ); + const encrypted = data.subarray( + this.saltLength + this.ivLength + this.tagLength, + ); - const decrypted = Buffer.concat([ - decipher.update(encrypted), - decipher.final(), - ]); - return decrypted.toString("utf8"); + const decipher: crypto.DecipherGCM = crypto.createDecipheriv( + this.algorithm, + key, + iv, + ) as crypto.DecipherGCM; + decipher.setAuthTag(tag); + + const decrypted = Buffer.concat([ + decipher.update(encrypted), + decipher.final(), + ]); + return decrypted.toString("utf8"); + } catch (error: any) { + // Log the error with context for debugging + console.error(`Failed to decrypt cache file ${filePath}:`, error.message); + throw new Error( + `Cache decryption failed: ${error.message}. The cache file may be corrupted.`, + ); + } } private keyToFilepath(key: string): string { @@ -100,8 +119,30 @@ export class SecretStorage { async get(key: string): Promise { const filePath = this.keyToFilepath(key); if (fs.existsSync(filePath)) { - const value = await this.decrypt(filePath); - return value; + try { + const value = await this.decrypt(filePath); + return value; + } catch (error: any) { + // Corrupted cache file - delete it and return undefined + // This allows the auth flow to continue with a fresh start + console.error( + `Corrupted cache file detected for key "${key}". Deleting file and returning undefined.`, + error.message, + ); + + try { + fs.unlinkSync(filePath); + console.log(`Successfully deleted corrupted cache file: ${filePath}`); + } catch (deleteError: any) { + console.error( + `Failed to delete corrupted cache file ${filePath}:`, + deleteError.message, + ); + } + + // Return undefined to signal missing data (same as if file didn't exist) + return undefined; + } } return undefined; } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index f0af9770d..99d697d65 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -161,22 +161,22 @@ 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}`); 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 = () => { From 0858aa41b00a3598602664c7301e96ef8f5a0cd3 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 15:53:25 -0700 Subject: [PATCH 21/37] fix: failing tests --- extensions/cli/src/ui/EditMessageSelector.tsx | 38 ++++++++++++------- extensions/cli/src/ui/UserInput.tsx | 10 ++--- .../ui/__tests__/TUIChat.editMessage.test.tsx | 16 +++++--- 3 files changed, 40 insertions(+), 24 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 02219261c..00d043cce 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -53,7 +53,7 @@ export function EditMessageSelector({ setIsEditing(false); // Reset text to original const content = - typeof userMessages[selectedIndex].item.message.content === "string" + typeof userMessages[selectedIndex]?.item.message.content === "string" ? userMessages[selectedIndex].item.message.content : ""; textBuffer.setText(content); @@ -79,22 +79,32 @@ export function EditMessageSelector({ } else { // If not editing, handle navigation if (key.upArrow || input === "k") { - setSelectedIndex((prev) => - prev > 0 ? prev - 1 : userMessages.length - 1, - ); + // 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") { - setSelectedIndex((prev) => - prev < userMessages.length - 1 ? prev + 1 : 0, - ); + // 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 - const content = - typeof userMessages[selectedIndex]?.item.message.content === "string" - ? userMessages[selectedIndex].item.message.content - : ""; - textBuffer.setCursor(content.length); - setCursorPosition(content.length); - setIsEditing(true); + // Only allow editing if there are messages + if (userMessages.length > 0) { + const content = + typeof userMessages[selectedIndex]?.item.message.content === + "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setCursor(content.length); + setCursorPosition(content.length); + setIsEditing(true); + } } else if (key.escape || (key.ctrl && input === "d")) { onExit(); } diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 7e6abd34a..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"; @@ -130,7 +130,7 @@ const UserInput: React.FC = ({ }) => { const [textBuffer] = useState(() => new TextBuffer()); const [inputHistory] = useState(() => new InputHistory()); - const [lastEscapePress, setLastEscapePress] = useState(0); + const lastEscapePressRef = useRef(0); // Stable callback for TextBuffer state changes to prevent race conditions const onStateChange = useCallback(() => { @@ -636,16 +636,16 @@ const UserInput: React.FC = ({ !showFileSearch && !showBashMode && onShowEditSelector && - now - lastEscapePress < 500 + now - lastEscapePressRef.current < 500 ) { // Double escape detected onShowEditSelector(); - setLastEscapePress(0); // Reset to prevent triple-escape + lastEscapePressRef.current = 0; // Reset to prevent triple-escape return true; } // Track single escape press - setLastEscapePress(now); + 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 index 1f33fb1be..9e6a92874 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -117,16 +117,22 @@ describe("TUIChat - Message Edit Feature", () => { const { lastFrame, stdin } = renderInMode(mode); // Perform various operations - stdin.write("\u001b\u001b"); // Open edit - await new Promise((resolve) => setTimeout(resolve, 50)); + stdin.write("\u001b"); + stdin.write("\u001b"); // Open edit with separate Esc presses + await new Promise((resolve) => setTimeout(resolve, 100)); - stdin.write("k"); // Navigate + // 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, 50)); + await new Promise((resolve) => setTimeout(resolve, 100)); - const frame = lastFrame(); + frame = lastFrame(); // UI should remain stable and edit selector should be closed expect(frame).toBeDefined(); From c8f5df90cb54ca015a52f08a1f710501a406ffe8 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 15:57:52 -0700 Subject: [PATCH 22/37] fix: lint --- extensions/cli/src/ui/EditMessageSelector.tsx | 65 ++++++++++++++----- 1 file changed, 50 insertions(+), 15 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 00d043cce..e1d8eb5b9 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -1,4 +1,5 @@ import { Box, Text, useInput } from "ink"; +import type { Key } from "ink/build/hooks/use-input.js"; import React, { useMemo, useState } from "react"; import type { ChatHistoryItem } from "../../../../core/index.js"; @@ -45,17 +46,23 @@ export function EditMessageSelector({ } }, [selectedIndex, isEditing, userMessages, textBuffer]); - useInput((input, key) => { - // If editing, handle text input - if (isEditing) { - // In edit mode, handle text input + // 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 = - typeof userMessages[selectedIndex]?.item.message.content === "string" - ? userMessages[selectedIndex].item.message.content - : ""; + const content = getMessageContent(selectedIndex); textBuffer.setText(content); setEditText(content); setCursorPosition(content.length); @@ -76,8 +83,22 @@ export function EditMessageSelector({ setEditText(textBuffer.text); setCursorPosition(textBuffer.cursor); } - } else { - // If not editing, handle navigation + }, + [ + 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) { @@ -96,11 +117,7 @@ export function EditMessageSelector({ // Start editing the selected message - set cursor to end // Only allow editing if there are messages if (userMessages.length > 0) { - const content = - typeof userMessages[selectedIndex]?.item.message.content === - "string" - ? userMessages[selectedIndex].item.message.content - : ""; + const content = getMessageContent(selectedIndex); textBuffer.setCursor(content.length); setCursorPosition(content.length); setIsEditing(true); @@ -108,6 +125,24 @@ export function EditMessageSelector({ } 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); } }); From db4f590dce8f15d4f1dabc9fef9a0a265b78e7a0 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 16:05:50 -0700 Subject: [PATCH 23/37] fix: lint --- extensions/cli/src/ui/EditMessageSelector.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index e1d8eb5b9..311197cb5 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -1,5 +1,4 @@ import { Box, Text, useInput } from "ink"; -import type { Key } from "ink/build/hooks/use-input.js"; import React, { useMemo, useState } from "react"; import type { ChatHistoryItem } from "../../../../core/index.js"; @@ -7,6 +6,10 @@ 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; From afb6a6eff5be004f927d83af1713fee31f67593a Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 8 Oct 2025 17:37:16 +0530 Subject: [PATCH 24/37] remove onboarding result from being returned --- extensions/cli/src/services/index.ts | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index a8d209d88..2f3c7ce4f 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,19 @@ 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( + await initializeWithOnboarding( authConfig, commandOptions.config, commandOptions.rule, ); - wasOnboarded = onboardingResult.wasOnboarded; } // Handle ANTHROPIC_API_KEY in headless mode when no config path is provided @@ -287,8 +282,6 @@ export async function initializeServices( await serviceContainer.initializeAll(); logger.debug("Service registry initialized"); - - return { wasOnboarded }; } /** From 401578a9f2bdfdf77d2655c030f0866bbb527cf3 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 8 Oct 2025 17:38:23 +0530 Subject: [PATCH 25/37] run normal initialization flow on parallel --- extensions/cli/src/onboarding.ts | 37 +++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts index 0108baa90..9bbe55f20 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -280,24 +280,35 @@ 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) { + const onboardingResult = await runOnboardingFlow(configPath, authConfig); + if (onboardingResult.wasOnboarded) { await markOnboardingComplete(); } + // Inject rules into the config if provided (for onboarding flow which doesn't handle rules directly) + if (rules && rules.length > 0 && !onboardingResult.wasOnboarded) { + onboardingResult.config = await injectRulesIntoConfig( + onboardingResult.config, + rules, + ); + } } else { - result = await runNormalFlow(authConfig, configPath, rules); + // when running normal flow, initialize (remote) config asynchronously + void (async () => { + const onboardingResult = await runNormalFlow( + authConfig, + configPath, + rules, + ); + if (rules && rules.length > 0) { + onboardingResult.config = await injectRulesIntoConfig( + onboardingResult.config, + 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; } From 3a5f1886a842ac3952ca2159893fc7ebe8d69bd3 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 8 Oct 2025 10:10:49 -0700 Subject: [PATCH 26/37] improv: clean up tests, fix paste block behavior --- .../cli/src/ui/EditMessageSelector.test.tsx | 21 -- extensions/cli/src/ui/EditMessageSelector.tsx | 2 + .../cli/src/ui/hooks/useChat.edit.test.ts | 344 ------------------ 3 files changed, 2 insertions(+), 365 deletions(-) delete mode 100644 extensions/cli/src/ui/hooks/useChat.edit.test.ts diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx index 06c7f8358..4577d6339 100644 --- a/extensions/cli/src/ui/EditMessageSelector.test.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -186,27 +186,6 @@ describe("EditMessageSelector", () => { }); }); - describe("Cursor positioning bug fix", () => { - it("should position cursor at end when entering edit mode", () => { - const chatHistory: ChatHistoryItem[] = [ - { message: { role: "user", content: "Hello world" }, contextItems: [] }, - ]; - - const mockTextBuffer = new TextBuffer(); - const mockSetCursor = vi.fn(); - mockTextBuffer.setCursor = mockSetCursor; - - // This test verifies the fix: when Enter is pressed to start editing, - // setCursor should be called with content.length - // The actual implementation test would require simulating Enter keypress - // which is complex with Ink components - - // For now, this test documents the expected behavior - const messageContent = "Hello world"; - expect(messageContent.length).toBe(11); - }); - }); - describe("Complex message content", () => { it("should handle message parts array", () => { const chatHistory: ChatHistoryItem[] = [ diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 311197cb5..e1e9bc19b 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -71,6 +71,8 @@ export function EditMessageSelector({ 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); diff --git a/extensions/cli/src/ui/hooks/useChat.edit.test.ts b/extensions/cli/src/ui/hooks/useChat.edit.test.ts deleted file mode 100644 index dd4020021..000000000 --- a/extensions/cli/src/ui/hooks/useChat.edit.test.ts +++ /dev/null @@ -1,344 +0,0 @@ -import type { ChatHistoryItem } from "core/index.js"; -import { describe, it, expect, vi } from "vitest"; - -/** - * Tests for the message edit feature in useChat hook - * - * This test suite covers: - * - handleEditMessage: Rewinds history and resubmits edited message - * - processMessage with baseHistory: Uses explicit base history instead of state - * - Integration: Full edit flow produces correct final history - */ - -describe("useChat - Message Edit Feature", () => { - const createMockChatHistory = (count: number): ChatHistoryItem[] => { - return Array.from({ length: count }, (_, i) => ({ - message: { - role: i % 2 === 0 ? "user" : "assistant", - content: `Message ${i + 1}`, - }, - contextItems: [], - })); - }; - - describe("handleEditMessage", () => { - it("should rewind history to exclude the message being edited", () => { - const chatHistory = createMockChatHistory(5); // [user, asst, user, asst, user] - const currentHistory = chatHistory; - - const setChatHistory = vi.fn(); - const setQueuedMessages = vi.fn(); - const setAttachedFiles = vi.fn(); - const updateSessionHistory = vi.fn(); - const onRefreshStatic = vi.fn(); - const processMessage = vi.fn(); - - // Mock handleEditMessage behavior - const handleEditMessage = async ( - messageIndex: number, - newContent: string, - ) => { - const rewindedHistory = currentHistory.slice(0, messageIndex); - setQueuedMessages([]); - setAttachedFiles([]); - updateSessionHistory(rewindedHistory); - if (onRefreshStatic) { - onRefreshStatic(); - } - await processMessage(newContent, undefined, false, rewindedHistory); - }; - - // Edit message at index 2 (third message) - handleEditMessage(2, "Edited message"); - - // Verify history was rewound to [0, 1] - expect(updateSessionHistory).toHaveBeenCalledWith( - chatHistory.slice(0, 2), - ); - - // Verify state was cleared - expect(setQueuedMessages).toHaveBeenCalledWith([]); - expect(setAttachedFiles).toHaveBeenCalledWith([]); - - // Verify refresh was called - expect(onRefreshStatic).toHaveBeenCalled(); - - // Verify processMessage was called with correct baseHistory - expect(processMessage).toHaveBeenCalledWith( - "Edited message", - undefined, - false, - chatHistory.slice(0, 2), - ); - }); - - it("should handle editing the first message", () => { - const chatHistory = createMockChatHistory(5); - const currentHistory = chatHistory; - - const updateSessionHistory = vi.fn(); - const processMessage = vi.fn(); - - const handleEditMessage = async ( - messageIndex: number, - newContent: string, - ) => { - const rewindedHistory = currentHistory.slice(0, messageIndex); - updateSessionHistory(rewindedHistory); - await processMessage(newContent, undefined, false, rewindedHistory); - }; - - // Edit first message (index 0) - handleEditMessage(0, "New first message"); - - // Should rewind to empty history - expect(updateSessionHistory).toHaveBeenCalledWith([]); - expect(processMessage).toHaveBeenCalledWith( - "New first message", - undefined, - false, - [], - ); - }); - - it("should handle editing the last message", () => { - const chatHistory = createMockChatHistory(5); - const currentHistory = chatHistory; - - const updateSessionHistory = vi.fn(); - const processMessage = vi.fn(); - - const handleEditMessage = async ( - messageIndex: number, - newContent: string, - ) => { - const rewindedHistory = currentHistory.slice(0, messageIndex); - updateSessionHistory(rewindedHistory); - await processMessage(newContent, undefined, false, rewindedHistory); - }; - - // Edit last message (index 4) - handleEditMessage(4, "Edited last message"); - - // Should rewind to [0, 1, 2, 3] - expect(updateSessionHistory).toHaveBeenCalledWith( - chatHistory.slice(0, 4), - ); - expect(processMessage).toHaveBeenCalledWith( - "Edited last message", - undefined, - false, - chatHistory.slice(0, 4), - ); - }); - }); - - describe("processMessage with baseHistory", () => { - it("should use baseHistory instead of chatHistory when provided", () => { - // Simulate the scenario where chatHistory state hasn't updated yet - const oldChatHistory = createMockChatHistory(5); - const baseHistory = oldChatHistory.slice(0, 2); // Rewound history - - // Mock processMessage that uses baseHistory parameter - const processMessage = ( - message: string, - imageMap?: Map, - isQueuedMessage: boolean = false, - baseHistory?: ChatHistoryItem[], - ) => { - const currentHistory = baseHistory ?? oldChatHistory; - return currentHistory; - }; - - // Call with baseHistory - const result = processMessage( - "New message", - undefined, - false, - baseHistory, - ); - - // Should use baseHistory, not oldChatHistory - expect(result).toEqual(baseHistory); - expect(result).not.toEqual(oldChatHistory); - }); - - it("should fall back to chatHistory when baseHistory is not provided", () => { - const chatHistory = createMockChatHistory(3); - - const processMessage = ( - message: string, - imageMap?: Map, - isQueuedMessage: boolean = false, - baseHistory?: ChatHistoryItem[], - ) => { - const currentHistory = baseHistory ?? chatHistory; - return currentHistory; - }; - - // Call without baseHistory - const result = processMessage("New message"); - - // Should use chatHistory - expect(result).toEqual(chatHistory); - }); - }); - - describe("Edit flow integration", () => { - it("should produce correct history after edit and resubmit", async () => { - // Initial history: [user1, asst1, user2, asst2, user3] - const initialHistory = createMockChatHistory(5); - let chatHistory = initialHistory; - - const setChatHistory = vi.fn((updater: any) => { - if (typeof updater === "function") { - chatHistory = updater(chatHistory); - } else { - chatHistory = updater; - } - }); - - // Simulate editing user2 (index 2) - const messageIndexToEdit = 2; - const newContent = "Edited user2"; - - // Step 1: Rewind history - const rewindedHistory = initialHistory.slice(0, messageIndexToEdit); - // Result: [user1, asst1] - - // Step 2: Simulate processMessage adding new user message - const newUserMessage: ChatHistoryItem = { - message: { role: "user", content: newContent }, - contextItems: [], - }; - - const expectedHistory = [...rewindedHistory, newUserMessage]; - // Expected: [user1, asst1, edited_user2] - - setChatHistory(expectedHistory); - - // Verify final history - expect(chatHistory).toHaveLength(3); - expect(chatHistory[0]).toEqual(initialHistory[0]); // user1 - expect(chatHistory[1]).toEqual(initialHistory[1]); // asst1 - expect(chatHistory[2].message.content).toBe(newContent); // edited message - - // Verify old messages are gone - expect(chatHistory).not.toContain(initialHistory[2]); // old user2 - expect(chatHistory).not.toContain(initialHistory[3]); // asst2 - expect(chatHistory).not.toContain(initialHistory[4]); // user3 - }); - - it("should handle editing with queued messages", () => { - const chatHistory = createMockChatHistory(3); - const queuedMessages = ["queued1", "queued2"]; - - const setQueuedMessages = vi.fn(); - const setAttachedFiles = vi.fn(); - - // When editing, should clear queued messages - const handleEdit = () => { - setQueuedMessages([]); - setAttachedFiles([]); - }; - - handleEdit(); - - expect(setQueuedMessages).toHaveBeenCalledWith([]); - expect(setAttachedFiles).toHaveBeenCalledWith([]); - }); - - it("should handle editing with attached files", () => { - const attachedFiles = [ - { path: "/test.txt", content: "test" }, - { path: "/test2.txt", content: "test2" }, - ]; - - const setAttachedFiles = vi.fn(); - - // When editing, should clear attached files - const handleEdit = () => { - setAttachedFiles([]); - }; - - handleEdit(); - - expect(setAttachedFiles).toHaveBeenCalledWith([]); - }); - }); - - describe("Edge cases", () => { - it("should handle editing with empty chat history", () => { - const chatHistory: ChatHistoryItem[] = []; - - const updateSessionHistory = vi.fn(); - const processMessage = vi.fn(); - - const handleEditMessage = async ( - messageIndex: number, - newContent: string, - ) => { - const rewindedHistory = chatHistory.slice(0, messageIndex); - updateSessionHistory(rewindedHistory); - await processMessage(newContent, undefined, false, rewindedHistory); - }; - - // Attempt to edit (should handle gracefully) - handleEditMessage(0, "New message"); - - expect(updateSessionHistory).toHaveBeenCalledWith([]); - expect(processMessage).toHaveBeenCalledWith( - "New message", - undefined, - false, - [], - ); - }); - - it("should handle editing with out-of-bounds index", () => { - const chatHistory = createMockChatHistory(3); - - const updateSessionHistory = vi.fn(); - - const handleEditMessage = (messageIndex: number) => { - const rewindedHistory = chatHistory.slice(0, messageIndex); - updateSessionHistory(rewindedHistory); - }; - - // Index beyond history length - handleEditMessage(10); - - // slice(0, 10) on array of length 3 returns full array - expect(updateSessionHistory).toHaveBeenCalledWith(chatHistory); - }); - - it("should preserve message structure during edit", () => { - const chatHistory: ChatHistoryItem[] = [ - { - message: { role: "user", content: "Original" }, - contextItems: [ - { - name: "file.txt", - content: "data", - description: "file.txt", - id: { providerTitle: "file", itemId: "file.txt" }, - }, - ], - }, - ]; - - const rewindedHistory = chatHistory.slice(0, 0); // Empty - const newMessage: ChatHistoryItem = { - message: { role: "user", content: "Edited" }, - contextItems: [], // New message may have different contextItems - }; - - const expectedHistory = [...rewindedHistory, newMessage]; - - expect(expectedHistory).toHaveLength(1); - expect(expectedHistory[0].message.content).toBe("Edited"); - // Original message with its contextItems is gone - expect(expectedHistory[0]).not.toEqual(chatHistory[0]); - }); - }); -}); From a3a35f67331edd9479f54767469d2acc93d43d50 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 8 Oct 2025 10:16:44 -0700 Subject: [PATCH 27/37] fix: linter errors --- extensions/cli/src/ui/EditMessageSelector.test.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx index 4577d6339..8a5282b6b 100644 --- a/extensions/cli/src/ui/EditMessageSelector.test.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -7,7 +7,6 @@ import React from "react"; import { describe, it, expect, vi, beforeEach } from "vitest"; import { EditMessageSelector } from "./EditMessageSelector.js"; -import { TextBuffer } from "./TextBuffer.js"; // Mock TextBuffer for controlled testing vi.mock("./TextBuffer.js", () => { From 1acc648a90919ebe8ee825ade83ff30b5a71d397 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 8 Oct 2025 10:45:08 -0700 Subject: [PATCH 28/37] fix: text buffer handling --- .../cli/src/ui/EditMessageSelector.test.tsx | 14 +------------- extensions/cli/src/ui/EditMessageSelector.tsx | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx index 8a5282b6b..81acd28c2 100644 --- a/extensions/cli/src/ui/EditMessageSelector.test.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -7,19 +7,7 @@ import React from "react"; import { describe, it, expect, vi, beforeEach } from "vitest"; import { EditMessageSelector } from "./EditMessageSelector.js"; - -// Mock TextBuffer for controlled testing -vi.mock("./TextBuffer.js", () => { - return { - TextBuffer: vi.fn().mockImplementation(() => ({ - text: "", - cursor: 0, - setText: vi.fn(), - setCursor: vi.fn(), - handleInput: vi.fn(), - })), - }; -}); +import { TextBuffer } from "./TextBuffer.js"; describe("EditMessageSelector", () => { const createMockChatHistory = (count: number): ChatHistoryItem[] => { diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index e1e9bc19b..60c8a23c0 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -36,6 +36,22 @@ export function EditMessageSelector({ 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]) { From 8f116b15340c33a046e65274a0fd2f6916b89138 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 8 Oct 2025 10:47:40 -0700 Subject: [PATCH 29/37] fix: lint --- extensions/cli/src/ui/EditMessageSelector.test.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx index 81acd28c2..c56bec21a 100644 --- a/extensions/cli/src/ui/EditMessageSelector.test.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -7,7 +7,6 @@ import React from "react"; import { describe, it, expect, vi, beforeEach } from "vitest"; import { EditMessageSelector } from "./EditMessageSelector.js"; -import { TextBuffer } from "./TextBuffer.js"; describe("EditMessageSelector", () => { const createMockChatHistory = (count: number): ChatHistoryItem[] => { From 3ec02338899eb893f06237611405b90aea50d4da Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Wed, 8 Oct 2025 14:37:29 -0700 Subject: [PATCH 30/37] chore: add github actions to CLA allowlist --- .github/workflows/cla.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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" From a58149c6d62faf08ece2d234401e8e6c8fb977c8 Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Wed, 8 Oct 2025 15:26:40 -0700 Subject: [PATCH 31/37] move corrupted cache cleanup from SecretStorage to WorkOsAuthProvider --- extensions/vscode/src/stubs/SecretStorage.ts | 103 +++++++----------- .../vscode/src/stubs/WorkOsAuthProvider.ts | 12 ++ 2 files changed, 51 insertions(+), 64 deletions(-) diff --git a/extensions/vscode/src/stubs/SecretStorage.ts b/extensions/vscode/src/stubs/SecretStorage.ts index 029ad1e5b..12cc98c35 100644 --- a/extensions/vscode/src/stubs/SecretStorage.ts +++ b/extensions/vscode/src/stubs/SecretStorage.ts @@ -59,50 +59,39 @@ export class SecretStorage { } async decrypt(filePath: string): Promise { - try { - const key = await this.getOrCreateEncryptionKey(); - const data = fs.readFileSync(filePath); + 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( - this.saltLength + this.ivLength, - this.saltLength + this.ivLength + this.tagLength, - ); - const encrypted = data.subarray( - this.saltLength + this.ivLength + this.tagLength, - ); - - const decipher: crypto.DecipherGCM = crypto.createDecipheriv( - this.algorithm, - key, - iv, - ) as crypto.DecipherGCM; - decipher.setAuthTag(tag); - - const decrypted = Buffer.concat([ - decipher.update(encrypted), - decipher.final(), - ]); - return decrypted.toString("utf8"); - } catch (error: any) { - // Log the error with context for debugging - console.error(`Failed to decrypt cache file ${filePath}:`, error.message); + // Validate minimum data size to detect corruption early + const minSize = this.saltLength + this.ivLength + this.tagLength; + if (data.length < minSize) { throw new Error( - `Cache decryption failed: ${error.message}. The cache file may be corrupted.`, + `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( + this.saltLength + this.ivLength, + this.saltLength + this.ivLength + this.tagLength, + ); + const encrypted = data.subarray( + this.saltLength + this.ivLength + this.tagLength, + ); + + const decipher: crypto.DecipherGCM = crypto.createDecipheriv( + this.algorithm, + key, + iv, + ) as crypto.DecipherGCM; + decipher.setAuthTag(tag); + + const decrypted = Buffer.concat([ + decipher.update(encrypted), + decipher.final(), + ]); + return decrypted.toString("utf8"); } private keyToFilepath(key: string): string { @@ -119,31 +108,17 @@ export class SecretStorage { async get(key: string): Promise { const filePath = this.keyToFilepath(key); if (fs.existsSync(filePath)) { - try { - const value = await this.decrypt(filePath); - return value; - } catch (error: any) { - // Corrupted cache file - delete it and return undefined - // This allows the auth flow to continue with a fresh start - console.error( - `Corrupted cache file detected for key "${key}". Deleting file and returning undefined.`, - error.message, - ); - - try { - fs.unlinkSync(filePath); - console.log(`Successfully deleted corrupted cache file: ${filePath}`); - } catch (deleteError: any) { - console.error( - `Failed to delete corrupted cache file ${filePath}:`, - deleteError.message, - ); - } - - // Return undefined to signal missing data (same as if file didn't exist) - return undefined; - } + const value = await this.decrypt(filePath); + return value; } 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 99d697d65..1c0e60bba 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -177,6 +177,18 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { }); 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 []; } } From 65aa21f11548935822ba9e30d707486c433c8848 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Wed, 8 Oct 2025 22:18:17 -0700 Subject: [PATCH 32/37] Update runloop-blueprint-template.json (#8156) --- .github/workflows/runloop-blueprint-template.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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" ] } From 452da6eaf0600818a5e8fbc2d4a9def348daad85 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 9 Oct 2025 11:11:59 +0530 Subject: [PATCH 33/37] remove rule injection during onboarding --- extensions/cli/src/config.ts | 23 --- extensions/cli/src/onboarding.ts | 201 ++------------------------- extensions/cli/src/services/index.ts | 8 +- 3 files changed, 16 insertions(+), 216 deletions(-) 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.ts b/extensions/cli/src/onboarding.ts index 9bbe55f20..f1d4b8c42 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -1,16 +1,10 @@ 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 { login } from "./auth/workos.js"; import { env } from "./env.js"; -import { processRule } from "./hubLoader.js"; -import { MCPService } from "./services/MCPService.js"; import { getApiKeyValidationError, isValidAnthropicApiKey, @@ -20,15 +14,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 +46,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 +57,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 +74,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 +94,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 +110,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,82 +131,13 @@ 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; - } - - const processedRules: string[] = []; - for (const ruleSpec of rules) { - try { - const processedRule = await processRule(ruleSpec); - processedRules.push(processedRule); - } catch (error: any) { - console.warn( - chalk.yellow( - `Warning: Failed to process rule "${ruleSpec}": ${error.message}`, - ), - ); - } - } - - if (processedRules.length === 0) { - return config; - } - - // 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[], -) { +export async function initializeWithOnboarding(configPath: string | undefined) { const firstTime = await isFirstTime(); - if (firstTime) { - const onboardingResult = await runOnboardingFlow(configPath, authConfig); - if (onboardingResult.wasOnboarded) { - await markOnboardingComplete(); - } - // Inject rules into the config if provided (for onboarding flow which doesn't handle rules directly) - if (rules && rules.length > 0 && !onboardingResult.wasOnboarded) { - onboardingResult.config = await injectRulesIntoConfig( - onboardingResult.config, - rules, - ); - } - } else { - // when running normal flow, initialize (remote) config asynchronously - void (async () => { - const onboardingResult = await runNormalFlow( - authConfig, - configPath, - rules, - ); - if (rules && rules.length > 0) { - onboardingResult.config = await injectRulesIntoConfig( - onboardingResult.config, - rules, - ); - } - })(); + if (!firstTime) return; + + const wasOnboarded = await runOnboardingFlow(configPath); + if (wasOnboarded) { + await markOnboardingComplete(); } } diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index 2f3c7ce4f..73395155f 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -1,4 +1,3 @@ -import { loadAuthConfig } from "../auth/workos.js"; import { initializeWithOnboarding } from "../onboarding.js"; import { logger } from "../util/logger.js"; @@ -54,12 +53,7 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { // Handle onboarding for TUI mode (headless: false) unless explicitly skipped if (!initOptions.headless && !initOptions.skipOnboarding) { - const authConfig = loadAuthConfig(); - await initializeWithOnboarding( - authConfig, - commandOptions.config, - commandOptions.rule, - ); + await initializeWithOnboarding(commandOptions.config); } // Handle ANTHROPIC_API_KEY in headless mode when no config path is provided From 55638464c5b969441007dbcee57740526870d7cb Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 9 Oct 2025 11:19:51 +0530 Subject: [PATCH 34/37] fix tests --- extensions/cli/src/onboarding.test.ts | 44 +++++++++++++++------------ extensions/cli/src/onboarding.ts | 24 +++++++++++++-- extensions/cli/src/services/index.ts | 4 ++- 3 files changed, 49 insertions(+), 23 deletions(-) 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 f1d4b8c42..a8f780591 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -3,7 +3,9 @@ import * as path from "path"; import chalk from "chalk"; -import { login } from "./auth/workos.js"; +import { AuthConfig, login } from "./auth/workos.js"; +import { getApiClient } from "./config.js"; +import { loadConfiguration } from "./configLoader.js"; import { env } from "./env.js"; import { getApiKeyValidationError, @@ -131,9 +133,27 @@ export async function markOnboardingComplete(): Promise { fs.writeFileSync(flagPath, new Date().toISOString()); } -export async function initializeWithOnboarding(configPath: string | undefined) { +export async function initializeWithOnboarding( + authConfig: AuthConfig, + configPath: string | undefined, +) { const firstTime = await isFirstTime(); + if (configPath !== undefined) { + // throw an early error is configPath is invalid or has errors + try { + await loadConfiguration( + authConfig, + configPath, + getApiClient(authConfig?.accessToken), + ); + } catch (errorMessage) { + throw new Error( + `Failed to load config from "${configPath}": ${errorMessage}`, + ); + } + } + if (!firstTime) return; const wasOnboarded = await runOnboardingFlow(configPath); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index 73395155f..9ff58f365 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -1,3 +1,4 @@ +import { loadAuthConfig } from "../auth/workos.js"; import { initializeWithOnboarding } from "../onboarding.js"; import { logger } from "../util/logger.js"; @@ -53,7 +54,8 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { // Handle onboarding for TUI mode (headless: false) unless explicitly skipped if (!initOptions.headless && !initOptions.skipOnboarding) { - await initializeWithOnboarding(commandOptions.config); + const authConfig = loadAuthConfig(); + await initializeWithOnboarding(authConfig, commandOptions.config); } // Handle ANTHROPIC_API_KEY in headless mode when no config path is provided From f35474bec116c2defa040fbac60d4caffba5afcc Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 9 Oct 2025 12:00:19 +0530 Subject: [PATCH 35/37] load last session after initial config load --- gui/src/hooks/ParallelListeners.tsx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 2d3413327..e0a2dcf37 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -107,6 +107,7 @@ function ParallelListeners() { await handleConfigUpdate(true, result.content); } dispatch(setConfigLoading(false)); + await dispatch(loadLastSession()); } void initialLoadConfig(); const interval = setInterval(() => { @@ -243,10 +244,6 @@ function ParallelListeners() { migrateLocalStorage(dispatch); }, []); - useEffect(() => { - void dispatch(loadLastSession()); - }, []); - return <>; } From bfebcc16a4dbb9d726be0b400580772cd10d85a6 Mon Sep 17 00:00:00 2001 From: Continue Agent Date: Thu, 9 Oct 2025 12:07:52 +0000 Subject: [PATCH 36/37] Add banner announcing Continue CLI v1.4.49 - Added dismissable banner to docs.json - Banner promotes CLI v1.4.49 release and links to MCP Cookbooks - Banner is dismissable for better UX Generated with [Continue](https://continue.dev) Co-Authored-By: Continue Co-authored-by: Username --- docs/docs.json | 4 ++++ 1 file changed, 4 insertions(+) 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", From 64b70616188e77101165f14997a9a3039ca3aa86 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Thu, 9 Oct 2025 16:31:26 -0700 Subject: [PATCH 37/37] Add debug logging to feedback capture in NextEditLoggingService (#8174) --- core/nextEdit/NextEditLoggingService.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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}`); + } } }