Merge branch 'main' of https://github.com/continuedev/continue into dependabot/npm_and_yarn/packages/terminal-security/vite-7.1.5

This commit is contained in:
Dallin Romney 2025-09-11 12:17:20 -07:00
commit 4fe9aa3e2d
17 changed files with 527 additions and 103 deletions

View file

@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Detailed PR Review
uses: continuedev/continue/actions/detailed-review@b3f4b82600f603ca28c65a319b80ec36c4644ed7
uses: continuedev/continue/actions/detailed-review@5dc7a050db441934c26eb910b8433291f627db7f
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: continuedev

View file

@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
uses: continuedev/continue/actions/general-review@b3f4b82600f603ca28c65a319b80ec36c4644ed7
uses: continuedev/continue/actions/general-review@5dc7a050db441934c26eb910b8433291f627db7f
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"

View file

@ -1061,6 +1061,7 @@ declare global {
filepath?: string;
fileContent?: string;
originalFileContent?: string;
autoFormattingDiff?: string;
}
export interface RangeInFileWithContents {

1
core/index.d.ts vendored
View file

@ -1387,6 +1387,7 @@ export interface ApplyState {
fileContent?: string;
originalFileContent?: string;
toolCallId?: string;
autoFormattingDiff?: string;
}
export interface StreamDiffLinesPayload {

View file

@ -0,0 +1,62 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../util/logger.js", () => ({
logger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
setLevel: vi.fn(),
configureHeadlessMode: vi.fn(),
getLogPath: vi.fn(),
getSessionId: vi.fn(),
},
}));
import { messageQueue } from "./messageQueue.js";
describe("messageQueue", () => {
beforeEach(() => {
// Drain any leftover items from previous tests
while (messageQueue.getAllQueuedMessages()) {}
});
it("enqueues and emits messageQueued", async () => {
const event = new Promise<any>((resolve) =>
messageQueue.once("messageQueued", resolve),
);
const ok = await messageQueue.enqueueMessage("hello world");
expect(ok).toBe(true);
expect(messageQueue.getQueueLength()).toBe(1);
const queued = await event;
expect(queued.message).toBe("hello world");
});
it("combines messages, merges image maps, writes history, and clears queue", async () => {
const bufA = Buffer.from("A");
const bufB = Buffer.from("B");
const img1 = new Map<string, Buffer>([["a", bufA]]);
const img2 = new Map<string, Buffer>([["b", bufB]]);
const history = { addEntry: vi.fn() } as any;
await messageQueue.enqueueMessage("one", img1);
await messageQueue.enqueueMessage("two", img2, history);
const combined = messageQueue.getAllQueuedMessages();
expect(combined).toBeTruthy();
expect(combined!.message).toBe("one\ntwo");
expect(combined!.imageMap).toBeDefined();
expect(combined!.imageMap!.get("a")).toEqual(bufA);
expect(combined!.imageMap!.get("b")).toEqual(bufB);
// queue should be cleared
expect(messageQueue.getQueueLength()).toBe(0);
// input history should receive the combined message
expect(history.addEntry).toHaveBeenCalledWith("one\ntwo");
});
});

View file

