Merge branch 'main' of https://github.com/continuedev/continue into dallin/silent-chat-errors

This commit is contained in:
Dallin Romney 2024-12-08 23:32:44 -08:00
commit 4814a496dd
38 changed files with 399 additions and 138 deletions

View file

@ -49,11 +49,11 @@ jobs:
platform: alpine
arch: x64
npm_config_arch: x64
- os: macos-12 # should migrate this to the newer x64 version of macos-14
- os: macos-13
platform: darwin
arch: x64
npm_config_arch: x64
- os: macos-12 # same here, especially
- os: macos-13
platform: darwin
arch: arm64
npm_config_arch: arm64

View file

@ -49,11 +49,11 @@ jobs:
platform: alpine
arch: x64
npm_config_arch: x64
- os: macos-12 # should migrate this to the newer x64 version of macos-14
- os: macos-13
platform: darwin
arch: x64
npm_config_arch: x64
- os: macos-12 # same here, especially
- os: macos-13
platform: darwin
arch: arm64
npm_config_arch: arm64

View file

@ -29,14 +29,23 @@ export class ImportDefinitionsService {
return this.cache.get(filepath);
}
private async _getFileInfo(filepath: string): Promise<FileInfo> {
private async _getFileInfo(filepath: string): Promise<FileInfo | null> {
const parser = await getParserForFile(filepath);
if (!parser) {
return {
imports: {},
};
}
const ast = parser.parse(await this.ide.readFile(filepath), undefined, {
let fileContents: string | undefined = undefined;
try {
fileContents = await this.ide.readFile(filepath);
} catch (err) {
// File removed
return null;
}
const ast = parser.parse(fileContents, undefined, {
includedRanges: [
{
startIndex: 0,

View file

@ -10,6 +10,7 @@ import {
showWhateverWeHaveAtXMs,
skipPrefixes,
stopAtLines,
stopAtLinesExact,
stopAtRepeatingLines,
stopAtSimilarLine,
streamWithNewLines,
@ -42,6 +43,12 @@ export class StreamTransformPipeline {
let lineGenerator = streamLines(charGenerator);
lineGenerator = stopAtLines(lineGenerator, fullStop);
const lineBelowCursor = this.getLineBelowCursor(helper);
if (lineBelowCursor.trim() !== "") {
lineGenerator = stopAtLinesExact(lineGenerator, fullStop, [
lineBelowCursor,
]);
}
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
lineGenerator = avoidEmptyComments(
lineGenerator,

View file

@ -2,7 +2,6 @@ import { distance } from "fastest-levenshtein";
import { DiffLine } from "../../..";
import { LineStream } from "../../../diff/util";
import { BRACKETS, BRACKETS_REVERSE } from "../BracketMatchingService";
export type LineFilter = (args: {
lines: LineStream;
@ -270,6 +269,20 @@ export async function* stopAtLines(
}
}
export async function* stopAtLinesExact(
stream: LineStream,
fullStop: () => void,
linesToStopAt: string[],
): LineStream {
for await (const line of stream) {
if (linesToStopAt.some((stopAt) => line === stopAt)) {
fullStop();
break;
}
yield line;
}
}
/**
* Filters a LineStream, skipping specified prefixes on the first line.
* @param {LineStream} lines - The input stream of lines.

View file

@ -810,8 +810,7 @@ func main() {}`,
}`,
expectedCompletion: `string
State string
ZipCode string
}`,
ZipCode string`,
},
{
@ -1118,8 +1117,7 @@ impl Calculator {
self.result /= number;
} else {
println!("Cannot divide by zero.");
}
}`,
}`,
},
{
description: "Should autocomplete Rust struct definition",
@ -1600,8 +1598,7 @@ interface User {
age: number;
}`,
expectedCompletion: `mail: string;
age: number;
}`,
age: number;`,
},
{
description: "Should autocomplete TypeScript interface declarations",
@ -1853,8 +1850,7 @@ let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`,
Address: string
}`,
expectedCompletion: `
Address: string
}`,
Address: string`,
},
{

View file

@ -1,7 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import Mock from "../../../llm/llms/Mock";
import MockLLM from "../../../llm/llms/Mock";
import { testConfigHandler, testIde } from "../../../test/fixtures";
import { CompletionProvider } from "../../CompletionProvider";
import { AutocompleteInput } from "../../util/types";
@ -30,7 +30,7 @@ export async function testAutocompleteFiltering(
const { prefix, suffix } = parseFimExample(test.input);
// Setup necessary objects
const llm = new Mock({
const llm = new MockLLM({
model: "mock",
});
llm.completion = test.llmOutput;

View file

@ -66,7 +66,6 @@ This is the question that you should select relevant files for: "${input}"`;
new AbortController().signal,
);
const content = renderChatMessage(response);
console.debug("Repo map retrieval response: ", content);
if (!content.includes("\n")) {
return [];

View file

@ -859,10 +859,7 @@ export class Core {
this.indexingCancellationController &&
!this.indexingCancellationController.signal.aborted
) {
return console.debug(
"Codebase indexing already in progress, skipping indexing of files\n" +
files.join("\n"),
);
return;
}
this.indexingCancellationController = new AbortController();
for await (const update of (await this.codebaseIndexerPromise).refreshFiles(

1
core/index.d.ts vendored
View file

@ -806,6 +806,7 @@ type ModelProvider =
| "nvidia"
| "vllm"
| "mock"
| "test"
| "cerebras"
| "askSage"
| "vertexai"

View file

@ -7,9 +7,9 @@ import {
ContinueConfig,
EmbeddingsProvider,
IDE,
IdeInfo,
IndexingStatus,
SiteIndexingConfig,
IdeInfo,
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { addContextProvider } from "../../config/util";
@ -69,7 +69,6 @@ export type AddParams = {
favicon?: string;
};
/*
General process:
- On config update:
@ -476,8 +475,6 @@ export default class DocsService {
const embeddings: number[][] = [];
// Create embeddings of retrieved articles
console.debug(`Creating embeddings for ${articles.length} articles`);
for (let i = 0; i < articles.length; i++) {
const article = articles[i];

View file

@ -1,7 +1,7 @@
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { BaseLLM } from "../index.js";
class Mock extends BaseLLM {
class MockLLM extends BaseLLM {
public completion: string = "Test Completion";
static providerName: ModelProvider = "mock";
@ -27,4 +27,4 @@ class Mock extends BaseLLM {
}
}
export default Mock;
export default MockLLM;

39
core/llm/llms/Test.ts Normal file
View file

@ -0,0 +1,39 @@
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { BaseLLM } from "../index.js";
const RESPONSES: Record<string, string> = {
"How are you?": "I'm fine",
};
const HARDCODED_CHAT_RESPONSE = "THIS IS A HARDCODED RESPONSE";
class TestLLM extends BaseLLM {
static providerName: ModelProvider = "test";
private findResponse(prompt: string) {
return Object.entries(RESPONSES).find(([key]) => prompt.includes(key))?.[1];
}
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
yield this.findResponse(prompt) || `PROMPT: ${prompt}`;
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
for (const char of HARDCODED_CHAT_RESPONSE) {
yield {
role: "assistant",
content: char,
};
}
}
}
export default TestLLM;

View file

@ -31,7 +31,7 @@ import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
import LMStudio from "./LMStudio";
import Mistral from "./Mistral";
import Mock from "./Mock";
import MockLLM from "./Mock";
import Moonshot from "./Moonshot";
import Msty from "./Msty";
import Nebius from "./Nebius";
@ -50,6 +50,7 @@ import Vllm from "./Vllm";
import WatsonX from "./WatsonX";
import xAI from "./xAI";
import SiliconFlow from "./SiliconFlow";
import TestLLM from "./Test";
const LLMs = [
Anthropic,
@ -87,7 +88,8 @@ const LLMs = [
Nvidia,
Vllm,
SambaNova,
Mock,
MockLLM,
TestLLM,
Cerebras,
Asksage,
Nebius,

View file

@ -1,7 +1,7 @@
export class PrecalculatedLruCache<V> {
private items: [string, V][] = [];
constructor(
private readonly calculateValue: (key: string) => Promise<V>,
private readonly calculateValue: (key: string) => Promise<V | null>,
private readonly N: number,
) {}
@ -11,7 +11,11 @@ export class PrecalculatedLruCache<V> {
if (index < 0) {
// Calculate info for new file
const value: V = await this.calculateValue(key);
const value: V | null = await this.calculateValue(key);
if (value === null) {
return;
}
this.items.push([key, value]);
if (this.items.length > this.N) {

1
core/util/constants.ts Normal file
View file

@ -0,0 +1 @@
export const NEW_SESSION_TITLE = "New Session";

View file

@ -1,6 +1,7 @@
import { v4 as uuidv4 } from "uuid";
import { Session } from "..";
import { NEW_SESSION_TITLE } from "./constants";
import historyManager from "./history";
import { getSessionFilePath } from "./paths";
@ -31,7 +32,7 @@ describe("No sessions have been created", () => {
const session = historyManager.load(testSessionId);
expect(session).toEqual({
history: [],
title: "Failed to load session",
title: NEW_SESSION_TITLE,
workspaceDirectory: "",
sessionId: testSessionId,
});

View file

@ -3,8 +3,8 @@ import * as fs from "fs";
import { Session, SessionMetadata } from "../index.js";
import { ListHistoryOptions } from "../protocol/core.js";
import { NEW_SESSION_TITLE } from "./constants.js";
import { getSessionFilePath, getSessionsListPath } from "./paths.js";
function safeParseArray<T>(
value: string,
errorMessage: string = "Error parsing array",
@ -80,7 +80,7 @@ class HistoryManager {
console.log(`Error loading session: ${e}`);
return {
history: [],
title: "Failed to load session",
title: NEW_SESSION_TITLE,
workspaceDirectory: "",
sessionId: sessionId,
};

View file

@ -231,7 +231,13 @@ export async function getSymbolsForFile(
return;
}
const tree = parser.parse(contents);
let tree: Parser.Tree;
try {
tree = parser.parse(contents);
} catch (e) {
console.log(`Error parsing file: ${filepath}`);
return;
}
// console.log(`file: ${filepath}`);
// Function to recursively find all named nodes (classes and functions)

View file

@ -444,7 +444,7 @@ Available connection types:
### `@Debugger`
Reference the contents of the local variables in the debugger.
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
```json title="config.json"
{

View file

@ -18,8 +18,9 @@ gui/**
continue_rc_schema.json
e2e/_output
e2e/.test-extensions
e2e/storage
e2e/vsix
e2e/test-continue/*
!e2e/test-continue/config.json

View file

@ -21,6 +21,7 @@ esbuild.js
esbuild.test.mjs
importMetaUrl.js
scripts
e2e
server/exe/**
!out/node_modules/**

View file

@ -1,86 +0,0 @@
import {
Workbench,
EditorView,
WebView,
By,
WebElement,
WebDriver,
Key,
} from "vscode-extension-tester";
import { expect } from "chai";
const switchToReactIframe = async (driver: WebDriver) => {
const iframes = await driver.findElements(By.css("iframe"));
let continueIFrame: WebElement | undefined = undefined;
for (let i = 0; i < iframes.length; i++) {
const iframe = iframes[i];
const src = await iframe.getAttribute("src");
if (src.includes("extensionId=Continue.continue")) {
continueIFrame = iframe;
break;
}
}
if (!continueIFrame) {
throw new Error("Could not find continue iframe");
}
await driver.switchTo().frame(continueIFrame);
await new Promise((res) => {
setTimeout(res, 500);
});
const reactIFrame = await driver.findElement(By.css("iframe"));
if (!reactIFrame) {
throw new Error("Could not find React iframe");
}
await driver.switchTo().frame(reactIFrame);
};
describe("GUI Test", () => {
let view: WebView;
let driver: WebDriver;
before(async function () {
this.timeout(10000);
await new Workbench().executeCommand("continue.focusContinueInput");
view = new WebView();
driver = view.getDriver();
await switchToReactIframe(driver);
});
after(async () => {
await view.switchBack();
await new EditorView().closeAllEditors();
});
it("should display correct panel description", async () => {
const description = await view.findWebElement(
By.xpath("//*[contains(text(), 'Quickly')]"),
);
expect(await description.getText()).has.string(
"Quickly get up and running using our API keys.",
);
});
it("should allow typing text in the editor", async () => {
const tiptap = await view.findWebElement(By.className("tiptap"));
await tiptap.sendKeys("Hello world!");
expect(await tiptap.getText()).has.string("Hello world!");
// Just to show that we can
await tiptap.sendKeys(Key.ENTER);
await new Promise((res) => {
setTimeout(res, 5000);
});
}).timeout(6000);
});

View file

@ -0,0 +1,27 @@
import { WebElement } from "vscode-extension-tester";
export class TestUtils {
public static async waitForElement(
locatorFn: () => Promise<WebElement>,
timeout: number = 5000,
interval: number = 500,
): Promise<WebElement> {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
try {
const element = await locatorFn();
if (element) {
return element;
}
} catch (e) {
if (Date.now() - startTime >= timeout) {
throw new Error(`Element not found after ${timeout}ms timeout`);
}
}
await new Promise((resolve) => setTimeout(resolve, interval));
}
throw new Error(`Element not found after ${timeout}ms timeout`);
}
}

View file

@ -0,0 +1,59 @@
import {
WebDriver,
WebElement,
WebView,
Workbench,
} from "vscode-extension-tester";
import { GUISelectors } from "../selectors/GUI.selectors";
import { TestUtils } from "../TestUtils";
export class GUIActions {
public static switchToReactIframe = async (driver: WebDriver) => {
const iframes = await GUISelectors.getAllIframes(driver);
let continueIFrame: WebElement | undefined = undefined;
for (let i = 0; i < iframes.length; i++) {
const iframe = iframes[i];
const src = await iframe.getAttribute("src");
if (src.includes("extensionId=Continue.continue")) {
continueIFrame = iframe;
break;
}
}
if (!continueIFrame) {
throw new Error("Could not find continue iframe");
}
await driver.switchTo().frame(continueIFrame);
await new Promise((res) => {
setTimeout(res, 500);
});
const reactIFrame = await GUISelectors.getReactIframe(driver);
if (!reactIFrame) {
throw new Error("Could not find React iframe");
}
await driver.switchTo().frame(reactIFrame);
};
public static openGui = async () => {
return new Workbench().executeCommand("continue.focusContinueInput");
};
public static selectModelFromDropdown = async (
view: WebView,
option: string,
) => {
const dropdownButton = await GUISelectors.getModelDropdownButton(view);
await dropdownButton.click();
const dropdownOption = await TestUtils.waitForElement(() => {
return GUISelectors.getModelDropdownOption(view, option);
});
await dropdownOption.click();
};
}

View file

@ -0,0 +1,40 @@
import { By, WebDriver, WebView } from "vscode-extension-tester";
import { SelectorUtils } from "./SelectorUtils";
export class GUISelectors {
public static getDescription(view: WebView) {
return view.findWebElement(By.xpath("//*[contains(text(), 'Quickly')]"));
}
public static getTipTapEditor(view: WebView) {
return view.findWebElement(By.className("tiptap"));
}
public static getAllIframes(driver: WebDriver) {
return driver.findElements(By.css("iframe"));
}
public static getReactIframe(driver: WebDriver) {
return driver.findElement(By.css("iframe"));
}
public static getSubmitInputButton(view: WebView) {
return SelectorUtils.getElementByDataTestId(view, "submit-input-button");
}
public static getModelDropdownButton(view: WebView) {
return SelectorUtils.getElementByDataTestId(view, "model-select-button");
}
public static getModelDropdownOption(view: WebView, option: string) {
return view.findWebElement(
By.xpath(`//*[@role="listbox"]//*[contains(text(), "${option}")]`),
);
}
public static getThreadMessageByText(view: WebView, text: string) {
return view.findWebElement(
By.xpath(`//*[@class="thread-message"]//*[contains(text(), "${text}")]`),
);
}
}

View file

@ -0,0 +1,16 @@
import { By, WebElement, WebView } from "vscode-extension-tester";
export class SelectorUtils {
/**
* Finds a web element by its data-testid attribute within a WebView.
* @param view - The WebView to search within.
* @param testId - The data-testid value to search for.
* @returns A promise that resolves to the WebElement found.
*/
public static getElementByDataTestId(
view: WebView,
testId: string,
): Promise<WebElement> {
return view.findWebElement(By.css(`[data-testid='${testId}']`));
}
}

View file

@ -0,0 +1,44 @@
{
"ui": {
"displayRawMarkdown": false
},
"models": [
{
"title": "TEST LLM",
"provider": "test",
"model": "this field is not used"
},
{
"title": "Mock",
"provider": "mock",
"model": "this field is not used"
}
],
"analytics": {
"provider": "continue-proxy"
},
"tabAutocompleteModel": {
"title": "Qwen",
"provider": "mistral",
"model": "codestral-latest",
"apiKey": ""
},
"tabAutocompleteOptions": {
"useCache": false
},
"contextProviders": [
{
"name": "docs"
},
{
"name": "diff"
},
{
"name": "url"
},
{
"name": "folder"
}
],
"docs": []
}

View file

@ -0,0 +1,59 @@
import {
EditorView,
WebView,
WebDriver,
VSBrowser,
} from "vscode-extension-tester";
import { expect } from "chai";
import { GUIActions } from "../actions/GUI.actions";
import { GUISelectors } from "../selectors/GUI.selectors";
import * as path from "path";
import { TestUtils } from "../TestUtils";
describe("GUI Test", () => {
let view: WebView;
let driver: WebDriver;
before(async function () {
this.timeout(10000000);
await VSBrowser.instance.openResources(path.join("e2e/test-continue"));
await GUIActions.openGui();
view = new WebView();
driver = view.getDriver();
await GUIActions.switchToReactIframe(driver);
// await new Promise((res) => {
// setTimeout(res, 10000000);
// });
});
after(async () => {
await view.switchBack();
await new EditorView().closeAllEditors();
});
it("should display correct panel description", async () => {
const description = await GUISelectors.getDescription(view);
expect(await description.getText()).has.string(
"Quickly get up and running using our API keys.",
);
}).timeout(20_000);
it("should allow typing text in the editor", async () => {
await GUIActions.selectModelFromDropdown(view, "Mock");
await GUIActions.selectModelFromDropdown(view, "TEST LLM");
const tiptap = await GUISelectors.getTipTapEditor(view);
await tiptap.sendKeys("How are you?");
(await GUISelectors.getSubmitInputButton(view)).click();
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, "I'm fine"),
);
}).timeout(20_000);
});

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.240",
"version": "0.9.242",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -625,9 +625,11 @@
"e2e:sign-vscode": "codesign --entitlements entitlements.plist --deep --force -s - './e2e/storage/Visual Studio Code.app'",
"e2e:copy-vsix": "chmod +x ./e2e/get-latest-vsix.sh && bash ./e2e/get-latest-vsix.sh",
"e2e:install-vsix": "extest install-vsix -f ./e2e/vsix/continue.vsix --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage",
"e2e:test": "extest run-tests './e2e/_output/*.test.js' --code_settings settings.json --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage",
"e2e:all": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:sign-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:test",
"e2e:ci": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:test"
"e2e:test": "extest run-tests './e2e/_output/tests/*.test.js' --code_settings settings.json --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage",
"e2e:clean": "rm -rf ./e2e/_output",
"e2e:all": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:sign-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean",
"e2e:quick": "npm run e2e:compile && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean",
"e2e:ci": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test"
},
"devDependencies": {
"@biomejs/biome": "1.6.4",

View file

@ -31,9 +31,15 @@ export default function FileIcon({ filename, height, width }: FileIconProps) {
const sanitizedSVG = DOMPurify.sanitize(svg);
return (
<div
<span
dangerouslySetInnerHTML={{ __html: sanitizedSVG }}
style={{ width: width, height: height, fill: color, flexShrink: 0 }}
style={{
width: width,
height: height,
fill: color,
flexShrink: 0,
display: "block",
}}
/>
);
}

View file

@ -9,11 +9,11 @@ import { getBasename } from "core/util";
import { useContext, useMemo, useState } from "react";
import { AnimatedEllipsis, lightGray, vscBackground } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
import { selectIsGatheringContext } from "../../redux/slices/sessionSlice";
import FileIcon from "../FileIcon";
import SafeImg from "../SafeImg";
import { getIconFromDropdownItem } from "./MentionList";
import { useAppSelector } from "../../redux/hooks";
import { selectIsGatheringContext } from "../../redux/slices/sessionSlice";
interface ContextItemsPeekProps {
contextItems?: ContextItemWithId[];
@ -172,7 +172,7 @@ function ContextItemsPeek({
<span className="ml-1 text-xs text-gray-400 transition-colors duration-200">
{isGatheringContext ? (
<>
Gathering context...
Gathering context
<AnimatedEllipsis />
</>
) : (

View file

@ -208,6 +208,7 @@ function InputToolbar(props: InputToolbarProps) {
)}
<EnterButton
data-testid="submit-input-button"
onClick={async (e) => {
if (props.onEnter) {
props.onEnter({

View file

@ -316,6 +316,7 @@ function ModelSelect() {
>
<div className="relative">
<StyledListboxButton
data-testid="model-select-button"
ref={buttonRef}
className="h-[18px] overflow-hidden"
style={{ padding: 0 }}

View file

@ -1,5 +1,6 @@
import { Dispatch } from "@reduxjs/toolkit";
import { Session, SessionMetadata } from "core";
import { NEW_SESSION_TITLE } from "core/util/constants";
import { renderChatMessage } from "core/util/messageContent";
import { useCallback, useContext } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
@ -65,7 +66,7 @@ function useHistory(dispatch: Dispatch) {
}
let currentTitle = title;
if (config?.ui?.getChatTitles && currentTitle === "New Session") {
if (config?.ui?.getChatTitles && currentTitle === NEW_SESSION_TITLE) {
try {
// Check if we have first assistant response
let assistantResponse = history
@ -82,7 +83,7 @@ function useHistory(dispatch: Dispatch) {
// Fallback if we get an error above or if the user has not set getChatTitles
let newTitle =
currentTitle === "New Session"
currentTitle === NEW_SESSION_TITLE
? truncateText(
renderChatMessage(history[0].message)
.split("\n")

View file

@ -57,6 +57,7 @@ import {
setShowDialog,
} from "../../redux/slices/uiSlice";
import { RootState } from "../../redux/store";
import { cancelStream } from "../../redux/thunks/cancelStream";
import { exitEditMode } from "../../redux/thunks/exitEditMode";
import { streamResponseThunk } from "../../redux/thunks/streamResponse";
import {
@ -203,7 +204,7 @@ export function Chat() {
isMetaEquivalentKeyPressed(e) &&
!e.shiftKey
) {
// dispatch(cancelGeneration()); TODO!!!
dispatch(cancelStream());
}
};
window.addEventListener("keydown", listener);
@ -341,7 +342,7 @@ export function Chat() {
<>
{isInEditMode && (
<PageHeader
title="Chat"
title="Back to Chat"
onClick={() => {
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),

View file

@ -19,6 +19,7 @@ import {
Session,
ToolCall,
} from "core";
import { NEW_SESSION_TITLE } from "core/util/constants";
import { incrementalParseJson } from "core/util/incrementalParseJson";
import { renderChatMessage } from "core/util/messageContent";
import { v4 as uuidv4 } from "uuid";
@ -73,7 +74,7 @@ function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) {
const initialState: SessionState = {
history: [],
isStreaming: false,
title: "New Session",
title: NEW_SESSION_TITLE,
id: uuidv4(),
selectedProfileId: "local",
curCheckpointIndex: 0,

View file

@ -0,0 +1,15 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { abortStream, setInactive } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
export const cancelStream = createAsyncThunk<void, undefined, ThunkApiType>(
"chat/cancelStream",
async (messages, { dispatch, extra, getState }) => {
dispatch(setInactive());
dispatch(abortStream());
// If the assistant message is empty, then remove it and the user message, placing the user input in the main text box
// TODO: Waiting until next release
// dispatch(clearLastEmptyResponse());
},
);