Merge branch 'main' of https://github.com/continuedev/continue into dallin/core-tests-1

This commit is contained in:
Dallin Romney 2024-12-07 19:20:54 -08:00
commit cff4167300
57 changed files with 2379 additions and 223 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

@ -88,6 +88,15 @@ jobs:
npx tsc --noEmit
npm run lint
- name: Install Xvfb for Linux and run e2e tests
run: |
sudo apt-get install -y xvfb # Install Xvfb
Xvfb :99 & # Start Xvfb
export DISPLAY=:99 # Export the display number to the environment
cd extensions/vscode
npm run package
npm run e2e:ci
- name: core checks
run: |
cd core

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

@ -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

@ -0,0 +1,99 @@
import {
BedrockRuntimeClient,
InvokeModelCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import { Chunk, Reranker, RerankerName } from "../../index.js";
export class BedrockReranker implements Reranker {
name: RerankerName = "bedrock";
static defaultOptions = {
region: "us-east-1",
model: "amazon.rerank-v1:0",
profile: "bedrock",
};
private supportedModels = ["amazon.rerank-v1:0", "cohere.rerank-v3-5:0"];
constructor(
private readonly params: {
region?: string;
model?: string;
profile?: string;
} = {},
) {
if (params.model && !this.supportedModels.includes(params.model)) {
throw new Error(
`Unsupported model: ${params.model}. Supported models are: ${this.supportedModels.join(", ")}`,
);
}
}
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
if (!query || !chunks.length) {
throw new Error("Query and chunks must not be empty");
}
try {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.params.region ?? BedrockReranker.defaultOptions.region,
credentials,
});
const model = this.params.model ?? BedrockReranker.defaultOptions.model;
// Base payload for both models
const payload: any = {
query: query,
documents: chunks.map((chunk) => chunk.content),
top_n: chunks.length,
};
// Add api_version for Cohere model
if (model.startsWith("cohere.rerank")) {
payload.api_version = 2;
}
const input = {
body: JSON.stringify(payload),
modelId: model,
accept: "*/*",
contentType: "application/json",
};
const command = new InvokeModelCommand(input);
const response = await client.send(command);
if (!response.body) {
throw new Error("Empty response received from Bedrock");
}
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
// Sort results by index to maintain original order
return responseBody.results
.sort((a: any, b: any) => a.index - b.index)
.map((result: any) => result.relevance_score);
} catch (error) {
console.error("Error in BedrockReranker.rerank:", error);
throw error;
}
}
private async _getCredentials() {
try {
const credentials = await fromIni({
profile: this.params.profile ?? BedrockReranker.defaultOptions.profile,
ignoreCache: true,
})();
return credentials;
} catch (e) {
console.warn(
`AWS profile with name ${this.params.profile ?? BedrockReranker.defaultOptions.profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
}
}

View file

@ -1,5 +1,6 @@
import { RerankerName } from "../../index.js";
import { BedrockReranker } from "./bedrock.js";
import { CohereReranker } from "./cohere.js";
import { ContinueProxyReranker } from "./ContinueProxyReranker.js";
import { FreeTrialReranker } from "./freeTrial.js";
@ -9,9 +10,10 @@ import { VoyageReranker } from "./voyage.js";
export const AllRerankers: { [key in RerankerName]: any } = {
cohere: CohereReranker,
bedrock: BedrockReranker,
llm: LLMReranker,
voyage: VoyageReranker,
"free-trial": FreeTrialReranker,
"huggingface-tei": HuggingFaceTEIReranker,
"continue-proxy": ContinueProxyReranker,
};
};

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

@ -860,10 +860,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(

2
core/index.d.ts vendored
View file

@ -807,6 +807,7 @@ type ModelProvider =
| "nvidia"
| "vllm"
| "mock"
| "test"
| "cerebras"
| "askSage"
| "vertexai"
@ -1086,6 +1087,7 @@ export interface EmbeddingsProvider {
export type RerankerName =
| "cohere"
| "bedrock"
| "voyage"
| "llm"
| "free-trial"

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";
@ -475,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

@ -25,59 +25,75 @@ function breakdownArticleComponent(
max_chunk_size: number,
): Chunk[] {
const chunks: Chunk[] = [];
const lines = article.body.split("\n");
let startLine = 0;
let endLine = 0;
let content = "";
let index = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (content.length + line.length <= max_chunk_size) {
content += `${line}\n`;
endLine = i;
} else {
chunks.push({
content: content.trim(),
startLine: startLine,
endLine: endLine,
otherMetadata: {
title: cleanHeader(article.title),
},
index: index,
filepath: new URL(
`${subpath}#${cleanFragment(article.title)}`,
url,
).toString(),
digest: subpath,
});
content = `${line}\n`;
startLine = i;
endLine = i;
index += 1;
}
}
// Push the last chunk
if (content) {
const createChunk = (
chunkContent: string,
chunkStartLine: number,
chunkEndLine: number,
) => {
chunks.push({
content: content.trim(),
startLine: startLine,
endLine: endLine,
content: chunkContent.trim(),
startLine: chunkStartLine,
endLine: chunkEndLine,
otherMetadata: {
title: cleanHeader(article.title),
},
index: index,
index: index++,
filepath: new URL(
`${subpath}#${cleanFragment(article.title)}`,
url,
).toString(),
digest: subpath,
});
};
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Handle oversized lines by splitting them
if (line.length > max_chunk_size) {
// First push any accumulated content
if (content.trim().length > 0) {
createChunk(content, startLine, endLine);
content = "";
}
// Split the long line into chunks
let remainingLine = line;
let subLineStart = i;
while (remainingLine.length > 0) {
const chunk = remainingLine.slice(0, max_chunk_size);
createChunk(chunk, subLineStart, i);
remainingLine = remainingLine.slice(max_chunk_size);
}
startLine = i + 1;
continue;
}
// Normal line handling
if (content.length + line.length + 1 <= max_chunk_size) {
content += `${line}\n`;
endLine = i;
} else {
if (content.trim().length > 0) {
createChunk(content, startLine, endLine);
}
content = `${line}\n`;
startLine = i;
endLine = i;
}
}
// Push the last chunk
if (content.trim().length > 0) {
createChunk(content, startLine, endLine);
}
// Don't use small chunks. Probably they're a mistake. Definitely they'll confuse the embeddings model.
return chunks.filter((c) => c.content.trim().length > 20);
}

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