@ -0,0 +1,94 @@
import { EventEmitter } from "events";
import { InputHistory } from "../util/inputHistory.js";
import { logger } from "../util/logger.js";
export interface QueuedMessage {
message: string;
imageMap?: Map<string, Buffer>;
timestamp: number;
}
export interface MessageProcessor {
(message: string, imageMap?: Map<string, Buffer>): Promise<void>;
}
/**
* A queue to store messages that need to be processed later
*/
class MessageQueue extends EventEmitter {
private queue: QueuedMessage[] = [];
private inputHistory: InputHistory | undefined;
constructor() {
super();
}
async enqueueMessage(
message: string,
imageMap?: Map<string, Buffer>,
inputHistory?: InputHistory,
): Promise<boolean> {
this.inputHistory = inputHistory;
const queuedMessage: QueuedMessage = {
message,
imageMap,
timestamp: Date.now(),
};
this.queue.push(queuedMessage);
logger.debug("MessageQueue: Message queued", {
queueLength: this.queue.length,
});
// Emit event for UI to show the queued message
this.emit("messageQueued", queuedMessage);
return true;
}
public getAllQueuedMessages() {
if (this.queue.length === 0) return undefined;
// Combine all queued messages into one
const combinedMessage = this.queue.map((msg) => msg.message).join("\n");
const combinedImageMap = new Map<string, Buffer>();
// Merge all image maps
for (const queuedMsg of this.queue) {
if (queuedMsg.imageMap) {
for (const [key, value] of queuedMsg.imageMap) {
combinedImageMap.set(key, value);
}
}
}
const result = {
message: combinedMessage,
imageMap: combinedImageMap.size > 0 ? combinedImageMap : undefined,
timestamp: Date.now(),
};
// Add to input history and clear the queue
this.inputHistory?.addEntry(combinedMessage);
this.queue = [];
logger.debug("MessageQueue: All messages dequeued and combined", {
combinedLength: combinedMessage.length,
queueLength: this.queue.length,
});
return result;
}
public getLatestMessage() {
return this.getAllQueuedMessages();
}
getQueueLength(): number {
return this.queue.length;
}
}
export const messageQueue = new MessageQueue();

View file

@ -188,6 +188,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
inputMode,
activePermissionRequest,
wasInterrupted,
queuedMessages,
handleUserMessage,
handleInterrupt,
handleFileAttached,
@ -282,6 +283,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
model={services.model?.model || undefined}
mcpService={services.mcp?.mcpService || undefined}
chatHistory={chatHistory}
queuedMessages={queuedMessages}
renderMessage={renderMessage}
refreshTrigger={staticRefreshTrigger}
/>

View file

