Merge branch 'main' into dallin/github-docs

This commit is contained in:
Nate 2025-01-19 21:02:32 -08:00
commit 33870be388
47 changed files with 976 additions and 538 deletions

View file

@ -5,6 +5,7 @@ on:
branches:
- main
paths:
- "extensions/intellij/**"
- "extensions/vscode/**"
- "core/**"
- "gui/**"
@ -96,7 +97,7 @@ jobs:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
install-gui:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -157,7 +158,7 @@ jobs:
npx tsc --noEmit
binary-checks:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -193,7 +194,7 @@ jobs:
npx tsc --noEmit
install-vscode:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -282,7 +283,7 @@ jobs:
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
needs: [install-root, install-vscode]
needs: [ install-root, install-vscode ]
outputs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
@ -311,7 +312,7 @@ jobs:
vscode-package-extension:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
needs: [ install-vscode, install-core ]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@ -343,7 +344,7 @@ jobs:
vscode-download-e2e-dependencies:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
needs: [ install-vscode, install-core ]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@ -389,7 +390,7 @@ jobs:
fail-fast: false
matrix:
test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }}
command: ["e2e:ci:run", "e2e:ci:run-yaml"]
command: [ "e2e:ci:run", "e2e:ci:run-yaml" ]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@ -439,7 +440,6 @@ jobs:
run: |
cd extensions/vscode
TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
env:
DISPLAY: :99
@ -451,7 +451,7 @@ jobs:
path: extensions/vscode/e2e/storage/screenshots
gui-tests:
needs: [install-gui, install-core]
needs: [ install-gui, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -482,7 +482,7 @@ jobs:
npm test
jetbrains-tests:
needs: [install-root, core-checks]
needs: [ install-root, core-checks ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -552,7 +552,7 @@ jobs:
with:
url: http://127.0.0.1:8082
max-attempts: 15
retry-delay: 5s
retry-delay: 30s
- name: Run tests
run: |
@ -578,4 +578,4 @@ jobs:
with:
name: jb-failure-report
path: |
${{ github.workspace }}/extensions/intellij/build/reports
${{ github.workspace }}/extensions/intellij/build/reports

View file

@ -42,5 +42,6 @@
"extensions/.continue-debug": true
// "sync/**": true
},
"eslint.workingDirectories": ["./core"]
"eslint.workingDirectories": ["./core"],
"typescript.tsdk": "node_modules/typescript/lib"
}

View file