@ -46,9 +46,19 @@ We recommend configuring [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazo
## Reranking model
Bedrock currently does not offer any reranking models.
We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may also use `amazon.rerank-v1:0`.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
```json title="~/.continue/config.json"
{
"reranker": {
"name": "bedrock",
"params": {
"model": "cohere.rerank-v3-5:0",
"region": "us-west-2"
}
}
}
```
## Authentication

View file

@ -206,10 +206,11 @@ Configuration for the reranker model used in response ranking.
**Properties:**
- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei`
- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei`, `bedrock`
- `params`:
- `model`: Model name
- `apiKey`: Api key
- `region`: Region (for Bedrock only)
Example

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=0.0.82
pluginVersion=0.0.83
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension

View file

@ -51,6 +51,7 @@ import java.net.NetworkInterface
import java.nio.charset.Charset
import java.nio.file.Paths
import java.util.*
import kotlin.coroutines.resume
fun uuid(): String {
@ -106,7 +107,9 @@ class AsyncFileSaveListener(private val ideProtocolClient: IdeProtocolClient) :
for (event in events) {
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(
".continue\\config.json"
) || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json") || event.path.endsWith(".continuerc.json")
) || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json") || event.path.endsWith(
".continuerc.json"
)
) {
return object : AsyncFileListener.ChangeApplier {
override fun afterVfsChange() {
@ -662,18 +665,41 @@ class IdeProtocolClient(
var llm = getModelByRole(config, "applyCodeBlock")
if (llm == null) {
val models = (config as? Map<*, *>)?.get("models") as? List<Map<*, *>>
llm = models?.find { model -> model["title"] == curSelectedModelTitle } as Map<String, Any>
llm = try {
suspendCancellableCoroutine { continuation ->
continuePluginService.coreMessenger?.request(
"config/getSerializedProfileInfo",
null,
null
) { response ->
val models =
((response as Map<String, Any>)["config"] as Map<String, Any>)["models"] as List<Map<String, Any>>
val foundModel = models.find { it["title"] == curSelectedModelTitle }
if (llm == null) {
showToast("error", "Model '$curSelectedModelTitle' not found in config.")
if (foundModel == null) {
launch {
showToast(
"error",
"Model '$curSelectedModelTitle' not found in config."
)
}
continuation.resume(null)
} else {
continuation.resume(foundModel)
}
}
}
} catch (e: Exception) {
launch { showToast("error", "Failed to fetch model configuration") }
respond(null)
return@launch
}
}
val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: ""
val prompt =
"The following code was suggested as an edit:\n```\n${text}\n```\nPlease apply it to the previous code."

View file

@ -271,12 +271,6 @@ class ContinueExtensionConfigurable : Configurable {
* it's a simple integer without dot notation, making it easier to compare.
*/
private fun shouldRenderOffScreen(): Boolean {
// With the 0.0.77 release, non-Mac users have been reporting issues with paste functionality
// in the browser. Disabling OSR for all non-Mac users for now.
if (!SystemInfo.isMac) {
return false
}
val minBuildNumber = 233
val applicationInfo = ApplicationInfo.getInstance()
val currentBuildNumber = applicationInfo.build.baselineVersion

View file

@ -16,4 +16,11 @@ gui/**
.devcontainer
.github
continue_rc_schema.json
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

@ -2642,6 +2642,7 @@
"properties": {
"name": {
"enum": [
"bedrock",
"cohere",
"voyage",
"llm",
@ -2743,6 +2744,32 @@
}
}
},
{
"if": {
"properties": {
"name": {
"enum": ["bedrock"]
}
},
"required": ["name"]
},
"then": {
"properties": {
"params": {
"type": "object",
"properties": {
"model": {
"enum": [
"cohere.rerank-v3-5:0",
"amazon.rerank-v1:0"
]
}
},
"required": ["model"]
}
}
}
},
{
"if": {
"properties": {

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,18 @@
#!/bin/bash
# echo pwd
echo "Current directory: $(pwd)"
# Find the latest VSIX file in the build directory
latest_vsix=$(ls -t ./build/continue-*.vsix | head -n1)
if [ -z "$latest_vsix" ]; then
echo "No VSIX file found in build directory"
exit 1
fi
# Create e2e/vsix directory if it doesn't exist
mkdir -p "./e2e/vsix"
# Copy the file to e2e directory with fixed name
cp "$latest_vsix" "./e2e/vsix/continue.vsix"

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

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.files.downloads.read-write</key>
<true/>
<key>com.apple.security.files.documents.read-write</key>
<true/>
<key>com.apple.security.automation.apple-events</key>
<true/>
</dict>
</plist>

File diff suppressed because it is too large Load diff

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.242",
"version": "0.9.241",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -617,12 +617,25 @@
"package:pre-release": "node scripts/package.js --pre-release",
"build:rust": "cargo-cp-artifact -ac sync sync.node -- cargo build --manifest-path ../../sync/Cargo.toml --message-format=json-render-diagnostics",
"build-debug:rust": "npm run build:rust --",
"build-release:rust": "npm run build:rust -- --release"
"build-release:rust": "npm run build:rust -- --release",
"e2e:compile": "tsc -p ./tsconfig.e2e.json",
"e2e:create-storage": "mkdir -p ./e2e/storage",
"e2e:get-chromedriver": "extest get-chromedriver --storage ./e2e/storage",
"e2e:get-vscode": "extest get-vscode --storage ./e2e/storage",
"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/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",
"@nestjs/common": "^8.4.7",
"@openapitools/openapi-generator-cli": "^2.5.2",
"@types/chai": "^5.0.1",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/follow-redirects": "^1.14.4",
@ -636,6 +649,7 @@
"@typescript-eslint/eslint-plugin": "^5.45.0",
"@vscode/vsce": "^2.22.0",
"cargo-cp-artifact": "^0.1",
"chai": "^4.5.0",
"esbuild": "0.17.19",
"eslint": "^8.28.0",
"glob": "^8.0.3",
@ -645,7 +659,8 @@
"rimraf": "^5.0.5",
"typescript": "^5.3.3",
"vite": "^4.3.9",
"vsce": "^2.15.0"
"vsce": "^2.15.0",
"vscode-extension-tester": "^8.10.0"
},
"dependencies": {
"@electron/rebuild": "^3.2.10",

View file

@ -0,0 +1,8 @@
{
"typescript.updateImportsOnFileMove.enabled": "always",
"workbench.editor.enablePreview": true,
"git.autoRepositoryDetection": false,
"terminal.integrated.sendKeybindingsToShell": true,
"workbench.remoteIndicator.showExtensionRecommendations": false,
"extensions.ignoreRecommendations": true
}

View file

@ -101,6 +101,10 @@ export class ContinueCompletionProvider
return null;
}
if (document.uri.scheme === "vscode-scm") {
return null;
}
// If the text at the range isn't a prefix of the intellisense text,
// no completion will be displayed, regardless of what we return
if (

View file

@ -408,7 +408,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
return await Promise.race([
codeExchangePromise.promise,
new Promise<string>((_, reject) =>
setTimeout(() => reject("Cancelled"), 60000),
setTimeout(() => reject("Cancelled"), 15 * 60 * 1_000),
),
promiseFromEvent<any, any>(
token.onCancellationRequested,

View file

@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "CommonJS",
"target": "ES2022",
"outDir": "e2e/_output",
"sourceMap": true,
"strict": true,
"rootDir": "e2e",
"resolveJsonModule": true,
"skipLibCheck": true
},
"exclude": [
"node_modules",
".vscode-test",
"e2e/resources/**",
".test-extensions"
],
"include": ["e2e"]
}

2
gui/package-lock.json generated
View file

@ -121,7 +121,7 @@
"comment-json": "^4.2.3",
"dbinfoz": "^0.14.0",
"diff": "^7.0.0",
"dotenv": "^16.4.7",
"dotenv": "^16.4.5",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
"google-auth-library": "^9.14.2",

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

@ -1,8 +1,9 @@
import { Editor } from "@tiptap/react";
import { KeyboardEvent } from "react";
import { isWebEnvironment } from "../../util";
import { getPlatform, isWebEnvironment } from "../../util";
const isWebEnv = isWebEnvironment();
const platform = getPlatform();
/**
* This handles various keypress issues when OSR is enabled
@ -56,15 +57,48 @@ export const handleVSCMetaKeyIssues = async (
}
};
const deleteSingleWord = (editor: Editor) => {
const textContent =
editor.state.doc.resolve(editor.state.selection.from).parent.textContent ??
"";
const cursorPosition = editor.state.selection.from;
const nodeStartPosition = editor.state.doc.resolve(cursorPosition).start();
const textBeforeCursor = textContent.slice(
0,
cursorPosition - nodeStartPosition,
);
// Match the last word including any trailing whitespace
const lastWordMatch = textBeforeCursor.match(/\S+\s*$/);
if (lastWordMatch) {
const lastWordWithSpace = lastWordMatch[0];
editor.commands.deleteRange({
from: editor.state.selection.from - lastWordWithSpace.length,
to: editor.state.selection.from,
});
}
};
export const handleJetBrainsMetaBackspace = (editor: Editor) => {
const { doc } = editor.state;
for (let i = doc.content.childCount - 1; i >= 0; i--) {
const node = doc.content.child(i);
if (node.type.name !== "codeBlock") {
editor.commands.deleteNode(node.type.name);
if (node.type.name === "codeBlock") {
continue;
}
// For Linux/Windows, only delete the word to the left of the cursor
if (platform !== "mac") {
deleteSingleWord(editor);
break;
}
editor.commands.deleteNode(node.type.name);
}
// Add an empty string so the user can keep typing

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

@ -37,14 +37,14 @@ export interface IIdeMessenger {
messageType: T,
data: FromWebviewProtocol[T][0],
cancelToken?: AbortSignal,
): FromWebviewProtocol[T][1];
): AsyncGenerator<unknown[]>;
llmStreamChat(
modelTitle: string,
cancelToken: AbortSignal | undefined,
messages: ChatMessage[],
options?: LLMFullCompletionOptions,
): AsyncGenerator<ChatMessage, PromptLog, unknown>;
): AsyncGenerator<ChatMessage[], PromptLog, unknown>;
ide: IDE;
}
@ -147,11 +147,20 @@ export class IdeMessenger implements IIdeMessenger {
});
}
/**
* Because of weird type stuff, we're actually yielding an array of the things
* that are streamed. For example, if the return type here says
* AsyncGenerator<ChatMessage>, then it's actually AsyncGenerator<ChatMessage[]>.
* This needs to be handled by the caller.
*
* Using unknown for now to make this more explicit
*/
async *streamRequest<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],
cancelToken?: AbortSignal,
): FromWebviewProtocol[T][1] {
): AsyncGenerator<unknown[]> {
// ): FromWebviewProtocol[T][1] {
const messageId = uuidv4();
this.post(messageType, data, messageId);
@ -181,17 +190,16 @@ export class IdeMessenger implements IIdeMessenger {
while (!done) {
if (buffer.length > index) {
const chunk = buffer[index];
index++;
yield chunk;
const chunks = buffer.slice(index);
index = buffer.length;
yield chunks;
}
await new Promise((resolve) => setTimeout(resolve, 50));
}
while (buffer.length > index) {
const chunk = buffer[index];
index++;
yield chunk;
if (buffer.length > index) {
const chunks = buffer.slice(index);
yield chunks;
}
return returnVal;
@ -202,7 +210,7 @@ export class IdeMessenger implements IIdeMessenger {
cancelToken: AbortSignal | undefined,
messages: ChatMessage[],
options: LLMFullCompletionOptions = {},
): AsyncGenerator<ChatMessage, PromptLog> {
): AsyncGenerator<ChatMessage[], PromptLog> {
const gen = this.streamRequest(
"llm/streamChat",
{

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

@ -7,6 +7,7 @@ import {
import { Editor, JSONContent } from "@tiptap/react";
import { InputModifiers, RangeInFileWithContents, ToolCallState } from "core";
import { streamResponse } from "core/llm/stream";
import { stripImages } from "core/util/messageContent";
import { usePostHog } from "posthog-js/react";
import { useCallback, useContext, useEffect, useRef, useState } from "react";
import { ErrorBoundary } from "react-error-boundary";
@ -19,22 +20,30 @@ import {
vscBackground,
} from "../../components";
import { ChatScrollAnchor } from "../../components/ChatScrollAnchor";
import CodeToEditCard from "../../components/CodeToEditCard";
import FeedbackDialog from "../../components/dialogs/FeedbackDialog";
import { useFindWidget } from "../../components/find/FindWidget";
import TimelineItem from "../../components/gui/TimelineItem";
import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks";
import ContinueInputBox from "../../components/mainInput/ContinueInputBox";
import { NewSessionButton } from "../../components/mainInput/NewSessionButton";
import resolveEditorContent from "../../components/mainInput/resolveInput";
import { TutorialCard } from "../../components/mainInput/TutorialCard";
import {
OnboardingCard,
useOnboardingCard,
} from "../../components/OnboardingCard";
import PageHeader from "../../components/PageHeader";
import StepContainer from "../../components/StepContainer";
import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import useHistory from "../../hooks/useHistory";
import { useTutorialCard } from "../../hooks/useTutorialCard";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall";
import { selectDefaultModel } from "../../redux/slices/configSlice";
import { submitEdit } from "../../redux/slices/editModeState";
import {
clearLastEmptyResponse,
newSession,
@ -42,6 +51,14 @@ import {
selectIsSingleRangeEditOrInsertion,
setInactive,
} from "../../redux/slices/sessionSlice";
import {
setDialogEntryOn,
setDialogMessage,
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 {
getFontSize,
@ -49,29 +66,12 @@ import {
isMetaEquivalentKeyPressed,
} from "../../util";
import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial";
import getMultifileEditPrompt from "../../util/getMultifileEditPrompt";
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
import ConfigErrorIndicator from "./ConfigError";
import { ToolCallDiv } from "./ToolCallDiv";
import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv";
import ToolOutput from "./ToolCallDiv/ToolOutput";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectDefaultModel } from "../../redux/slices/configSlice";
import {
setDialogMessage,
setDialogEntryOn,
setShowDialog,
} from "../../redux/slices/uiSlice";
import { RootState } from "../../redux/store";
import FeedbackDialog from "../../components/dialogs/FeedbackDialog";
import getMultifileEditPrompt from "../../util/getMultifileEditPrompt";
import { submitEdit } from "../../redux/slices/editModeState";
import { stripImages } from "core/util/messageContent";
import resolveEditorContent from "../../components/mainInput/resolveInput";
import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons";
import CodeToEditCard from "../../components/CodeToEditCard";
import { exitEditMode } from "../../redux/thunks/exitEditMode";
import PageHeader from "../../components/PageHeader";
import Spinner from "../../components/gui/Spinner";
const StopButton = styled.div`
background-color: ${vscBackground};
@ -204,7 +204,7 @@ export function Chat() {
isMetaEquivalentKeyPressed(e) &&
!e.shiftKey
) {
// dispatch(cancelGeneration()); TODO!!!
dispatch(cancelStream());
}
};
window.addEventListener("keydown", listener);
@ -342,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}`),
@ -496,19 +496,23 @@ export function Chat() {
}}
>
<div className="flex flex-row items-center justify-between pb-1 pl-0.5 pr-2">
{history.length === 0 && getLastSessionId() && !isInEditMode && (
<NewSessionButton
onClick={() =>
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),
)
}
className="xs:inline flex hidden items-center gap-2"
>
<ArrowLeftIcon className="h-3 w-3" />
Last Session
</NewSessionButton>
)}
<div className="xs:inline hidden">
{history.length === 0 && getLastSessionId() && !isInEditMode && (
<div className="xs:inline hidden">
<NewSessionButton
onClick={() =>
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),
)
}
className="flex items-center gap-2"
>
<ArrowLeftIcon className="h-3 w-3" />
Last Session
</NewSessionButton>
</div>
)}
</div>
<ConfigErrorIndicator />
</div>

View file

@ -10,21 +10,22 @@ import {
ApplyState,
ChatHistoryItem,
ChatMessage,
CodeToEdit,
ContextItem,
ContextItemWithId,
FileSymbolMap,
Session,
PromptLog,
CodeToEdit,
ToolCall,
ContextItem,
MessageModes,
PromptLog,
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";
import { RootState } from "../store";
import { streamResponseThunk } from "../thunks/streamResponse";
import { findCurrentToolCall } from "../util";
import { RootState } from "../store";
// We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
// The proper fix is adding a UUID to all chat messages, but this is the temp workaround.
@ -86,7 +87,7 @@ function getBaseHistoryItem(): ChatHistoryItemWithMessageId {
const initialState: SessionState = {
history: [],
isStreaming: false,
title: "New Session",
title: NEW_SESSION_TITLE,
id: uuidv4(),
selectedProfileId: "local",
curCheckpointIndex: 0,
@ -284,72 +285,74 @@ export const sessionSlice = createSlice({
state.streamAborter.abort();
state.streamAborter = new AbortController();
},
streamUpdate: (state, action: PayloadAction<ChatMessage>) => {
streamUpdate: (state, action: PayloadAction<ChatMessage[]>) => {
if (state.history.length) {
const lastMessage = state.history[state.history.length - 1];
for (const message of action.payload) {
const lastMessage = state.history[state.history.length - 1];
if (
action.payload.role &&
(lastMessage.message.role !== action.payload.role ||
// This is when a tool call comes after assistant text
(lastMessage.message.content !== "" &&
action.payload.role === "assistant" &&
action.payload.toolCalls?.length))
) {
const baseHistoryItem = getBaseHistoryItem();
// Create a new message
const historyItem: ChatHistoryItemWithMessageId = {
...baseHistoryItem,
message: { ...baseHistoryItem.message, ...action.payload },
};
if (action.payload.role === "assistant" && action.payload.toolCalls) {
const [_, parsedArgs] = incrementalParseJson(
action.payload.toolCalls[0].function.arguments,
);
historyItem.toolCallState = {
status: "generating",
toolCall: action.payload.toolCalls[0] as ToolCall,
toolCallId: action.payload.toolCalls[0].id,
parsedArgs,
};
}
state.history.push(historyItem);
} else {
// Add to the existing message
const msg = state.history[state.history.length - 1].message;
if (action.payload.content) {
msg.content += renderChatMessage(action.payload);
} else if (
action.payload.role === "assistant" &&
action.payload.toolCalls &&
msg.role === "assistant"
if (
message.role &&
(lastMessage.message.role !== message.role ||
// This is when a tool call comes after assistant text
(lastMessage.message.content !== "" &&
message.role === "assistant" &&
message.toolCalls?.length))
) {
if (!msg.toolCalls) {
msg.toolCalls = [];
const baseHistoryItem = getBaseHistoryItem();
// Create a new message
const historyItem: ChatHistoryItemWithMessageId = {
...baseHistoryItem,
message: { ...baseHistoryItem.message, ...message },
};
if (message.role === "assistant" && message.toolCalls) {
const [_, parsedArgs] = incrementalParseJson(
message.toolCalls[0].function.arguments,
);
historyItem.toolCallState = {
status: "generating",
toolCall: message.toolCalls[0] as ToolCall,
toolCallId: message.toolCalls[0].id,
parsedArgs,
};
}
action.payload.toolCalls.forEach((toolCall, i) => {
if (msg.toolCalls.length <= i) {
msg.toolCalls.push(toolCall);
} else {
msg.toolCalls[i].function.arguments +=
toolCall.function.arguments;
const [_, parsedArgs] = incrementalParseJson(
msg.toolCalls[i].function.arguments,
);
state.history[
state.history.length - 1
].toolCallState.parsedArgs = parsedArgs;
state.history[
state.history.length - 1
].toolCallState.toolCall.function.arguments +=
toolCall.function.arguments;
state.history.push(historyItem);
} else {
// Add to the existing message
const msg = state.history[state.history.length - 1].message;
if (message.content) {
msg.content += renderChatMessage(message);
} else if (
message.role === "assistant" &&
message.toolCalls &&
msg.role === "assistant"
) {
if (!msg.toolCalls) {
msg.toolCalls = [];
}
});
message.toolCalls.forEach((toolCall, i) => {
if (msg.toolCalls.length <= i) {
msg.toolCalls.push(toolCall);
} else {
msg.toolCalls[i].function.arguments +=
toolCall.function.arguments;
const [_, parsedArgs] = incrementalParseJson(
msg.toolCalls[i].function.arguments,
);
state.history[
state.history.length - 1
].toolCallState.parsedArgs = parsedArgs;
state.history[
state.history.length - 1
].toolCallState.toolCall.function.arguments +=
toolCall.function.arguments;
}
});
}
}
}
}

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());
},
);

View file

@ -1,6 +1,7 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { ChatMessage, PromptLog } from "core";
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
import { selectDefaultModel } from "../slices/configSlice";
import {
abortStream,
addPromptCompletionPair,
@ -10,7 +11,6 @@ import {
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { callTool } from "./callTool";
import { selectDefaultModel } from "../slices/configSlice";
export const streamNormalInput = createAsyncThunk<
void,
@ -56,14 +56,9 @@ export const streamNormalInput = createAsyncThunk<
break;
}
const update = next.value as ChatMessage;
dispatch(streamUpdate(update));
const updates = next.value as ChatMessage[];
dispatch(streamUpdate(updates));
next = await gen.next();
// There has been lag when streaming tool calls. This is a temporary solution
if (update.role === "assistant" && update.toolCalls) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
// Attach prompt log

View file

@ -2,6 +2,7 @@ import { createAsyncThunk } from "@reduxjs/toolkit";
import { ChatMessage, ContextItem } from "core";
import { constructMessages } from "core/llm/constructMessages";
import { renderContextItems } from "core/util/messageContent";
import { selectDefaultModel } from "../slices/configSlice";
import {
addContextItemsAtIndex,
setActive,
@ -11,7 +12,6 @@ import { ThunkApiType } from "../store";
import { handleErrors } from "./handleErrors";
import { resetStateForNewMessage } from "./resetStateForNewMessage";
import { streamNormalInput } from "./streamNormalInput";
import { selectDefaultModel } from "../slices/configSlice";
export const streamResponseAfterToolCall = createAsyncThunk<
void,
@ -39,7 +39,7 @@ export const streamResponseAfterToolCall = createAsyncThunk<
toolCallId,
};
dispatch(streamUpdate(newMessage));
dispatch(streamUpdate([newMessage]));
dispatch(
addContextItemsAtIndex({
index: initialHistory.length,

View file

@ -5,9 +5,9 @@ import {
RangeInFile,
SlashCommandDescription,
} from "core";
import { ThunkApiType } from "../store";
import { abortStream, streamUpdate } from "../slices/sessionSlice";
import { selectDefaultModel } from "../slices/configSlice";
import { abortStream, streamUpdate } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
export const streamSlashCommand = createAsyncThunk<
void,
@ -62,8 +62,17 @@ export const streamSlashCommand = createAsyncThunk<
dispatch(abortStream());
break;
}
if (typeof update === "string") {
dispatch(streamUpdate(update));
for (const item of update) {
if (typeof item === "string") {
dispatch(
streamUpdate([
{
role: "assistant",
content: item,
},
]),
);
}
}
}
clearInterval(checkActiveInterval);