@ -9,6 +9,7 @@ import type { PermissionMode } from "../permissions/types.js";
import type { FileIndexServiceState } from "../services/FileIndexService.js";
import { SERVICE_NAMES, serviceContainer } from "../services/index.js";
import { modeService } from "../services/ModeService.js";
import { messageQueue } from "../stream/messageQueue.js";
import { InputHistory } from "../util/inputHistory.js";
import { FileSearchUI } from "./FileSearchUI.js";
@ -515,7 +516,7 @@ const UserInput: React.FC<UserInputProps> = ({
}
// Normal Enter behavior - submit if there's content
if ((textBuffer.text.trim() || wasInterrupted) && !isWaitingForResponse) {
if (textBuffer.text.trim() || wasInterrupted) {
// Get images before expanding paste blocks
const imageMap = textBuffer.getAllImages();
@ -523,14 +524,19 @@ const UserInput: React.FC<UserInputProps> = ({
textBuffer.expandAllPasteBlocks();
const submittedText = textBuffer.text.trim();
// Only add to history if there's actual text (not when resuming)
if (submittedText) {
if (isWaitingForResponse) {
// Process message later when LLM has responded
void messageQueue.enqueueMessage(
submittedText,
imageMap,
inputHistory,
);
} else {
// Submit with images
inputHistory.addEntry(submittedText);
onSubmit(submittedText, imageMap);
}
// Submit with images
onSubmit(submittedText, imageMap);
textBuffer.clear();
setInputText("");
setCursorPosition(0);
@ -647,15 +653,6 @@ const UserInput: React.FC<UserInputProps> = ({
return;
}
// Allow typing during streaming, but block submission
if (!inputMode) {
// Block only Enter key submission during streaming
if (key.return && !key.shift) {
return;
}
// Allow all other input (typing, navigation, etc.)
}
// Handle slash command navigation
if (showSlashCommands) {
if (handleSlashCommandNavigation(key)) {

View file

@ -1,9 +1,10 @@
import type { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { Box, Static, useStdout } from "ink";
import { Box, Static, Text, useStdout } from "ink";
import React, { useCallback, useEffect, useRef, useState } from "react";
import type { ChatHistoryItem } from "../../../../../core/index.js";
import type { MCPService } from "../../services/MCPService.js";
import type { QueuedMessage } from "../../stream/messageQueue.js";
import { useTerminalSize } from "../hooks/useTerminalSize.js";
import { IntroMessage } from "../IntroMessage.js";
@ -13,6 +14,7 @@ interface StaticChatContentProps {
model?: ModelConfig;
mcpService?: MCPService;
chatHistory: ChatHistoryItem[];
queuedMessages?: QueuedMessage[];
renderMessage: (item: ChatHistoryItem, index: number) => React.ReactElement;
refreshTrigger?: number; // Add a prop to trigger refresh from parent
}
@ -23,6 +25,7 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
model,
mcpService,
chatHistory,
queuedMessages = [],
renderMessage,
refreshTrigger,
}) => {
@ -140,6 +143,15 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
<React.Fragment key={`pending-${index}`}>{item}</React.Fragment>
))}
</Box>
{/* Queued messages - show at bottom with queue indicators */}
{queuedMessages.length > 0 && (
<Box paddingLeft={2} paddingBottom={1}>
<Text color="gray" italic>
{queuedMessages.map((msg) => msg.message).join("\n")}
</Text>
</Box>
)}
</Box>
);
};

View file

@ -1,3 +1,4 @@
/* eslint-disable max-lines */
import type { ChatHistoryItem, Session } from "core/index.js";
import { useApp } from "ink";
import { useEffect, useRef, useState } from "react";
@ -11,6 +12,7 @@ import {
updateSessionHistory,
} from "../../session.js";
import { handleSlashCommands } from "../../slashCommands.js";
import { messageQueue, QueuedMessage } from "../../stream/messageQueue.js";
import { telemetryService } from "../../telemetry/telemetryService.js";
import { formatError } from "../../util/formatError.js";
import { logger } from "../../util/logger.js";
@ -166,6 +168,22 @@ export function useChat({
// Track interrupted state for resume functionality
const [wasInterrupted, setWasInterrupted] = useState(false);
// Track queued messages for immediate display
const [queuedMessages, setQueuedMessages] = useState<QueuedMessage[]>([]);
// Set up message queue listeners
useEffect(() => {
const onMessageQueued = (queuedMessage: QueuedMessage) => {
setQueuedMessages((prev) => [...prev, queuedMessage]);
};
messageQueue.on("messageQueued", onMessageQueued);
return () => {
messageQueue.off("messageQueued", onMessageQueued);
};
}, []);
// Clean up abort controller on unmount
useEffect(() => {
return () => {
@ -306,6 +324,30 @@ export function useChat({
setIsWaitingForResponse(false);
setResponseStartTime(null);
setInputMode(true);
// Check if there are queued messages and process them after a microtask delay
// This ensures the GUI state has been updated before processing the next message
const queuedMessageData = messageQueue.getLatestMessage();
if (queuedMessageData) {
const { message: latestQueuedMessage, imageMap } = queuedMessageData;
logger.debug("processing queued message", { latestQueuedMessage });
// Clear all queued messages from display since we're processing them all together
setQueuedMessages([]);
// Add the queued message to chat history so it shows in the GUI
const formattedQueuedMessage = await formatMessageWithFiles(
latestQueuedMessage,
[], // No attached files for queued messages
imageMap,
);
setChatHistory((prev) => [...prev, formattedQueuedMessage]);
await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui
// Process the queued message using the internal processing logic without re-adding to history
await processQueuedMessage(latestQueuedMessage, imageMap);
}
}
};
@ -398,20 +440,11 @@ export function useChat({
.join("");
};
const handleUserMessage = async (
const processMessage = async (
message: string,
imageMap?: Map<string, Buffer>,
isQueuedMessage: boolean = false,
) => {
// Check if this is a resume request (empty message after interruption)
if (await handleResumeRequest(message)) {
return;
}
// Clear interrupted state if user types a new message
if (wasInterrupted && message !== "") {
setWasInterrupted(false);
}
// Handle special commands
const handled = await handleSpecialCommands({
message,
@ -440,27 +473,9 @@ export function useChat({
// Track telemetry
trackUserMessage(message, model);
// Format message with attached files and images
logger.debug("Processing message with images", {
hasImages: !!(imageMap && imageMap.size > 0),
imageCount: imageMap?.size || 0,
});
const newUserMessage = await formatMessageWithFiles(
message,
attachedFiles,
imageMap,
);
logger.debug("Message formatted successfully");
if (attachedFiles.length > 0) {
setAttachedFiles([]);
}
// In remote mode, send message to server instead of processing locally
if (isRemoteMode && remoteUrl) {
const messageContentString = convertMessageContentToString(
newUserMessage.message.content,
);
const messageContentString = convertMessageContentToString(message);
await handleRemoteMessage({
remoteUrl,
@ -469,23 +484,87 @@ export function useChat({
return;
}
// Check if auto-compacting is needed BEFORE adding user message
const { currentChatHistory, currentCompactionIndex } =
await handleAutoCompaction({
chatHistory,
model,
llmApi,
compactionIndex,
setChatHistory: setChatHistory,
setCompactionIndex,
// For non-queued messages, format and add to chat history
if (isQueuedMessage) {
// For queued messages, chat history is already updated
// Check if auto-compacting is needed with current history
const { currentChatHistory, currentCompactionIndex } =
await handleAutoCompaction({
chatHistory,
model,
llmApi,
compactionIndex,
setChatHistory: setChatHistory,
setCompactionIndex,
});
// Execute the streaming response with the current history (which already includes the queued message)
await executeStreamingResponse(
currentChatHistory,
currentCompactionIndex,
);
} else {
// Format message with attached files and images
logger.debug("Processing message with images", {
hasImages: !!(imageMap && imageMap.size > 0),
imageCount: imageMap?.size || 0,
});
const newUserMessage = await formatMessageWithFiles(
message,
attachedFiles,
imageMap,
);
logger.debug("Message formatted successfully");
// Add the formatted user message to history
const newHistory = [...currentChatHistory, newUserMessage];
setChatHistory(newHistory);
if (attachedFiles.length > 0) {
setAttachedFiles([]);
}
// Execute the streaming response
await executeStreamingResponse(newHistory, currentCompactionIndex);
// Check if auto-compacting is needed BEFORE adding user message
const { currentChatHistory, currentCompactionIndex } =
await handleAutoCompaction({
chatHistory,
model,
llmApi,
compactionIndex,
setChatHistory: setChatHistory,
setCompactionIndex,
});
// Add the formatted user message to history
const newHistory = [...currentChatHistory, newUserMessage];
setChatHistory(newHistory);
// Execute the streaming response
await executeStreamingResponse(newHistory, currentCompactionIndex);
}
};
const processQueuedMessage = async (
message: string,
imageMap?: Map<string, Buffer>,
) => {
// For queued messages, we can reuse the core message processing logic
// by calling the internal processing function directly
await processMessage(message, imageMap, true);
};
const handleUserMessage = async (
message: string,
imageMap?: Map<string, Buffer>,
) => {
// Check if this is a resume request (empty message after interruption)
if (await handleResumeRequest(message)) {
return;
}
// Clear interrupted state if user types a new message
if (wasInterrupted && message !== "") {
setWasInterrupted(false);
}
// Use the common message processing logic
await processMessage(message, imageMap, false);
};
const handleInterrupt = () => {
@ -537,6 +616,8 @@ export function useChat({
additionalRules,
);
setChatHistory(newHistory);
// Clear any queued messages when resetting chat
setQueuedMessages([]);
};
const handleToolPermissionResponse = async (
@ -614,6 +695,7 @@ export function useChat({
attachedFiles,
activePermissionRequest,
wasInterrupted,
queuedMessages,
handleUserMessage,
handleInterrupt,
handleFileAttached,

View file

@ -4,12 +4,12 @@ import {
InputBox,
Key,
TextEditor,
until,
VSBrowser,
WebDriver,
WebElement,
WebView,
Workbench,
until,
} from "vscode-extension-tester";
import { GlobalActions } from "../actions/Global.actions";
@ -47,11 +47,31 @@ describe("Keyboard Shortcuts", () => {
afterEach(async function () {
this.timeout(DEFAULT_TIMEOUT.XL * 1000);
await cleanupChat();
await view.switchBack();
await editor.clearText();
await new EditorView().closeAllEditors();
});
async function cleanupChat(chatInput?: WebElement) {
try {
if (!chatInput) {
chatInput = await TestUtils.waitForSuccess(async () => {
return GUISelectors.getMessageInputFieldAtIndex(view, 0);
});
}
if (
chatInput &&
(await chatInput.isDisplayed()) &&
(await chatInput.isEnabled())
) {
await chatInput.clear();
}
} catch (e) {
console.error(`Failed to clear chat: ${e}`);
}
}
it("Should correctly undo and redo using keyboard shortcuts when writing a chat message", async () => {
await GUIActions.executeFocusContinueInputShortcut(driver);
({ view } = await GUIActions.switchToReactIframe());
@ -105,10 +125,8 @@ describe("Keyboard Shortcuts", () => {
);
}).timeout(DEFAULT_TIMEOUT.XL);
it("Should not create a code block when Cmd+L is pressed without text highlighted", async () => {
const text = "Hello, world!";
await editor.setText(text);
it("Should not create a code block when Cmd+L is pressed on an empty document", async () => {
expect((await editor.getText()).trim()).to.equal("");
await GUIActions.executeFocusContinueInputShortcut(driver);
@ -174,6 +192,9 @@ describe("Keyboard Shortcuts", () => {
await driver.wait(until.elementIsNotVisible(textInput), DEFAULT_TIMEOUT.XS);
expect(await textInput.isDisplayed()).to.equal(false);
// Make sure the view is visible again, so it can be cleared in afterEach()
await GUIActions.executeFocusContinueInputShortcut(driver);
}).timeout(DEFAULT_TIMEOUT.XL);
it("Should create a code block when Cmd+L is pressed with text highlighted", async () => {
@ -197,4 +218,44 @@ describe("Keyboard Shortcuts", () => {
await GUIActions.executeFocusContinueInputShortcut(driver);
}).timeout(DEFAULT_TIMEOUT.XL);
it("Should create a code block with the whole file when Cmd+L is pressed on an empty line", async () => {
const text = "Hello,\n\n\nworld!";
await editor.setText(text);
await editor.moveCursor(2, 1); //Move cursor to an empty line
await GUIActions.executeFocusContinueInputShortcut(driver);
({ view } = await GUIActions.switchToReactIframe());
const codeBlock = await TestUtils.waitForSuccess(() =>
GUISelectors.getInputBoxCodeBlockAtIndex(view, 0),
);
const codeblockContent = await codeBlock.getAttribute(
"data-codeblockcontent",
);
expect(codeblockContent).to.equal(text);
});
it("Should create a code block when Cmd+L is pressed on a non-empty line", async () => {
const text = "Hello, world!";
await editor.setText(text);
await editor.moveCursor(1, 7); //Move cursor to the 1st space
await GUIActions.executeFocusContinueInputShortcut(driver);
({ view } = await GUIActions.switchToReactIframe());
const codeBlock = await TestUtils.waitForSuccess(() =>
GUISelectors.getInputBoxCodeBlockAtIndex(view, 0),
);
const codeblockContent = await codeBlock.getAttribute(
"data-codeblockcontent",
);
expect(codeblockContent).to.equal(text);
}).timeout(DEFAULT_TIMEOUT.XL);
});

View file

@ -524,13 +524,12 @@
"continue.continueSubMenu": [
{
"command": "continue.focusContinueInputWithoutClear",
"group": "Continue",
"when": "editorHasSelection"
"group": "Continue"
},
{
"command": "continue.focusEdit",
"group": "Continue",
"when": "editorHasSelection && !editorReadonly"
"when": "!editorReadonly"
}
],
"explorer/context": [

View file

@ -1,8 +1,11 @@
import { Core } from "core/core";
import { DataLogger } from "core/data/log";
import { myersDiff } from "core/diff/myers";
import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
import { editOutcomeTracker } from "../extension/EditOutcomeTracker";
import { VsCodeIde } from "../VsCodeIde";
import { VerticalDiffManager } from "./vertical/manager";
export async function processDiff(
@ -42,7 +45,8 @@ export async function processDiff(
}
if (streamId) {
const fileContent = await ide.readFile(newOrCurrentUri);
// Capture file content before save to detect autoformatting
const preSaveContent = await ide.readFile(newOrCurrentUri);
// Record the edit outcome before updating the apply state
await editOutcomeTracker.recordEditOutcome(
@ -51,16 +55,45 @@ export async function processDiff(
DataLogger.getInstance(),
);
// Save the file
await ide.saveFile(newOrCurrentUri);
// Capture file content after save to detect autoformatting
const postSaveContent = await ide.readFile(newOrCurrentUri);
// Detect autoformatting by comparing normalized content
let autoFormattingDiff: string | undefined;
const normalizedPreSave = preSaveContent.trim();
const normalizedPostSave = postSaveContent.trim();
if (normalizedPreSave !== normalizedPostSave) {
// Auto-formatting was applied by the editor
const diffLines = myersDiff(preSaveContent, postSaveContent);
autoFormattingDiff = diffLines
.map((line) => {
switch (line.type) {
case "old":
return `-${line.line}`;
case "new":
return `+${line.line}`;
case "same":
return ` ${line.line}`;
}
})
.join("\n");
}
await sidebar.webviewProtocol.request("updateApplyState", {
fileContent,
fileContent: postSaveContent, // Use post-save content
filepath: newOrCurrentUri,
streamId,
status: "closed",
numDiffs: 0,
toolCallId,
autoFormattingDiff, // Include autoformatting diff
});
} else {
// Save the file even if no streamId
await ide.saveFile(newOrCurrentUri);
}
// Save the file
await ide.saveFile(newOrCurrentUri);
}

View file

@ -36,22 +36,38 @@ export function getRangeInFileWithContents(
};
}
if (selection.isEmpty && !allowEmpty) {
if ((selection.isEmpty && !allowEmpty) || isEmptyFile(editor.document)) {
return null;
}
let selectionRange = new vscode.Range(selection.start, selection.end);
const document = editor.document;
// Select the context from the beginning of the selection start line to the selection start position
const beginningOfSelectionStartLine = selection.start.with(undefined, 0);
const textBeforeSelectionStart = document.getText(
new vscode.Range(beginningOfSelectionStartLine, selection.start),
);
// If there are only whitespace before the start of the selection, include the indentation
if (textBeforeSelectionStart.trim().length === 0) {
selectionRange = selectionRange.with({
start: beginningOfSelectionStartLine,
});
let selectionRange: vscode.Range | undefined;
// if the selection is empty and document is not empty, select the whole document
if (selection.isEmpty) {
selectionRange = new vscode.Range(
new vscode.Position(0, 0),
new vscode.Position(
editor.document.lineCount - 1,
editor.document.lineAt(
editor.document.lineCount - 1,
).range.end.character,
),
);
}
if (!selectionRange) {
selectionRange = new vscode.Range(selection.start, selection.end);
const document = editor.document;
// Select the context from the beginning of the selection start line to the selection start position
const beginningOfSelectionStartLine = selection.start.with(undefined, 0);
const textBeforeSelectionStart = document.getText(
new vscode.Range(beginningOfSelectionStartLine, selection.start),
);
// If there are only whitespace before the start of the selection, include the indentation
if (textBeforeSelectionStart.trim().length === 0) {
selectionRange = selectionRange.with({
start: beginningOfSelectionStartLine,
});
}
}
const contents = editor.document.getText(selectionRange);
@ -61,12 +77,12 @@ export function getRangeInFileWithContents(
contents,
range: {
start: {
line: selection.start.line,
character: selection.start.character,
line: selectionRange.start.line,
character: selectionRange.start.character,
},
end: {
line: selection.end.line,
character: selection.end.character,
line: selectionRange.end.line,
character: selectionRange.end.character,
},
},
};
@ -78,7 +94,7 @@ export function getRangeInFileWithContents(
export async function addHighlightedCodeToContext(
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
const rangeInFileWithContents = getRangeInFileWithContents();
const rangeInFileWithContents = getRangeInFileWithContents(true);
if (rangeInFileWithContents) {
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
@ -129,6 +145,10 @@ export async function addEntireFileToContext(
});
}
export function isEmptyFile(document: vscode.TextDocument) {
return document.lineCount === 1 && document.lineAt(0).range.isEmpty;
}
export function addCodeToContextFromRange(
range: vscode.Range,
webviewProtocol: VsCodeWebviewProtocol,

View file

@ -1,3 +1,4 @@
import { useMemo, useRef } from "react";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { saveCurrentSession } from "../../redux/thunks/session";
import { useCompactConversation } from "../../util/compactConversation";
@ -8,15 +9,36 @@ const ContextStatus = () => {
const contextPercentage = useAppSelector(
(state) => state.session.contextPercentage,
);
const selectedChatModel = useAppSelector(
(state) => state.config.config.selectedModelByRole.chat?.model,
);
const previousHistoryLength = useRef<number | null>(null);
const previousSelectedChatModel = useRef<string | null>(null);
const history = useAppSelector((state) => state.session.history);
const percent = Math.round((contextPercentage ?? 0) * 100);
const isPruned = useAppSelector((state) => state.session.isPruned);
const isDifferentModelAndSameHistory = useMemo(() => {
if (!selectedChatModel) return false;
// only reset if history changes
if (previousHistoryLength.current !== history.length) {
previousHistoryLength.current = history.length;
previousSelectedChatModel.current = selectedChatModel;
return false;
}
return previousSelectedChatModel.current !== selectedChatModel;
}, [history.length, selectedChatModel]);
const compactConversation = useCompactConversation();
if (!isPruned && percent < 60) {
return null;
}
// if user changed to a different model, we shouldn't show the context status until the user sends a new message
if (isDifferentModelAndSameHistory) {
return null;
}
const barColorClass = isPruned ? "bg-error" : "bg-description";
return (

View file

@ -83,12 +83,57 @@ export const handleApplyStateUpdate = createAsyncThunk<
}
if (accepted) {
// Add autoformatting diff to tool output if present
if (applyState.autoFormattingDiff) {
dispatch(
updateToolCallOutput({
toolCallId: applyState.toolCallId,
contextItems: [
{
icon: "info",
name: "Auto-formatting Applied",
description: "Editor auto-formatting changes",
content: `Along with your edits, the editor applied the following auto-formatting:\n\n${applyState.autoFormattingDiff}\n\n(Note: Pay close attention to changes such as single quotes being converted to double quotes, semicolons being removed or added, long lines being broken into multiple lines, adjusting indentation style, adding/removing trailing commas, etc. This will help you ensure future SEARCH/REPLACE operations to this file are accurate.)`,
hidden: false,
},
],
}),
);
}
if (toolCallState.status !== "errored") {
dispatch(
acceptToolCall({
toolCallId: applyState.toolCallId,
}),
);
dispatch(
updateToolCallOutput({
toolCallId: applyState.toolCallId,
contextItems: [
{
name: "Edit Success",
content: `Successfully edited ${applyState.filepath}`,
description: "",
hidden: true,
},
],
}),
);
} else {
dispatch(
updateToolCallOutput({
toolCallId: applyState.toolCallId,
contextItems: [
{
name: "Edit Failed",
content: `Failed to edit ${applyState.filepath}. To continue working with the file, read it again to see the most up-to-date contents`,
description: "",
hidden: true,
},
],
}),
);
}
void dispatch(
@ -98,7 +143,6 @@ export const handleApplyStateUpdate = createAsyncThunk<
);
}
}
// TODO return output from edit tools so the model knows the result
}
}
}

View file

@ -17,13 +17,13 @@ export const editToolImpl: ClientToolImpl = async (
filepath = filepath.slice(2);
}
const openFiles = await extras.ideMessenger.ide.getOpenFiles();
let firstUriMatch = await resolveRelativePathInDir(
filepath,
extras.ideMessenger.ide,
);
if (!firstUriMatch) {
const openFiles = await extras.ideMessenger.ide.getOpenFiles();
for (const uri of openFiles) {
if (uri.endsWith(filepath)) {
firstUriMatch = uri;
@ -46,13 +46,7 @@ export const editToolImpl: ClientToolImpl = async (
);
return {
respondImmediately: true,
output: [
{
name: "File edited successfully",
content: `Successfully initiated edit for ${firstUriMatch}`,
description: "File edit operation started",
},
],
respondImmediately: false,
output: undefined, // no immediate output - output for edit tools should be added based on apply state coming in
};
};