@ -118,6 +118,22 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
}
(async () => {
// Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
// This is only needed for our `pkg` command at build time
fs.writeFileSync(
"out/package.json",
JSON.stringify(
{
name: "binary",
version: "1.0.0",
author: "Continue Dev, Inc",
license: "Apache-2.0",
},
undefined,
2,
),
);
console.log("[info] Downloading prebuilt lancedb...");
for (const target of targets) {
if (targetToLanceDb[target]) {
@ -263,9 +279,12 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
// Informs the `continue-binary` of where to look for node_sqlite3.node
// https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
fs.writeFileSync(`${targetDir}/package.json`, "");
// fs.writeFileSync(`${targetDir}/package.json`, "");
}
// Cleanup - this is needed when running locally
fs.rmSync("out/package.json");
const pathsToVerify = [];
for (const target of targets) {
const exe = target.startsWith("win") ? ".exe" : "";

View file

@ -1,158 +0,0 @@
# Tab Autocomplete (beta)
Continue now provides support for tab autocomplete in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains IDEs](https://plugins.jetbrains.com/plugin/22707-continue/edit). We will be greatly improving the experience over the next few releases, and it is always helpful to hear feedback. If you have any problems or suggestions, please let us know in our [Discord](https://discord.gg/vapESyrFmJ).
## Setting up with Ollama (default)
We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model:
```bash
ollama run qwen2.5-coder:1.5b-base
```
Once it has been downloaded, you should begin to see completions in VS Code.
## Setting up with LM Studio
You can also set up tab-autocomplete with a local LM Studio instance by following these steps:
1. Download the latest version of LM Studio from [here](https://lmstudio.ai/)
2. Download a model (e.g. search for `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF` and choose one of the options there)
3. Go to the server section (button is on the left), select your model from the dropdown at the top, and click "Start Server"
4. Go to the "My Models" section (button is on the left), find your selected model, and copy the name the path (example: `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`); this will be used as the "model" attribute in Continue
5. Go to Continue and modify the configurations for a [custom model](#setting-up-a-custom-model)
6. Set the "provider" to `lmstudio` and the "model" to the path copied earlier
Example:
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5b",
"model": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF",
"provider": "lmstudio"
}
}
```
## Setting up a custom model
All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote vLLM instance you would edit your `config.json` like this (note that it is not inside the models array), filling in the correct model name and vLLM endpoint:
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "openai",
"model": "<MODEL_NAME>",
"apiBase": "<VLLM_ENDPOINT_URL>"
},
...
}
```
As another example, say you want to use a different model, `deepseek-coder:6.7b-base`, with Ollama:
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "deepseek-coder:6.7b-base"
},
...
}
```
If you aren't yet familiar with the available options, you can learn more in our [overview](../setup/overview.md).
### What model should I use?
If you are running the model locally, we recommend `qwen2.5-coder:1.5b`.
If you have a bit more compute, or are running a model in the cloud, you can upgrade to `qwen2.5-coder:7b`.
Regardless of what you are willing to spend, we do not recommend using GPT or Claude for autocomplete. Learn why [below](#i-want-better-completions-should-i-use-gpt-4).
## Configuration Options
The following can be configured in `config.json`:
### `tabAutocompleteModel`
This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `qwen2.5-coder:1.5b`, or `starcoder-3b`.
### `tabAutocompleteOptions`
This object allows you to customize the behavior of tab-autocomplete. The available options are:
- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean)
- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number)
- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number)
- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number)
- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number)
- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String)
- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto".
### Full example
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
},
"tabAutocompleteOptions": {
"maxPromptTokens": 400,
"prefixPercentage": 0.5
}
}
```
## Troubleshooting
### I want better completions, should I use GPT-4?
Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance.
### I'm not seeing any completions
Follow these steps to ensure that everything is set up correctly:
1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar).
2. Make sure you have downloaded Ollama.
3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded.
4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere.
5. If you are using another Ollama model for chat and your resources are limited, this will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. A resolution for this could be using the same model for chat and autocomplete.
6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains).
7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible.
### Completions are slow
Depending on your hardware, you may want to try a smaller, faster model. If 3b isn't working for you we recommend trying `deepseek-coder:1.3b-base`.
### Completions don't know about my code
We are working on this! Right now Continue uses the Language Server Protocol to add definitions to the prompt, as well as using similarity search over recently edited files. We will be improving the accuracy of this system greatly over the next few weeks.
### Completions contain formatting errors
If you're seeing a common pattern of mistake that might be helpful to report, please share in Discord. We will do our best to fix it as soon as possible.
## How to turn off autocomplete
### VS Code
Click the "Continue" button in the status panel at the bottom right of the screen. The checkmark will become a "cancel" symbol and you will no longer see completions. You can click again to turn it back on.
Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete".
### JetBrains
Open Settings -> Tools -> Continue and uncheck the box for "Enable Tab Autocomplete".
### Feedback
If you're turning off autocomplete, we'd love to hear how we can improve! Please let us know in our [Discord](https://discord.gg/vapESyrFmJ) or file an issue on GitHub.

View file

@ -37,16 +37,21 @@ export function slashFromCustomCommand(
if (
Array.isArray(content) &&
content.some((part) =>
part.text?.startsWith(`/${customCommand.name}`),
content.some(
(part) =>
"text" in part && part.text?.startsWith(`/${customCommand.name}`),
)
) {
messages[i] = {
...message,
content: content.map((part) => {
return part.text?.startsWith(`/${customCommand.name}`)
? { ...part, text: promptUserInput }
: part;
if (
"text" in part &&
part.text.startsWith(`/${customCommand.name}`)
) {
return { type: "text", text: promptUserInput };
}
return part;
}),
};
break;

View file

@ -15,7 +15,6 @@ import { GlobalContext } from "../util/GlobalContext.js";
import { getConfigJsonPath } from "../util/paths.js";
import { ConfigResult } from "@continuedev/config-yaml";
import { pathToFileURL } from "url";
import { controlPlaneEnv } from "../control-plane/env.js";
import { usePlatform } from "../control-plane/flags.js";
import {
@ -29,6 +28,7 @@ import {
ProfileDescription,
ProfileLifecycleManager,
} from "./ProfileLifecycleManager.js";
import { localPathToUri } from "../util/pathToUri.js";
export type { ProfileDescription };
@ -95,7 +95,7 @@ export class ConfigHandler {
async openConfigProfile(profileId?: string) {
let openProfileId = profileId || this.selectedProfileId;
if (openProfileId === "local") {
await this.ide.openFile(pathToFileURL(getConfigJsonPath()).toString());
await this.ide.openFile(localPathToUri(getConfigJsonPath()));
} else {
await this.ide.openUrl(`${controlPlaneEnv.APP_URL}${openProfileId}`);
}

View file

@ -73,6 +73,7 @@ import {
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
// import { isSupportedLanceDbCpuTarget } from "./util";
import { validateConfig } from "./validation.js";
import { localPathToUri } from "../util/pathToUri";
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
let content = fs.readFileSync(filepath, "utf8");
@ -813,7 +814,7 @@ async function loadFullConfigNode(
"Could not load config.ts as absolute path, retrying as file url ...",
);
try {
module = await import(`file://${configJsPath}`);
module = await import(localPathToUri(configJsPath));
} catch (e) {
throw new Error("Could not load config.ts as file url either", {
cause: e,

View file

@ -43,7 +43,15 @@ import { Telemetry } from "./util/posthog";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
import { type ContextItemId, type IDE, type IndexingProgressUpdate } from ".";
import {
ChatMessage,
DiffLine,
PromptLog,
type ContextItemId,
type IDE,
type IndexingProgressUpdate,
} from ".";
import { usePlatform } from "./control-plane/flags";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
@ -396,7 +404,7 @@ export class Core {
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
) {
): AsyncGenerator<ChatMessage, PromptLog> {
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
@ -432,7 +440,7 @@ export class Core {
const chunk = next.value;
yield { content: chunk };
yield chunk;
next = await gen.next();
}
@ -449,7 +457,11 @@ export class Core {
true,
);
return { done: true, content: next.value };
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
}
on("llm/streamChat", (msg) =>
@ -459,9 +471,8 @@ export class Core {
async function* llmStreamComplete(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamComplete"][0]>,
) {
): AsyncGenerator<string, PromptLog> {
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamComplete(
msg.data.prompt,
@ -483,11 +494,13 @@ export class Core {
});
break;
}
yield { content: next.value };
yield next.value;
next = await gen.next();
}
return { done: true, content: next.value };
if (!next.done) {
throw new Error("This will never happen");
}
return next.value;
}
on("llm/streamComplete", (msg) =>
@ -549,7 +562,7 @@ export class Core {
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["command/run"][0]>,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
) {
): AsyncGenerator<string> {
const {
input,
history,
@ -614,7 +627,7 @@ export class Core {
break;
}
if (content) {
yield { content };
yield content;
}
}
} catch (e) {
@ -622,7 +635,6 @@ export class Core {
} finally {
clearInterval(checkActiveInterval);
}
yield { done: true, content: "" };
}
on("command/run", (msg) =>
runNodeJsSlashCommand(
@ -653,7 +665,7 @@ export class Core {
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
) {
): AsyncGenerator<DiffLine> {
const data = msg.data;
const llm = await configHandler.llmFromTitle(msg.data.modelTitle);
for await (const diffLine of streamDiffLines(
@ -668,10 +680,8 @@ export class Core {
abortedMessageIds.delete(msg.messageId);
break;
}
yield { content: diffLine };
yield diffLine;
}
return { done: true };
}
on("streamDiffLines", (msg) =>

16
core/index.d.ts vendored
View file

@ -300,11 +300,17 @@ export interface CompletionOptions extends BaseCompletionOptions {
export type ChatMessageRole = "user" | "assistant" | "system" | "tool";
export interface MessagePart {
type: "text" | "imageUrl";
text?: string;
imageUrl?: { url: string };
}
export type TextMessagePart = {
type: "text";
text: string;
};
export type ImageMessagePart = {
type: "imageUrl";
imageUrl: { url: string };
};
export type MessagePart = TextMessagePart | ImageMessagePart;
export type MessageContent = string | MessagePart[];

View file

@ -14,12 +14,12 @@ import {
} from "../test/testDir.js";
import { getIndexSqlitePath } from "../util/paths.js";
import { pathToFileURL } from "node:url";
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
import { CodebaseIndex } from "./types.js";
import { walkDir } from "./walkDir.js";
import { localPathToUri } from "../util/pathToUri.js";
jest.useFakeTimers();
@ -159,7 +159,7 @@ describe("CodebaseIndexer", () => {
test("should have created index folder with all necessary files", async () => {
const exists = await testIde.fileExists(
pathToFileURL(getIndexSqlitePath()).toString(),
localPathToUri(getIndexSqlitePath()),
);
expect(exists).toBe(true);
});

View file

@ -106,9 +106,12 @@ function countTokens(
const encoding = encodingForModel(modelName);
if (Array.isArray(content)) {
return content.reduce((acc, part) => {
return acc + part.type === "imageUrl"
? countImageTokens(part)
: encoding.encode(part.text ?? "", "all", []).length;
return (
acc +
(part.type === "text"
? encoding.encode(part.text ?? "", "all", []).length
: countImageTokens(part))
);
}, 0);
} else {
return encoding.encode(content ?? "", "all", []).length;
@ -335,7 +338,7 @@ function messageIsEmpty(message: ChatMessage): boolean {
}
if (Array.isArray(message.content)) {
return message.content.every(
(item) => !item.imageUrl && item.text?.trim() === "",
(item) => item.type === "text" && item.text?.trim() === "",
);
}
return false;

View file

@ -1,4 +1,9 @@
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
TextMessagePart,
} from "../../index.js";
import { BaseLLM } from "../index.js";
class Asksage extends BaseLLM {
@ -14,8 +19,8 @@ class Asksage extends BaseLLM {
"gpt4-gov": "gpt4-gov", // Works
"gpt-gov": "gpt-gov", // Works
"gpt-4o": "gpt-4o", // Works
"gpt-4o-mini": "gpt-4o-mini", // Works
"gpt4": "gpt4", // Works
"gpt-4o-mini": "gpt-4o-mini", // Works
gpt4: "gpt4", // Works
"gpt4-32k": "gpt4-32k",
"gpt-o1": "gpt-o1", // Works
"gpt-o1-mini": "gpt-o1-mini", // Works
@ -25,7 +30,7 @@ class Asksage extends BaseLLM {
"claude-3-opus-20240229": "claude-3-opus", // Works
"claude-3-sonnet-20240229": "claude-3-sonnet", // Works
"grok-beta": "xai-grok",
"groq-llama33": "groq-llama33",
"groq-llama33": "groq-llama33",
"groq-70b": "groq-70b",
"mistral-large-latest": "mistral-large", // Works
"llama3-70b": "llma3", // Works
@ -50,7 +55,10 @@ class Asksage extends BaseLLM {
message:
typeof message.content === "string"
? message.content
: message.content.map((part) => part.text).join(""),
: message.content
.filter((part) => part.type === "text")
.map((part) => (part as TextMessagePart).text)
.join(""),
};
}

View file

@ -113,10 +113,18 @@ class FreeTrial extends BaseLLM {
}
const parts = message.content.map((part) => {
if (part.type === "imageUrl") {
return {
type: "image_url",
image_url: {
url: part.imageUrl.url,
detail: "low",
},
};
}
return {
type: part.type,
type: "text",
text: part.text,
image_url: { ...part.imageUrl, detail: "low" },
};
});
return {

View file

@ -1,12 +1,23 @@
import { r } from "tar";
import {
AssistantChatMessage,
ChatMessage,
CompletionOptions,
LLMOptions,
MessagePart,
ToolCallDelta,
} from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
import {
GeminiChatContentPart,
GeminiChatRequestBody,
GeminiChatResponse,
GeminiGenerationConfig,
GeminiToolFunctionDeclaration,
} from "./gemini-types.js";
import { findLast } from "../../util/findLast.js";
class Gemini extends BaseLLM {
static providerName = "gemini";
@ -19,7 +30,7 @@ class Gemini extends BaseLLM {
};
// Function to convert completion options to Gemini format
public convertArgs(options: CompletionOptions) {
public convertArgs(options: CompletionOptions): GeminiGenerationConfig {
// should be public for use within VertexAI
const finalOptions: any = {}; // Initialize an empty object
@ -42,7 +53,7 @@ class Gemini extends BaseLLM {
.slice(0, this.maxStopWords ?? Gemini.defaultOptions.maxStopWords);
}
return { generationConfig: finalOptions }; // Wrap options under 'generationConfig'
return finalOptions;
}
protected async *_streamComplete(
@ -59,7 +70,7 @@ class Gemini extends BaseLLM {
}
}
public removeSystemMessage(messages: ChatMessage[]) {
public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] {
// should be public for use within VertexAI
const msgs = [...messages];
@ -92,8 +103,8 @@ class Gemini extends BaseLLM {
? this.removeSystemMessage(messages)
: messages;
if (options.model.includes("gemini")) {
for await (const message of this.streamChatGemini(
if (options.model.includes("bison")) {
for await (const message of this.streamChatBison(
convertedMsgs,
signal,
options,
@ -101,7 +112,7 @@ class Gemini extends BaseLLM {
yield message;
}
} else {
for await (const message of this.streamChatBison(
for await (const message of this.streamChatGemini(
convertedMsgs,
signal,
options,
@ -111,7 +122,7 @@ class Gemini extends BaseLLM {
}
}
continuePartToGeminiPart(part: MessagePart) {
continuePartToGeminiPart(part: MessagePart): GeminiChatContentPart {
return part.type === "text"
? {
text: part.text,
@ -135,39 +146,129 @@ class Gemini extends BaseLLM {
);
// This feels hacky to repeat code from above function but was the quickest
// way to ensure system message re-formatting isn't done if user has specified v1
const apiBase =
this.apiBase ||
Gemini.defaultOptions?.apiBase ||
"https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase
const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase
const isV1API = apiBase.includes("/v1/");
const contents = messages
.map((msg) => {
if (msg.role === "system" && !isV1API) {
return null; // Don't include system message in contents
}
if (msg.role === "tool") {
return null;
}
return {
role: msg.role === "assistant" ? "model" : "user",
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this.continuePartToGeminiPart),
};
})
.filter((c) => c !== null);
// Convert chat messages to contents
const body: GeminiChatRequestBody = {
contents: messages
.filter((msg) => !(msg.role === "system" && isV1API))
.map((msg) => {
if (msg.role === "tool") {
let fn_name = "";
const lastToolCallMessage = findLast(
messages,
(msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name,
) as AssistantChatMessage;
if (lastToolCallMessage) {
fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!;
}
if (!fn_name) {
console.warn(
"Sending tool call response for unidentified tool call",
);
}
return {
role: "user",
parts: [
{
functionResponse: {
name: fn_name || "unknown",
response: {
output: msg.content, // "output" key is opinionated - not all functions will output objects
},
},
},
],
};
}
const assistantMsg = {
role:
msg.role === "assistant" ? ("model" as const) : ("user" as const),
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this.continuePartToGeminiPart),
};
if (msg.role === "assistant" && msg.toolCalls) {
msg.toolCalls.forEach((toolCall) => {
if (toolCall.function?.name && toolCall.function?.arguments) {
assistantMsg.parts.push({
functionCall: {
name: toolCall.function.name,
args: JSON.parse(toolCall.function.arguments),
},
});
}
});
}
const body = {
...this.convertArgs(options),
contents,
// if this.systemMessage is defined, reformat it for Gemini API
...(this.systemMessage &&
!isV1API && {
systemInstruction: { parts: [{ text: this.systemMessage }] },
return assistantMsg;
}),
};
if (options) {
body.generationConfig = this.convertArgs(options);
}
// https://ai.google.dev/gemini-api/docs/api-versions
if (!isV1API) {
if (this.systemMessage) {
body.systemInstruction = { parts: [{ text: this.systemMessage }] };
}
// Convert and add tools if present
if (options.tools?.length) {
// Choosing to map all tools to the functionDeclarations of one tool
// Rather than map each tool to its own tool + functionDeclaration
// Same difference
const functions: GeminiToolFunctionDeclaration[] = [];
options.tools.forEach((tool) => {
if (tool.function.description && tool.function.name) {
const fn: GeminiToolFunctionDeclaration = {
description: tool.function.description,
name: tool.function.name,
};
if (
tool.function.parameters &&
"type" in tool.function.parameters
// && typeof tool.function.parameters.type === "string"
) {
// const paramType = "TYPE_UNSPECIFIED"
// | "STRING"
// | "NUMBER"
// | "INTEGER"
// | "BOOLEAN"
// | "ARRAY"
// | "OBJECT"
if (tool.function.parameters.type === "object") {
// Gemini can't take an empty object
// So if empty object param is present just don't add parameters
if (
JSON.stringify(tool.function.parameters.properties) === "{}"
) {
functions.push(fn);
return;
}
}
fn.parameters = {
type: tool.function.parameters.type.toUpperCase(),
...tool.function.parameters,
};
}
functions.push(fn);
}
});
if (functions.length) {
body.tools = [
{
functionDeclarations: functions,
},
];
}
}
}
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
@ -192,24 +293,68 @@ class Gemini extends BaseLLM {
let foundIncomplete = false;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
let data;
let data: GeminiChatResponse;
try {
data = JSON.parse(part);
data = JSON.parse(part) as GeminiChatResponse;
} catch (e) {
foundIncomplete = true;
continue; // yo!
}
if (data.error) {
if ("error" in data) {
throw new Error(data.error.message);
}
// Check for existence of each level before accessing the final 'text' property
if (data?.candidates?.[0]?.content?.parts?.[0]?.text) {
// Incrementally stream the content to make it smoother
const content = data.candidates[0].content.parts[0].text;
yield {
role: "assistant",
content,
};
const content = data?.candidates?.[0]?.content;
if (content) {
const supportedParts: MessagePart[] = [];
const toolCalls: ToolCallDelta[] = [];
for (const part of content.parts) {
if ("text" in part) {
supportedParts.push({ type: "text", text: part.text });
} else if ("inlineData" in part) {
// TODO does this image url conversion actually work?
supportedParts.push({
type: "imageUrl",
imageUrl: {
url: `data:image/jpeg;base64,${part.inlineData.data}`,
},
});
} else if ("functionCall" in part) {
// Handle function call
toolCalls.push({
type: "function",
id: "", // Not supported by gemini
function: {
name: part.functionCall.name,
arguments:
typeof part.functionCall.args === "string"
? part.functionCall.args
: JSON.stringify(part.functionCall.args),
},
});
} else if ("functionResponse" in part) {
// TODO hypothetically order could be off here
// Where function response is in the middle of something
yield {
role: "tool",
content: part.functionResponse.response.output as string,
toolCallId: part.functionResponse.name,
};
} else {
console.warn("Unsupported gemini part type received", part);
}
}
if (supportedParts.length || toolCalls.length) {
// Incrementally stream the content to make it smoother
yield {
role: "assistant",
content: supportedParts.length ? supportedParts : "",
...(toolCalls.length ? { toolCalls } : {}),
};
}
} else {
// Handle the case where the expected data structure is not found
console.warn("Unexpected response format:", data);

View file

@ -1,4 +1,4 @@
import { JSONSchema7Object, JSONSchema7Type } from "json-schema";
import { JSONSchema7, JSONSchema7Object } from "json-schema";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
@ -12,7 +12,7 @@ type OllamaChatMessage = {
tool_calls?: {
function: {
name: string;
arguments: Record<string, JSONSchema7Type>;
arguments: JSONSchema7Object;
};
}[];
};
@ -119,7 +119,7 @@ interface OllamaTool {
function: {
name: string;
description?: string;
parameters?: JSONSchema7Object;
parameters?: JSONSchema7;
};
}
@ -273,10 +273,8 @@ class Ollama extends BaseLLM {
content: "",
};
if (typeof message.content === "string") {
ollamaMessage.content = message.content;
} else {
ollamaMessage.content = renderChatMessage(message);
ollamaMessage.content = renderChatMessage(message);
if (Array.isArray(message.content)) {
const images: string[] = [];
message.content.forEach((part) => {
if (part.type === "imageUrl" && part.imageUrl) {

View file

@ -124,7 +124,7 @@ class VertexAI extends BaseLLM {
}
for await (const value of streamSse(response)) {
if (value.type == "message_start") {
if (value.type === "message_start") {
console.log(value);
}
if (value.delta?.text) {
@ -389,11 +389,11 @@ class VertexAI extends BaseLLM {
const convertedMsgs = isV1API
? this.geminiInstance.removeSystemMessage(messages)
: messages;
if (this.vertexProvider == "gemini") {
if (this.vertexProvider === "gemini") {
yield* this.streamChatGemini(convertedMsgs, options);
} else if (this.vertexProvider == "mistral") {
} else if (this.vertexProvider === "mistral") {
yield* this.StreamChatMistral(messages, options);
} else if (this.vertexProvider == "anthropic") {
} else if (this.vertexProvider === "anthropic") {
yield* this.StreamChatAnthropic(messages, options);
} else {
if (options.model.includes("bison")) {

View file

@ -95,15 +95,16 @@ class WatsonX extends BaseLLM {
}
const parts = message.content.map((part) => {
const msg: any = {
type: part.type,
if (part.type === "imageUrl") {
return {
type: "image_url",
image_url: { ...part.imageUrl, detail: "low" },
};
}
return {
type: "text",
text: part.text,
};
if (part.type === "imageUrl") {
msg.image_url = { ...part.imageUrl, detail: "low" };
msg.type = "image_url";
}
return msg;
});
return {
...message,

View file

@ -0,0 +1,268 @@
import { JSONSchema7Object } from "json-schema";
// https://ai.google.dev/api/generate-content
export interface GeminiGenerationConfig {
stopSequences?: string[];
responseMimeType?: string;
candidateCount?: number;
maxOutputTokens?: number;
temperature?: number;
topP?: number;
topK?: number;
presencePenalty?: number;
frequencyPenalty?: number;
responseLogprobs?: boolean;
logprobs?: number;
// responseSchema?: object; // https://ai.google.dev/api/caching#Schema
}
export interface GeminiFunctionSchema {
type:
| "TYPE_UNSPECIFIED"
| "STRING"
| "NUMBER"
| "INTEGER"
| "BOOLEAN"
| "ARRAY"
| "OBJECT";
format?: string;
description?: string;
nullable?: boolean;
enum?: string[];
maxItems?: string;
minItems?: string;
properties?: Record<string, GeminiFunctionSchema>;
required?: string[];
items?: GeminiFunctionSchema;
}
export type GeminiChatContentPart =
| {
text: string;
}
| {
inlineData: {
mimeType: string;
data: string;
};
}
| {
functionCall: {
name: string;
args: JSONSchema7Object;
};
}
| {
functionResponse: {
name: string;
response: JSONSchema7Object;
};
}
| {
fileData: {
fileUri: string;
mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata
};
}
| {
executableCode: {
language: "PYTHON" | "LANGUAGE_UNSPECIFIED";
code: string;
};
}
| {
codeExecutionResult: {
outcome:
| "OUTCOME_UNSPECIFIED"
| "OUTCOME_OK"
| "OUTCOME_FAILED"
| "OUTCOME_DEADLINE_EXCEEDED";
output: string;
};
};
export interface GeminiChatContent {
role?: "user" | "model";
parts: GeminiChatContentPart[];
}
export interface GeminiToolFunctionDeclaration {
name: string;
description: string;
parameters?: GeminiFunctionSchema;
}
export interface GeminiTool {
functionDeclarations?: GeminiToolFunctionDeclaration[];
googleSearchRetrieval?: {
dynamicRetrievalConfig: {
mode?: "MODE_DYNAMIC" | "MODE_UNSPECIFIED";
dynamicThreshold?: number;
};
};
codeExecution?: {};
}
export interface GeminiToolConfig {
functionCallingConfig?: {
mode?: "NONE" | "ANY" | "AUTO";
allowedFunctionNames?: string[];
};
}
// https://ai.google.dev/api/generate-content#request-body
export interface GeminiChatRequestBody {
contents: GeminiChatContent[];
tools?: GeminiTool[];
toolConfig?: GeminiToolConfig;
systemInstruction?: GeminiChatContent;
generationConfig?: GeminiGenerationConfig;
// cachedContent?: string;
}
export interface GeminiChatResponseSuccess {
candidates: Candidate[];
promptFeedback: PromptFeedback;
usageMetadata: UsageMetadata;
}
export interface GeminiChatResponseError {
error: {
message: string;
};
}
export type GeminiChatResponse =
| GeminiChatResponseError
| GeminiChatResponseSuccess;
interface PromptFeedback {
blockReason?: BlockReason;
safetyRatings: SafetyRating[];
}
enum BlockReason {
BLOCK_REASON_UNSPECIFIED = "BLOCK_REASON_UNSPECIFIED",
SAFETY = "SAFETY",
OTHER = "OTHER",
BLOCKLIST = "BLOCKLIST",
PROHIBITED_CONTENT = "PROHIBITED_CONTENT",
}
interface SafetyRating {
harmCategory: HarmCategory;
harmProbability: HarmProbability;
blocked: boolean;
}
enum HarmCategory {
HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED",
HARM_CATEGORY_DEROGATORY = "HARM_CATEGORY_DEROGATORY",
HARM_CATEGORY_TOXICITY = "HARM_CATEGORY_TOXICITY",
HARM_CATEGORY_VIOLENCE = "HARM_CATEGORY_VIOLENCE",
HARM_CATEGORY_SEXUAL = "HARM_CATEGORY_SEXUAL",
HARM_CATEGORY_MEDICAL = "HARM_CATEGORY_MEDICAL",
HARM_CATEGORY_DANGEROUS = "HARM_CATEGORY_DANGEROUS",
HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT",
HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH",
HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT",
HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT",
HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY",
}
enum HarmProbability {
HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED",
NEGLIGIBLE = "NEGLIGIBLE",
LOW = "LOW",
MEDIUM = "MEDIUM",
HIGH = "HIGH",
}
interface UsageMetadata {
promptTokenCount: number;
cachedContentTokenCount: number;
candidatesTokenCount: number;
totalTokenCount: number;
}
interface Candidate {
content: GeminiChatContent;
finishReason: FinishReason;
safetyRatings: SafetyRating[];
tokenCount: number;
groundingAttribution?: GroundingAttribution;
groundingMetadata?: GroundingMetadata;
avgLogprobs?: number;
logprobs?: LogprobsResult;
index: number;
}
enum FinishReason {
FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED",
STOP = "STOP",
MAX_TOKENS = "MAX_TOKENS",
SAFETY = "SAFETY",
RECITATION = "RECITATION",
LANGUAGE = "LANGUAGE",
OTHER = "OTHER",
BLOCKLIST = "BLOCKLIST",
PROHIBITED_CONTENT = "PROHIBITED_CONTENT",
SPII = "SPII",
MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL",
}
interface GroundingAttribution {
attributionSourceId: AttributionSourceId;
groundingSourceContent: string;
}
interface AttributionSourceId {
groundingPassage?: GroundingPassageId;
semanticRetrieverChunk?: SemanticRetrieverChunk;
}
interface GroundingPassageId {
passageId: string;
partIndex: number;
}
interface SemanticRetrieverChunk {
source: string;
chunk: string;
}
interface GroundingMetadata {
groundingSupport?: GroundingSupport[];
webSearchQueries?: string[];
searchEntryPoint?: SearchEntryPoint;
retrievalMetadata?: RetrievalMetadata;
}
interface SearchEntryPoint {
renderedContent?: string;
sdkBlob?: string;
}
interface RetrievalMetadata {
googleSearchDynamicRetrievalScore?: number;
}
interface GroundingSupport {
groundingChunkIndices: number[];
confidenceScores: number[];
segment: Segment;
}
interface Segment {
partIndex: number;
startIndex: number;
endIndex: number;
text: string;
}
interface LogprobsResult {
topCandidates: TopCandidates[];
chosenCandidates: Candidate[];
}
interface TopCandidates {
candidates: Candidate[];
}

View file

@ -1,13 +1,21 @@
import { FimCreateParamsStreaming } from "@continuedev/openai-adapters/dist/apis/base";
import {
Chat,
ChatCompletion,
ChatCompletionAssistantMessageParam,
ChatCompletionChunk,
ChatCompletionCreateParams,
ChatCompletionMessageParam,
ChatCompletionUserMessageParam,
CompletionCreateParams,
} from "openai/resources/index";
import { ChatMessage, CompletionOptions } from "..";
import {
ChatMessage,
CompletionOptions,
MessageContent,
TextMessagePart,
} from "..";
export function toChatMessage(
message: ChatMessage,
@ -26,43 +34,55 @@ export function toChatMessage(
};
}
let msg: ChatCompletionMessageParam = {
role: message.role,
content:
typeof message.content === "string"
? message.content || " " // LM Studio (and other providers) don't accept empty content
: !message.content.some((item) => item.type !== "text")
? // If no multi-media is in the message, just send as text
if (message.role === "assistant") {
const msg: ChatCompletionAssistantMessageParam = {
role: "assistant",
content:
typeof message.content === "string"
? message.content || " " // LM Studio (and other providers) don't accept empty content
: message.content
.filter((part) => part.type === "text")
.map((part) => part as TextMessagePart), // can remove with newer typescript version
};
if (message.toolCalls) {
msg.tool_calls = message.toolCalls.map((toolCall) => ({
id: toolCall.id!,
type: toolCall.type!,
function: {
name: toolCall.function?.name!,
arguments: toolCall.function?.arguments!,
},
}));
}
return msg;
} else {
return {
role: "user",
content:
typeof message.content === "string"
? message.content || " " // LM Studio (and other providers) don't accept empty content
: // If no multi-media is in the message, just send as text
// for compatibility with OpenAI-"compatible" servers
// that don't support multi-media format
message.content.map((item) => item.text).join("") || " "
: message.content.map((part) => {
const msg: any = {
type: part.type,
text: part.text,
};
if (part.type === "imageUrl") {
msg.image_url = { ...part.imageUrl, detail: "auto" };
msg.type = "image_url";
}
return msg;
}),
};
if (
msg.role === "assistant" &&
message.role === "assistant" &&
message.toolCalls
) {
msg.tool_calls = message.toolCalls.map((toolCall) => ({
id: toolCall.id!,
type: toolCall.type!,
function: {
name: toolCall.function?.name!,
arguments: toolCall.function?.arguments!,
},
}));
message.content.some((item) => item.type !== "text")
? message.content
.map((item) => (item as TextMessagePart).text)
.join("") || " "
: message.content.map((part) => {
if (part.type === "imageUrl") {
return {
type: "image_url" as const,
image_url: {
url: part.imageUrl.url,
detail: "auto" as const,
},
};
}
return part;
}),
};
}
return msg;
}
export function toChatBody(

View file

@ -17,6 +17,10 @@ export const PROVIDER_TOOL_SUPPORT: Record<
return true;
}
},
gemini: (model) => {
// All gemini models support function calling
return model.toLowerCase().includes("gemini");
},
// https://ollama.com/search?c=tools
ollama: (model) => {
if (

View file

@ -16,11 +16,11 @@ export async function getPromptFilesFromDir(
return [];
}
const paths = await walkDir(dir, ide, { ignoreFiles: [] });
const promptFilePaths = paths.filter((p) => p.endsWith(".prompt"));
const results = promptFilePaths.map(async (path) => {
const content = await ide.readFile(path); // make a try catch
return { path, content };
const uris = await walkDir(dir, ide, { ignoreFiles: [] });
const promptFilePaths = uris.filter((p) => p.endsWith(".prompt"));
const results = promptFilePaths.map(async (uri) => {
const content = await ide.readFile(uri); // make a try catch
return { path: uri, content };
});
return Promise.all(results);
} catch (e) {

View file

@ -1,6 +1,3 @@
import { AutocompleteInput } from "../autocomplete/util/types";
import { ProfileDescription } from "../config/ConfigHandler";
import { ConfigResult } from "@continuedev/config-yaml";
import type {
BrowserSerializedContinueConfig,
@ -15,6 +12,7 @@ import type {
LLMFullCompletionOptions,
ModelDescription,
ModelRoles,
PromptLog,
RangeInFile,
SerializedContinueConfig,
Session,
@ -22,27 +20,8 @@ import type {
SiteIndexingConfig,
ToolCall,
} from "../";
export type ProtocolGeneratorYield<T> = {
done?: boolean;
content: T;
};
export type ProtocolGeneratorType<Y> = AsyncGenerator<
ProtocolGeneratorYield<Y>
>;
export type AsyncGeneratorYieldType<T> =
T extends AsyncGenerator<infer Y, any, any>
? Y extends ProtocolGeneratorYield<infer PR>
? PR
: never
: never;
// export type AsyncGeneratorReturnType<T> =
// T extends AsyncGenerator<any, infer R, any>
// ? R extends ProtocolGeneratorYield<infer PR>
// ? PR
// : never
// : never;
import { AutocompleteInput } from "../autocomplete/util/types";
import { ProfileDescription } from "../config/ConfigHandler";
export type OnboardingModes =
| "Local"
@ -120,7 +99,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
historyIndex: number;
selectedCode: RangeInFile[];
},
ProtocolGeneratorType<string>,
AsyncGenerator<string>,
];
"llm/complete": [
{
@ -137,7 +116,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
completionOptions: LLMFullCompletionOptions;
title: string;
},
ProtocolGeneratorType<string>,
AsyncGenerator<string>,
];
"llm/streamChat": [
{
@ -145,7 +124,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
completionOptions: LLMFullCompletionOptions;
title: string;
},
ProtocolGeneratorType<ChatMessage>,
AsyncGenerator<ChatMessage, PromptLog>,
];
streamDiffLines: [
{
@ -156,7 +135,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
language: string | undefined;
modelTitle: string | undefined;
},
ProtocolGeneratorType<DiffLine>,
AsyncGenerator<DiffLine>,
];
"chatDescriber/describe": [
{

View file

@ -66,6 +66,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
[
"configUpdate",
"configError",
"getDefaultModelTitle",
"indexProgress", // Codebase
"indexing/statusUpdate", // Docs, etc.

View file

@ -1,17 +1,53 @@
import { FromWebviewProtocol } from ".";
interface ErrorWebviewMessengerResult {
done: boolean;
export interface ErrorWebviewMessage {
status: "error";
error: string;
done: true;
}
interface SuccessWebviewMessengerResult<T extends keyof FromWebviewProtocol> {
done: boolean;
export interface SuccessWebviewSingleMessage<T> {
done: true;
status: "success";
content: FromWebviewProtocol[T][1];
content: T;
}
export type WebviewMessengerResult<T extends keyof FromWebviewProtocol> =
| ErrorWebviewMessengerResult
| SuccessWebviewMessengerResult<T>;
export type WebviewSingleMessage<T> =
| ErrorWebviewMessage
| SuccessWebviewSingleMessage<T>;
export type WebviewSingleProtocolMessage<T extends keyof FromWebviewProtocol> =
WebviewSingleMessage<FromWebviewProtocol[T][1]>;
// Generators
export type GeneratorYieldType<T> =
T extends AsyncGenerator<infer Yield, any, any> ? Yield : never;
export type GeneratorReturnType<T> =
T extends AsyncGenerator<any, infer Return, any> ? Return : never;
type SuccessWebviewGeneratorMessage<T, R> =
| {
status: "success";
done: false;
content: T;
}
| {
status: "success";
done: true;
content: R;
};
export type WebviewGeneratorMessage<T, R> =
| SuccessWebviewGeneratorMessage<T, R>
| ErrorWebviewMessage;
export type WebviewProtocolGeneratorMessage<
T extends keyof FromWebviewProtocol,
> = WebviewGeneratorMessage<
GeneratorYieldType<FromWebviewProtocol[T][1]>,
GeneratorReturnType<FromWebviewProtocol[T][1]>
>;
export type WebviewMessage<T = unknown, R = unknown> =
| WebviewSingleMessage<T>
| WebviewGeneratorMessage<T, R>;

View file

@ -13,7 +13,7 @@ export const searchWebTool: Tool = {
"Performs a web search, returning top results. This tool should only be called for questions that require external knowledge. Common programming questions do not require web search.",
parameters: {
type: "object",
required: ["query"],
required: ["repo_url"],
properties: {
repo_url: {
type: "string",

View file

@ -12,3 +12,14 @@ export function findLastIndex(
}
return lastIndex;
}
export function findLast<T>(
arr: T[],
criterion: (item: T) => any,
): T | undefined {
for (let i = arr.length - 1; i >= 0; i--) {
if (criterion(arr[i])) {
return arr[i];
}
}
}

View file

@ -3,6 +3,7 @@ import {
ContextItem,
MessageContent,
MessagePart,
TextMessagePart,
} from "../index";
export function stripImages(messageContent: MessageContent): string {
@ -12,7 +13,7 @@ export function stripImages(messageContent: MessageContent): string {
return messageContent
.filter((part) => part.type === "text")
.map((part) => part.text)
.map((part) => (part as TextMessagePart).text)
.join("\n");
}

View file

@ -4,7 +4,7 @@ import * as URI from "uri-js";
// CAN ONLY BE USED IN CORE
// Converts a local path to a file:// URI
// Converts a local path to a file:/// URI
export function localPathToUri(path: string) {
const url = pathToFileURL(path);
return URI.normalize(url.toString());

View file

@ -5,7 +5,7 @@
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/../../binary" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/binary" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="" />
<option name="INTERPRETER_OPTIONS" value="" />

View file

@ -5,7 +5,7 @@
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/../../gui" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/gui" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="/bin/zsh" />
<option name="INTERPRETER_OPTIONS" value="" />

View file

@ -152,6 +152,8 @@ This will generate a .zip file in `./build/distributions` with the version defin
The e2e tests are written using [intellij-ui-test-robot](`https://github.com/JetBrains/intellij-ui-test-robot`). The
README for this project has a lot of helpful info on how to use the library.
Note that these tests fully take control of your mouse while executing.
#### Setup
If you are on macOS, you'll need to give IntelliJ permission to control your computer in order to run the e2e tests.
@ -174,7 +176,18 @@ to run.
#### Identifying selectors
While the `runIdeForUiTests` task is runnung, you can visit the following URL
While the `runIdeForUiTests` task is running, you can visit the following URL
to view the UI hierarchy of the running IDE:
http://127.0.0.1:8082/
http://127.0.0.1:8082/
#### Rebuilding the extension
To rebuild the extension with the latest source code, run the following:
```sh
./gradlew buildPlugin
```
This will update the contents of the extension that is loaded into the test IDE from
`build/idea-sandbox/plugins-uiTest/continue-intellij-extension`

View file

@ -47,6 +47,22 @@ dependencies {
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
implementation("com.automation-remarks:video-recorder-junit5:2.0")
// Exclude vulnerable Log4j from all dependencies
configurations.all {
resolutionStrategy {
eachDependency {
if (requested.group == "log4j" && requested.name == "log4j") {
useTarget("org.slf4j:log4j-over-slf4j:1.7.36")
}
}
}
}
// Add Log4j 2.x explicitly
implementation("org.apache.logging.log4j:log4j-core:2.20.0")
implementation("org.apache.logging.log4j:log4j-api:2.20.0")
}
// Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for
@ -105,13 +121,10 @@ tasks {
wrapper { gradleVersion = properties("gradleVersion").get() }
patchPluginXml {
version = properties("pluginVersion")
sinceBuild = properties("pluginSinceBuild")
untilBuild = properties("pluginUntilBuild")
// Extract the <!-- Plugin description --> section from README.md and provide for the plugin's
// manifest
pluginDescription =
version.set(properties("pluginVersion"))
sinceBuild.set(properties("pluginSinceBuild"))
untilBuild.set(properties("pluginUntilBuild"))
pluginDescription.set(
providers.fileContents(layout.projectDirectory.file("README.md")).asText.map {
val start = "<!-- Plugin description -->"
val end = "<!-- Plugin description end -->"
@ -125,6 +138,7 @@ tasks {
subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML)
}
}
)
}
// Configure UI tests plugin
@ -149,9 +163,9 @@ tasks {
// This is to ensure we load the GUI with OSR enabled. We have logic that
// renders with OSR disabled below a particular IDE version.
// See ContinueExtensionSettingsService.kt for more info.
intellij {
version.set("2024.1")
}
// intellij {
// version.set("2024.1")
// }
}
signPlugin {

View file

@ -53,6 +53,7 @@ class MessageTypes {
// Note: If updating these values, make a corresponding update in
// core/protocol/passThrough.ts
val PASS_THROUGH_TO_WEBVIEW = listOf(
"configError",
"configUpdate",
"getDefaultModelTitle",
"indexProgress", // Codebase

View file

@ -58,10 +58,10 @@ class CoreMessengerManager(
private fun setupCoreMessenger(continueCorePath: String) {
coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope)
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { resp ->
val data = resp as? Map<String, Any>
val profileInfo = data?.get("config") as? Map<String, Any>
val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val result = (response as Map<String, Any>)["result"] as Map<String, Any>
val config = result["config"] as Map<String, Any>
val allowAnonymousTelemetry = config?.get("allowAnonymousTelemetry") as? Boolean
val telemetryService = service<TelemetryService>()
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
telemetryService.setup(getMachineUniqueID())

View file

@ -439,7 +439,8 @@ class IdeProtocolClient(
null,
null
) { response ->
val config = (response as Map<String, Any>)["config"] as Map<String, Any>
val result = (response as Map<String, Any>)["result"] as Map<String, Any>
val config = result["config"] as Map<String, Any>
val applyCodeBlockModel = getModelByRole(config, "applyCodeBlock")
if (applyCodeBlockModel != null) {

View file

@ -128,11 +128,14 @@ fun openInlineEdit(project: Project?, editor: Editor) {
// Get list of model titles
val continuePluginService = project.service<ContinuePluginService>()
val modelTitles = mutableListOf<String>()
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val config = response as Map<String, Any>
val models = (config["config"] as Map<String, Any>)["models"] as List<Map<String, Any>>
val result = (response as Map<String, Any>)["result"] as Map<String, Any>
val config = result["config"] as Map<String, Any>
val models = config["models"] as List<Map<String, Any>>
modelTitles.addAll(models.map { it["title"] as String })
}
val maxWaitTime = 200
val startTime = System.currentTimeMillis()
while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) {
@ -427,7 +430,7 @@ class CustomPanel(
}
selectedIndex =
if(itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
if (modelTitles.isEmpty()) -1
else {
val index = modelTitles.indexOf(it)

View file

@ -34,7 +34,7 @@ class Autocomplete {
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
@Test
@Video
fun displayCompletion(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
@ -50,7 +50,7 @@ class Autocomplete {
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
).isNotEmpty()
}
@ -64,7 +64,7 @@ class Autocomplete {
enterText(" ")
}
waitFor(ofSeconds(10)) {
waitFor(ofSeconds(20)) {
editor.hasText("TEST_LLM_RESPONSE_0")
}
}

View file

@ -39,7 +39,7 @@ class GUI {
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
// @Test
@Video
fun highlightCode(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
@ -57,7 +57,7 @@ class GUI {
// while the `continue_tutorial.java` is loading.
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
).isNotEmpty()
}

View file

@ -35,7 +35,7 @@ class Onboarding {
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
// @Test
@Video
fun onboarding(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
@ -53,7 +53,7 @@ class Onboarding {
// So we need to wait for that to occur, and then focus on "continue_tutorial.java.ft"
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
).isNotEmpty()
}

View file

@ -1,6 +1,5 @@
import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
import { Message } from "core/protocol/messenger";
import { WebviewMessengerResult } from "core/protocol/util";
import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
import { Telemetry } from "core/util/posthog";
import { v4 as uuidv4 } from "uuid";
@ -51,34 +50,40 @@ export class VsCodeWebviewProtocol
this._webview = webView;
this._webviewListener?.dispose();
this._webviewListener = this._webview.onDidReceiveMessage(async (msg) => {
if (!msg.messageType || !msg.messageId) {
const handleMessage = async (msg: Message): Promise<void> => {
if (!("messageType" in msg) || !("messageId" in msg)) {
throw new Error(`Invalid webview protocol msg: ${JSON.stringify(msg)}`);
}
const respond = (message: WebviewMessengerResult<any>) =>
const respond = (message: any) =>
this.send(msg.messageType, message, msg.messageId);
const handlers = this.listeners.get(msg.messageType) || [];
const handlers =
this.listeners.get(msg.messageType as keyof FromWebviewProtocol) || [];
for (const handler of handlers) {
try {
const response = await handler(msg);
// For generator types e.g. llm/streamChat
if (
response &&
typeof response[Symbol.asyncIterator] === "function"
) {
let next = await response.next();
while (!next.done) {
respond(next.value);
respond({
done: false,
content: next.value,
status: "success",
});
next = await response.next();
}
respond({
done: true,
content: next.value?.content,
content: next.value,
status: "success",
});
} else {
respond({ done: true, content: response ?? {}, status: "success" });
respond({ content: response, status: "success" });
}
} catch (e: any) {
respond({ done: true, error: e.message, status: "error" });
@ -92,7 +97,6 @@ export class VsCodeWebviewProtocol
stringified.includes("llm/streamChat") ||
stringified.includes("chatDescriber/describe")
) {
// handle these errors in the GUI
return;
}
@ -143,7 +147,9 @@ export class VsCodeWebviewProtocol
}
}
}
});
};
this._webviewListener = this._webview.onDidReceiveMessage(handleMessage);
}
constructor(private readonly reloadConfig: () => void) {}

View file

@ -6,6 +6,7 @@ import {
MessageContent,
MessagePart,
RangeInFile,
TextMessagePart,
} from "core";
import { stripImages } from "core/util/messageContent";
import { IIdeMessenger } from "../../context/IdeMessenger";
@ -65,7 +66,7 @@ async function resolveEditorContent({
}
if (parts[parts.length - 1]?.type === "text") {
parts[parts.length - 1].text += "\n" + text;
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
} else {
parts.push({ type: "text", text });
}
@ -88,7 +89,7 @@ async function resolveEditorContent({
contextItem.content +
"\n```";
if (parts[parts.length - 1]?.type === "text") {
parts[parts.length - 1].text += "\n" + text;
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
} else {
parts.push({
type: "text",
@ -181,9 +182,10 @@ async function resolveEditorContent({
if (slashCommand) {
let lastTextIndex = findLastIndex(parts, (part) => part.type === "text");
const lastPart = `${slashCommand} ${parts[lastTextIndex]?.text || ""}`;
const lastTextPart = parts[lastTextIndex] as TextMessagePart;
const lastPart = `${slashCommand} ${lastTextPart?.text || ""}`;
if (parts.length > 0) {
parts[lastTextIndex].text = lastPart;
lastTextPart.text = lastPart;
} else {
parts = [{ type: "text", text: lastPart }];
}

View file

@ -1,16 +1,19 @@
import { ChatMessage, IDE, LLMFullCompletionOptions, PromptLog } from "core";
import type { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
import { WebviewMessengerResult } from "core/protocol/util";
import {
GeneratorReturnType,
GeneratorYieldType,
WebviewMessage,
WebviewProtocolGeneratorMessage,
WebviewSingleMessage,
WebviewSingleProtocolMessage,
} from "core/protocol/util";
import { MessageIde } from "core/protocol/messenger/messageIde";
import { Message } from "core/protocol/messenger";
import { createContext } from "react";
import { v4 as uuidv4 } from "uuid";
import "vscode-webview";
import { isJetBrains } from "../util";
import {
AsyncGeneratorYieldType,
ProtocolGeneratorYield,
} from "core/protocol/core";
interface vscode {
postMessage(message: any): vscode;
@ -35,20 +38,23 @@ export interface IIdeMessenger {
request<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],
): Promise<WebviewMessengerResult<T>>;
): Promise<WebviewSingleProtocolMessage<T>>;
streamRequest<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],
cancelToken?: AbortSignal,
): AsyncGenerator<unknown[]>;
): AsyncGenerator<
GeneratorYieldType<FromWebviewProtocol[T][1]>[],
GeneratorReturnType<FromWebviewProtocol[T][1]> | undefined
>;
llmStreamChat(
modelTitle: string,
cancelToken: AbortSignal | undefined,
messages: ChatMessage[],
options?: LLMFullCompletionOptions,
): AsyncGenerator<ChatMessage[], PromptLog, unknown>;
): AsyncGenerator<ChatMessage[], PromptLog | undefined>;
ide: IDE;
}
@ -140,14 +146,14 @@ export class IdeMessenger implements IIdeMessenger {
request<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],
): Promise<WebviewMessengerResult<T>> {
): Promise<WebviewSingleMessage<T>> {
const messageId = uuidv4();
return new Promise((resolve) => {
const handler = (event: any) => {
if (event.data.messageId === messageId) {
window.removeEventListener("message", handler);
resolve(event.data.data as WebviewMessengerResult<T>);
resolve(event.data.data as WebviewSingleMessage<T>);
}
};
window.addEventListener("message", handler);
@ -168,24 +174,33 @@ export class IdeMessenger implements IIdeMessenger {
messageType: T,
data: FromWebviewProtocol[T][0],
cancelToken?: AbortSignal,
): AsyncGenerator<AsyncGeneratorYieldType<FromWebviewProtocol[T][1]>[], any> {
type GenYield = AsyncGeneratorYieldType<FromWebviewProtocol[T][1]>;
// type GenReturn = AsyncGeneratorReturnType<FromWebviewProtocol[T][1]>;
): AsyncGenerator<
GeneratorYieldType<FromWebviewProtocol[T][1]>[],
GeneratorReturnType<FromWebviewProtocol[T][1]> | undefined
> {
const messageId = uuidv4();
this.post(messageType, data, messageId);
const buffer: GenYield[] = [];
const buffer: GeneratorYieldType<FromWebviewProtocol[T][1]>[] = [];
let index = 0;
let done = false;
let returnVal = undefined;
let returnVal: GeneratorReturnType<FromWebviewProtocol[T][1]> | undefined =
undefined;
let error: string | null = null;
// This handler receieves individual WebviewMessengerResults
// And pushes them to buffer
const handler = (event: {
data: Message<ProtocolGeneratorYield<GenYield>>;
data: Message<WebviewProtocolGeneratorMessage<T>>;
}) => {
if (event.data.messageId === messageId) {
const responseData = event.data.data;
if ("error" in responseData) {
error = responseData.error;
return;
// throw new Error(responseData.error);
}
if (responseData.done) {
window.removeEventListener("message", handler);
done = true;
@ -204,6 +219,9 @@ export class IdeMessenger implements IIdeMessenger {
try {
while (!done) {
if (error) {
throw error;
}
if (buffer.length > index) {
const chunks = buffer.slice(index);
index = buffer.length;
@ -217,6 +235,9 @@ export class IdeMessenger implements IIdeMessenger {
yield chunks;
}
if (!returnVal) {
return undefined;
}
return returnVal;
} catch (e) {
throw e;
@ -230,7 +251,7 @@ export class IdeMessenger implements IIdeMessenger {
cancelToken: AbortSignal | undefined,
messages: ChatMessage[],
options: LLMFullCompletionOptions = {},
): AsyncGenerator<ChatMessage[], PromptLog> {
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
const gen = this.streamRequest(
"llm/streamChat",
{
@ -246,17 +267,7 @@ export class IdeMessenger implements IIdeMessenger {
yield next.value;
next = await gen.next();
}
if (!next.done) {
throw new Error();
}
return {
modelTitle: next.value.content?.modelTitle,
prompt: next.value.content?.prompt,
completion: next.value.content?.completion,
completionOptions: next.value.content?.completionOptions,
};
return next.value;
}
}

View file

@ -28,12 +28,10 @@ interface SubtextContextProvidersContextType {
providerTitle: string | undefined,
query: string,
) => ContextSubmenuItemWithProvider[];
initialLoadComplete: boolean;
}
const initialContextProviders: SubtextContextProvidersContextType = {
getSubmenuContextItems: () => [],
initialLoadComplete: false,
};
const SubmenuContextProvidersContext =
@ -118,8 +116,7 @@ export const SubmenuContextProvidersProvider = ({
};
}, [ideMessenger]);
const [initialLoadComplete, setInitialLoadComplete] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const providersLoading = useRef(new Set<string>()).current;
const getSubmenuContextItems = useCallback(
(
@ -176,8 +173,8 @@ export const SubmenuContextProvidersProvider = ({
};
});
if (fallbackItems.length === 0 && !initialLoadComplete) {
return [
if (fallbackItems.length === 0) {
const loadingFiller = [
{
id: "loading",
title: "Loading...",
@ -185,6 +182,19 @@ export const SubmenuContextProvidersProvider = ({
providerTitle: providerTitle || "unknown",
},
];
// If getting for all providers
if (!providerTitle) {
// then show loading if ANY loading
if (providersLoading.size > 0) {
return loadingFiller;
}
} else {
// Otherwise just check if the provider is loading
if (providersLoading.has(providerTitle)) {
return loadingFiller;
}
}
}
return fallbackItems;
@ -203,124 +213,124 @@ export const SubmenuContextProvidersProvider = ({
return [];
}
},
[fallbackResults, minisearches, initialLoadComplete],
[fallbackResults, minisearches],
);
const loadSubmenuItems = useCallback(
async (providers: "dependsOnIndexing" | "all" | ContextProviderName[]) => {
setIsLoading(true);
await Promise.allSettled(
submenuContextProviders.map(
async (description: ContextProviderDescription) => {
try {
const refreshProvider =
providers === "all"
? true
: providers === "dependsOnIndexing"
? description.dependsOnIndexing
: providers.includes(description.title);
if (!refreshProvider) {
return;
}
if (description.dependsOnIndexing && disableIndexing) {
console.debug(
`Skipping ${description.title} provider due to disabled indexing`,
);
return;
}
const result = await ideMessenger.request(
"context/loadSubmenuItems",
{
title: description.title,
},
);
if (result.status === "error") {
throw new Error(result.error);
}
const submenuItems = result.content;
const providerTitle = description.title;
const itemsWithProvider = submenuItems.map((item) => ({
...item,
providerTitle,
}));
const minisearch = new MiniSearch<ContextSubmenuItemWithProvider>(
{
fields: ["title", "description"],
storeFields: ["id", "title", "description", "providerTitle"],
},
);
minisearch.addAll(
submenuItems.map((item) => ({ ...item, providerTitle })),
);
setMinisearches((prev) => ({
...prev,
[providerTitle]: minisearch,
}));
if (providerTitle === "file") {
setFallbackResults((prev) => ({
...prev,
file: deduplicateArray(
[...lastOpenFilesRef.current, ...(prev.file ?? [])],
(a, b) => a.id === b.id,
),
}));
} else {
setFallbackResults((prev) => ({
...prev,
[providerTitle]: itemsWithProvider,
}));
}
} catch (error) {
console.error(
`Error loading items for ${description.title}:`,
error,
);
console.error(
"Error details:",
JSON.stringify(error, Object.getOwnPropertyNames(error)),
);
(providers: "dependsOnIndexing" | "all" | ContextProviderName[]) => {
submenuContextProviders.forEach(
async (description: ContextProviderDescription) => {
try {
if (providersLoading.has(description.title)) {
return;
}
},
),
providersLoading.add(description.title);
const refreshProvider =
providers === "all"
? true
: providers === "dependsOnIndexing"
? description.dependsOnIndexing
: providers.includes(description.title);
if (!refreshProvider) {
return;
}
if (description.dependsOnIndexing && disableIndexing) {
console.debug(
`Skipping ${description.title} provider due to disabled indexing`,
);
return;
}
const result = await ideMessenger.request(
"context/loadSubmenuItems",
{
title: description.title,
},
);
if (result.status === "error") {
throw new Error(result.error);
}
const submenuItems = result.content;
const providerTitle = description.title;
const itemsWithProvider = submenuItems.map((item) => ({
...item,
providerTitle,
}));
const minisearch = new MiniSearch<ContextSubmenuItemWithProvider>({
fields: ["title", "description"],
storeFields: ["id", "title", "description", "providerTitle"],
});
minisearch.addAll(
submenuItems.map((item) => ({ ...item, providerTitle })),
);
setMinisearches((prev) => ({
...prev,
[providerTitle]: minisearch,
}));
if (providerTitle === "file") {
setFallbackResults((prev) => ({
...prev,
file: deduplicateArray(
[...lastOpenFilesRef.current, ...(prev.file ?? [])],
(a, b) => a.id === b.id,
),
}));
} else {
setFallbackResults((prev) => ({
...prev,
[providerTitle]: itemsWithProvider,
}));
}
} catch (error) {
console.error(
`Error loading items for ${description.title}:`,
error,
);
console.error(
"Error details:",
JSON.stringify(error, Object.getOwnPropertyNames(error)),
);
} finally {
providersLoading.delete(description.title);
}
},
);
setInitialLoadComplete(true);
setIsLoading(false);
},
[submenuContextProviders, disableIndexing],
[submenuContextProviders, disableIndexing, providersLoading],
);
useWebviewListener(
"refreshSubmenuItems",
async (data) => {
if (isLoading) {
return;
}
if (data.providers === "all") {
setInitialLoadComplete(false);
}
await loadSubmenuItems(data.providers);
loadSubmenuItems(data.providers);
},
[isLoading, loadSubmenuItems],
[loadSubmenuItems],
);
// Reload all submenu items on the initial config load
// TODO - could refresh on any change
const initialLoad = useRef(false);
const config = useAppSelector((store) => store.config.config);
useEffect(() => {
if (!config?.contextProviders?.length || initialLoad.current) {
return;
}
void loadSubmenuItems("all");
}, []);
initialLoad.current = true;
}, [loadSubmenuItems, config, initialLoad]);
return (
<SubmenuContextProvidersContext.Provider
value={{
getSubmenuContextItems,
initialLoadComplete,
}}
>
{children}

View file

@ -332,13 +332,13 @@ export const sessionSlice = createSlice({
const historyItem: ChatHistoryItemWithMessageId = {
message: {
...message,
content: renderChatMessage(message),
id: uuidv4(),
},
contextItems: [],
};
if (message.role === "assistant" && message.toolCalls?.[0]) {
const toolCallDelta = message.toolCalls[0];
if (
toolCallDelta.id &&
toolCallDelta.function?.arguments &&
@ -356,6 +356,8 @@ export const sessionSlice = createSlice({
} else {
// Add to the existing message
if (message.content) {
// Note this only works because new message above
// was already rendered from parts to string
lastMessage.content += renderChatMessage(message);
} else if (
message.role === "assistant" &&

View file

@ -96,7 +96,7 @@ export const gatherContext = createAsyncThunk<
if (promptPreamble) {
if (typeof content === "string") {
content = promptPreamble + content;
} else {
} else if (content[0].type === "text") {
content[0].text = promptPreamble + content[0].text;
}
}

View file

@ -52,13 +52,12 @@ export const streamNormalInput = createAsyncThunk<
break;
}
const updates = next.value;
dispatch(streamUpdate(updates));
dispatch(streamUpdate(next.value));
next = await gen.next();
}
// Attach prompt log
if (next.done) {
if (next.done && next.value) {
dispatch(addPromptCompletionPair([next.value]));
}

View file

@ -1,6 +1,11 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/core";
import { InputModifiers, MessageContent, SlashCommandDescription } from "core";
import {
InputModifiers,
MessageContent,
SlashCommandDescription,
TextMessagePart,
} from "core";
import { constructMessages } from "core/llm/constructMessages";
import { renderChatMessage } from "core/util/messageContent";
import posthog from "posthog-js";
@ -28,7 +33,11 @@ const getSlashCommandForInput = (
let lastText =
typeof input === "string"
? input
: input.filter((part) => part.type === "text").slice(-1)[0]?.text || "";
: (
input.filter((part) => part.type === "text").slice(-1)[0] as
| TextMessagePart
| undefined
)?.text || "";
if (lastText.startsWith("/")) {
slashCommandName = lastText.split(" ")[0].substring(1);